diff --git a/DMSETUP/build.txt b/DMSETUP/build.txt new file mode 100644 index 00000000..1c2d5ed5 --- /dev/null +++ b/DMSETUP/build.txt @@ -0,0 +1,30 @@ +Build a static linked, small dmsetup tool + +======== Source Code ======== +use an old version of dmsetup +xxx/centos-vault/5.3/os/SRPMS/device-mapper-1.02.28-2.el5.src.rpm + +======== Build Envrioment ======== +build for 32bit, static linked with dietlibc +1. install centos 6.10 i386 with CentOS-6.10-i386-bin-DVD1.iso +2. yum install gcc kernel-devel package +3. install dietc libc (just make && make install) +4. export PATH=$PATH:/opt/diet/bin + +======== Build Step ======== +1. extract device mapper source code +2. CC="diet gcc" ./configure --disable-nls --disable-selinux --disable-shared +3. modify include/configure.h file + --- delete the line with "#define malloc rpl_malloc" + --- add 2 defines as follow: + #ifndef UINT32_MAX + #define UINT32_MAX (4294967295U) + #endif + + #ifndef UINT64_C + #define UINT64_C(c) c ## ULL + #endif + +4. make +5. strip dmsetup/dmsetup +5. get dmsetup/dmsetup as the binary file diff --git a/DMSETUP/dmsetup b/DMSETUP/dmsetup new file mode 100644 index 00000000..d5347ece Binary files /dev/null and b/DMSETUP/dmsetup differ diff --git a/EDK2/README.txt b/EDK2/README.txt new file mode 100644 index 00000000..3d802235 --- /dev/null +++ b/EDK2/README.txt @@ -0,0 +1,8 @@ + +========== About Source Code ============= +Ventoy add an UEFI application module in MdeModulePkg, so I only put the module's source code here. +You can download the EDK2 code from https://github.com/tianocore/edk2 and merge the code together. + + +========== Build ============= +Follow the EDK2's build instructions diff --git a/EDK2/edk2-edk2-stable201911/MdeModulePkg/Application/Ventoy/Ventoy.c b/EDK2/edk2-edk2-stable201911/MdeModulePkg/Application/Ventoy/Ventoy.c new file mode 100644 index 00000000..d3c8216b --- /dev/null +++ b/EDK2/edk2-edk2-stable201911/MdeModulePkg/Application/Ventoy/Ventoy.c @@ -0,0 +1,1073 @@ +/****************************************************************************** + * Ventoy.c + * + * Copyright (c) 2020, longpanda + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, see . + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +BOOLEAN gDebugPrint = FALSE; +BOOLEAN gLoadIsoEfi = FALSE; +ventoy_chain_head *g_chain; +ventoy_img_chunk *g_chunk; +UINT32 g_img_chunk_num; +ventoy_override_chunk *g_override_chunk; +UINT32 g_override_chunk_num; +ventoy_virt_chunk *g_virt_chunk; +UINT32 g_virt_chunk_num; +vtoy_block_data gBlockData; +ventoy_sector_flag *g_sector_flag = NULL; +UINT32 g_sector_flag_num = 0; +static grub_env_get_pf grub_env_get = NULL; + +CONST CHAR16 gIso9660EfiDriverPath[] = ISO9660_EFI_DRIVER_PATH; + +/* Boot filename */ +CONST CHAR16 *gEfiBootFileName[] = +{ + EFI_REMOVABLE_MEDIA_FILE_NAME, + L"\\EFI\\BOOT\\GRUBX64.EFI", + L"\\EFI\\BOOT\\BOOTx64.EFI", + L"\\EFI\\BOOT\\bootx64.efi", +}; + +/* EFI block device vendor device path GUID */ +EFI_GUID gVtoyBlockDevicePathGuid = VTOY_BLOCK_DEVICE_PATH_GUID; + +VOID EFIAPI VtoyDebug(IN CONST CHAR8 *Format, ...) +{ + VA_LIST Marker; + CHAR16 Buffer[512]; + + VA_START (Marker, Format); + UnicodeVSPrintAsciiFormat(Buffer, sizeof(Buffer), Format, Marker); + VA_END (Marker); + + gST->ConOut->OutputString(gST->ConOut, Buffer); +} + +VOID EFIAPI ventoy_clear_input(VOID) +{ + EFI_INPUT_KEY Key; + + gST->ConIn->Reset(gST->ConIn, FALSE); + while (EFI_SUCCESS == gST->ConIn->ReadKeyStroke(gST->ConIn, &Key)) + { + ; + } + gST->ConIn->Reset(gST->ConIn, FALSE); +} + +static void EFIAPI ventoy_dump_img_chunk(ventoy_chain_head *chain) +{ + UINT32 i; + int errcnt = 0; + UINT64 img_sec = 0; + ventoy_img_chunk *chunk; + + chunk = (ventoy_img_chunk *)((char *)chain + chain->img_chunk_offset); + + debug("##################### ventoy_dump_img_chunk #######################"); + + for (i = 0; i < chain->img_chunk_num; i++) + { + debug("%2u: [ %u - %u ] <==> [ %llu - %llu ]", + i, chunk[i].img_start_sector, chunk[i].img_end_sector, + chunk[i].disk_start_sector, chunk[i].disk_end_sector); + + if (i > 0 && (chunk[i].img_start_sector != chunk[i - 1].img_end_sector + 1)) + { + errcnt++; + } + + img_sec += chunk[i].img_end_sector - chunk[i].img_start_sector + 1; + } + + if (errcnt == 0 && (img_sec * 2048 == g_chain->real_img_size_in_bytes)) + { + debug("image chunk size check success"); + } + else + { + debug("image chunk size check failed %d", errcnt); + } + + ventoy_debug_pause(); +} + +static void EFIAPI ventoy_dump_override_chunk(ventoy_chain_head *chain) +{ + UINT32 i; + ventoy_override_chunk *chunk; + + chunk = (ventoy_override_chunk *)((char *)chain + chain->override_chunk_offset); + + debug("##################### ventoy_dump_override_chunk #######################"); + + for (i = 0; i < g_override_chunk_num; i++) + { + debug("%2u: [ %llu, %u ]", i, chunk[i].img_offset, chunk[i].override_size); + } + + ventoy_debug_pause(); +} + +static void EFIAPI ventoy_dump_virt_chunk(ventoy_chain_head *chain) +{ + UINT32 i; + ventoy_virt_chunk *node; + + debug("##################### ventoy_dump_virt_chunk #######################"); + debug("virt_chunk_offset=%u", chain->virt_chunk_offset); + debug("virt_chunk_num=%u", chain->virt_chunk_num); + + node = (ventoy_virt_chunk *)((char *)chain + chain->virt_chunk_offset); + for (i = 0; i < chain->virt_chunk_num; i++, node++) + { + debug("%2u: mem:[ %u, %u, %u ] remap:[ %u, %u, %u ]", i, + node->mem_sector_start, + node->mem_sector_end, + node->mem_sector_offset, + node->remap_sector_start, + node->remap_sector_end, + node->org_sector_start); + } + + ventoy_debug_pause(); +} + +static void EFIAPI ventoy_dump_chain(ventoy_chain_head *chain) +{ + UINT32 i = 0; + UINT8 chksum = 0; + UINT8 *guid; + + guid = chain->os_param.vtoy_disk_guid; + for (i = 0; i < sizeof(ventoy_os_param); i++) + { + chksum += *((UINT8 *)(&(chain->os_param)) + i); + } + + debug("##################### ventoy_dump_chain #######################"); + + debug("os_param->chksum=0x%x (%a)", chain->os_param.chksum, chksum ? "FAILED" : "SUCCESS"); + debug("os_param->vtoy_disk_guid=%02x%02x%02x%02x", guid[0], guid[1], guid[2], guid[3]); + debug("os_param->vtoy_disk_size=%llu", chain->os_param.vtoy_disk_size); + debug("os_param->vtoy_disk_part_id=%u", chain->os_param.vtoy_disk_part_id); + debug("os_param->vtoy_disk_part_type=%u", chain->os_param.vtoy_disk_part_type); + debug("os_param->vtoy_img_path=<%a>", chain->os_param.vtoy_img_path); + debug("os_param->vtoy_img_size=<%llu>", chain->os_param.vtoy_img_size); + debug("os_param->vtoy_img_location_addr=<0x%llx>", chain->os_param.vtoy_img_location_addr); + debug("os_param->vtoy_img_location_len=<%u>", chain->os_param.vtoy_img_location_len); + + ventoy_debug_pause(); + + debug("chain->disk_drive=0x%x", chain->disk_drive); + debug("chain->disk_sector_size=%u", chain->disk_sector_size); + debug("chain->real_img_size_in_bytes=%llu", chain->real_img_size_in_bytes); + debug("chain->virt_img_size_in_bytes=%llu", chain->virt_img_size_in_bytes); + debug("chain->boot_catalog=%u", chain->boot_catalog); + debug("chain->img_chunk_offset=%u", chain->img_chunk_offset); + debug("chain->img_chunk_num=%u", chain->img_chunk_num); + debug("chain->override_chunk_offset=%u", chain->override_chunk_offset); + debug("chain->override_chunk_num=%u", chain->override_chunk_num); + + ventoy_debug_pause(); + + ventoy_dump_img_chunk(chain); + ventoy_dump_override_chunk(chain); + ventoy_dump_virt_chunk(chain); +} + +EFI_HANDLE EFIAPI ventoy_get_parent_handle(IN EFI_DEVICE_PATH_PROTOCOL *pDevPath) +{ + EFI_HANDLE Handle = NULL; + EFI_STATUS Status = EFI_SUCCESS; + EFI_DEVICE_PATH_PROTOCOL *pLastNode = NULL; + EFI_DEVICE_PATH_PROTOCOL *pCurNode = NULL; + EFI_DEVICE_PATH_PROTOCOL *pTmpDevPath = NULL; + + pTmpDevPath = DuplicateDevicePath(pDevPath); + if (!pTmpDevPath) + { + return NULL; + } + + pCurNode = pTmpDevPath; + while (!IsDevicePathEnd(pCurNode)) + { + pLastNode = pCurNode; + pCurNode = NextDevicePathNode(pCurNode); + } + if (pLastNode) + { + CopyMem(pLastNode, pCurNode, sizeof(EFI_DEVICE_PATH_PROTOCOL)); + } + + pCurNode = pTmpDevPath; + Status = gBS->LocateDevicePath(&gEfiDevicePathProtocolGuid, &pCurNode, &Handle); + debug("Status:%r Parent Handle:%p DP:%s", Status, Handle, ConvertDevicePathToText(pTmpDevPath, FALSE, FALSE)); + + FreePool(pTmpDevPath); + + return Handle; +} + +EFI_STATUS EFIAPI ventoy_block_io_reset +( + IN EFI_BLOCK_IO_PROTOCOL *This, + IN BOOLEAN ExtendedVerification +) +{ + (VOID)This; + (VOID)ExtendedVerification; + return EFI_SUCCESS; +} + +STATIC EFI_STATUS EFIAPI ventoy_read_iso_sector +( + IN UINT64 Sector, + IN UINTN Count, + OUT VOID *Buffer +) +{ + EFI_STATUS Status = EFI_SUCCESS; + EFI_LBA MapLba = 0; + UINT32 i = 0; + UINTN secLeft = 0; + UINTN secRead = 0; + UINT64 ReadStart = 0; + UINT64 ReadEnd = 0; + UINT64 OverrideStart = 0; + UINT64 OverrideEnd= 0; + UINT8 *pCurBuf = (UINT8 *)Buffer; + ventoy_img_chunk *pchunk = g_chunk; + ventoy_override_chunk *pOverride = g_override_chunk; + EFI_BLOCK_IO_PROTOCOL *pRawBlockIo = gBlockData.pRawBlockIo; + + debug("read iso sector %lu count %u", Sector, Count); + + ReadStart = Sector * 2048; + ReadEnd = (Sector + Count) * 2048; + + for (i = 0; Count > 0 && i < g_img_chunk_num; i++, pchunk++) + { + if (Sector >= pchunk->img_start_sector && Sector <= pchunk->img_end_sector) + { + if (g_chain->disk_sector_size == 512) + { + MapLba = (Sector - pchunk->img_start_sector) * 4 + pchunk->disk_start_sector; + } + else + { + MapLba = (Sector - pchunk->img_start_sector) * 2048 / g_chain->disk_sector_size + pchunk->disk_start_sector; + } + + secLeft = pchunk->img_end_sector + 1 - Sector; + secRead = (Count < secLeft) ? Count : secLeft; + + Status = pRawBlockIo->ReadBlocks(pRawBlockIo, pRawBlockIo->Media->MediaId, + MapLba, secRead * 2048, pCurBuf); + if (EFI_ERROR(Status)) + { + debug("Raw disk read block failed %r", Status); + return Status; + } + + Count -= secRead; + Sector += secRead; + pCurBuf += secRead * 2048; + } + } + + if (ReadStart > g_chain->real_img_size_in_bytes) + { + return EFI_SUCCESS; + } + + /* override data */ + pCurBuf = (UINT8 *)Buffer; + for (i = 0; i < g_override_chunk_num; i++, pOverride++) + { + OverrideStart = pOverride->img_offset; + OverrideEnd = pOverride->img_offset + pOverride->override_size; + + if (OverrideStart >= ReadEnd || ReadStart >= OverrideEnd) + { + continue; + } + + if (ReadStart <= OverrideStart) + { + if (ReadEnd <= OverrideEnd) + { + CopyMem(pCurBuf + OverrideStart - ReadStart, pOverride->override_data, ReadEnd - OverrideStart); + } + else + { + CopyMem(pCurBuf + OverrideStart - ReadStart, pOverride->override_data, pOverride->override_size); + } + } + else + { + if (ReadEnd <= OverrideEnd) + { + CopyMem(pCurBuf, pOverride->override_data + ReadStart - OverrideStart, ReadEnd - ReadStart); + } + else + { + CopyMem(pCurBuf, pOverride->override_data + ReadStart - OverrideStart, OverrideEnd - ReadStart); + } + } + } + + return EFI_SUCCESS; +} + +EFI_STATUS EFIAPI ventoy_block_io_read +( + IN EFI_BLOCK_IO_PROTOCOL *This, + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN UINTN BufferSize, + OUT VOID *Buffer +) +{ + UINT32 i = 0; + UINT32 j = 0; + UINT32 lbacount = 0; + UINT32 secNum = 0; + UINT64 offset = 0; + EFI_LBA curlba = 0; + EFI_LBA lastlba = 0; + UINT8 *lastbuffer; + ventoy_sector_flag *cur_flag; + ventoy_virt_chunk *node; + + //debug("### ventoy_block_io_read sector:%u count:%u", (UINT32)Lba, (UINT32)BufferSize / 2048); + + secNum = BufferSize / 2048; + offset = Lba * 2048; + + if (offset + BufferSize < g_chain->real_img_size_in_bytes) + { + return ventoy_read_iso_sector(Lba, secNum, Buffer); + } + + if (secNum > g_sector_flag_num) + { + cur_flag = AllocatePool(secNum * sizeof(ventoy_sector_flag)); + if (NULL == cur_flag) + { + return EFI_OUT_OF_RESOURCES; + } + + FreePool(g_sector_flag); + g_sector_flag = cur_flag; + g_sector_flag_num = secNum; + } + + for (curlba = Lba, cur_flag = g_sector_flag, j = 0; j < secNum; j++, curlba++, cur_flag++) + { + cur_flag->flag = 0; + for (node = g_virt_chunk, i = 0; i < g_virt_chunk_num; i++, node++) + { + if (curlba >= node->mem_sector_start && curlba < node->mem_sector_end) + { + CopyMem((UINT8 *)Buffer + j * 2048, + (char *)g_virt_chunk + node->mem_sector_offset + (curlba - node->mem_sector_start) * 2048, + 2048); + cur_flag->flag = 1; + break; + } + else if (curlba >= node->remap_sector_start && curlba < node->remap_sector_end) + { + cur_flag->remap_lba = node->org_sector_start + curlba - node->remap_sector_start; + cur_flag->flag = 2; + break; + } + } + } + + for (curlba = Lba, cur_flag = g_sector_flag, j = 0; j < secNum; j++, curlba++, cur_flag++) + { + if (cur_flag->flag == 2) + { + if (lastlba == 0) + { + lastbuffer = (UINT8 *)Buffer + j * 2048; + lastlba = cur_flag->remap_lba; + lbacount = 1; + } + else if (lastlba + lbacount == cur_flag->remap_lba) + { + lbacount++; + } + else + { + ventoy_read_iso_sector(lastlba, lbacount, lastbuffer); + lastbuffer = (UINT8 *)Buffer + j * 2048; + lastlba = cur_flag->remap_lba; + lbacount = 1; + } + } + } + + if (lbacount > 0) + { + ventoy_read_iso_sector(lastlba, lbacount, lastbuffer); + } + + return EFI_SUCCESS; +} + +EFI_STATUS EFIAPI ventoy_block_io_write +( + IN EFI_BLOCK_IO_PROTOCOL *This, + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN UINTN BufferSize, + IN VOID *Buffer +) +{ + (VOID)This; + (VOID)MediaId; + (VOID)Lba; + (VOID)BufferSize; + (VOID)Buffer; + return EFI_WRITE_PROTECTED; +} + +EFI_STATUS EFIAPI ventoy_block_io_flush(IN EFI_BLOCK_IO_PROTOCOL *This) +{ + (VOID)This; + return EFI_SUCCESS; +} + + +EFI_STATUS EFIAPI ventoy_fill_device_path(VOID) +{ + UINTN NameLen = 0; + UINT8 TmpBuf[128] = {0}; + VENDOR_DEVICE_PATH *venPath = NULL; + + venPath = (VENDOR_DEVICE_PATH *)TmpBuf; + NameLen = StrSize(VTOY_BLOCK_DEVICE_PATH_NAME); + venPath->Header.Type = HARDWARE_DEVICE_PATH; + venPath->Header.SubType = HW_VENDOR_DP; + venPath->Header.Length[0] = sizeof(VENDOR_DEVICE_PATH) + NameLen; + venPath->Header.Length[1] = 0; + CopyMem(&venPath->Guid, &gVtoyBlockDevicePathGuid, sizeof(EFI_GUID)); + CopyMem(venPath + 1, VTOY_BLOCK_DEVICE_PATH_NAME, NameLen); + + gBlockData.Path = AppendDevicePathNode(NULL, (EFI_DEVICE_PATH_PROTOCOL *)TmpBuf); + gBlockData.DevicePathCompareLen = sizeof(VENDOR_DEVICE_PATH) + NameLen; + + debug("gBlockData.Path=<%s>\n", ConvertDevicePathToText(gBlockData.Path, FALSE, FALSE)); + + return EFI_SUCCESS; +} + +EFI_STATUS EFIAPI ventoy_set_variable(VOID) +{ + EFI_STATUS Status = EFI_SUCCESS; + EFI_GUID VarGuid = VENTOY_GUID; + + Status = gRT->SetVariable(L"VentoyOsParam", &VarGuid, + EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS, + sizeof(g_chain->os_param), &(g_chain->os_param)); + debug("set efi variable %r", Status); + + return Status; +} + +EFI_STATUS EFIAPI ventoy_delete_variable(VOID) +{ + EFI_STATUS Status = EFI_SUCCESS; + EFI_GUID VarGuid = VENTOY_GUID; + + Status = gRT->SetVariable(L"VentoyOsParam", &VarGuid, + EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS, + 0, NULL); + debug("delete efi variable %r", Status); + + return Status; +} + + +EFI_STATUS EFIAPI ventoy_install_blockio(IN EFI_HANDLE ImageHandle) +{ + EFI_STATUS Status = EFI_SUCCESS; + EFI_BLOCK_IO_PROTOCOL *pBlockIo = &(gBlockData.BlockIo); + + ventoy_fill_device_path(); + + gBlockData.Media.BlockSize = 2048; + gBlockData.Media.LastBlock = g_chain->virt_img_size_in_bytes / 2048 - 1; + gBlockData.Media.ReadOnly = TRUE; + gBlockData.Media.MediaPresent = 1; + gBlockData.Media.LogicalBlocksPerPhysicalBlock = 1; + + pBlockIo->Revision = EFI_BLOCK_IO_PROTOCOL_REVISION3; + pBlockIo->Media = &(gBlockData.Media); + pBlockIo->Reset = ventoy_block_io_reset; + pBlockIo->ReadBlocks = ventoy_block_io_read; + pBlockIo->WriteBlocks = ventoy_block_io_write; + pBlockIo->FlushBlocks = ventoy_block_io_flush; + + Status = gBS->InstallMultipleProtocolInterfaces(&gBlockData.Handle, + &gEfiBlockIoProtocolGuid, &gBlockData.BlockIo, + &gEfiDevicePathProtocolGuid, gBlockData.Path, + NULL); + + debug("Install protocol %r", Status); + + if (EFI_ERROR(Status)) + { + return Status; + } + + Status = gBS->ConnectController(gBlockData.Handle, NULL, NULL, 1); + debug("Connect controller %r", Status); + + return EFI_SUCCESS; +} + + +EFI_STATUS EFIAPI ventoy_load_image +( + IN EFI_HANDLE ImageHandle, + IN EFI_DEVICE_PATH_PROTOCOL *pDevicePath, + IN CONST CHAR16 *FileName, + IN UINTN FileNameLen, + OUT EFI_HANDLE *Image +) +{ + EFI_STATUS Status = EFI_SUCCESS; + CHAR16 TmpBuf[256] = {0}; + FILEPATH_DEVICE_PATH *pFilePath = NULL; + EFI_DEVICE_PATH_PROTOCOL *pImgPath = NULL; + + pFilePath = (FILEPATH_DEVICE_PATH *)TmpBuf; + pFilePath->Header.Type = MEDIA_DEVICE_PATH; + pFilePath->Header.SubType = MEDIA_FILEPATH_DP; + pFilePath->Header.Length[0] = FileNameLen + sizeof(EFI_DEVICE_PATH_PROTOCOL); + pFilePath->Header.Length[1] = 0; + CopyMem(pFilePath->PathName, FileName, FileNameLen); + + pImgPath = AppendDevicePathNode(pDevicePath, (EFI_DEVICE_PATH_PROTOCOL *)pFilePath); + if (!pImgPath) + { + return EFI_NOT_FOUND; + } + + Status = gBS->LoadImage(FALSE, ImageHandle, pImgPath, NULL, 0, Image); + + debug("Load Image File %r DP: <%s>", Status, ConvertDevicePathToText(pImgPath, FALSE, FALSE)); + + FreePool(pImgPath); + + return Status; +} + + +STATIC EFI_STATUS EFIAPI ventoy_find_iso_disk(IN EFI_HANDLE ImageHandle) +{ + UINTN i = 0; + UINTN Count = 0; + UINT64 DiskSize = 0; + UINT8 *pBuffer = NULL; + EFI_HANDLE *Handles; + EFI_STATUS Status = EFI_SUCCESS; + EFI_BLOCK_IO_PROTOCOL *pBlockIo; + + pBuffer = AllocatePool(2048); + if (!pBuffer) + { + return EFI_OUT_OF_RESOURCES; + } + + Status = gBS->LocateHandleBuffer(ByProtocol, &gEfiBlockIoProtocolGuid, + NULL, &Count, &Handles); + if (EFI_ERROR(Status)) + { + FreePool(pBuffer); + return Status; + } + + for (i = 0; i < Count; i++) + { + Status = gBS->HandleProtocol(Handles[i], &gEfiBlockIoProtocolGuid, (VOID **)&pBlockIo); + if (EFI_ERROR(Status)) + { + continue; + } + + DiskSize = (pBlockIo->Media->LastBlock + 1) * pBlockIo->Media->BlockSize; + debug("This Disk size: %llu", DiskSize); + if (g_chain->os_param.vtoy_disk_size != DiskSize) + { + continue; + } + + Status = pBlockIo->ReadBlocks(pBlockIo, pBlockIo->Media->MediaId, 0, 512, pBuffer); + if (EFI_ERROR(Status)) + { + debug("ReadBlocks filed %r", Status); + continue; + } + + if (CompareMem(g_chain->os_param.vtoy_disk_guid, pBuffer + 0x180, 16) == 0) + { + gBlockData.RawBlockIoHandle = Handles[i]; + gBlockData.pRawBlockIo = pBlockIo; + gBS->OpenProtocol(Handles[i], &gEfiDevicePathProtocolGuid, + (VOID **)&(gBlockData.pDiskDevPath), + ImageHandle, + Handles[i], + EFI_OPEN_PROTOCOL_GET_PROTOCOL); + + debug("Find Ventoy Disk Handle:%p DP:%s", Handles[i], + ConvertDevicePathToText(gBlockData.pDiskDevPath, FALSE, FALSE)); + break; + } + } + + FreePool(Handles); + + if (i >= Count) + { + return EFI_NOT_FOUND; + } + else + { + return EFI_SUCCESS; + } +} + +STATIC EFI_STATUS EFIAPI ventoy_find_iso_disk_fs(IN EFI_HANDLE ImageHandle) +{ + UINTN i = 0; + UINTN Count = 0; + EFI_HANDLE Parent = NULL; + EFI_HANDLE *Handles = NULL; + EFI_STATUS Status = EFI_SUCCESS; + EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *pFile = NULL; + EFI_DEVICE_PATH_PROTOCOL *pDevPath = NULL; + + Status = gBS->LocateHandleBuffer(ByProtocol, &gEfiSimpleFileSystemProtocolGuid, + NULL, &Count, &Handles); + if (EFI_ERROR(Status)) + { + return Status; + } + + debug("ventoy_find_iso_disk_fs fs count:%u", Count); + + for (i = 0; i < Count; i++) + { + Status = gBS->HandleProtocol(Handles[i], &gEfiSimpleFileSystemProtocolGuid, (VOID **)&pFile); + if (EFI_ERROR(Status)) + { + continue; + } + + Status = gBS->OpenProtocol(Handles[i], &gEfiDevicePathProtocolGuid, + (VOID **)&pDevPath, + ImageHandle, + Handles[i], + EFI_OPEN_PROTOCOL_GET_PROTOCOL); + if (EFI_ERROR(Status)) + { + debug("Failed to open device path protocol %r", Status); + continue; + } + + debug("Handle:%p FS DP: <%s>", Handles[i], ConvertDevicePathToText(pDevPath, FALSE, FALSE)); + Parent = ventoy_get_parent_handle(pDevPath); + + if (Parent == gBlockData.RawBlockIoHandle) + { + debug("Find ventoy disk fs"); + gBlockData.DiskFsHandle = Handles[i]; + gBlockData.pDiskFs = pFile; + gBlockData.pDiskFsDevPath = pDevPath; + break; + } + } + + FreePool(Handles); + + return EFI_SUCCESS; +} + +STATIC EFI_STATUS EFIAPI ventoy_load_isoefi_driver(IN EFI_HANDLE ImageHandle) +{ + EFI_HANDLE Image = NULL; + EFI_STATUS Status = EFI_SUCCESS; + CHAR16 LogVar[4] = L"5"; + + Status = ventoy_load_image(ImageHandle, gBlockData.pDiskFsDevPath, + gIso9660EfiDriverPath, + sizeof(gIso9660EfiDriverPath), + &Image); + debug("load iso efi driver status:%r", Status); + + if (gDebugPrint) + { + gRT->SetVariable(L"FS_LOGGING", &gShellVariableGuid, + EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS, + sizeof(LogVar), LogVar); + } + + gRT->SetVariable(L"FS_NAME_NOCASE", &gShellVariableGuid, + EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS, + sizeof(LogVar), LogVar); + + gBlockData.IsoDriverImage = Image; + Status = gBS->StartImage(Image, NULL, NULL); + debug("Start iso efi driver status:%r", Status); + + return EFI_SUCCESS; +} + +static int ventoy_update_image_location(ventoy_os_param *param) +{ + EFI_STATUS Status = EFI_SUCCESS; + UINT8 chksum = 0; + unsigned int i; + unsigned int length; + UINTN address = 0; + void *buffer = NULL; + ventoy_image_location *location = NULL; + ventoy_image_disk_region *region = NULL; + ventoy_img_chunk *chunk = g_chunk; + + length = sizeof(ventoy_image_location) + (g_img_chunk_num - 1) * sizeof(ventoy_image_disk_region); + + Status = gBS->AllocatePool(EfiRuntimeServicesData, length + 4096 * 2, &buffer); + if (EFI_ERROR(Status) || NULL == buffer) + { + debug("Failed to allocate runtime pool %r\n", Status); + return 1; + } + + address = (UINTN)buffer; + + if (address % 4096) + { + address += 4096 - (address % 4096); + } + + param->chksum = 0; + param->vtoy_img_location_addr = address; + param->vtoy_img_location_len = length; + + /* update check sum */ + for (i = 0; i < sizeof(ventoy_os_param); i++) + { + chksum += *((UINT8 *)param + i); + } + param->chksum = (chksum == 0) ? 0 : (UINT8)(0x100 - chksum); + + location = (ventoy_image_location *)(unsigned long)(param->vtoy_img_location_addr); + if (NULL == location) + { + return 0; + } + + CopyMem(&location->guid, ¶m->guid, sizeof(ventoy_guid)); + location->image_sector_size = 2048; + location->disk_sector_size = g_chain->disk_sector_size; + location->region_count = g_img_chunk_num; + + region = location->regions; + + for (i = 0; i < g_img_chunk_num; i++) + { + region->image_sector_count = chunk->img_end_sector - chunk->img_start_sector + 1; + region->image_start_sector = chunk->img_start_sector; + region->disk_start_sector = chunk->disk_start_sector; + region++; + chunk++; + } + + return 0; +} + +STATIC EFI_STATUS EFIAPI ventoy_parse_cmdline(IN EFI_HANDLE ImageHandle) +{ + UINT32 i = 0; + UINT8 chksum = 0; + CHAR16 *pPos = NULL; + CHAR16 *pCmdLine = NULL; + EFI_STATUS Status = EFI_SUCCESS; + ventoy_grub_param *pGrubParam = NULL; + EFI_LOADED_IMAGE_PROTOCOL *pImageInfo = NULL; + + Status = gBS->HandleProtocol(ImageHandle, &gEfiLoadedImageProtocolGuid, (VOID **)&pImageInfo); + if (EFI_ERROR(Status)) + { + VtoyDebug("Failed to handle load image protocol %r", Status); + return Status; + } + + pCmdLine = (CHAR16 *)AllocatePool(pImageInfo->LoadOptionsSize + 4); + SetMem(pCmdLine, pImageInfo->LoadOptionsSize + 4, 0); + CopyMem(pCmdLine, pImageInfo->LoadOptions, pImageInfo->LoadOptionsSize); + + if (StrStr(pCmdLine, L"debug")) + { + gDebugPrint = TRUE; + } + + if (StrStr(pCmdLine, L"isoefi=on")) + { + gLoadIsoEfi = TRUE; + } + + debug("cmdline:<%s>", pCmdLine); + + pPos = StrStr(pCmdLine, L"env_param="); + if (!pPos) + { + return EFI_INVALID_PARAMETER; + } + + pGrubParam = (ventoy_grub_param *)StrHexToUintn(pPos + StrLen(L"env_param=")); + grub_env_get = pGrubParam->grub_env_get; + + + pPos = StrStr(pCmdLine, L"mem:"); + g_chain = (ventoy_chain_head *)StrHexToUintn(pPos + 4); + + g_chunk = (ventoy_img_chunk *)((char *)g_chain + g_chain->img_chunk_offset); + g_img_chunk_num = g_chain->img_chunk_num; + g_override_chunk = (ventoy_override_chunk *)((char *)g_chain + g_chain->override_chunk_offset); + g_override_chunk_num = g_chain->override_chunk_num; + g_virt_chunk = (ventoy_virt_chunk *)((char *)g_chain + g_chain->virt_chunk_offset); + g_virt_chunk_num = g_chain->virt_chunk_num; + + for (i = 0; i < sizeof(ventoy_os_param); i++) + { + chksum += *((UINT8 *)(&(g_chain->os_param)) + i); + } + + if (gDebugPrint) + { + debug("os param checksum: 0x%x %a", g_chain->os_param.chksum, chksum ? "FAILED" : "SUCCESS"); + } + + ventoy_update_image_location(&(g_chain->os_param)); + + if (gDebugPrint) + { + ventoy_dump_chain(g_chain); + } + + FreePool(pCmdLine); + return EFI_SUCCESS; +} + +EFI_STATUS EFIAPI ventoy_boot(IN EFI_HANDLE ImageHandle) +{ + UINTN i = 0; + UINTN j = 0; + UINTN Find = 0; + UINTN Count = 0; + EFI_HANDLE Image = NULL; + EFI_HANDLE *Handles = NULL; + EFI_STATUS Status = EFI_SUCCESS; + EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *pFile = NULL; + EFI_DEVICE_PATH_PROTOCOL *pDevPath = NULL; + + Status = gBS->LocateHandleBuffer(ByProtocol, &gEfiSimpleFileSystemProtocolGuid, + NULL, &Count, &Handles); + if (EFI_ERROR(Status)) + { + return Status; + } + + debug("ventoy_boot fs count:%u", Count); + + for (i = 0; i < Count; i++) + { + Status = gBS->HandleProtocol(Handles[i], &gEfiSimpleFileSystemProtocolGuid, (VOID **)&pFile); + if (EFI_ERROR(Status)) + { + continue; + } + + Status = gBS->OpenProtocol(Handles[i], &gEfiDevicePathProtocolGuid, + (VOID **)&pDevPath, + ImageHandle, + Handles[i], + EFI_OPEN_PROTOCOL_GET_PROTOCOL); + if (EFI_ERROR(Status)) + { + debug("Failed to open device path protocol %r", Status); + continue; + } + + debug("Handle:%p FS DP: <%s>", Handles[i], ConvertDevicePathToText(pDevPath, FALSE, FALSE)); + if (CompareMem(gBlockData.Path, pDevPath, gBlockData.DevicePathCompareLen)) + { + debug("Not ventoy disk file system"); + continue; + } + + for (j = 0; j < ARRAY_SIZE(gEfiBootFileName); j++) + { + Status = ventoy_load_image(ImageHandle, pDevPath, gEfiBootFileName[j], + StrSize(gEfiBootFileName[j]), &Image); + if (EFI_SUCCESS == Status) + { + break; + } + debug("Failed to load image %r <%s>", Status, gEfiBootFileName[j]); + } + + if (j >= ARRAY_SIZE(gEfiBootFileName)) + { + continue; + } + + Find++; + debug("Find boot file, now try to boot ....."); + ventoy_debug_pause(); + + if (gDebugPrint) + { + gST->ConIn->Reset(gST->ConIn, FALSE); + } + + Status = gBS->StartImage(Image, NULL, NULL); + if (EFI_ERROR(Status)) + { + debug("Failed to start image %r", Status); + gBS->UnloadImage(Image); + break; + } + } + + FreePool(Handles); + + if (Find == 0) + { + return EFI_NOT_FOUND; + } + + return EFI_SUCCESS; +} + +EFI_STATUS EFIAPI ventoy_clean_env(VOID) +{ + FreePool(g_sector_flag); + g_sector_flag_num = 0; + + if (gLoadIsoEfi && gBlockData.IsoDriverImage) + { + gBS->UnloadImage(gBlockData.IsoDriverImage); + } + + gBS->DisconnectController(gBlockData.Handle, NULL, NULL); + + gBS->UninstallMultipleProtocolInterfaces(gBlockData.Handle, + &gEfiBlockIoProtocolGuid, &gBlockData.BlockIo, + &gEfiDevicePathProtocolGuid, gBlockData.Path, + NULL); + + ventoy_delete_variable(); + + if (g_chain->os_param.vtoy_img_location_addr) + { + FreePool((VOID *)(UINTN)g_chain->os_param.vtoy_img_location_addr); + } + + return EFI_SUCCESS; +} + +EFI_STATUS EFIAPI VentoyEfiMain + +( + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable +) +{ + EFI_STATUS Status = EFI_SUCCESS; + + g_sector_flag_num = 512; /* initial value */ + + g_sector_flag = AllocatePool(g_sector_flag_num * sizeof(ventoy_sector_flag)); + if (NULL == g_sector_flag) + { + return EFI_OUT_OF_RESOURCES; + } + + gST->ConOut->ClearScreen(gST->ConOut); + ventoy_clear_input(); + + ventoy_parse_cmdline(ImageHandle); + ventoy_set_variable(); + ventoy_find_iso_disk(ImageHandle); + + if (gLoadIsoEfi) + { + ventoy_find_iso_disk_fs(ImageHandle); + ventoy_load_isoefi_driver(ImageHandle); + } + + ventoy_debug_pause(); + + ventoy_install_blockio(ImageHandle); + + ventoy_debug_pause(); + + Status = ventoy_boot(ImageHandle); + if (EFI_NOT_FOUND == Status) + { + gST->ConOut->OutputString(gST->ConOut, L"No bootfile found for UEFI!\r\n"); + gST->ConOut->OutputString(gST->ConOut, L"Maybe the image does not support " VENTOY_UEFI_DESC L"!\r\n"); + sleep(300); + } + + ventoy_clean_env(); + + ventoy_clear_input(); + gST->ConOut->ClearScreen(gST->ConOut); + + + + return EFI_SUCCESS; +} + + diff --git a/EDK2/edk2-edk2-stable201911/MdeModulePkg/Application/Ventoy/Ventoy.h b/EDK2/edk2-edk2-stable201911/MdeModulePkg/Application/Ventoy/Ventoy.h new file mode 100644 index 00000000..988421cb --- /dev/null +++ b/EDK2/edk2-edk2-stable201911/MdeModulePkg/Application/Ventoy/Ventoy.h @@ -0,0 +1,233 @@ +/****************************************************************************** + * Ventoy.h + * + * Copyright (c) 2020, longpanda + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, see . + * + */ + +#ifndef __VENTOY_H__ +#define __VENTOY_H__ + +#define COMPILE_ASSERT(expr) extern char __compile_assert[(expr) ? 1 : -1] + +#define VENTOY_GUID { 0x77772020, 0x2e77, 0x6576, { 0x6e, 0x74, 0x6f, 0x79, 0x2e, 0x6e, 0x65, 0x74 }} + +#pragma pack(1) + +typedef struct ventoy_guid +{ + UINT32 data1; + UINT16 data2; + UINT16 data3; + UINT8 data4[8]; +}ventoy_guid; + +typedef struct ventoy_image_disk_region +{ + UINT32 image_sector_count; /* image sectors contained in this region */ + UINT32 image_start_sector; /* image sector start */ + UINT64 disk_start_sector; /* disk sector start */ +}ventoy_image_disk_region; + +typedef struct ventoy_image_location +{ + ventoy_guid guid; + + /* image sector size, currently this value is always 2048 */ + UINT32 image_sector_size; + + /* disk sector size, normally the value is 512 */ + UINT32 disk_sector_size; + + UINT32 region_count; + + /* + * disk region data + * If the image file has more than one fragments in disk, + * there will be more than one region data here. + * + */ + ventoy_image_disk_region regions[1]; + + /* ventoy_image_disk_region regions[2~region_count-1] */ +}ventoy_image_location; + +typedef struct ventoy_os_param +{ + ventoy_guid guid; // VENTOY_GUID + UINT8 chksum; // checksum + + UINT8 vtoy_disk_guid[16]; + UINT64 vtoy_disk_size; // disk size in bytes + UINT16 vtoy_disk_part_id; // begin with 1 + UINT16 vtoy_disk_part_type; // 0:exfat 1:ntfs other: reserved + char vtoy_img_path[384]; // It seems to be enough, utf-8 format + UINT64 vtoy_img_size; // image file size in bytes + + /* + * Ventoy will write a copy of ventoy_image_location data into runtime memory + * this is the physically address and length of that memory. + * Address 0 means no such data exist. + * Address will be aligned by 4KB. + * + */ + UINT64 vtoy_img_location_addr; + UINT32 vtoy_img_location_len; + + UINT64 vtoy_reserved[4]; // Internal use by ventoy + + UINT8 reserved[31]; +}ventoy_os_param; + +#pragma pack() + +// compile assert to check that size of ventoy_os_param must be 512 +COMPILE_ASSERT(sizeof(ventoy_os_param) == 512); + + + +#pragma pack(4) + +typedef struct ventoy_chain_head +{ + ventoy_os_param os_param; + + UINT32 disk_drive; + UINT32 drive_map; + UINT32 disk_sector_size; + + UINT64 real_img_size_in_bytes; + UINT64 virt_img_size_in_bytes; + UINT32 boot_catalog; + UINT8 boot_catalog_sector[2048]; + + UINT32 img_chunk_offset; + UINT32 img_chunk_num; + + UINT32 override_chunk_offset; + UINT32 override_chunk_num; + + UINT32 virt_chunk_offset; + UINT32 virt_chunk_num; +}ventoy_chain_head; + + +typedef struct ventoy_img_chunk +{ + UINT32 img_start_sector; //2KB + UINT32 img_end_sector; + + UINT64 disk_start_sector; // in disk_sector_size + UINT64 disk_end_sector; +}ventoy_img_chunk; + + +typedef struct ventoy_override_chunk +{ + UINT64 img_offset; + UINT32 override_size; + UINT8 override_data[512]; +}ventoy_override_chunk; + +typedef struct ventoy_virt_chunk +{ + UINT32 mem_sector_start; + UINT32 mem_sector_end; + UINT32 mem_sector_offset; + UINT32 remap_sector_start; + UINT32 remap_sector_end; + UINT32 org_sector_start; +}ventoy_virt_chunk; + + +#pragma pack() + + +#define VTOY_BLOCK_DEVICE_PATH_GUID \ + { 0x37b87ac6, 0xc180, 0x4583, { 0xa7, 0x05, 0x41, 0x4d, 0xa8, 0xf7, 0x7e, 0xd2 }} + +#define VTOY_BLOCK_DEVICE_PATH_NAME L"ventoy" + +#if defined (MDE_CPU_IA32) + #define VENTOY_UEFI_DESC L"IA32 UEFI" +#elif defined (MDE_CPU_X64) + #define VENTOY_UEFI_DESC L"X64 UEFI" +#elif defined (MDE_CPU_EBC) +#elif defined (MDE_CPU_ARM) + #define VENTOY_UEFI_DESC L"ARM UEFI" +#elif defined (MDE_CPU_AARCH64) + #define VENTOY_UEFI_DESC L"ARM64 UEFI" +#else + #error Unknown Processor Type +#endif + +typedef struct ventoy_sector_flag +{ + UINT8 flag; // 0:init 1:mem 2:remap + UINT64 remap_lba; +}ventoy_sector_flag; + + +typedef struct vtoy_block_data +{ + EFI_HANDLE Handle; + EFI_BLOCK_IO_MEDIA Media; /* Media descriptor */ + EFI_BLOCK_IO_PROTOCOL BlockIo; /* Block I/O protocol */ + + UINTN DevicePathCompareLen; + EFI_DEVICE_PATH_PROTOCOL *Path; /* Device path protocol */ + + EFI_HANDLE RawBlockIoHandle; + EFI_BLOCK_IO_PROTOCOL *pRawBlockIo; + EFI_DEVICE_PATH_PROTOCOL *pDiskDevPath; + + /* ventoy disk part2 ESP */ + EFI_HANDLE DiskFsHandle; + EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *pDiskFs; + EFI_DEVICE_PATH_PROTOCOL *pDiskFsDevPath; + + EFI_HANDLE IsoDriverImage; +}vtoy_block_data; + +#define ISO9660_EFI_DRIVER_PATH L"\\ventoy\\iso9660_x64.efi" + +#define debug(expr, ...) if (gDebugPrint) VtoyDebug("[VTOY] "expr"\r\n", ##__VA_ARGS__) +#define sleep(sec) gBS->Stall(1000000 * (sec)) + +#define ventoy_debug_pause() \ +if (gDebugPrint) \ +{ \ + UINTN __Index = 0; \ + gST->ConOut->OutputString(gST->ConOut, L"[VTOY] ###### Press Enter to continue... ######\r\n");\ + gST->ConIn->Reset(gST->ConIn, FALSE); \ + gBS->WaitForEvent(1, &gST->ConIn->WaitForKey, &__Index);\ +} + +typedef const char * (*grub_env_get_pf)(const char *name); + +#pragma pack(1) +typedef struct ventoy_grub_param +{ + grub_env_get_pf grub_env_get; +}ventoy_grub_param; +#pragma pack() + + +extern BOOLEAN gDebugPrint; +VOID EFIAPI VtoyDebug(IN CONST CHAR8 *Format, ...); + +#endif + diff --git a/EDK2/edk2-edk2-stable201911/MdeModulePkg/Application/Ventoy/Ventoy.inf b/EDK2/edk2-edk2-stable201911/MdeModulePkg/Application/Ventoy/Ventoy.inf new file mode 100644 index 00000000..057577eb --- /dev/null +++ b/EDK2/edk2-edk2-stable201911/MdeModulePkg/Application/Ventoy/Ventoy.inf @@ -0,0 +1,49 @@ +#************************************************************************************ +# Copyright (c) 2020, longpanda +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see . +# +#************************************************************************************ + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = Ventoy + FILE_GUID = 1c3a0915-09dc-49c2-873d-0aaaa7733299 + MODULE_TYPE = UEFI_APPLICATION + VERSION_STRING = 1.0 + ENTRY_POINT = VentoyEfiMain + + +[Sources] + Ventoy.h + Ventoy.c + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + ShellPkg/ShellPkg.dec + +[LibraryClasses] + UefiApplicationEntryPoint + UefiLib + DebugLib + +[Guids] + gShellVariableGuid + +[Protocols] + gEfiLoadedImageProtocolGuid + gEfiBlockIoProtocolGuid + gEfiDevicePathProtocolGuid + gEfiSimpleFileSystemProtocolGuid diff --git a/EDK2/edk2-edk2-stable201911/MdeModulePkg/MdeModulePkg.dsc b/EDK2/edk2-edk2-stable201911/MdeModulePkg/MdeModulePkg.dsc new file mode 100644 index 00000000..2bdadd28 --- /dev/null +++ b/EDK2/edk2-edk2-stable201911/MdeModulePkg/MdeModulePkg.dsc @@ -0,0 +1,496 @@ +## @file +# EFI/PI Reference Module Package for All Architectures +# +# (C) Copyright 2014 Hewlett-Packard Development Company, L.P.
+# Copyright (c) 2007 - 2019, Intel Corporation. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + PLATFORM_NAME = MdeModule + PLATFORM_GUID = 587CE499-6CBE-43cd-94E2-186218569478 + PLATFORM_VERSION = 0.98 + DSC_SPECIFICATION = 0x00010005 + OUTPUT_DIRECTORY = Build/MdeModule + SUPPORTED_ARCHITECTURES = IA32|X64|EBC|ARM|AARCH64 + BUILD_TARGETS = DEBUG|RELEASE|NOOPT + SKUID_IDENTIFIER = DEFAULT + +[LibraryClasses] + # + # Entry point + # + PeiCoreEntryPoint|MdePkg/Library/PeiCoreEntryPoint/PeiCoreEntryPoint.inf + PeimEntryPoint|MdePkg/Library/PeimEntryPoint/PeimEntryPoint.inf + DxeCoreEntryPoint|MdePkg/Library/DxeCoreEntryPoint/DxeCoreEntryPoint.inf + UefiDriverEntryPoint|MdePkg/Library/UefiDriverEntryPoint/UefiDriverEntryPoint.inf + UefiApplicationEntryPoint|MdePkg/Library/UefiApplicationEntryPoint/UefiApplicationEntryPoint.inf + # + # Basic + # + BaseLib|MdePkg/Library/BaseLib/BaseLib.inf + BaseMemoryLib|MdePkg/Library/BaseMemoryLib/BaseMemoryLib.inf + SynchronizationLib|MdePkg/Library/BaseSynchronizationLib/BaseSynchronizationLib.inf + PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf + IoLib|MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsic.inf + PciLib|MdePkg/Library/BasePciLibCf8/BasePciLibCf8.inf + PciCf8Lib|MdePkg/Library/BasePciCf8Lib/BasePciCf8Lib.inf + PciSegmentLib|MdePkg/Library/BasePciSegmentLibPci/BasePciSegmentLibPci.inf + CacheMaintenanceLib|MdePkg/Library/BaseCacheMaintenanceLib/BaseCacheMaintenanceLib.inf + PeCoffLib|MdePkg/Library/BasePeCoffLib/BasePeCoffLib.inf + PeCoffGetEntryPointLib|MdePkg/Library/BasePeCoffGetEntryPointLib/BasePeCoffGetEntryPointLib.inf + SortLib|MdeModulePkg/Library/BaseSortLib/BaseSortLib.inf + # + # UEFI & PI + # + UefiBootServicesTableLib|MdePkg/Library/UefiBootServicesTableLib/UefiBootServicesTableLib.inf + UefiRuntimeServicesTableLib|MdePkg/Library/UefiRuntimeServicesTableLib/UefiRuntimeServicesTableLib.inf + UefiRuntimeLib|MdePkg/Library/UefiRuntimeLib/UefiRuntimeLib.inf + UefiLib|MdePkg/Library/UefiLib/UefiLib.inf + UefiHiiServicesLib|MdeModulePkg/Library/UefiHiiServicesLib/UefiHiiServicesLib.inf + HiiLib|MdeModulePkg/Library/UefiHiiLib/UefiHiiLib.inf + DevicePathLib|MdePkg/Library/UefiDevicePathLib/UefiDevicePathLib.inf + UefiDecompressLib|MdePkg/Library/BaseUefiDecompressLib/BaseUefiDecompressLib.inf + PeiServicesTablePointerLib|MdePkg/Library/PeiServicesTablePointerLib/PeiServicesTablePointerLib.inf + PeiServicesLib|MdePkg/Library/PeiServicesLib/PeiServicesLib.inf + DxeServicesLib|MdePkg/Library/DxeServicesLib/DxeServicesLib.inf + DxeServicesTableLib|MdePkg/Library/DxeServicesTableLib/DxeServicesTableLib.inf + UefiBootManagerLib|MdeModulePkg/Library/UefiBootManagerLib/UefiBootManagerLib.inf + # + # Generic Modules + # + UefiUsbLib|MdePkg/Library/UefiUsbLib/UefiUsbLib.inf + UefiScsiLib|MdePkg/Library/UefiScsiLib/UefiScsiLib.inf + SecurityManagementLib|MdeModulePkg/Library/DxeSecurityManagementLib/DxeSecurityManagementLib.inf + TimerLib|MdePkg/Library/BaseTimerLibNullTemplate/BaseTimerLibNullTemplate.inf + SerialPortLib|MdePkg/Library/BaseSerialPortLibNull/BaseSerialPortLibNull.inf + CapsuleLib|MdeModulePkg/Library/DxeCapsuleLibNull/DxeCapsuleLibNull.inf + PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf + CustomizedDisplayLib|MdeModulePkg/Library/CustomizedDisplayLib/CustomizedDisplayLib.inf + FrameBufferBltLib|MdeModulePkg/Library/FrameBufferBltLib/FrameBufferBltLib.inf + # + # Misc + # + DebugLib|MdePkg/Library/BaseDebugLibNull/BaseDebugLibNull.inf + DebugPrintErrorLevelLib|MdePkg/Library/BaseDebugPrintErrorLevelLib/BaseDebugPrintErrorLevelLib.inf + ReportStatusCodeLib|MdePkg/Library/BaseReportStatusCodeLibNull/BaseReportStatusCodeLibNull.inf + PeCoffExtraActionLib|MdePkg/Library/BasePeCoffExtraActionLibNull/BasePeCoffExtraActionLibNull.inf + PerformanceLib|MdePkg/Library/BasePerformanceLibNull/BasePerformanceLibNull.inf + DebugAgentLib|MdeModulePkg/Library/DebugAgentLibNull/DebugAgentLibNull.inf + PlatformHookLib|MdeModulePkg/Library/BasePlatformHookLibNull/BasePlatformHookLibNull.inf + ResetSystemLib|MdeModulePkg/Library/BaseResetSystemLibNull/BaseResetSystemLibNull.inf + SmbusLib|MdePkg/Library/DxeSmbusLib/DxeSmbusLib.inf + S3BootScriptLib|MdeModulePkg/Library/PiDxeS3BootScriptLib/DxeS3BootScriptLib.inf + CpuExceptionHandlerLib|MdeModulePkg/Library/CpuExceptionHandlerLibNull/CpuExceptionHandlerLibNull.inf + PlatformBootManagerLib|MdeModulePkg/Library/PlatformBootManagerLibNull/PlatformBootManagerLibNull.inf + PciHostBridgeLib|MdeModulePkg/Library/PciHostBridgeLibNull/PciHostBridgeLibNull.inf + TpmMeasurementLib|MdeModulePkg/Library/TpmMeasurementLibNull/TpmMeasurementLibNull.inf + AuthVariableLib|MdeModulePkg/Library/AuthVariableLibNull/AuthVariableLibNull.inf + VarCheckLib|MdeModulePkg/Library/VarCheckLib/VarCheckLib.inf + FileExplorerLib|MdeModulePkg/Library/FileExplorerLib/FileExplorerLib.inf + NonDiscoverableDeviceRegistrationLib|MdeModulePkg/Library/NonDiscoverableDeviceRegistrationLib/NonDiscoverableDeviceRegistrationLib.inf + + FmpAuthenticationLib|MdeModulePkg/Library/FmpAuthenticationLibNull/FmpAuthenticationLibNull.inf + CapsuleLib|MdeModulePkg/Library/DxeCapsuleLibNull/DxeCapsuleLibNull.inf + BmpSupportLib|MdeModulePkg/Library/BaseBmpSupportLib/BaseBmpSupportLib.inf + SafeIntLib|MdePkg/Library/BaseSafeIntLib/BaseSafeIntLib.inf + DisplayUpdateProgressLib|MdeModulePkg/Library/DisplayUpdateProgressLibGraphics/DisplayUpdateProgressLibGraphics.inf + +[LibraryClasses.EBC.PEIM] + IoLib|MdePkg/Library/PeiIoLibCpuIo/PeiIoLibCpuIo.inf + +[LibraryClasses.common.PEI_CORE] + HobLib|MdePkg/Library/PeiHobLib/PeiHobLib.inf + MemoryAllocationLib|MdePkg/Library/PeiMemoryAllocationLib/PeiMemoryAllocationLib.inf + +[LibraryClasses.common.PEIM] + HobLib|MdePkg/Library/PeiHobLib/PeiHobLib.inf + MemoryAllocationLib|MdePkg/Library/PeiMemoryAllocationLib/PeiMemoryAllocationLib.inf + ExtractGuidedSectionLib|MdePkg/Library/PeiExtractGuidedSectionLib/PeiExtractGuidedSectionLib.inf + LockBoxLib|MdeModulePkg/Library/SmmLockBoxLib/SmmLockBoxPeiLib.inf + +[LibraryClasses.common.DXE_CORE] + HobLib|MdePkg/Library/DxeCoreHobLib/DxeCoreHobLib.inf + MemoryAllocationLib|MdeModulePkg/Library/DxeCoreMemoryAllocationLib/DxeCoreMemoryAllocationLib.inf + ExtractGuidedSectionLib|MdePkg/Library/DxeExtractGuidedSectionLib/DxeExtractGuidedSectionLib.inf + +[LibraryClasses.common.DXE_DRIVER] + HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf + LockBoxLib|MdeModulePkg/Library/SmmLockBoxLib/SmmLockBoxDxeLib.inf + MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf + ExtractGuidedSectionLib|MdePkg/Library/DxeExtractGuidedSectionLib/DxeExtractGuidedSectionLib.inf + CapsuleLib|MdeModulePkg/Library/DxeCapsuleLibFmp/DxeCapsuleLib.inf + +[LibraryClasses.common.DXE_RUNTIME_DRIVER] + HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf + MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf + DebugLib|MdePkg/Library/UefiDebugLibConOut/UefiDebugLibConOut.inf + LockBoxLib|MdeModulePkg/Library/SmmLockBoxLib/SmmLockBoxDxeLib.inf + CapsuleLib|MdeModulePkg/Library/DxeCapsuleLibFmp/DxeRuntimeCapsuleLib.inf + +[LibraryClasses.common.SMM_CORE] + HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf + MemoryAllocationLib|MdeModulePkg/Library/PiSmmCoreMemoryAllocationLib/PiSmmCoreMemoryAllocationLib.inf + SmmServicesTableLib|MdeModulePkg/Library/PiSmmCoreSmmServicesTableLib/PiSmmCoreSmmServicesTableLib.inf + SmmCorePlatformHookLib|MdeModulePkg/Library/SmmCorePlatformHookLibNull/SmmCorePlatformHookLibNull.inf + SmmMemLib|MdePkg/Library/SmmMemLib/SmmMemLib.inf + +[LibraryClasses.common.DXE_SMM_DRIVER] + HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf + DebugLib|MdePkg/Library/BaseDebugLibNull/BaseDebugLibNull.inf + MemoryAllocationLib|MdePkg/Library/SmmMemoryAllocationLib/SmmMemoryAllocationLib.inf + MmServicesTableLib|MdePkg/Library/MmServicesTableLib/MmServicesTableLib.inf + SmmServicesTableLib|MdePkg/Library/SmmServicesTableLib/SmmServicesTableLib.inf + LockBoxLib|MdeModulePkg/Library/SmmLockBoxLib/SmmLockBoxSmmLib.inf + SmmMemLib|MdePkg/Library/SmmMemLib/SmmMemLib.inf + +[LibraryClasses.common.UEFI_DRIVER] + HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf + MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf + DebugLib|MdePkg/Library/UefiDebugLibConOut/UefiDebugLibConOut.inf + LockBoxLib|MdeModulePkg/Library/SmmLockBoxLib/SmmLockBoxDxeLib.inf + +[LibraryClasses.common.UEFI_APPLICATION] + HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf + MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf + DebugLib|MdePkg/Library/UefiDebugLibStdErr/UefiDebugLibStdErr.inf + FileHandleLib|MdePkg/Library/UefiFileHandleLib/UefiFileHandleLib.inf + +[LibraryClasses.common.MM_STANDALONE] + HobLib|MdeModulePkg/Library/BaseHobLibNull/BaseHobLibNull.inf + MemoryAllocationLib|MdeModulePkg/Library/BaseMemoryAllocationLibNull/BaseMemoryAllocationLibNull.inf + StandaloneMmDriverEntryPoint|MdePkg/Library/StandaloneMmDriverEntryPoint/StandaloneMmDriverEntryPoint.inf + MmServicesTableLib|MdePkg/Library/StandaloneMmServicesTableLib/StandaloneMmServicesTableLib.inf + +[LibraryClasses.ARM, LibraryClasses.AARCH64] + ArmLib|ArmPkg/Library/ArmLib/ArmBaseLib.inf + ArmMmuLib|ArmPkg/Library/ArmMmuLib/ArmMmuBaseLib.inf + LockBoxLib|MdeModulePkg/Library/LockBoxNullLib/LockBoxNullLib.inf + + # + # It is not possible to prevent ARM compiler calls to generic intrinsic functions. + # This library provides the instrinsic functions generated by a given compiler. + # [LibraryClasses.ARM] and NULL mean link this library into all ARM images. + # + NULL|ArmPkg/Library/CompilerIntrinsicsLib/CompilerIntrinsicsLib.inf + + # + # Since software stack checking may be heuristically enabled by the compiler + # include BaseStackCheckLib unconditionally. + # + NULL|MdePkg/Library/BaseStackCheckLib/BaseStackCheckLib.inf + +[LibraryClasses.EBC] + LockBoxLib|MdeModulePkg/Library/LockBoxNullLib/LockBoxNullLib.inf + +[PcdsFeatureFlag] + gEfiMdePkgTokenSpaceGuid.PcdDriverDiagnostics2Disable|TRUE + gEfiMdePkgTokenSpaceGuid.PcdComponentName2Disable|TRUE + gEfiMdeModulePkgTokenSpaceGuid.PcdInstallAcpiSdtProtocol|TRUE + gEfiMdeModulePkgTokenSpaceGuid.PcdDevicePathSupportDevicePathFromText|FALSE + gEfiMdeModulePkgTokenSpaceGuid.PcdDevicePathSupportDevicePathToText|FALSE + +[PcdsFixedAtBuild] + gEfiMdePkgTokenSpaceGuid.PcdDebugPropertyMask|0x0f + gEfiMdePkgTokenSpaceGuid.PcdReportStatusCodePropertyMask|0x06 + gEfiMdeModulePkgTokenSpaceGuid.PcdMaxSizeNonPopulateCapsule|0x0 + gEfiMdeModulePkgTokenSpaceGuid.PcdMaxSizePopulateCapsule|0x0 + gEfiMdeModulePkgTokenSpaceGuid.PcdMaxPeiPerformanceLogEntries|28 + +[PcdsDynamicExDefault] + gEfiMdeModulePkgTokenSpaceGuid.PcdRecoveryFileName|L"FVMAIN.FV" + +[Components] + MdeModulePkg/Application/Ventoy/Ventoy.inf + MdeModulePkg/Application/HelloWorld/HelloWorld.inf + MdeModulePkg/Application/DumpDynPcd/DumpDynPcd.inf + MdeModulePkg/Application/MemoryProfileInfo/MemoryProfileInfo.inf + + MdeModulePkg/Library/UefiSortLib/UefiSortLib.inf + MdeModulePkg/Logo/Logo.inf + MdeModulePkg/Logo/LogoDxe.inf + MdeModulePkg/Library/BaseSortLib/BaseSortLib.inf + MdeModulePkg/Library/BootMaintenanceManagerUiLib/BootMaintenanceManagerUiLib.inf + MdeModulePkg/Library/BootManagerUiLib/BootManagerUiLib.inf + MdeModulePkg/Library/CustomizedDisplayLib/CustomizedDisplayLib.inf + MdeModulePkg/Library/DebugAgentLibNull/DebugAgentLibNull.inf + MdeModulePkg/Library/DeviceManagerUiLib/DeviceManagerUiLib.inf + MdeModulePkg/Library/LockBoxNullLib/LockBoxNullLib.inf + MdeModulePkg/Library/PciHostBridgeLibNull/PciHostBridgeLibNull.inf + MdeModulePkg/Library/PiSmmCoreSmmServicesTableLib/PiSmmCoreSmmServicesTableLib.inf + MdeModulePkg/Library/UefiHiiServicesLib/UefiHiiServicesLib.inf + MdeModulePkg/Library/BaseHobLibNull/BaseHobLibNull.inf + MdeModulePkg/Library/BaseMemoryAllocationLibNull/BaseMemoryAllocationLibNull.inf + + MdeModulePkg/Bus/Pci/PciHostBridgeDxe/PciHostBridgeDxe.inf + MdeModulePkg/Bus/Pci/PciSioSerialDxe/PciSioSerialDxe.inf + MdeModulePkg/Bus/Pci/PciBusDxe/PciBusDxe.inf + MdeModulePkg/Bus/Pci/IncompatiblePciDeviceSupportDxe/IncompatiblePciDeviceSupportDxe.inf + MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressDxe.inf + MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPei.inf + MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHcDxe.inf + MdeModulePkg/Bus/Pci/SdMmcPciHcPei/SdMmcPciHcPei.inf + MdeModulePkg/Bus/Sd/EmmcBlockIoPei/EmmcBlockIoPei.inf + MdeModulePkg/Bus/Sd/SdBlockIoPei/SdBlockIoPei.inf + MdeModulePkg/Bus/Sd/EmmcDxe/EmmcDxe.inf + MdeModulePkg/Bus/Sd/SdDxe/SdDxe.inf + MdeModulePkg/Bus/Pci/UfsPciHcDxe/UfsPciHcDxe.inf + MdeModulePkg/Bus/Ufs/UfsPassThruDxe/UfsPassThruDxe.inf + MdeModulePkg/Bus/Pci/UfsPciHcPei/UfsPciHcPei.inf + MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsBlockIoPei.inf + MdeModulePkg/Bus/Pci/XhciDxe/XhciDxe.inf + MdeModulePkg/Bus/Pci/EhciDxe/EhciDxe.inf + MdeModulePkg/Bus/Pci/UhciDxe/UhciDxe.inf + MdeModulePkg/Bus/Pci/UhciPei/UhciPei.inf + MdeModulePkg/Bus/Pci/EhciPei/EhciPei.inf + MdeModulePkg/Bus/Pci/XhciPei/XhciPei.inf + MdeModulePkg/Bus/Pci/IdeBusPei/IdeBusPei.inf + MdeModulePkg/Bus/Usb/UsbBusPei/UsbBusPei.inf + MdeModulePkg/Bus/Usb/UsbBotPei/UsbBotPei.inf + MdeModulePkg/Bus/Pci/SataControllerDxe/SataControllerDxe.inf + MdeModulePkg/Bus/Ata/AtaBusDxe/AtaBusDxe.inf + MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AtaAtapiPassThru.inf + MdeModulePkg/Bus/Ata/AhciPei/AhciPei.inf + MdeModulePkg/Bus/Scsi/ScsiBusDxe/ScsiBusDxe.inf + MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDiskDxe.inf + MdeModulePkg/Bus/Usb/UsbBusDxe/UsbBusDxe.inf + MdeModulePkg/Bus/Usb/UsbKbDxe/UsbKbDxe.inf + MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassStorageDxe.inf + MdeModulePkg/Bus/Usb/UsbMouseAbsolutePointerDxe/UsbMouseAbsolutePointerDxe.inf + MdeModulePkg/Bus/Usb/UsbMouseDxe/UsbMouseDxe.inf + MdeModulePkg/Bus/I2c/I2cDxe/I2cBusDxe.inf + MdeModulePkg/Bus/I2c/I2cDxe/I2cHostDxe.inf + MdeModulePkg/Bus/I2c/I2cDxe/I2cDxe.inf + MdeModulePkg/Bus/Isa/IsaBusDxe/IsaBusDxe.inf + MdeModulePkg/Bus/Isa/Ps2KeyboardDxe/Ps2KeyboardDxe.inf + MdeModulePkg/Bus/Isa/Ps2MouseDxe/Ps2MouseDxe.inf + MdeModulePkg/Bus/Pci/NonDiscoverablePciDeviceDxe/NonDiscoverablePciDeviceDxe.inf + + MdeModulePkg/Core/DxeIplPeim/DxeIpl.inf + MdeModulePkg/Core/Pei/PeiMain.inf + MdeModulePkg/Core/RuntimeDxe/RuntimeDxe.inf + + MdeModulePkg/Library/DxeCapsuleLibNull/DxeCapsuleLibNull.inf + MdeModulePkg/Library/UefiMemoryAllocationProfileLib/UefiMemoryAllocationProfileLib.inf + MdeModulePkg/Library/DxeCoreMemoryAllocationLib/DxeCoreMemoryAllocationLib.inf + MdeModulePkg/Library/DxeCoreMemoryAllocationLib/DxeCoreMemoryAllocationProfileLib.inf + MdeModulePkg/Library/DxeCorePerformanceLib/DxeCorePerformanceLib.inf + MdeModulePkg/Library/DxeCrc32GuidedSectionExtractLib/DxeCrc32GuidedSectionExtractLib.inf + MdeModulePkg/Library/DxePerformanceLib/DxePerformanceLib.inf + MdeModulePkg/Library/DxeResetSystemLib/DxeResetSystemLib.inf + MdeModulePkg/Library/DxePrintLibPrint2Protocol/DxePrintLibPrint2Protocol.inf + MdeModulePkg/Library/PeiCrc32GuidedSectionExtractLib/PeiCrc32GuidedSectionExtractLib.inf + MdeModulePkg/Library/PeiPerformanceLib/PeiPerformanceLib.inf + MdeModulePkg/Library/PeiResetSystemLib/PeiResetSystemLib.inf + MdeModulePkg/Library/UefiHiiLib/UefiHiiLib.inf + MdeModulePkg/Library/ResetUtilityLib/ResetUtilityLib.inf + MdeModulePkg/Library/BaseResetSystemLibNull/BaseResetSystemLibNull.inf + MdeModulePkg/Library/DxeSecurityManagementLib/DxeSecurityManagementLib.inf + MdeModulePkg/Library/OemHookStatusCodeLibNull/OemHookStatusCodeLibNull.inf + MdeModulePkg/Library/PeiReportStatusCodeLib/PeiReportStatusCodeLib.inf + MdeModulePkg/Library/DxeReportStatusCodeLib/DxeReportStatusCodeLib.inf + MdeModulePkg/Library/RuntimeDxeReportStatusCodeLib/RuntimeDxeReportStatusCodeLib.inf + MdeModulePkg/Library/RuntimeResetSystemLib/RuntimeResetSystemLib.inf + MdeModulePkg/Library/BaseSerialPortLib16550/BaseSerialPortLib16550.inf + MdeModulePkg/Library/BasePlatformHookLibNull/BasePlatformHookLibNull.inf + MdeModulePkg/Library/DxeDebugPrintErrorLevelLib/DxeDebugPrintErrorLevelLib.inf + MdeModulePkg/Library/PiDxeS3BootScriptLib/DxeS3BootScriptLib.inf + MdeModulePkg/Library/PeiDebugPrintHobLib/PeiDebugPrintHobLib.inf + MdeModulePkg/Library/CpuExceptionHandlerLibNull/CpuExceptionHandlerLibNull.inf + MdeModulePkg/Library/PlatformHookLibSerialPortPpi/PlatformHookLibSerialPortPpi.inf + MdeModulePkg/Library/LzmaCustomDecompressLib/LzmaCustomDecompressLib.inf + MdeModulePkg/Library/PeiDxeDebugLibReportStatusCode/PeiDxeDebugLibReportStatusCode.inf + MdeModulePkg/Library/PeiDebugLibDebugPpi/PeiDebugLibDebugPpi.inf + MdeModulePkg/Library/UefiBootManagerLib/UefiBootManagerLib.inf + MdeModulePkg/Library/PlatformBootManagerLibNull/PlatformBootManagerLibNull.inf + MdeModulePkg/Library/BootLogoLib/BootLogoLib.inf + MdeModulePkg/Library/TpmMeasurementLibNull/TpmMeasurementLibNull.inf + MdeModulePkg/Library/AuthVariableLibNull/AuthVariableLibNull.inf + MdeModulePkg/Library/VarCheckLib/VarCheckLib.inf + MdeModulePkg/Library/VarCheckHiiLib/VarCheckHiiLib.inf + MdeModulePkg/Library/VarCheckPcdLib/VarCheckPcdLib.inf + MdeModulePkg/Library/PlatformVarCleanupLib/PlatformVarCleanupLib.inf + MdeModulePkg/Library/FileExplorerLib/FileExplorerLib.inf + MdeModulePkg/Library/DxeFileExplorerProtocol/DxeFileExplorerProtocol.inf + MdeModulePkg/Library/BaseIpmiLibNull/BaseIpmiLibNull.inf + MdeModulePkg/Library/DxeIpmiLibIpmiProtocol/DxeIpmiLibIpmiProtocol.inf + MdeModulePkg/Library/PeiIpmiLibIpmiPpi/PeiIpmiLibIpmiPpi.inf + MdeModulePkg/Library/SmmIpmiLibSmmIpmiProtocol/SmmIpmiLibSmmIpmiProtocol.inf + MdeModulePkg/Library/FrameBufferBltLib/FrameBufferBltLib.inf + MdeModulePkg/Library/NonDiscoverableDeviceRegistrationLib/NonDiscoverableDeviceRegistrationLib.inf + MdeModulePkg/Library/BaseBmpSupportLib/BaseBmpSupportLib.inf + MdeModulePkg/Library/DisplayUpdateProgressLibGraphics/DisplayUpdateProgressLibGraphics.inf + MdeModulePkg/Library/DisplayUpdateProgressLibText/DisplayUpdateProgressLibText.inf + + MdeModulePkg/Universal/BdsDxe/BdsDxe.inf + MdeModulePkg/Application/BootManagerMenuApp/BootManagerMenuApp.inf + MdeModulePkg/Application/UiApp/UiApp.inf{ + + NULL|MdeModulePkg/Library/DeviceManagerUiLib/DeviceManagerUiLib.inf + NULL|MdeModulePkg/Library/BootManagerUiLib/BootManagerUiLib.inf + NULL|MdeModulePkg/Library/BootMaintenanceManagerUiLib/BootMaintenanceManagerUiLib.inf + } + MdeModulePkg/Universal/DriverHealthManagerDxe/DriverHealthManagerDxe.inf + MdeModulePkg/Universal/BootManagerPolicyDxe/BootManagerPolicyDxe.inf + MdeModulePkg/Universal/CapsulePei/CapsulePei.inf + MdeModulePkg/Universal/CapsuleOnDiskLoadPei/CapsuleOnDiskLoadPei.inf + MdeModulePkg/Universal/CapsuleRuntimeDxe/CapsuleRuntimeDxe.inf + MdeModulePkg/Universal/Console/ConPlatformDxe/ConPlatformDxe.inf + MdeModulePkg/Universal/Console/ConSplitterDxe/ConSplitterDxe.inf + MdeModulePkg/Universal/Console/GraphicsConsoleDxe/GraphicsConsoleDxe.inf + MdeModulePkg/Universal/Console/GraphicsOutputDxe/GraphicsOutputDxe.inf + MdeModulePkg/Universal/Console/TerminalDxe/TerminalDxe.inf + MdeModulePkg/Universal/DebugPortDxe/DebugPortDxe.inf + MdeModulePkg/Universal/DevicePathDxe/DevicePathDxe.inf + MdeModulePkg/Universal/PrintDxe/PrintDxe.inf + MdeModulePkg/Universal/Disk/DiskIoDxe/DiskIoDxe.inf + MdeModulePkg/Universal/Disk/PartitionDxe/PartitionDxe.inf + MdeModulePkg/Universal/Disk/UdfDxe/UdfDxe.inf + MdeModulePkg/Universal/Disk/UnicodeCollation/EnglishDxe/EnglishDxe.inf + MdeModulePkg/Universal/Disk/CdExpressPei/CdExpressPei.inf + MdeModulePkg/Universal/DriverSampleDxe/DriverSampleDxe.inf + MdeModulePkg/Universal/HiiDatabaseDxe/HiiDatabaseDxe.inf + MdeModulePkg/Universal/MemoryTest/GenericMemoryTestDxe/GenericMemoryTestDxe.inf + MdeModulePkg/Universal/MemoryTest/NullMemoryTestDxe/NullMemoryTestDxe.inf + MdeModulePkg/Universal/Metronome/Metronome.inf + MdeModulePkg/Universal/MonotonicCounterRuntimeDxe/MonotonicCounterRuntimeDxe.inf + MdeModulePkg/Universal/ResetSystemPei/ResetSystemPei.inf { + + ResetSystemLib|MdeModulePkg/Library/BaseResetSystemLibNull/BaseResetSystemLibNull.inf + } + MdeModulePkg/Universal/ResetSystemRuntimeDxe/ResetSystemRuntimeDxe.inf { + + ResetSystemLib|MdeModulePkg/Library/BaseResetSystemLibNull/BaseResetSystemLibNull.inf + } + MdeModulePkg/Universal/SmbiosDxe/SmbiosDxe.inf + MdeModulePkg/Universal/SmbiosMeasurementDxe/SmbiosMeasurementDxe.inf + + MdeModulePkg/Universal/PcatSingleSegmentPciCfg2Pei/PcatSingleSegmentPciCfg2Pei.inf + MdeModulePkg/Universal/PCD/Dxe/Pcd.inf + MdeModulePkg/Universal/PCD/Pei/Pcd.inf + MdeModulePkg/Universal/PlatformDriOverrideDxe/PlatformDriOverrideDxe.inf + + MdeModulePkg/Universal/ReportStatusCodeRouter/Pei/ReportStatusCodeRouterPei.inf + MdeModulePkg/Universal/ReportStatusCodeRouter/RuntimeDxe/ReportStatusCodeRouterRuntimeDxe.inf + + MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.inf + MdeModulePkg/Universal/SetupBrowserDxe/SetupBrowserDxe.inf + MdeModulePkg/Universal/DisplayEngineDxe/DisplayEngineDxe.inf + MdeModulePkg/Application/VariableInfo/VariableInfo.inf + MdeModulePkg/Universal/FaultTolerantWritePei/FaultTolerantWritePei.inf + MdeModulePkg/Universal/Variable/Pei/VariablePei.inf + MdeModulePkg/Universal/WatchdogTimerDxe/WatchdogTimer.inf + MdeModulePkg/Universal/TimestampDxe/TimestampDxe.inf + MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteDxe.inf + + MdeModulePkg/Universal/Acpi/AcpiPlatformDxe/AcpiPlatformDxe.inf + MdeModulePkg/Universal/Acpi/AcpiTableDxe/AcpiTableDxe.inf + MdeModulePkg/Universal/HiiResourcesSampleDxe/HiiResourcesSampleDxe.inf + MdeModulePkg/Universal/LegacyRegion2Dxe/LegacyRegion2Dxe.inf + + MdeModulePkg/Universal/StatusCodeHandler/Pei/StatusCodeHandlerPei.inf + MdeModulePkg/Universal/StatusCodeHandler/RuntimeDxe/StatusCodeHandlerRuntimeDxe.inf + + MdeModulePkg/Universal/Acpi/FirmwarePerformanceDataTablePei/FirmwarePerformancePei.inf { + + LockBoxLib|MdeModulePkg/Library/LockBoxNullLib/LockBoxNullLib.inf + } + MdeModulePkg/Universal/Acpi/FirmwarePerformanceDataTableDxe/FirmwarePerformanceDxe.inf + MdeModulePkg/Universal/Acpi/BootGraphicsResourceTableDxe/BootGraphicsResourceTableDxe.inf + MdeModulePkg/Universal/SectionExtractionDxe/SectionExtractionDxe.inf { + + NULL|MdeModulePkg/Library/DxeCrc32GuidedSectionExtractLib/DxeCrc32GuidedSectionExtractLib.inf + } + MdeModulePkg/Universal/SectionExtractionPei/SectionExtractionPei.inf { + + NULL|MdeModulePkg/Library/PeiCrc32GuidedSectionExtractLib/PeiCrc32GuidedSectionExtractLib.inf + } + + MdeModulePkg/Universal/FvSimpleFileSystemDxe/FvSimpleFileSystemDxe.inf + MdeModulePkg/Universal/EsrtDxe/EsrtDxe.inf + MdeModulePkg/Universal/EsrtFmpDxe/EsrtFmpDxe.inf + + MdeModulePkg/Universal/FileExplorerDxe/FileExplorerDxe.inf { + + FileExplorerLib|MdeModulePkg/Library/FileExplorerLib/FileExplorerLib.inf + } + + MdeModulePkg/Universal/SerialDxe/SerialDxe.inf + MdeModulePkg/Universal/LoadFileOnFv2/LoadFileOnFv2.inf + + MdeModulePkg/Universal/DebugServicePei/DebugServicePei.inf + + MdeModulePkg/Application/CapsuleApp/CapsuleApp.inf + MdeModulePkg/Library/FmpAuthenticationLibNull/FmpAuthenticationLibNull.inf + MdeModulePkg/Library/DxeCapsuleLibFmp/DxeCapsuleLib.inf + MdeModulePkg/Library/DxeCapsuleLibFmp/DxeRuntimeCapsuleLib.inf + +[Components.IA32, Components.X64, Components.AARCH64] + MdeModulePkg/Universal/EbcDxe/EbcDxe.inf + MdeModulePkg/Universal/EbcDxe/EbcDebugger.inf + MdeModulePkg/Universal/EbcDxe/EbcDebuggerConfig.inf + +[Components.IA32, Components.X64, Components.ARM, Components.AARCH64] + MdeModulePkg/Library/BrotliCustomDecompressLib/BrotliCustomDecompressLib.inf + MdeModulePkg/Library/VarCheckUefiLib/VarCheckUefiLib.inf + MdeModulePkg/Core/Dxe/DxeMain.inf { + + NULL|MdeModulePkg/Library/DxeCrc32GuidedSectionExtractLib/DxeCrc32GuidedSectionExtractLib.inf + } + +!if $(TOOL_CHAIN_TAG) != "XCODE5" + MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteStandaloneMm.inf + MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.inf +!endif + +[Components.IA32, Components.X64] + MdeModulePkg/Universal/DebugSupportDxe/DebugSupportDxe.inf + MdeModulePkg/Application/SmiHandlerProfileInfo/SmiHandlerProfileInfo.inf + MdeModulePkg/Core/PiSmmCore/PiSmmIpl.inf + MdeModulePkg/Core/PiSmmCore/PiSmmCore.inf + MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf { + + NULL|MdeModulePkg/Library/VarCheckUefiLib/VarCheckUefiLib.inf + NULL|MdeModulePkg/Library/VarCheckHiiLib/VarCheckHiiLib.inf + NULL|MdeModulePkg/Library/VarCheckPcdLib/VarCheckPcdLib.inf + } + MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf { + + NULL|MdeModulePkg/Library/VarCheckUefiLib/VarCheckUefiLib.inf + NULL|MdeModulePkg/Library/VarCheckHiiLib/VarCheckHiiLib.inf + NULL|MdeModulePkg/Library/VarCheckPcdLib/VarCheckPcdLib.inf + } + MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.inf + MdeModulePkg/Library/SmmReportStatusCodeLib/SmmReportStatusCodeLib.inf + MdeModulePkg/Universal/StatusCodeHandler/Smm/StatusCodeHandlerSmm.inf + MdeModulePkg/Universal/ReportStatusCodeRouter/Smm/ReportStatusCodeRouterSmm.inf + MdeModulePkg/Universal/LockBox/SmmLockBox/SmmLockBox.inf + MdeModulePkg/Library/SmmMemoryAllocationProfileLib/SmmMemoryAllocationProfileLib.inf + MdeModulePkg/Library/PiSmmCoreMemoryAllocationLib/PiSmmCoreMemoryAllocationProfileLib.inf + MdeModulePkg/Library/PiSmmCoreMemoryAllocationLib/PiSmmCoreMemoryAllocationLib.inf + MdeModulePkg/Library/SmmCorePerformanceLib/SmmCorePerformanceLib.inf + MdeModulePkg/Library/SmmPerformanceLib/SmmPerformanceLib.inf + MdeModulePkg/Library/SmmLockBoxLib/SmmLockBoxPeiLib.inf + MdeModulePkg/Library/SmmLockBoxLib/SmmLockBoxDxeLib.inf + MdeModulePkg/Library/SmmLockBoxLib/SmmLockBoxSmmLib.inf + MdeModulePkg/Library/SmmCorePlatformHookLibNull/SmmCorePlatformHookLibNull.inf + MdeModulePkg/Library/SmmSmiHandlerProfileLib/SmmSmiHandlerProfileLib.inf + MdeModulePkg/Library/LzmaCustomDecompressLib/LzmaArchCustomDecompressLib.inf + MdeModulePkg/Universal/Acpi/BootScriptExecutorDxe/BootScriptExecutorDxe.inf + MdeModulePkg/Universal/Acpi/S3SaveStateDxe/S3SaveStateDxe.inf + MdeModulePkg/Universal/Acpi/SmmS3SaveState/SmmS3SaveState.inf + MdeModulePkg/Universal/Acpi/FirmwarePerformanceDataTableSmm/FirmwarePerformanceSmm.inf + MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteSmm.inf + MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteSmmDxe.inf + MdeModulePkg/Universal/RegularExpressionDxe/RegularExpressionDxe.inf + MdeModulePkg/Universal/SmmCommunicationBufferDxe/SmmCommunicationBufferDxe.inf + MdeModulePkg/Universal/Disk/RamDiskDxe/RamDiskDxe.inf + +[Components.X64] + MdeModulePkg/Universal/CapsulePei/CapsuleX64.inf + +[BuildOptions] + *_*_*_CC_FLAGS = -D DISABLE_NEW_DEPRECATED_INTERFACES + diff --git a/ExFAT/README.txt b/ExFAT/README.txt new file mode 100644 index 00000000..5a7d039b --- /dev/null +++ b/ExFAT/README.txt @@ -0,0 +1,8 @@ +Please download exfat-1.3.0.zip and mirrors-libfuse-fuse-2.9.9.zip first. + +exfat-1.3.0.zip: +https://codeload.github.com/relan/exfat/zip/v1.3.0 + +mirrors-libfuse-fuse-2.9.9.zip: +https://gitee.com/mirrors/libfuse/repository/archive/fuse-2.9.9.zip + diff --git a/ExFAT/buidexfat.sh b/ExFAT/buidexfat.sh new file mode 100644 index 00000000..97d6a156 --- /dev/null +++ b/ExFAT/buidexfat.sh @@ -0,0 +1,62 @@ +#!/bin/bash +# +# For 32bit, for example CentOS 6.10 i386 +# automake 1.11.1 must update to automake 1.11.2 +# pkg-config must be installed +# +# + +if uname -a | egrep -q 'x86_64|amd64'; then + opt= +else + opt=-lrt +fi + +CUR="$PWD" + +if ! [ -e LIBFUSE ]; then + ./buidlibfuse.sh +fi + + +rm -f EXFAT/shared/* +rm -f EXFAT/static/* + + +rm -rf exfat-1.3.0 +unzip exfat-1.3.0.zip + + +cd exfat-1.3.0 +autoreconf --install +./configure --prefix="$CUR" CFLAGS='-static -O2 -D_FILE_OFFSET_BITS=64' FUSE_CFLAGS="-I$CUR/LIBFUSE/include/" FUSE_LIBS="$CUR/LIBFUSE/lib/libfuse.a -pthread $opt -ldl" +make + +strip --strip-all fuse/mount.exfat-fuse +strip --strip-all mkfs/mkexfatfs + +cp fuse/mount.exfat-fuse ../EXFAT/static/mount.exfat-fuse +cp mkfs/mkexfatfs ../EXFAT/static/mkexfatfs + +cd .. +rm -rf exfat-1.3.0 + +unzip exfat-1.3.0.zip + +cd exfat-1.3.0 +autoreconf --install +./configure --prefix="$CUR" CFLAGS='-O2 -D_FILE_OFFSET_BITS=64' FUSE_CFLAGS="-I$CUR/LIBFUSE/include/" FUSE_LIBS="$CUR/LIBFUSE/lib/libfuse.a -lpthread -ldl $opt" +make + +strip --strip-all fuse/mount.exfat-fuse +strip --strip-all mkfs/mkexfatfs + +cp fuse/mount.exfat-fuse ../EXFAT/shared/mount.exfat-fuse +cp mkfs/mkexfatfs ../EXFAT/shared/mkexfatfs + +cd .. +rm -rf exfat-1.3.0 + + + + diff --git a/ExFAT/buidlibfuse.sh b/ExFAT/buidlibfuse.sh new file mode 100644 index 00000000..7e0ad013 --- /dev/null +++ b/ExFAT/buidlibfuse.sh @@ -0,0 +1,18 @@ +#!/bin/bash + +CUR="$PWD" + +rm -rf libfuse +rm -rf LIBFUSE + +unzip mirrors-libfuse-fuse-2.9.9.zip + + +cd libfuse +./makeconf.sh + +./configure --prefix="$CUR/LIBFUSE" +make -j 16 +make install +cd .. +rm -rf libfuse diff --git a/FUSEISO/build.sh b/FUSEISO/build.sh new file mode 100644 index 00000000..69f3b80e --- /dev/null +++ b/FUSEISO/build.sh @@ -0,0 +1,27 @@ +#!/bin/bash + +CUR="$PWD" + +#LIBFUSE_DIR=$CUR/LIBFUSE +LIBFUSE_DIR=../ExFAT/LIBFUSE + +if uname -a | egrep -q 'x86_64|amd64'; then + name=vtoy_fuse_iso_64 +else + name=vtoy_fuse_iso_32 + opt=-lrt +fi + +export C_INCLUDE_PATH=$LIBFUSE_DIR/include + +rm -f $name +gcc -O2 -D_FILE_OFFSET_BITS=64 vtoy_fuse_iso.c -o $name $LIBFUSE_DIR/lib/libfuse.a -lpthread -ldl $opt + +if [ -e $name ]; then + echo -e "\n############### SUCCESS $name ##################\n" +else + echo -e "\n############### FAILED $name ##################\n" +fi + +strip --strip-all $name + diff --git a/FUSEISO/build_libfuse.sh b/FUSEISO/build_libfuse.sh new file mode 100644 index 00000000..25ef02a6 --- /dev/null +++ b/FUSEISO/build_libfuse.sh @@ -0,0 +1,33 @@ +#!/bin/bash + +# +# +# Package Dependency: +# gcc automake autoconf gettext gettext-devel libtool unzip +# +# + + +CUR="$PWD" +LIBFUSE_DIR=$CUR/LIBFUSE + +rm -rf libfuse +rm -rf $LIBFUSE_DIR + +# please download https://gitee.com/mirrors/libfuse/repository/archive/fuse-2.9.9.zip +if ! [ -e mirrors-libfuse-fuse-2.9.9.zip ]; then + echo "Please download mirrors-libfuse-fuse-2.9.9.zip first" + exit 1 +fi + +unzip mirrors-libfuse-fuse-2.9.9.zip + + +cd libfuse +./makeconf.sh + +./configure --prefix="$LIBFUSE_DIR" +make -j 16 +make install +cd .. +rm -rf libfuse diff --git a/FUSEISO/vtoy_fuse_iso.c b/FUSEISO/vtoy_fuse_iso.c new file mode 100644 index 00000000..0350ea0c --- /dev/null +++ b/FUSEISO/vtoy_fuse_iso.c @@ -0,0 +1,346 @@ +/****************************************************************************** + * vtoy_fuse_iso.c + * + * Copyright (c) 2020, longpanda + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, see . + * + */ + +#define FUSE_USE_VERSION 26 + +#include +#include +#include +#include +#include +#include +#include + +typedef unsigned int uint32_t; + +typedef struct dmtable_entry +{ + uint32_t isoSector; + uint32_t sectorNum; + unsigned long long diskSector; +}dmtable_entry; + +#define MAX_ENTRY_NUM (1024 * 1024 / sizeof(dmtable_entry)) + +static int verbose = 0; +#define debug(fmt, ...) if(verbose) printf(fmt, ##__VA_ARGS__) + +static int g_disk_fd = -1; +static uint64_t g_iso_file_size; +static char g_mnt_point[512]; +static char g_iso_file_name[512]; +static dmtable_entry *g_disk_entry_list = NULL; +static int g_disk_entry_num = 0; + +static int ventoy_iso_getattr(const char *path, struct stat *statinfo) +{ + int ret = -ENOENT; + + if (path && statinfo) + { + memset(statinfo, 0, sizeof(struct stat)); + + if (path[0] == '/' && path[1] == 0) + { + statinfo->st_mode = S_IFDIR | 0755; + statinfo->st_nlink = 2; + ret = 0; + } + else if (strcmp(path, g_iso_file_name) == 0) + { + statinfo->st_mode = S_IFREG | 0444; + statinfo->st_nlink = 1; + statinfo->st_size = g_iso_file_size; + ret = 0; + } + } + + return ret; +} + +static int ventoy_iso_readdir +( + const char *path, + void *buf, + fuse_fill_dir_t filler, + off_t offset, + struct fuse_file_info *file +) +{ + (void)offset; + (void)file; + + if (path[0] != '/' || path[1] != 0) + { + return -ENOENT; + } + + filler(buf, ".", NULL, 0); + filler(buf, "..", NULL, 0); + filler(buf, g_iso_file_name + 1, NULL, 0); + + return 0; +} + +static int ventoy_iso_open(const char *path, struct fuse_file_info *file) +{ + if (strcmp(path, g_iso_file_name) != 0) + { + return -ENOENT; + } + + if ((file->flags & 3) != O_RDONLY) + { + return -EACCES; + } + + return 0; +} + +static int ventoy_read_iso_sector(uint32_t sector, uint32_t num, void *buf) +{ + uint32_t i = 0; + uint32_t leftSec = 0; + uint32_t readSec = 0; + dmtable_entry *entry = NULL; + + for (i = 0; i < g_disk_entry_num && num > 0; i++) + { + entry = g_disk_entry_list + i; + + if (sector >= entry->isoSector && sector < entry->isoSector + entry->sectorNum) + { + lseek(g_disk_fd, (entry->diskSector + (sector - entry->isoSector)) * 512, SEEK_SET); + + leftSec = entry->sectorNum - (sector - entry->isoSector); + readSec = (leftSec > num) ? num : leftSec; + + read(g_disk_fd, buf, readSec * 512); + + sector += readSec; + num -= readSec; + } + } + + return 0; +} + +static int ventoy_iso_read +( + const char *path, char *buf, + size_t size, off_t offset, + struct fuse_file_info *file +) +{ + uint32_t mod = 0; + uint32_t align = 0; + uint32_t sector = 0; + uint32_t number = 0; + size_t leftsize = 0; + char secbuf[512]; + + (void)file; + + if(strcmp(path, g_iso_file_name) != 0) + { + return -ENOENT; + } + + if (offset >= g_iso_file_size) + { + return 0; + } + + if (offset + size > g_iso_file_size) + { + size = g_iso_file_size - offset; + } + + leftsize = size; + sector = offset / 512; + + mod = offset % 512; + if (mod > 0) + { + align = 512 - mod; + ventoy_read_iso_sector(sector, 1, secbuf); + + if (leftsize > align) + { + memcpy(buf, secbuf + mod, align); + buf += align; + offset += align; + sector++; + leftsize -= align; + } + else + { + memcpy(buf, secbuf + mod, leftsize); + return size; + } + } + + number = leftsize / 512; + ventoy_read_iso_sector(sector, number, buf); + buf += number * 512; + + mod = leftsize % 512; + if (mod > 0) + { + ventoy_read_iso_sector(sector + number, 1, secbuf); + memcpy(buf, secbuf, mod); + } + + return size; +} + +static struct fuse_operations ventoy_op = +{ + .getattr = ventoy_iso_getattr, + .readdir = ventoy_iso_readdir, + .open = ventoy_iso_open, + .read = ventoy_iso_read, +}; + +static int ventoy_parse_dmtable(const char *filename) +{ + FILE *fp = NULL; + char diskname[128] = {0}; + char line[256] = {0}; + dmtable_entry *entry= g_disk_entry_list; + + fp = fopen(filename, "r"); + if (NULL == fp) + { + printf("Failed to open file %s\n", filename); + return 1; + } + + /* read untill the last line */ + while (fgets(line, sizeof(line), fp) && g_disk_entry_num < MAX_ENTRY_NUM) + { + sscanf(line, "%u %u linear %s %llu", + &entry->isoSector, &entry->sectorNum, + diskname, &entry->diskSector); + + g_iso_file_size += (uint64_t)entry->sectorNum * 512ULL; + g_disk_entry_num++; + entry++; + } + fclose(fp); + + if (g_disk_entry_num >= MAX_ENTRY_NUM) + { + fprintf(stderr, "ISO file has too many fragments ( more than %u )\n", MAX_ENTRY_NUM); + return 1; + } + + debug("iso file size: %llu disk name %s\n", g_iso_file_size, diskname); + + g_disk_fd = open(diskname, O_RDONLY); + if (g_disk_fd < 0) + { + debug("Failed to open %s\n", diskname); + return 1; + } + + return 0; +} + +int main(int argc, char **argv) +{ + int rc; + int ch; + char filename[512] = {0}; + + /* Avoid to be killed by systemd */ + if (access("/etc/initrd-release", F_OK) >= 0) + { + argv[0][0] = '@'; + } + + g_iso_file_name[0] = '/'; + + while ((ch = getopt(argc, argv, "f:s:m:v::t::")) != -1) + { + if (ch == 'f') + { + strncpy(filename, optarg, sizeof(filename) - 1); + } + else if (ch == 'm') + { + strncpy(g_mnt_point, optarg, sizeof(g_mnt_point) - 1); + } + else if (ch == 's') + { + strncpy(g_iso_file_name + 1, optarg, sizeof(g_iso_file_name) - 2); + } + else if (ch == 'v') + { + verbose = 1; + } + else if (ch == 't') // for test + { + return 0; + } + } + + if (filename[0] == 0) + { + fprintf(stderr, "Must input dmsetup table file with -f\n"); + return 1; + } + + if (g_mnt_point[0] == 0) + { + fprintf(stderr, "Must input mount point with -m\n"); + return 1; + } + + if (g_iso_file_name[1] == 0) + { + strncpy(g_iso_file_name + 1, "ventoy.iso", sizeof(g_iso_file_name) - 2); + } + + debug("ventoy fuse iso: %s %s %s\n", filename, g_iso_file_name, g_mnt_point); + + g_disk_entry_list = malloc(MAX_ENTRY_NUM * sizeof(dmtable_entry)); + if (NULL == g_disk_entry_list) + { + return 1; + } + + rc = ventoy_parse_dmtable(filename); + if (rc) + { + free(g_disk_entry_list); + return rc; + } + + argv[1] = g_mnt_point; + argv[2] = NULL; + rc = fuse_main(2, argv, &ventoy_op, NULL); + + close(g_disk_fd); + + free(g_disk_entry_list); + return rc; +} + diff --git a/LICENSE b/GPLv3 similarity index 100% rename from LICENSE rename to GPLv3 diff --git a/GRUB2/README.txt b/GRUB2/README.txt new file mode 100644 index 00000000..57f0008d --- /dev/null +++ b/GRUB2/README.txt @@ -0,0 +1,14 @@ + +========== About Source Code ============= +Ventoy use grub-2.04, so I only put the added and modified source code here. + +You can download grub-2.04 source code from this site: +https://ftp.gnu.org/gnu/grub/ + +Just merge the code here with the original code of grub-2.04 + + +========== Build ============= +./autogen.sh +./configure +make diff --git a/GRUB2/grub-2.04/grub-core/Makefile.core.def b/GRUB2/grub-2.04/grub-core/Makefile.core.def new file mode 100644 index 00000000..d0455f9f --- /dev/null +++ b/GRUB2/grub-2.04/grub-core/Makefile.core.def @@ -0,0 +1,2517 @@ +AutoGen definitions Makefile.tpl; + +transform_data = { + installdir = noinst; + name = gensyminfo.sh; + common = gensyminfo.sh.in; +}; + +transform_data = { + installdir = noinst; + name = genmod.sh; + common = genmod.sh.in; +}; + +transform_data = { + installdir = noinst; + name = modinfo.sh; + common = modinfo.sh.in; +}; + +transform_data = { + installdir = platform; + name = gmodule.pl; + common = gmodule.pl.in; +}; + +transform_data = { + installdir = platform; + name = gdb_grub; + common = gdb_grub.in; +}; + +transform_data = { + installdir = platform; + name = grub.chrp; + common = boot/powerpc/grub.chrp.in; + enable = powerpc_ieee1275; +}; + +transform_data = { + installdir = platform; + name = bootinfo.txt; + common = boot/powerpc/bootinfo.txt.in; + enable = powerpc_ieee1275; +}; + +kernel = { + name = kernel; + + nostrip = emu; + + emu_ldflags = '-Wl,-r,-d'; + i386_efi_ldflags = '-Wl,-r,-d'; + i386_efi_stripflags = '--strip-unneeded -K start -R .note -R .comment -R .note.gnu.gold-version'; + x86_64_efi_ldflags = '-Wl,-r,-d'; + x86_64_efi_stripflags = '--strip-unneeded -K start -R .note -R .comment -R .note.gnu.gold-version'; + + ia64_efi_cflags = '-fno-builtin -fpic -minline-int-divide-max-throughput'; + ia64_efi_ldflags = '-Wl,-r,-d'; + ia64_efi_stripflags = '--strip-unneeded -K start -R .note -R .comment -R .note.gnu.gold-version'; + + arm_efi_ldflags = '-Wl,-r,-d'; + arm_efi_stripflags = '--strip-unneeded -K start -R .note -R .comment -R .note.gnu.gold-version'; + + arm64_efi_ldflags = '-Wl,-r,-d'; + arm64_efi_stripflags = '--strip-unneeded -K start -R .note -R .comment -R .note.gnu.gold-version -R .eh_frame'; + + riscv32_efi_ldflags = '-Wl,-r,-d'; + riscv32_efi_stripflags = '--strip-unneeded -K start -R .note -R .comment -R .note.gnu.gold-version -R .eh_frame'; + + riscv64_efi_ldflags = '-Wl,-r,-d'; + riscv64_efi_stripflags = '--strip-unneeded -K start -R .note -R .comment -R .note.gnu.gold-version -R .eh_frame'; + + i386_pc_ldflags = '$(TARGET_IMG_LDFLAGS)'; + i386_pc_ldflags = '$(TARGET_IMG_BASE_LDOPT),0x9000'; + i386_qemu_ldflags = '$(TARGET_IMG_LDFLAGS)'; + i386_qemu_ldflags = '$(TARGET_IMG_BASE_LDOPT),0x9000'; + i386_coreboot_ldflags = '$(TARGET_IMG_LDFLAGS)'; + i386_coreboot_ldflags = '$(TARGET_IMG_BASE_LDOPT),0x9000'; + i386_multiboot_ldflags = '$(TARGET_IMG_LDFLAGS)'; + i386_multiboot_ldflags = '$(TARGET_IMG_BASE_LDOPT),0x9000'; + i386_ieee1275_ldflags = '$(TARGET_IMG_LDFLAGS)'; + i386_ieee1275_ldflags = '$(TARGET_IMG_BASE_LDOPT),0x10000'; + i386_xen_ldflags = '$(TARGET_IMG_LDFLAGS)'; + i386_xen_ldflags = '$(TARGET_IMG_BASE_LDOPT),0'; + x86_64_xen_ldflags = '$(TARGET_IMG_LDFLAGS)'; + x86_64_xen_ldflags = '$(TARGET_IMG_BASE_LDOPT),0'; + i386_xen_pvh_ldflags = '$(TARGET_IMG_LDFLAGS)'; + i386_xen_pvh_ldflags = '$(TARGET_IMG_BASE_LDOPT),0x100000'; + + mips_loongson_ldflags = '-Wl,-Ttext,0x80200000'; + powerpc_ieee1275_ldflags = '-Wl,-Ttext,0x200000'; + sparc64_ieee1275_ldflags = '-Wl,-Ttext,0x4400'; + mips_arc_ldflags = '-Wl,-Ttext,$(TARGET_LINK_ADDR)'; + mips_qemu_mips_ldflags = '-Wl,-Ttext,0x80200000'; + + mips_arc_cppflags = '-DGRUB_DECOMPRESSOR_LINK_ADDR=$(TARGET_DECOMPRESSOR_LINK_ADDR)'; + i386_qemu_cppflags = '-DGRUB_BOOT_MACHINE_LINK_ADDR=$(GRUB_BOOT_MACHINE_LINK_ADDR)'; + emu_cflags = '$(CFLAGS_GNULIB)'; + emu_cppflags = '$(CPPFLAGS_GNULIB)'; + arm_uboot_ldflags = '-Wl,-r,-d'; + arm_uboot_stripflags = '--strip-unneeded -K start -R .note -R .comment -R .note.gnu.gold-version'; + arm_coreboot_ldflags = '-Wl,-r,-d'; + arm_coreboot_stripflags = '--strip-unneeded -K start -R .note -R .comment -R .note.gnu.gold-version'; + + i386_pc_startup = kern/i386/pc/startup.S; + i386_efi_startup = kern/i386/efi/startup.S; + x86_64_efi_startup = kern/x86_64/efi/startup.S; + i386_xen_startup = kern/i386/xen/startup.S; + x86_64_xen_startup = kern/x86_64/xen/startup.S; + i386_xen_pvh_startup = kern/i386/xen/startup_pvh.S; + i386_qemu_startup = kern/i386/qemu/startup.S; + i386_ieee1275_startup = kern/i386/ieee1275/startup.S; + i386_coreboot_startup = kern/i386/coreboot/startup.S; + i386_multiboot_startup = kern/i386/coreboot/startup.S; + mips_startup = kern/mips/startup.S; + sparc64_ieee1275_startup = kern/sparc64/ieee1275/crt0.S; + powerpc_ieee1275_startup = kern/powerpc/ieee1275/startup.S; + arm_uboot_startup = kern/arm/startup.S; + arm_coreboot_startup = kern/arm/startup.S; + arm_efi_startup = kern/arm/efi/startup.S; + arm64_efi_startup = kern/arm64/efi/startup.S; + riscv32_efi_startup = kern/riscv/efi/startup.S; + riscv64_efi_startup = kern/riscv/efi/startup.S; + + common = kern/command.c; + common = kern/corecmd.c; + common = kern/device.c; + common = kern/disk.c; + common = kern/dl.c; + common = kern/env.c; + common = kern/err.c; + common = kern/file.c; + common = kern/fs.c; + common = kern/list.c; + common = kern/main.c; + common = kern/misc.c; + common = kern/parser.c; + common = kern/partition.c; + common = kern/rescue_parser.c; + common = kern/rescue_reader.c; + common = kern/term.c; + + noemu = kern/compiler-rt.c; + noemu = kern/mm.c; + noemu = kern/time.c; + noemu = kern/generic/millisleep.c; + + noemu_nodist = symlist.c; + + mips = kern/generic/rtc_get_time_ms.c; + + ieee1275 = disk/ieee1275/ofdisk.c; + ieee1275 = kern/ieee1275/cmain.c; + ieee1275 = kern/ieee1275/ieee1275.c; + ieee1275 = kern/ieee1275/mmap.c; + ieee1275 = kern/ieee1275/openfw.c; + ieee1275 = term/ieee1275/console.c; + ieee1275 = kern/ieee1275/init.c; + + uboot = disk/uboot/ubootdisk.c; + uboot = kern/uboot/uboot.c; + uboot = kern/uboot/init.c; + uboot = kern/uboot/hw.c; + uboot = term/uboot/console.c; + arm_uboot = kern/arm/uboot/init.c; + arm_uboot = kern/arm/uboot/uboot.S; + + arm_coreboot = kern/arm/coreboot/init.c; + arm_coreboot = kern/arm/coreboot/timer.c; + arm_coreboot = kern/arm/coreboot/coreboot.S; + arm_coreboot = lib/fdt.c; + arm_coreboot = bus/fdt.c; + arm_coreboot = term/ps2.c; + arm_coreboot = term/arm/pl050.c; + arm_coreboot = term/arm/cros.c; + arm_coreboot = term/arm/cros_ec.c; + arm_coreboot = bus/spi/rk3288_spi.c; + arm_coreboot = commands/keylayouts.c; + arm_coreboot = kern/arm/coreboot/dma.c; + + terminfoinkernel = term/terminfo.c; + terminfoinkernel = term/tparm.c; + terminfoinkernel = commands/extcmd.c; + terminfoinkernel = lib/arg.c; + + softdiv = lib/division.c; + + i386 = kern/i386/dl.c; + i386_xen = kern/i386/dl.c; + i386_xen_pvh = kern/i386/dl.c; + + i386_coreboot = kern/i386/coreboot/init.c; + i386_multiboot = kern/i386/coreboot/init.c; + i386_qemu = kern/i386/qemu/init.c; + i386_coreboot_multiboot_qemu = term/i386/pc/vga_text.c; + coreboot = video/coreboot/cbfb.c; + + efi = disk/efi/efidisk.c; + efi = kern/efi/efi.c; + efi = kern/efi/init.c; + efi = kern/efi/mm.c; + efi = term/efi/console.c; + efi = kern/acpi.c; + efi = kern/efi/acpi.c; + i386_coreboot = kern/i386/pc/acpi.c; + i386_multiboot = kern/i386/pc/acpi.c; + i386_coreboot = kern/acpi.c; + i386_multiboot = kern/acpi.c; + + x86 = kern/i386/tsc.c; + x86 = kern/i386/tsc_pit.c; + i386_efi = kern/i386/efi/tsc.c; + x86_64_efi = kern/i386/efi/tsc.c; + i386_efi = kern/i386/tsc_pmtimer.c; + i386_coreboot = kern/i386/tsc_pmtimer.c; + x86_64_efi = kern/i386/tsc_pmtimer.c; + + i386_efi = kern/i386/efi/init.c; + i386_efi = bus/pci.c; + + x86_64 = kern/x86_64/dl.c; + x86_64_xen = kern/x86_64/dl.c; + x86_64_efi = kern/x86_64/efi/callwrap.S; + x86_64_efi = kern/i386/efi/init.c; + x86_64_efi = bus/pci.c; + + xen = kern/i386/tsc.c; + xen = kern/i386/xen/tsc.c; + x86_64_xen = kern/x86_64/xen/hypercall.S; + i386_xen = kern/i386/xen/hypercall.S; + xen = kern/xen/init.c; + xen = term/xen/console.c; + xen = disk/xen/xendisk.c; + xen = commands/boot.c; + + i386_xen_pvh = commands/boot.c; + i386_xen_pvh = disk/xen/xendisk.c; + i386_xen_pvh = kern/i386/tsc.c; + i386_xen_pvh = kern/i386/xen/tsc.c; + i386_xen_pvh = kern/i386/xen/pvh.c; + i386_xen_pvh = kern/xen/init.c; + i386_xen_pvh = term/xen/console.c; + + ia64_efi = kern/ia64/efi/startup.S; + ia64_efi = kern/ia64/efi/init.c; + ia64_efi = kern/ia64/dl.c; + ia64_efi = kern/ia64/dl_helper.c; + ia64_efi = kern/ia64/cache.c; + + arm_efi = kern/arm/efi/init.c; + arm_efi = kern/efi/fdt.c; + + arm64_efi = kern/arm64/efi/init.c; + arm64_efi = kern/efi/fdt.c; + + riscv32_efi = kern/riscv/efi/init.c; + riscv32_efi = kern/efi/fdt.c; + + riscv64_efi = kern/riscv/efi/init.c; + riscv64_efi = kern/efi/fdt.c; + + i386_pc = kern/i386/pc/init.c; + i386_pc = kern/i386/pc/mmap.c; + i386_pc = term/i386/pc/console.c; + + i386_qemu = bus/pci.c; + i386_qemu = kern/vga_init.c; + i386_qemu = kern/i386/qemu/mmap.c; + + coreboot = kern/coreboot/mmap.c; + i386_coreboot = kern/i386/coreboot/cbtable.c; + coreboot = kern/coreboot/cbtable.c; + arm_coreboot = kern/arm/coreboot/cbtable.c; + + i386_multiboot = kern/i386/multiboot_mmap.c; + + mips = kern/mips/cache.S; + mips = kern/mips/dl.c; + mips = kern/mips/init.c; + + mips_qemu_mips = kern/mips/qemu_mips/init.c; + mips_qemu_mips = term/ns8250.c; + mips_qemu_mips = term/serial.c; + mips_qemu_mips = term/at_keyboard.c; + mips_qemu_mips = term/ps2.c; + mips_qemu_mips = commands/boot.c; + mips_qemu_mips = commands/keylayouts.c; + mips_qemu_mips = term/i386/pc/vga_text.c; + mips_qemu_mips = kern/vga_init.c; + + mips_arc = kern/mips/arc/init.c; + mips_arc = term/arc/console.c; + mips_arc = disk/arc/arcdisk.c; + + mips_loongson = term/ns8250.c; + mips_loongson = bus/bonito.c; + mips_loongson = bus/cs5536.c; + mips_loongson = bus/pci.c; + mips_loongson = kern/mips/loongson/init.c; + mips_loongson = term/at_keyboard.c; + mips_loongson = term/ps2.c; + mips_loongson = commands/boot.c; + mips_loongson = term/serial.c; + mips_loongson = video/sm712.c; + mips_loongson = video/sis315pro.c; + mips_loongson = video/radeon_fuloong2e.c; + mips_loongson = video/radeon_yeeloong3a.c; + extra_dist = video/sm712_init.c; + extra_dist = video/sis315_init.c; + mips_loongson = commands/keylayouts.c; + + powerpc_ieee1275 = kern/powerpc/cache.S; + powerpc_ieee1275 = kern/powerpc/dl.c; + powerpc_ieee1275 = kern/powerpc/compiler-rt.S; + + sparc64_ieee1275 = kern/sparc64/cache.S; + sparc64_ieee1275 = kern/sparc64/dl.c; + sparc64_ieee1275 = kern/sparc64/ieee1275/ieee1275.c; + sparc64_ieee1275 = disk/ieee1275/obdisk.c; + + arm = kern/arm/dl.c; + arm = kern/arm/dl_helper.c; + arm = kern/arm/cache_armv6.S; + arm = kern/arm/cache_armv7.S; + extra_dist = kern/arm/cache.S; + arm = kern/arm/cache.c; + arm = kern/arm/compiler-rt.S; + + arm64 = kern/arm64/cache.c; + arm64 = kern/arm64/cache_flush.S; + arm64 = kern/arm64/dl.c; + arm64 = kern/arm64/dl_helper.c; + + riscv32 = kern/riscv/cache.c; + riscv32 = kern/riscv/cache_flush.S; + riscv32 = kern/riscv/dl.c; + + riscv64 = kern/riscv/cache.c; + riscv64 = kern/riscv/cache_flush.S; + riscv64 = kern/riscv/dl.c; + + emu = disk/host.c; + emu = kern/emu/cache_s.S; + emu = kern/emu/hostdisk.c; + emu = osdep/unix/hostdisk.c; + emu = osdep/exec.c; + extra_dist = osdep/unix/exec.c; + emu = osdep/devmapper/hostdisk.c; + emu = osdep/hostdisk.c; + emu = kern/emu/hostfs.c; + emu = kern/emu/main.c; + emu = kern/emu/argp_common.c; + emu = kern/emu/misc.c; + emu = kern/emu/mm.c; + emu = kern/emu/time.c; + emu = kern/emu/cache.c; + emu = osdep/emuconsole.c; + extra_dist = osdep/unix/emuconsole.c; + extra_dist = osdep/windows/emuconsole.c; + emu = osdep/dl.c; + extra_dist = osdep/unix/dl.c; + extra_dist = osdep/windows/dl.c; + emu = osdep/sleep.c; + emu = osdep/init.c; + emu = osdep/emunet.c; + extra_dist = osdep/linux/emunet.c; + extra_dist = osdep/basic/emunet.c; + emu = osdep/cputime.c; + extra_dist = osdep/unix/cputime.c; + extra_dist = osdep/windows/cputime.c; + + videoinkernel = term/gfxterm.c; + videoinkernel = font/font.c; + videoinkernel = font/font_cmd.c; + videoinkernel = io/bufio.c; + videoinkernel = video/fb/fbblit.c; + videoinkernel = video/fb/fbfill.c; + videoinkernel = video/fb/fbutil.c; + videoinkernel = video/fb/video_fb.c; + videoinkernel = video/video.c; + + extra_dist = kern/i386/int.S; + extra_dist = kern/i386/realmode.S; + extra_dist = boot/i386/pc/lzma_decode.S; + extra_dist = kern/mips/cache_flush.S; +}; + +program = { + name = grub-emu; + mansection = 1; + + emu = kern/emu/full.c; + emu_nodist = grub_emu_init.c; + + ldadd = 'kernel.exec$(EXEEXT)'; + ldadd = '$(MODULE_FILES)'; + ldadd = 'lib/gnulib/libgnu.a $(LIBINTL) $(LIBUTIL) $(LIBSDL) $(LIBUSB) $(LIBPCIACCESS) $(LIBDEVMAPPER) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)'; + + enable = emu; +}; + +program = { + name = grub-emu-lite; + + emu = kern/emu/lite.c; + emu_nodist = symlist.c; + + ldadd = 'kernel.exec$(EXEEXT)'; + ldadd = 'lib/gnulib/libgnu.a $(LIBINTL) $(LIBUTIL) $(LIBSDL) $(LIBUSB) $(LIBPCIACCESS) $(LIBDEVMAPPER) $(LIBZFS) $(LIBNVPAIR) $(LIBGEOM)'; + + enable = emu; +}; + +image = { + name = boot; + i386_pc = boot/i386/pc/boot.S; + i386_qemu = boot/i386/qemu/boot.S; + sparc64_ieee1275 = boot/sparc64/ieee1275/boot.S; + + i386_pc_ldflags = '$(TARGET_IMG_LDFLAGS)'; + i386_pc_ldflags = '$(TARGET_IMG_BASE_LDOPT),0x7C00'; + + i386_qemu_ldflags = '$(TARGET_IMG_LDFLAGS)'; + i386_qemu_ldflags = '$(TARGET_IMG_BASE_LDOPT),$(GRUB_BOOT_MACHINE_LINK_ADDR)'; + i386_qemu_ccasflags = '-DGRUB_BOOT_MACHINE_LINK_ADDR=$(GRUB_BOOT_MACHINE_LINK_ADDR)'; + + /* The entry point for a.out binaries on sparc64 starts + at 0x4000. Since we are writing the 32 bytes long a.out + header in the assembly code ourselves, we need to tell + the linker to adjust the start of the text segment to + 0x4000 - 0x20 = 0x3fe0. + */ + sparc64_ieee1275_ldflags = ' -Wl,-Ttext=0x3fe0'; + sparc64_ieee1275_objcopyflags = '-O binary'; + + objcopyflags = '-O binary'; + enable = i386_pc; + enable = i386_qemu; + enable = sparc64_ieee1275; +}; + +image = { + name = boot_hybrid; + i386_pc = boot/i386/pc/boot.S; + + cppflags = '-DHYBRID_BOOT=1'; + + i386_pc_ldflags = '$(TARGET_IMG_LDFLAGS)'; + i386_pc_ldflags = '$(TARGET_IMG_BASE_LDOPT),0x7C00'; + + objcopyflags = '-O binary'; + enable = i386_pc; +}; + +image = { + name = cdboot; + + i386_pc = boot/i386/pc/cdboot.S; + i386_pc_ldflags = '$(TARGET_IMG_LDFLAGS)'; + i386_pc_ldflags = '$(TARGET_IMG_BASE_LDOPT),0x7C00'; + + sparc64_ieee1275 = boot/sparc64/ieee1275/boot.S; + + /* See comment for sparc64_ieee1275_ldflags above. */ + sparc64_ieee1275_ldflags = ' -Wl,-Ttext=0x3fe0'; + sparc64_ieee1275_objcopyflags = '-O binary'; + sparc64_ieee1275_cppflags = '-DCDBOOT=1'; + + objcopyflags = '-O binary'; + + enable = sparc64_ieee1275; + enable = i386_pc; +}; + +image = { + name = pxeboot; + i386_pc = boot/i386/pc/pxeboot.S; + + i386_pc_ldflags = '$(TARGET_IMG_LDFLAGS)'; + i386_pc_ldflags = '$(TARGET_IMG_BASE_LDOPT),0x7C00'; + + objcopyflags = '-O binary'; + enable = i386_pc; +}; + +image = { + name = diskboot; + i386_pc = boot/i386/pc/diskboot.S; + + i386_pc_ldflags = '$(TARGET_IMG_LDFLAGS)'; + i386_pc_ldflags = '$(TARGET_IMG_BASE_LDOPT),0x8000'; + + sparc64_ieee1275 = boot/sparc64/ieee1275/diskboot.S; + sparc64_ieee1275_ldflags = '-Wl,-Ttext=0x4200'; + + objcopyflags = '-O binary'; + + enable = i386_pc; + enable = sparc64_ieee1275; +}; + +image = { + name = lnxboot; + i386_pc = boot/i386/pc/lnxboot.S; + + i386_pc_ldflags = '$(TARGET_IMG_LDFLAGS)'; + i386_pc_ldflags = '$(TARGET_IMG_BASE_LDOPT),0x6000'; + + objcopyflags = '-O binary'; + enable = i386_pc; +}; + +image = { + name = xz_decompress; + mips = boot/mips/startup_raw.S; + common = boot/decompressor/minilib.c; + common = boot/decompressor/xz.c; + common = lib/xzembed/xz_dec_bcj.c; + common = lib/xzembed/xz_dec_lzma2.c; + common = lib/xzembed/xz_dec_stream.c; + common = kern/compiler-rt.c; + + cppflags = '-I$(srcdir)/lib/posix_wrap -I$(srcdir)/lib/xzembed -DGRUB_EMBED_DECOMPRESSOR=1'; + + objcopyflags = '-O binary'; + mips_ldflags = '-Wl,-Ttext,$(TARGET_DECOMPRESSOR_LINK_ADDR)'; + cflags = '-Wno-unreachable-code'; + enable = mips; +}; + +image = { + name = none_decompress; + mips = boot/mips/startup_raw.S; + common = boot/decompressor/none.c; + + cppflags = '-DGRUB_EMBED_DECOMPRESSOR=1'; + + objcopyflags = '-O binary'; + mips_ldflags = '-Wl,-Ttext,$(TARGET_DECOMPRESSOR_LINK_ADDR)'; + enable = mips; +}; + +image = { + name = lzma_decompress; + i386_pc = boot/i386/pc/startup_raw.S; + i386_pc_nodist = rs_decoder.h; + + objcopyflags = '-O binary'; + ldflags = '$(TARGET_IMG_LDFLAGS) $(TARGET_IMG_BASE_LDOPT),0x8200'; + enable = i386_pc; +}; + +image = { + name = fwstart; + mips_loongson = boot/mips/loongson/fwstart.S; + objcopyflags = '-O binary'; + ldflags = '-Wl,-N,-S,-Ttext,0xbfc00000,-Bstatic'; + enable = mips_loongson; +}; + +image = { + name = fwstart_fuloong2f; + mips_loongson = boot/mips/loongson/fuloong2f.S; + objcopyflags = '-O binary'; + ldflags = '-Wl,-N,-S,-Ttext,0xbfc00000,-Bstatic'; + enable = mips_loongson; +}; + +module = { + name = disk; + common = lib/disk.c; + extra_dist = kern/disk_common.c; +}; + +module = { + name = trig; + common_nodist = trigtables.c; + extra_dist = gentrigtables.c; +}; + +module = { + name = cs5536; + x86 = bus/cs5536.c; + enable = x86; +}; + +module = { + name = lsspd; + mips_loongson = commands/mips/loongson/lsspd.c; + enable = mips_loongson; +}; + +module = { + name = usb; + common = bus/usb/usb.c; + common = bus/usb/usbtrans.c; + common = bus/usb/usbhub.c; + enable = usb; +}; + +module = { + name = usbserial_common; + common = bus/usb/serial/common.c; + enable = usb; +}; + +module = { + name = usbserial_pl2303; + common = bus/usb/serial/pl2303.c; + enable = usb; +}; + +module = { + name = usbserial_ftdi; + common = bus/usb/serial/ftdi.c; + enable = usb; +}; + +module = { + name = usbserial_usbdebug; + common = bus/usb/serial/usbdebug_late.c; + enable = usb; +}; + +module = { + name = uhci; + common = bus/usb/uhci.c; + enable = pci; +}; + +module = { + name = ohci; + common = bus/usb/ohci.c; + enable = pci; +}; + +module = { + name = ehci; + common = bus/usb/ehci.c; + arm_coreboot = bus/usb/ehci-fdt.c; + pci = bus/usb/ehci-pci.c; + enable = pci; + enable = arm_coreboot; +}; + +module = { + name = pci; + common = bus/pci.c; + i386_ieee1275 = bus/i386/ieee1275/pci.c; + + enable = i386_pc; + enable = i386_ieee1275; + enable = i386_coreboot; + enable = i386_multiboot; +}; + +module = { + name = nativedisk; + common = commands/nativedisk.c; + + enable = x86; + enable = mips_loongson; + enable = mips_qemu_mips; +}; + +module = { + name = emupci; + common = bus/emu/pci.c; + common = commands/lspci.c; + + enable = emu; + condition = COND_GRUB_EMU_PCI; +}; + +module = { + name = lsdev; + common = commands/arc/lsdev.c; + + enable = mips_arc; +}; + +module = { + name = lsxen; + common = commands/xen/lsxen.c; + + enable = xen; +}; + +module = { + name = cmostest; + common = commands/i386/cmostest.c; + enable = cmos; +}; + +module = { + name = cmosdump; + common = commands/i386/cmosdump.c; + enable = cmos; +}; + +module = { + name = iorw; + common = commands/iorw.c; + enable = x86; +}; + +module = { + name = cbtable; + common = kern/i386/coreboot/cbtable.c; + common = kern/coreboot/cbtable.c; + enable = i386_pc; + enable = i386_efi; + enable = i386_qemu; + enable = i386_multiboot; + enable = i386_ieee1275; + enable = x86_64_efi; +}; + +module = { + name = cbtime; + common = commands/i386/coreboot/cb_timestamps.c; + enable = x86; +}; + +module = { + name = cbls; + common = commands/i386/coreboot/cbls.c; + enable = x86; +}; + +module = { + name = cbmemc; + common = term/i386/coreboot/cbmemc.c; + enable = x86; +}; + +module = { + name = regexp; + common = commands/regexp.c; + common = commands/wildcard.c; + common = lib/gnulib/regex.c; + cflags = '$(CFLAGS_POSIX) $(CFLAGS_GNULIB)'; + cppflags = '$(CPPFLAGS_POSIX) $(CPPFLAGS_GNULIB)'; +}; + +module = { + name = acpi; + + common = commands/acpi.c; + i386_pc = kern/acpi.c; + i386_pc = kern/i386/pc/acpi.c; + + enable = efi; + enable = i386_pc; + enable = i386_coreboot; + enable = i386_multiboot; +}; + +module = { + name = lsacpi; + + common = commands/lsacpi.c; + + enable = efi; + enable = i386_pc; + enable = i386_coreboot; + enable = i386_multiboot; +}; + +module = { + name = lsefisystab; + + common = commands/efi/lsefisystab.c; + + enable = efi; +}; + +module = { + name = lssal; + + common = commands/efi/lssal.c; + + enable = efi; +}; + +module = { + name = lsefimmap; + + common = commands/efi/lsefimmap.c; + + enable = efi; +}; + +module = { + name = lsefi; + common = commands/efi/lsefi.c; + enable = efi; +}; + +module = { + name = efifwsetup; + efi = commands/efi/efifwsetup.c; + enable = efi; +}; + +module = { + name = blocklist; + common = commands/blocklist.c; +}; + +module = { + name = boot; + common = commands/boot.c; + i386_pc = lib/i386/pc/biosnum.c; + enable = x86; + enable = emu; + enable = sparc64_ieee1275; + enable = powerpc_ieee1275; + enable = mips_arc; + enable = ia64_efi; + enable = arm_efi; + enable = arm64_efi; + enable = arm_uboot; + enable = arm_coreboot; + enable = riscv32_efi; + enable = riscv64_efi; +}; + +module = { + name = cat; + common = commands/cat.c; +}; + +module = { + name = cmp; + common = commands/cmp.c; +}; + +module = { + name = configfile; + common = commands/configfile.c; +}; + +module = { + name = cpuid; + common = commands/i386/cpuid.c; + enable = x86; + enable = i386_xen_pvh; + enable = i386_xen; + enable = x86_64_xen; +}; + +module = { + name = date; + common = commands/date.c; +}; + +module = { + name = drivemap; + + i386_pc = commands/i386/pc/drivemap.c; + i386_pc = commands/i386/pc/drivemap_int13h.S; + enable = i386_pc; +}; + +module = { + name = echo; + common = commands/echo.c; +}; + +module = { + name = eval; + common = commands/eval.c; +}; + +module = { + name = extcmd; + common = commands/extcmd.c; + common = lib/arg.c; + enable = terminfomodule; +}; + +module = { + name = fixvideo; + common = commands/efi/fixvideo.c; + enable = i386_efi; + enable = x86_64_efi; +}; + +module = { + name = gptsync; + common = commands/gptsync.c; +}; + +module = { + name = halt; + nopc = commands/halt.c; + i386_pc = commands/i386/pc/halt.c; + i386_pc = commands/acpihalt.c; + i386_coreboot = commands/acpihalt.c; + i386_multiboot = commands/acpihalt.c; + i386_efi = commands/acpihalt.c; + x86_64_efi = commands/acpihalt.c; + i386_multiboot = lib/i386/halt.c; + i386_coreboot = lib/i386/halt.c; + i386_qemu = lib/i386/halt.c; + xen = lib/xen/halt.c; + i386_xen_pvh = lib/xen/halt.c; + efi = lib/efi/halt.c; + ieee1275 = lib/ieee1275/halt.c; + emu = lib/emu/halt.c; + uboot = lib/dummy/halt.c; + arm_coreboot = lib/dummy/halt.c; +}; + +module = { + name = reboot; + i386 = lib/i386/reboot.c; + i386 = lib/i386/reboot_trampoline.S; + powerpc_ieee1275 = lib/ieee1275/reboot.c; + sparc64_ieee1275 = lib/ieee1275/reboot.c; + mips_arc = lib/mips/arc/reboot.c; + mips_loongson = lib/mips/loongson/reboot.c; + mips_qemu_mips = lib/mips/qemu_mips/reboot.c; + xen = lib/xen/reboot.c; + i386_xen_pvh = lib/xen/reboot.c; + uboot = lib/uboot/reboot.c; + arm_coreboot = lib/dummy/reboot.c; + common = commands/reboot.c; +}; + +module = { + name = hashsum; + common = commands/hashsum.c; +}; + +module = { + name = pgp; + common = commands/pgp.c; + cflags = '$(CFLAGS_POSIX)'; + cppflags = '-I$(srcdir)/lib/posix_wrap'; +}; + +module = { + name = verifiers; + common = commands/verifiers.c; +}; + +module = { + name = shim_lock; + common = commands/efi/shim_lock.c; + enable = x86_64_efi; +}; + +module = { + name = hdparm; + common = commands/hdparm.c; + enable = pci; + enable = mips_qemu_mips; +}; + +module = { + name = help; + common = commands/help.c; +}; + +module = { + name = hexdump; + common = commands/hexdump.c; + common = lib/hexdump.c; +}; + +module = { + name = keystatus; + common = commands/keystatus.c; +}; + +module = { + name = loadbios; + common = commands/efi/loadbios.c; + enable = i386_efi; + enable = x86_64_efi; +}; + +module = { + name = loadenv; + common = commands/loadenv.c; + common = lib/envblk.c; +}; + +module = { + name = ls; + common = commands/ls.c; +}; + +module = { + name = lsmmap; + common = commands/lsmmap.c; +}; + +module = { + name = lspci; + common = commands/lspci.c; + + enable = pci; +}; + +module = { + name = memrw; + common = commands/memrw.c; +}; + +module = { + name = minicmd; + common = commands/minicmd.c; +}; + +module = { + name = parttool; + common = commands/parttool.c; +}; + +module = { + name = password; + common = commands/password.c; +}; + +module = { + name = password_pbkdf2; + common = commands/password_pbkdf2.c; +}; + +module = { + name = play; + x86 = commands/i386/pc/play.c; + enable = x86; +}; + +module = { + name = spkmodem; + x86 = term/spkmodem.c; + enable = x86; +}; + +module = { + name = morse; + x86 = term/morse.c; + enable = x86; +}; + +module = { + name = probe; + common = commands/probe.c; +}; + +module = { + name = read; + common = commands/read.c; +}; + +module = { + name = search; + common = commands/search_wrap.c; + extra_dist = commands/search.c; +}; + +module = { + name = search_fs_file; + common = commands/search_file.c; +}; + +module = { + name = search_fs_uuid; + common = commands/search_uuid.c; +}; + +module = { + name = search_label; + common = commands/search_label.c; +}; + +module = { + name = setpci; + common = commands/setpci.c; + enable = pci; +}; + +module = { + name = pcidump; + common = commands/pcidump.c; + enable = pci; +}; + +module = { + name = sleep; + common = commands/sleep.c; +}; + +module = { + name = suspend; + ieee1275 = commands/ieee1275/suspend.c; + enable = i386_ieee1275; + enable = powerpc_ieee1275; +}; + +module = { + name = escc; + ieee1275 = term/ieee1275/escc.c; + enable = powerpc_ieee1275; +}; + +module = { + name = terminal; + common = commands/terminal.c; +}; + +module = { + name = test; + common = commands/test.c; +}; + +module = { + name = true; + common = commands/true.c; +}; + +module = { + name = usbtest; + common = commands/usbtest.c; + enable = usb; +}; + +module = { + name = videoinfo; + common = commands/videoinfo.c; +}; + +module = { + name = videotest; + common = commands/videotest.c; +}; + +module = { + name = xnu_uuid; + common = commands/xnu_uuid.c; +}; + +module = { + name = dm_nv; + common = disk/dmraid_nvidia.c; +}; + +module = { + name = loopback; + common = disk/loopback.c; +}; + +module = { + name = cryptodisk; + common = disk/cryptodisk.c; +}; + +module = { + name = luks; + common = disk/luks.c; + common = disk/AFSplitter.c; +}; + +module = { + name = geli; + common = disk/geli.c; +}; + +module = { + name = lvm; + common = disk/lvm.c; +}; + +module = { + name = ldm; + common = disk/ldm.c; +}; + +module = { + name = mdraid09; + common = disk/mdraid_linux.c; +}; + +module = { + name = mdraid09_be; + common = disk/mdraid_linux_be.c; +}; + +module = { + name = mdraid1x; + common = disk/mdraid1x_linux.c; +}; + +module = { + name = diskfilter; + common = disk/diskfilter.c; +}; + +module = { + name = raid5rec; + common = disk/raid5_recover.c; +}; + +module = { + name = raid6rec; + common = disk/raid6_recover.c; +}; + +module = { + name = scsi; + common = disk/scsi.c; +}; + +module = { + name = memdisk; + common = disk/memdisk.c; +}; + +module = { + name = ata; + common = disk/ata.c; + enable = pci; + enable = mips_qemu_mips; +}; + +module = { + name = ahci; + common = disk/ahci.c; + enable = pci; +}; + +module = { + name = pata; + common = disk/pata.c; + enable = pci; + enable = mips_qemu_mips; +}; + +module = { + name = biosdisk; + i386_pc = disk/i386/pc/biosdisk.c; + enable = i386_pc; +}; + +module = { + name = usbms; + common = disk/usbms.c; + enable = usb; +}; + +module = { + name = nand; + ieee1275 = disk/ieee1275/nand.c; + enable = i386_ieee1275; +}; + +module = { + name = efiemu; + common = efiemu/main.c; + common = efiemu/i386/loadcore32.c; + common = efiemu/i386/loadcore64.c; + i386_pc = efiemu/i386/pc/cfgtables.c; + i386_coreboot = efiemu/i386/pc/cfgtables.c; + i386_multiboot = efiemu/i386/pc/cfgtables.c; + i386_ieee1275 = efiemu/i386/nocfgtables.c; + i386_qemu = efiemu/i386/nocfgtables.c; + common = efiemu/mm.c; + common = efiemu/loadcore_common.c; + common = efiemu/symbols.c; + common = efiemu/loadcore32.c; + common = efiemu/loadcore64.c; + common = efiemu/prepare32.c; + common = efiemu/prepare64.c; + common = efiemu/pnvram.c; + common = efiemu/i386/coredetect.c; + + extra_dist = efiemu/prepare.c; + extra_dist = efiemu/loadcore.c; + extra_dist = efiemu/runtime/efiemu.S; + extra_dist = efiemu/runtime/efiemu.c; + + enable = i386_pc; + enable = i386_coreboot; + enable = i386_ieee1275; + enable = i386_multiboot; + enable = i386_qemu; +}; + +module = { + name = font; + common = font/font.c; + common = font/font_cmd.c; + enable = videomodules; +}; + +module = { + name = procfs; + common = fs/proc.c; +}; + +module = { + name = affs; + common = fs/affs.c; +}; + +module = { + name = afs; + common = fs/afs.c; +}; + +module = { + name = bfs; + common = fs/bfs.c; +}; + +module = { + name = zstd; + common = lib/zstd/debug.c; + common = lib/zstd/entropy_common.c; + common = lib/zstd/error_private.c; + common = lib/zstd/fse_decompress.c; + common = lib/zstd/huf_decompress.c; + common = lib/zstd/module.c; + common = lib/zstd/xxhash.c; + common = lib/zstd/zstd_common.c; + common = lib/zstd/zstd_decompress.c; + cflags = '$(CFLAGS_POSIX) -Wno-undef'; + cppflags = '-I$(srcdir)/lib/posix_wrap -I$(srcdir)/lib/zstd'; +}; + +module = { + name = btrfs; + common = fs/btrfs.c; + common = lib/crc.c; + cflags = '$(CFLAGS_POSIX) -Wno-undef'; + cppflags = '-I$(srcdir)/lib/posix_wrap -I$(srcdir)/lib/minilzo -I$(srcdir)/lib/zstd -DMINILZO_HAVE_CONFIG_H'; +}; + +module = { + name = archelp; + common = fs/archelp.c; +}; + +module = { + name = cbfs; + common = fs/cbfs.c; +}; + +module = { + name = cpio; + common = fs/cpio.c; +}; + +module = { + name = cpio_be; + common = fs/cpio_be.c; +}; + +module = { + name = newc; + common = fs/newc.c; +}; + +module = { + name = odc; + common = fs/odc.c; +}; + +module = { + name = ext2; + common = fs/ext2.c; +}; + +module = { + name = fat; + common = fs/fat.c; +}; + +module = { + name = exfat; + common = fs/exfat.c; +}; + +module = { + name = f2fs; + common = fs/f2fs.c; +}; + +module = { + name = fshelp; + common = fs/fshelp.c; +}; + +module = { + name = hfs; + common = fs/hfs.c; +}; + +module = { + name = hfsplus; + common = fs/hfsplus.c; +}; + +module = { + name = hfspluscomp; + common = fs/hfspluscomp.c; +}; + +module = { + name = iso9660; + common = fs/iso9660.c; +}; + +module = { + name = jfs; + common = fs/jfs.c; +}; + +module = { + name = minix; + common = fs/minix.c; +}; + +module = { + name = minix2; + common = fs/minix2.c; +}; + +module = { + name = minix3; + common = fs/minix3.c; +}; + +module = { + name = minix_be; + common = fs/minix_be.c; +}; + +module = { + name = minix2_be; + common = fs/minix2_be.c; +}; + +module = { + name = minix3_be; + common = fs/minix3_be.c; +}; + +module = { + name = nilfs2; + common = fs/nilfs2.c; +}; + +module = { + name = ntfs; + common = fs/ntfs.c; +}; + +module = { + name = ntfscomp; + common = fs/ntfscomp.c; +}; + +module = { + name = reiserfs; + common = fs/reiserfs.c; +}; + +module = { + name = romfs; + common = fs/romfs.c; +}; + +module = { + name = sfs; + common = fs/sfs.c; +}; + +module = { + name = squash4; + common = fs/squash4.c; + cflags = '$(CFLAGS_POSIX) -Wno-undef'; + cppflags = '-I$(srcdir)/lib/posix_wrap -I$(srcdir)/lib/xzembed -I$(srcdir)/lib/minilzo -DMINILZO_HAVE_CONFIG_H'; +}; + +module = { + name = tar; + common = fs/tar.c; +}; + +module = { + name = udf; + common = fs/udf.c; +}; + +module = { + name = ufs1; + common = fs/ufs.c; +}; + +module = { + name = ufs1_be; + common = fs/ufs_be.c; +}; + +module = { + name = ufs2; + common = fs/ufs2.c; +}; + +module = { + name = xfs; + common = fs/xfs.c; +}; + +module = { + name = zfs; + common = fs/zfs/zfs.c; + common = fs/zfs/zfs_lzjb.c; + common = fs/zfs/zfs_lz4.c; + common = fs/zfs/zfs_sha256.c; + common = fs/zfs/zfs_fletcher.c; +}; + +module = { + name = zfscrypt; + common = fs/zfs/zfscrypt.c; +}; + +module = { + name = zfsinfo; + common = fs/zfs/zfsinfo.c; +}; + +module = { + name = macbless; + common = commands/macbless.c; +}; + +module = { + name = pxe; + i386_pc = net/drivers/i386/pc/pxe.c; + enable = i386_pc; +}; + +module = { + name = gettext; + common = gettext/gettext.c; +}; + +module = { + name = gfxmenu; + common = gfxmenu/gfxmenu.c; + common = gfxmenu/view.c; + common = gfxmenu/font.c; + common = gfxmenu/icon_manager.c; + common = gfxmenu/theme_loader.c; + common = gfxmenu/widget-box.c; + common = gfxmenu/gui_canvas.c; + common = gfxmenu/gui_circular_progress.c; + common = gfxmenu/gui_box.c; + common = gfxmenu/gui_label.c; + common = gfxmenu/gui_list.c; + common = gfxmenu/gui_image.c; + common = gfxmenu/gui_progress_bar.c; + common = gfxmenu/gui_util.c; + common = gfxmenu/gui_string_util.c; +}; + +/* Added by longpanda for Ventoy Project */ +module = { + name = ventoy; + common = ventoy/ventoy.c; + common = ventoy/ventoy_linux.c; + common = ventoy/ventoy_windows.c; + common = ventoy/ventoy_plugin.c; + common = ventoy/ventoy_json.c; + common = ventoy/lzx.c; + common = ventoy/huffman.c; +}; + +module = { + name = hello; + common = hello/hello.c; +}; + +module = { + name = gzio; + common = io/gzio.c; +}; + +module = { + name = offsetio; + common = io/offset.c; +}; + +module = { + name = bufio; + common = io/bufio.c; + enable = videomodules; +}; + +module = { + name = elf; + common = kern/elf.c; + + extra_dist = kern/elfXX.c; +}; + +module = { + name = crypto; + common = lib/crypto.c; + + extra_dist = lib/libgcrypt-grub/cipher/crypto.lst; +}; + +module = { + name = pbkdf2; + common = lib/pbkdf2.c; +}; + +module = { + name = relocator; + common = lib/relocator.c; + x86 = lib/i386/relocator16.S; + x86 = lib/i386/relocator32.S; + x86 = lib/i386/relocator64.S; + i386_xen_pvh = lib/i386/relocator16.S; + i386_xen_pvh = lib/i386/relocator32.S; + i386_xen_pvh = lib/i386/relocator64.S; + i386 = lib/i386/relocator_asm.S; + i386_xen_pvh = lib/i386/relocator_asm.S; + x86_64 = lib/x86_64/relocator_asm.S; + i386_xen = lib/i386/relocator_asm.S; + x86_64_xen = lib/x86_64/relocator_asm.S; + x86 = lib/i386/relocator.c; + x86 = lib/i386/relocator_common_c.c; + i386_xen_pvh = lib/i386/relocator.c; + i386_xen_pvh = lib/i386/relocator_common_c.c; + ieee1275 = lib/ieee1275/relocator.c; + efi = lib/efi/relocator.c; + mips = lib/mips/relocator_asm.S; + mips = lib/mips/relocator.c; + powerpc = lib/powerpc/relocator_asm.S; + powerpc = lib/powerpc/relocator.c; + xen = lib/xen/relocator.c; + i386_xen = lib/i386/xen/relocator.S; + x86_64_xen = lib/x86_64/xen/relocator.S; + xen = lib/i386/relocator_common_c.c; + x86_64_efi = lib/x86_64/efi/relocator.c; + + extra_dist = lib/i386/relocator_common.S; + extra_dist = kern/powerpc/cache_flush.S; + + enable = mips; + enable = powerpc; + enable = x86; + enable = i386_xen_pvh; + enable = xen; +}; + +module = { + name = datetime; + cmos = lib/cmos_datetime.c; + efi = lib/efi/datetime.c; + uboot = lib/dummy/datetime.c; + arm_coreboot = lib/dummy/datetime.c; + sparc64_ieee1275 = lib/ieee1275/datetime.c; + powerpc_ieee1275 = lib/ieee1275/datetime.c; + sparc64_ieee1275 = lib/ieee1275/cmos.c; + powerpc_ieee1275 = lib/ieee1275/cmos.c; + xen = lib/xen/datetime.c; + i386_xen_pvh = lib/xen/datetime.c; + + mips_arc = lib/arc/datetime.c; + enable = noemu; +}; + +module = { + name = setjmp; + common = lib/setjmp.S; + extra_dist = lib/i386/setjmp.S; + extra_dist = lib/mips/setjmp.S; + extra_dist = lib/x86_64/setjmp.S; + extra_dist = lib/sparc64/setjmp.S; + extra_dist = lib/powerpc/setjmp.S; + extra_dist = lib/ia64/setjmp.S; + extra_dist = lib/ia64/longjmp.S; + extra_dist = lib/arm/setjmp.S; + extra_dist = lib/arm64/setjmp.S; + extra_dist = lib/riscv/setjmp.S; +}; + +module = { + name = aout; + common = loader/aout.c; + enable = x86; +}; + +module = { + name = bsd; + x86 = loader/i386/bsd.c; + x86 = loader/i386/bsd32.c; + x86 = loader/i386/bsd64.c; + + extra_dist = loader/i386/bsdXX.c; + extra_dist = loader/i386/bsd_pagetable.c; + + enable = x86; +}; + +module = { + name = plan9; + i386_pc = loader/i386/pc/plan9.c; + enable = i386_pc; +}; + + +module = { + name = linux16; + common = loader/i386/pc/linux.c; + enable = x86; +}; + +module = { + name = ntldr; + i386_pc = loader/i386/pc/ntldr.c; + enable = i386_pc; +}; + + +module = { + name = truecrypt; + i386_pc = loader/i386/pc/truecrypt.c; + enable = i386_pc; +}; + + +module = { + name = freedos; + i386_pc = loader/i386/pc/freedos.c; + enable = i386_pc; +}; + +module = { + name = pxechain; + i386_pc = loader/i386/pc/pxechainloader.c; + enable = i386_pc; +}; + +module = { + name = multiboot2; + cppflags = "-DGRUB_USE_MULTIBOOT2"; + + common = loader/multiboot.c; + common = loader/multiboot_mbi2.c; + enable = x86; + enable = i386_xen_pvh; + enable = mips; +}; + +module = { + name = multiboot; + common = loader/multiboot.c; + x86 = loader/i386/multiboot_mbi.c; + i386_xen_pvh = loader/i386/multiboot_mbi.c; + extra_dist = loader/multiboot_elfxx.c; + enable = x86; + enable = i386_xen_pvh; +}; + +module = { + name = xen_boot; + arm64 = loader/arm64/xen_boot.c; + enable = arm64; +}; + +module = { + name = linux; + x86 = loader/i386/linux.c; + i386_xen_pvh = loader/i386/linux.c; + xen = loader/i386/xen.c; + i386_pc = lib/i386/pc/vesa_modes_table.c; + i386_xen_pvh = lib/i386/pc/vesa_modes_table.c; + mips = loader/mips/linux.c; + powerpc_ieee1275 = loader/powerpc/ieee1275/linux.c; + sparc64_ieee1275 = loader/sparc64/ieee1275/linux.c; + ia64_efi = loader/ia64/efi/linux.c; + arm_coreboot = loader/arm/linux.c; + arm_efi = loader/arm64/linux.c; + arm_uboot = loader/arm/linux.c; + arm64 = loader/arm64/linux.c; + riscv32 = loader/riscv/linux.c; + riscv64 = loader/riscv/linux.c; + common = loader/linux.c; + common = lib/cmdline.c; + enable = noemu; +}; + +module = { + name = fdt; + efi = loader/efi/fdt.c; + common = lib/fdt.c; + enable = fdt; +}; + +module = { + name = xnu; + x86 = loader/xnu_resume.c; + x86 = loader/i386/xnu.c; + x86 = loader/xnu.c; + + /* Code is pretty generic but relies on RNG which + is available only on few platforms. It's not a + big deal as xnu needs ACPI anyway and we have + RNG on all platforms with ACPI. + */ + enable = i386_multiboot; + enable = i386_coreboot; + enable = i386_pc; + enable = i386_efi; + enable = x86_64_efi; +}; + +module = { + name = random; + x86 = lib/i386/random.c; + common = lib/random.c; + + i386_multiboot = kern/i386/tsc_pmtimer.c; + i386_coreboot = kern/i386/tsc_pmtimer.c; + i386_pc = kern/i386/tsc_pmtimer.c; + + enable = i386_multiboot; + enable = i386_coreboot; + enable = i386_pc; + enable = i386_efi; + enable = x86_64_efi; +}; + +module = { + name = macho; + + common = loader/macho.c; + common = loader/macho32.c; + common = loader/macho64.c; + common = loader/lzss.c; + extra_dist = loader/machoXX.c; +}; + +module = { + name = appleldr; + common = loader/efi/appleloader.c; + enable = i386_efi; + enable = x86_64_efi; +}; + +module = { + name = chain; + efi = loader/efi/chainloader.c; + i386_pc = loader/i386/pc/chainloader.c; + i386_coreboot = loader/i386/coreboot/chainloader.c; + i386_coreboot = lib/LzmaDec.c; + enable = i386_pc; + enable = i386_coreboot; + enable = efi; +}; + +module = { + name = mmap; + common = mmap/mmap.c; + x86 = mmap/i386/uppermem.c; + x86 = mmap/i386/mmap.c; + i386_xen_pvh = mmap/i386/uppermem.c; + i386_xen_pvh = mmap/i386/mmap.c; + + i386_pc = mmap/i386/pc/mmap.c; + i386_pc = mmap/i386/pc/mmap_helper.S; + + efi = mmap/efi/mmap.c; + + mips = mmap/mips/uppermem.c; + + enable = x86; + enable = i386_xen_pvh; + enable = ia64_efi; + enable = arm_efi; + enable = arm64_efi; + enable = riscv32_efi; + enable = riscv64_efi; + enable = mips; +}; + +module = { + name = normal; + common = normal/main.c; + common = normal/cmdline.c; + common = normal/dyncmd.c; + common = normal/auth.c; + common = normal/autofs.c; + common = normal/color.c; + common = normal/completion.c; + common = normal/datetime.c; + common = normal/menu.c; + common = normal/menu_entry.c; + common = normal/menu_text.c; + common = normal/misc.c; + common = normal/crypto.c; + common = normal/term.c; + common = normal/context.c; + common = normal/charset.c; + common = lib/getline.c; + + common = script/main.c; + common = script/script.c; + common = script/execute.c; + common = script/function.c; + common = script/lexer.c; + common = script/argv.c; + + common = commands/menuentry.c; + + common = unidata.c; + common_nodist = grub_script.tab.c; + common_nodist = grub_script.yy.c; + common_nodist = grub_script.tab.h; + common_nodist = grub_script.yy.h; + + extra_dist = script/yylex.l; + extra_dist = script/parser.y; + + cflags = '$(CFLAGS_POSIX) -Wno-redundant-decls'; + cppflags = '$(CPPFLAGS_POSIX)'; +}; + +module = { + name = part_acorn; + common = partmap/acorn.c; +}; + +module = { + name = part_amiga; + common = partmap/amiga.c; +}; + +module = { + name = part_apple; + common = partmap/apple.c; +}; + +module = { + name = part_gpt; + common = partmap/gpt.c; +}; + +module = { + name = part_msdos; + common = partmap/msdos.c; +}; + +module = { + name = part_sun; + common = partmap/sun.c; +}; + +module = { + name = part_plan; + common = partmap/plan.c; +}; + +module = { + name = part_dvh; + common = partmap/dvh.c; +}; + +module = { + name = part_bsd; + common = partmap/bsdlabel.c; +}; + +module = { + name = part_sunpc; + common = partmap/sunpc.c; +}; + +module = { + name = part_dfly; + common = partmap/dfly.c; +}; + +module = { + name = msdospart; + common = parttool/msdospart.c; +}; + +module = { + name = at_keyboard; + common = term/at_keyboard.c; + common = term/ps2.c; + enable = x86; +}; + +module = { + name = gfxterm; + common = term/gfxterm.c; + enable = videomodules; +}; + +module = { + name = gfxterm_background; + common = term/gfxterm_background.c; +}; + +module = { + name = serial; + common = term/serial.c; + x86 = term/ns8250.c; + ieee1275 = term/ieee1275/serial.c; + mips_arc = term/arc/serial.c; + efi = term/efi/serial.c; + + enable = terminfomodule; + enable = ieee1275; + enable = mips_arc; +}; + +module = { + name = sendkey; + i386_pc = commands/i386/pc/sendkey.c; + enable = i386_pc; +}; + +module = { + name = terminfo; + common = term/terminfo.c; + common = term/tparm.c; + enable = terminfomodule; +}; + +module = { + name = usb_keyboard; + common = term/usb_keyboard.c; + enable = usb; +}; + +module = { + name = vga; + common = video/i386/pc/vga.c; + enable = i386_pc; +}; + +module = { + name = vga_text; + common = term/i386/pc/vga_text.c; + enable = i386_pc; +}; + +module = { + name = mda_text; + common = term/i386/pc/mda_text.c; + enable = i386_pc; + enable = i386_coreboot_multiboot_qemu; +}; + +module = { + name = video_cirrus; + x86 = video/cirrus.c; + enable = x86; +}; + +module = { + name = video_bochs; + x86 = video/bochs.c; + enable = x86; +}; + +module = { + name = functional_test; + common = tests/lib/functional_test.c; + common = tests/lib/test.c; + common = tests/checksums.h; + common = tests/video_checksum.c; + common = tests/fake_input.c; + common = video/capture.c; +}; + +module = { + name = exfctest; + common = tests/example_functional_test.c; +}; + +module = { + name = strtoull_test; + common = tests/strtoull_test.c; +}; + +module = { + name = setjmp_test; + common = tests/setjmp_test.c; +}; + +module = { + name = signature_test; + common = tests/signature_test.c; + common = tests/signatures.h; +}; + +module = { + name = sleep_test; + common = tests/sleep_test.c; +}; + +module = { + name = xnu_uuid_test; + common = tests/xnu_uuid_test.c; +}; + +module = { + name = pbkdf2_test; + common = tests/pbkdf2_test.c; +}; + +module = { + name = legacy_password_test; + common = tests/legacy_password_test.c; + enable = i386_pc; + enable = i386_xen_pvh; + enable = i386_efi; + enable = x86_64_efi; + enable = emu; + enable = xen; +}; + +module = { + name = div; + common = lib/division.c; + enable = no_softdiv; +}; + +module = { + name = div_test; + common = tests/div_test.c; +}; + +module = { + name = mul_test; + common = tests/mul_test.c; +}; + +module = { + name = shift_test; + common = tests/shift_test.c; +}; + +module = { + name = cmp_test; + common = tests/cmp_test.c; +}; + +module = { + name = ctz_test; + common = tests/ctz_test.c; +}; + +module = { + name = bswap_test; + common = tests/bswap_test.c; +}; + +module = { + name = videotest_checksum; + common = tests/videotest_checksum.c; +}; + +module = { + name = gfxterm_menu; + common = tests/gfxterm_menu.c; +}; + +module = { + name = cmdline_cat_test; + common = tests/cmdline_cat_test.c; +}; + +module = { + name = bitmap; + common = video/bitmap.c; +}; + +module = { + name = bitmap_scale; + common = video/bitmap_scale.c; +}; + +module = { + name = efi_gop; + efi = video/efi_gop.c; + enable = efi; +}; + +module = { + name = efi_uga; + efi = video/efi_uga.c; + enable = i386_efi; + enable = x86_64_efi; +}; + +module = { + name = jpeg; + common = video/readers/jpeg.c; +}; + +module = { + name = png; + common = video/readers/png.c; +}; + +module = { + name = tga; + common = video/readers/tga.c; +}; + +module = { + name = vbe; + common = video/i386/pc/vbe.c; + enable = i386_pc; +}; + +module = { + name = video_fb; + common = video/fb/video_fb.c; + common = video/fb/fbblit.c; + common = video/fb/fbfill.c; + common = video/fb/fbutil.c; + enable = videomodules; +}; + +module = { + name = video; + common = video/video.c; + enable = videomodules; +}; + +module = { + name = video_colors; + common = video/colors.c; +}; + +module = { + name = ieee1275_fb; + ieee1275 = video/ieee1275.c; + enable = powerpc_ieee1275; +}; + +module = { + name = sdl; + emu = video/emu/sdl.c; + enable = emu; + condition = COND_GRUB_EMU_SDL; +}; + +module = { + name = datehook; + common = hook/datehook.c; +}; + +module = { + name = net; + common = net/net.c; + common = net/dns.c; + common = net/bootp.c; + common = net/ip.c; + common = net/udp.c; + common = net/tcp.c; + common = net/icmp.c; + common = net/icmp6.c; + common = net/ethernet.c; + common = net/arp.c; + common = net/netbuff.c; +}; + +module = { + name = tftp; + common = net/tftp.c; +}; + +module = { + name = http; + common = net/http.c; +}; + +module = { + name = ofnet; + common = net/drivers/ieee1275/ofnet.c; + enable = ieee1275; +}; + +module = { + name = ubootnet; + common = net/drivers/uboot/ubootnet.c; + enable = uboot; +}; + +module = { + name = efinet; + common = net/drivers/efi/efinet.c; + enable = efi; +}; + +module = { + name = emunet; + emu = net/drivers/emu/emunet.c; + enable = emu; +}; + +module = { + name = legacycfg; + common = commands/legacycfg.c; + common = lib/legacy_parse.c; + emu = lib/i386/pc/vesa_modes_table.c; + i386_efi = lib/i386/pc/vesa_modes_table.c; + x86_64_efi = lib/i386/pc/vesa_modes_table.c; + xen = lib/i386/pc/vesa_modes_table.c; + + enable = i386_pc; + enable = i386_xen_pvh; + enable = i386_efi; + enable = x86_64_efi; + enable = emu; + enable = xen; +}; + +module = { + name = syslinuxcfg; + common = lib/syslinux_parse.c; + common = commands/syslinuxcfg.c; +}; + +module = { + name = test_blockarg; + common = tests/test_blockarg.c; +}; + +module = { + name = xzio; + common = io/xzio.c; + common = lib/xzembed/xz_dec_bcj.c; + common = lib/xzembed/xz_dec_lzma2.c; + common = lib/xzembed/xz_dec_stream.c; + cppflags = '-I$(srcdir)/lib/posix_wrap -I$(srcdir)/lib/xzembed'; + cflags='-Wno-unreachable-code'; +}; + +module = { + name = lzopio; + common = io/lzopio.c; + common = lib/minilzo/minilzo.c; + cflags = '$(CFLAGS_POSIX) -Wno-undef -Wno-redundant-decls -Wno-error'; + cppflags = '-I$(srcdir)/lib/posix_wrap -I$(srcdir)/lib/minilzo -DMINILZO_HAVE_CONFIG_H'; +}; + +module = { + name = testload; + common = commands/testload.c; +}; + +module = { + name = backtrace; + x86 = lib/i386/backtrace.c; + i386_xen_pvh = lib/i386/backtrace.c; + i386_xen = lib/i386/backtrace.c; + x86_64_xen = lib/i386/backtrace.c; + common = lib/backtrace.c; + enable = x86; + enable = i386_xen_pvh; + enable = i386_xen; + enable = x86_64_xen; +}; + +module = { + name = lsapm; + common = commands/i386/pc/lsapm.c; + enable = i386_pc; +}; + +module = { + name = keylayouts; + common = commands/keylayouts.c; + enable = x86; +}; + +module = { + name = priority_queue; + common = lib/priority_queue.c; +}; + +module = { + name = time; + common = commands/time.c; +}; + +module = { + name = cacheinfo; + common = commands/cacheinfo.c; + condition = COND_ENABLE_CACHE_STATS; +}; + +module = { + name = boottime; + common = commands/boottime.c; + condition = COND_ENABLE_BOOT_TIME_STATS; +}; + +module = { + name = adler32; + common = lib/adler32.c; +}; + +module = { + name = crc64; + common = lib/crc64.c; +}; + +module = { + name = mpi; + common = lib/libgcrypt-grub/mpi/mpiutil.c; + common = lib/libgcrypt-grub/mpi/mpi-bit.c; + common = lib/libgcrypt-grub/mpi/mpi-add.c; + common = lib/libgcrypt-grub/mpi/mpi-mul.c; + common = lib/libgcrypt-grub/mpi/mpi-mod.c; + common = lib/libgcrypt-grub/mpi/mpi-gcd.c; + common = lib/libgcrypt-grub/mpi/mpi-div.c; + common = lib/libgcrypt-grub/mpi/mpi-cmp.c; + common = lib/libgcrypt-grub/mpi/mpi-inv.c; + common = lib/libgcrypt-grub/mpi/mpi-pow.c; + common = lib/libgcrypt-grub/mpi/mpi-mpow.c; + common = lib/libgcrypt-grub/mpi/mpih-lshift.c; + common = lib/libgcrypt-grub/mpi/mpih-mul.c; + common = lib/libgcrypt-grub/mpi/mpih-mul1.c; + common = lib/libgcrypt-grub/mpi/mpih-mul2.c; + common = lib/libgcrypt-grub/mpi/mpih-mul3.c; + common = lib/libgcrypt-grub/mpi/mpih-add1.c; + common = lib/libgcrypt-grub/mpi/mpih-sub1.c; + common = lib/libgcrypt-grub/mpi/mpih-div.c; + common = lib/libgcrypt-grub/mpi/mpicoder.c; + common = lib/libgcrypt-grub/mpi/mpih-rshift.c; + common = lib/libgcrypt-grub/mpi/mpi-inline.c; + common = lib/libgcrypt_wrap/mem.c; + + cflags = '$(CFLAGS_GCRY) -Wno-redundant-decls -Wno-sign-compare'; + cppflags = '$(CPPFLAGS_GCRY)'; +}; + +module = { + name = all_video; + common = lib/fake_module.c; +}; + +module = { + name = gdb; + common = gdb/cstub.c; + common = gdb/gdb.c; + i386 = gdb/i386/idt.c; + i386 = gdb/i386/machdep.S; + i386 = gdb/i386/signal.c; + enable = i386; +}; + +module = { + name = testspeed; + common = commands/testspeed.c; +}; + +module = { + name = tpm; + common = commands/tpm.c; + efi = commands/efi/tpm.c; + enable = x86_64_efi; +}; + +module = { + name = tr; + common = commands/tr.c; +}; + +module = { + name = progress; + common = lib/progress.c; +}; + +module = { + name = file; + common = commands/file.c; + common = commands/file32.c; + common = commands/file64.c; + extra_dist = commands/fileXX.c; + common = loader/i386/xen_file.c; + common = loader/i386/xen_file32.c; + common = loader/i386/xen_file64.c; + extra_dist = loader/i386/xen_fileXX.c; +}; +module = { + name = rdmsr; + common = commands/i386/rdmsr.c; + enable = x86; +}; +module = { + name = wrmsr; + common = commands/i386/wrmsr.c; + enable = x86; +}; diff --git a/GRUB2/grub-2.04/grub-core/boot/i386/pc/boot.S b/GRUB2/grub-2.04/grub-core/boot/i386/pc/boot.S new file mode 100644 index 00000000..18c99b37 --- /dev/null +++ b/GRUB2/grub-2.04/grub-core/boot/i386/pc/boot.S @@ -0,0 +1,545 @@ +/* -*-Asm-*- */ +/* + * GRUB -- GRand Unified Bootloader + * Copyright (C) 1999,2000,2001,2002,2005,2006,2007,2008,2009 Free Software Foundation, Inc. + * + * GRUB is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GRUB is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with GRUB. If not, see . + */ + +#include +#include + +/* + * defines for the code go here + */ + + /* Print message string */ +#define MSG(x) movw $x, %si; call LOCAL(message) +#define ERR(x) movw $x, %si; jmp LOCAL(error_message) + + .macro floppy +part_start: + +LOCAL(probe_values): + .byte 36, 18, 15, 9, 0 + +LOCAL(floppy_probe): + pushw %dx +/* + * Perform floppy probe. + */ +#ifdef __APPLE__ + LOCAL(probe_values_minus_one) = LOCAL(probe_values) - 1 + movw MACRO_DOLLAR(LOCAL(probe_values_minus_one)), %si +#else + movw MACRO_DOLLAR(LOCAL(probe_values)) - 1, %si +#endif + +LOCAL(probe_loop): + /* reset floppy controller INT 13h AH=0 */ + xorw %ax, %ax + int MACRO_DOLLAR(0x13) + + incw %si + movb (%si), %cl + + /* if number of sectors is 0, display error and die */ + testb %cl, %cl + jnz 1f + +/* + * Floppy disk probe failure. + */ + MSG(fd_probe_error_string) + jmp LOCAL(general_error) + +/* "Floppy" */ +fd_probe_error_string: .asciz "Floppy" + +1: + /* perform read */ + movw MACRO_DOLLAR(GRUB_BOOT_MACHINE_BUFFER_SEG), %bx + movw %bx, %es + xorw %bx, %bx + movw MACRO_DOLLAR(0x201), %ax + movb MACRO_DOLLAR(0), %ch + movb MACRO_DOLLAR(0), %dh + int MACRO_DOLLAR(0x13) + + /* if error, jump to "LOCAL(probe_loop)" */ + jc LOCAL(probe_loop) + + /* %cl is already the correct value! */ + movb MACRO_DOLLAR(1), %dh + movb MACRO_DOLLAR(79), %ch + + jmp LOCAL(final_init) + .endm + + .macro scratch + + /* scratch space */ +mode: + .byte 0 +disk_address_packet: +sectors: + .long 0 +heads: + .long 0 +cylinders: + .word 0 +sector_start: + .byte 0 +head_start: + .byte 0 +cylinder_start: + .word 0 + /* more space... */ + .endm + + .file "boot.S" + + .text + + /* Tell GAS to generate 16-bit instructions so that this code works + in real mode. */ + .code16 + +.globl _start, start; +_start: +start: + /* + * _start is loaded at 0x7c00 and is jumped to with CS:IP 0:0x7c00 + */ + + /* + * Beginning of the sector is compatible with the FAT/HPFS BIOS + * parameter block. + */ + + jmp LOCAL(after_BPB) + nop /* do I care about this ??? */ + +#ifdef HYBRID_BOOT + nop + nop + nop + nop + nop + nop + nop + nop + nop + nop + nop + nop + nop + + nop + nop + nop + nop + nop + nop + nop + nop + + nop + nop + jmp LOCAL(after_BPB) +#else + /* + * This space is for the BIOS parameter block!!!! Don't change + * the first jump, nor start the code anywhere but right after + * this area. + */ + + .org GRUB_BOOT_MACHINE_BPB_START + .org 4 +#endif +#ifdef HYBRID_BOOT + floppy +#else + scratch +#endif + + .org GRUB_BOOT_MACHINE_BPB_END + /* + * End of BIOS parameter block. + */ + +LOCAL(kernel_address): + .word GRUB_BOOT_MACHINE_KERNEL_ADDR + +#ifndef HYBRID_BOOT + .org GRUB_BOOT_MACHINE_KERNEL_SECTOR +LOCAL(kernel_sector): + .long 1 +LOCAL(kernel_sector_high): + .long 0 +#endif + + .org GRUB_BOOT_MACHINE_BOOT_DRIVE +boot_drive: + .byte 0xff /* the disk to load kernel from */ + /* 0xff means use the boot drive */ + +LOCAL(after_BPB): + +/* general setup */ + cli /* we're not safe here! */ + + /* + * This is a workaround for buggy BIOSes which don't pass boot + * drive correctly. If GRUB is installed into a HDD, check if + * DL is masked correctly. If not, assume that the BIOS passed + * a bogus value and set DL to 0x80, since this is the only + * possible boot drive. If GRUB is installed into a floppy, + * this does nothing (only jump). + */ + .org GRUB_BOOT_MACHINE_DRIVE_CHECK +boot_drive_check: + jmp 3f /* grub-setup may overwrite this jump */ + testb $0x80, %dl + jz 2f +3: + /* Ignore %dl different from 0-0x0f and 0x80-0x8f. */ + testb $0x70, %dl + jz 1f +2: + movb $0x80, %dl +1: + /* + * ljmp to the next instruction because some bogus BIOSes + * jump to 07C0:0000 instead of 0000:7C00. + */ + ljmp $0, $real_start + +real_start: + + /* set up %ds and %ss as offset from 0 */ + xorw %ax, %ax + movw %ax, %ds + movw %ax, %ss + + /* set up the REAL stack */ + movw $GRUB_BOOT_MACHINE_STACK_SEG, %sp + + sti /* we're safe again */ + + /* + * Check if we have a forced disk reference here + */ + movb boot_drive, %al + cmpb $0xff, %al + je 1f + movb %al, %dl +1: + /* save drive reference first thing! */ + pushw %dx + + /* print a notification message on the screen */ + MSG(notification_string) + + /* set %si to the disk address packet */ + movw $disk_address_packet, %si + + /* check if LBA is supported */ + movb $0x41, %ah + movw $0x55aa, %bx + int $0x13 + + /* + * %dl may have been clobbered by INT 13, AH=41H. + * This happens, for example, with AST BIOS 1.04. + */ + popw %dx + pushw %dx + + /* use CHS if fails */ + jc LOCAL(chs_mode) + cmpw $0xaa55, %bx + jne LOCAL(chs_mode) + + andw $1, %cx + jz LOCAL(chs_mode) + +LOCAL(lba_mode): + xorw %ax, %ax + movw %ax, 4(%si) + + incw %ax + /* set the mode to non-zero */ + movb %al, -1(%si) + + /* the blocks */ + movw %ax, 2(%si) + + /* the size and the reserved byte */ + movw $0x0010, (%si) + + /* the absolute address */ + movl LOCAL(kernel_sector), %ebx + movl %ebx, 8(%si) + movl LOCAL(kernel_sector_high), %ebx + movl %ebx, 12(%si) + + /* the segment of buffer address */ + movw $GRUB_BOOT_MACHINE_BUFFER_SEG, 6(%si) + +/* + * BIOS call "INT 0x13 Function 0x42" to read sectors from disk into memory + * Call with %ah = 0x42 + * %dl = drive number + * %ds:%si = segment:offset of disk address packet + * Return: + * %al = 0x0 on success; err code on failure + */ + + movb $0x42, %ah + int $0x13 + + /* LBA read is not supported, so fallback to CHS. */ + jc LOCAL(chs_mode) + + movw $GRUB_BOOT_MACHINE_BUFFER_SEG, %bx + jmp LOCAL(copy_buffer) + +LOCAL(chs_mode): + /* + * Determine the hard disk geometry from the BIOS! + * We do this first, so that LS-120 IDE floppies work correctly. + */ + movb $8, %ah + int $0x13 + jnc LOCAL(final_init) + + popw %dx + /* + * The call failed, so maybe use the floppy probe instead. + */ + testb %dl, %dl + jnb LOCAL(floppy_probe) + + /* Nope, we definitely have a hard disk, and we're screwed. */ + ERR(hd_probe_error_string) + +LOCAL(final_init): + /* set the mode to zero */ + movzbl %dh, %eax + movb %ah, -1(%si) + + /* save number of heads */ + incw %ax + movl %eax, 4(%si) + + movzbw %cl, %dx + shlw $2, %dx + movb %ch, %al + movb %dh, %ah + + /* save number of cylinders */ + incw %ax + movw %ax, 8(%si) + + movzbw %dl, %ax + shrb $2, %al + + /* save number of sectors */ + movl %eax, (%si) + +setup_sectors: + /* load logical sector start (top half) */ + movl LOCAL(kernel_sector_high), %eax + + orl %eax, %eax + jnz LOCAL(geometry_error) + + /* load logical sector start (bottom half) */ + movl LOCAL(kernel_sector), %eax + + /* zero %edx */ + xorl %edx, %edx + + /* divide by number of sectors */ + divl (%si) + + /* save sector start */ + movb %dl, %cl + + xorw %dx, %dx /* zero %edx */ + divl 4(%si) /* divide by number of heads */ + + /* do we need too many cylinders? */ + cmpw 8(%si), %ax + jge LOCAL(geometry_error) + + /* normalize sector start (1-based) */ + incb %cl + + /* low bits of cylinder start */ + movb %al, %ch + + /* high bits of cylinder start */ + xorb %al, %al + shrw $2, %ax + orb %al, %cl + + /* save head start */ + movb %dl, %al + + /* restore %dl */ + popw %dx + + /* head start */ + movb %al, %dh + +/* + * BIOS call "INT 0x13 Function 0x2" to read sectors from disk into memory + * Call with %ah = 0x2 + * %al = number of sectors + * %ch = cylinder + * %cl = sector (bits 6-7 are high bits of "cylinder") + * %dh = head + * %dl = drive (0x80 for hard disk, 0x0 for floppy disk) + * %es:%bx = segment:offset of buffer + * Return: + * %al = 0x0 on success; err code on failure + */ + + movw $GRUB_BOOT_MACHINE_BUFFER_SEG, %bx + movw %bx, %es /* load %es segment with disk buffer */ + + xorw %bx, %bx /* %bx = 0, put it at 0 in the segment */ + movw $0x0201, %ax /* function 2 */ + int $0x13 + + jc LOCAL(read_error) + + movw %es, %bx + +LOCAL(copy_buffer): + /* + * We need to save %cx and %si because the startup code in + * kernel uses them without initializing them. + */ + pusha + pushw %ds + + movw $0x100, %cx + movw %bx, %ds + xorw %si, %si + movw $GRUB_BOOT_MACHINE_KERNEL_ADDR, %di + movw %si, %es + + cld + + rep + movsw + + popw %ds + popa + + /* boot kernel */ + jmp *(LOCAL(kernel_address)) + +/* END OF MAIN LOOP */ + +/* + * BIOS Geometry translation error (past the end of the disk geometry!). + */ +LOCAL(geometry_error): + ERR(geometry_error_string) + +/* + * Read error on the disk. + */ +LOCAL(read_error): + movw $read_error_string, %si +LOCAL(error_message): + call LOCAL(message) +LOCAL(general_error): + MSG(general_error_string) + +/* go here when you need to stop the machine hard after an error condition */ + /* tell the BIOS a boot failure, which may result in no effect */ + int $0x18 +LOCAL(stop): + jmp LOCAL(stop) + +ventoy_uuid: .ascii "XXXXXXXXXXXXXXXX" +notification_string: .asciz "GR" +geometry_error_string: .asciz "Ge" +hd_probe_error_string: .asciz "HD" +read_error_string: .asciz "Rd" +general_error_string: .asciz " Er\r\n" + + + +/* + * message: write the string pointed to by %si + * + * WARNING: trashes %si, %ax, and %bx + */ + + /* + * Use BIOS "int 10H Function 0Eh" to write character in teletype mode + * %ah = 0xe %al = character + * %bh = page %bl = foreground color (graphics modes) + */ +1: + movw $0x0001, %bx + movb $0xe, %ah + int $0x10 /* display a byte */ +LOCAL(message): + lodsb + cmpb $0, %al + jne 1b /* if not end of string, jmp to display */ + ret + + /* + * Windows NT breaks compatibility by embedding a magic + * number here. + */ + +#ifdef HYBRID_BOOT + .org 0x1b0 +LOCAL(kernel_sector): + .long 1 +LOCAL(kernel_sector_high): + .long 0 +#endif + .org GRUB_BOOT_MACHINE_WINDOWS_NT_MAGIC +nt_magic: + .long 0 + .word 0 + + /* + * This is where an MBR would go if on a hard disk. The code + * here isn't even referenced unless we're on a floppy. Kinda + * sneaky, huh? + */ + + .org GRUB_BOOT_MACHINE_PART_START + +#ifndef HYBRID_BOOT + floppy +#else + scratch +#endif + + .org GRUB_BOOT_MACHINE_PART_END + +/* the last 2 bytes in the sector 0 contain the signature */ + .word GRUB_BOOT_MACHINE_SIGNATURE diff --git a/GRUB2/grub-2.04/grub-core/commands/blocklist.c b/GRUB2/grub-2.04/grub-core/commands/blocklist.c new file mode 100644 index 00000000..6256f37b --- /dev/null +++ b/GRUB2/grub-2.04/grub-core/commands/blocklist.c @@ -0,0 +1,162 @@ +/* blocklist.c - print the block list of a file */ +/* + * GRUB -- GRand Unified Bootloader + * Copyright (C) 2006,2007 Free Software Foundation, Inc. + * + * GRUB is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GRUB is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with GRUB. If not, see . + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +GRUB_MOD_LICENSE ("GPLv3+"); + +/* Context for grub_cmd_blocklist. */ +struct blocklist_ctx +{ + unsigned long start_sector; + unsigned num_sectors; + int num_entries; + grub_disk_addr_t part_start; +}; + +/* Helper for grub_cmd_blocklist. */ +static void +print_blocklist (grub_disk_addr_t sector, unsigned num, + unsigned offset, unsigned length, struct blocklist_ctx *ctx) +{ + if (ctx->num_entries++) + grub_printf (","); + + grub_printf ("%llu", (unsigned long long) (sector - ctx->part_start)); + if (num > 0) + grub_printf ("+%u", num); + if (offset != 0 || length != 0) + grub_printf ("[%u-%u]", offset, offset + length); +} + +/* Helper for grub_cmd_blocklist. */ +static void +read_blocklist (grub_disk_addr_t sector, unsigned offset, unsigned length, + void *data) +{ + struct blocklist_ctx *ctx = data; + + if (ctx->num_sectors > 0) + { + if (ctx->start_sector + ctx->num_sectors == sector + && offset == 0 && length >= GRUB_DISK_SECTOR_SIZE) + { + ctx->num_sectors += length >> GRUB_DISK_SECTOR_BITS; + sector += length >> GRUB_DISK_SECTOR_BITS; + length &= (GRUB_DISK_SECTOR_SIZE - 1); + } + + if (!length) + return; + print_blocklist (ctx->start_sector, ctx->num_sectors, 0, 0, ctx); + ctx->num_sectors = 0; + } + + if (offset) + { + unsigned l = length + offset; + l &= (GRUB_DISK_SECTOR_SIZE - 1); + l -= offset; + print_blocklist (sector, 0, offset, l, ctx); + length -= l; + sector++; + offset = 0; + } + + if (!length) + return; + + if (length & (GRUB_DISK_SECTOR_SIZE - 1)) + { + if (length >> GRUB_DISK_SECTOR_BITS) + { + print_blocklist (sector, length >> GRUB_DISK_SECTOR_BITS, 0, 0, ctx); + sector += length >> GRUB_DISK_SECTOR_BITS; + } + print_blocklist (sector, 0, 0, length & (GRUB_DISK_SECTOR_SIZE - 1), ctx); + } + else + { + ctx->start_sector = sector; + ctx->num_sectors = length >> GRUB_DISK_SECTOR_BITS; + } +} + +static grub_err_t +grub_cmd_blocklist (grub_command_t cmd __attribute__ ((unused)), + int argc, char **args) +{ + grub_file_t file; + char buf[GRUB_DISK_SECTOR_SIZE]; + struct blocklist_ctx ctx = { + .start_sector = 0, + .num_sectors = 0, + .num_entries = 0, + .part_start = 0 + }; + + if (argc < 1) + return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("filename expected")); + + file = grub_file_open (args[0], GRUB_FILE_TYPE_PRINT_BLOCKLIST + | GRUB_FILE_TYPE_NO_DECOMPRESS); + if (! file) + return grub_errno; + + if (! file->device->disk) + return grub_error (GRUB_ERR_BAD_DEVICE, + "this command is available only for disk devices"); + + ctx.part_start = grub_partition_get_start (file->device->disk->partition); + + file->read_hook = read_blocklist; + file->read_hook_data = &ctx; + + while (grub_file_read (file, buf, sizeof (buf)) > 0) + ; + + if (ctx.num_sectors > 0) + print_blocklist (ctx.start_sector, ctx.num_sectors, 0, 0, &ctx); + + grub_printf("\nentry number:%d \n", ctx.num_entries); + + grub_file_close (file); + + return grub_errno; +} + +static grub_command_t cmd; + +GRUB_MOD_INIT(blocklist) +{ + cmd = grub_register_command ("blocklist", grub_cmd_blocklist, + N_("FILE"), N_("Print a block list.")); +} + +GRUB_MOD_FINI(blocklist) +{ + grub_unregister_command (cmd); +} diff --git a/GRUB2/grub-2.04/grub-core/disk/i386/pc/biosdisk.c b/GRUB2/grub-2.04/grub-core/disk/i386/pc/biosdisk.c new file mode 100644 index 00000000..ee2ebe9c --- /dev/null +++ b/GRUB2/grub-2.04/grub-core/disk/i386/pc/biosdisk.c @@ -0,0 +1,764 @@ +/* + * GRUB -- GRand Unified Bootloader + * Copyright (C) 1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010 Free Software Foundation, Inc. + * + * GRUB is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GRUB is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with GRUB. If not, see . + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +GRUB_MOD_LICENSE ("GPLv3+"); + +static int cd_drive = 0; +static int grub_biosdisk_rw_int13_extensions (int ah, int drive, void *dap); + +static int grub_biosdisk_get_num_floppies (void) +{ + struct grub_bios_int_registers regs; + int drive; + + /* reset the disk system first */ + regs.eax = 0; + regs.edx = 0; + regs.flags = GRUB_CPU_INT_FLAGS_DEFAULT; + + grub_bios_interrupt (0x13, ®s); + + for (drive = 0; drive < 2; drive++) + { + regs.flags = GRUB_CPU_INT_FLAGS_DEFAULT | GRUB_CPU_INT_FLAGS_CARRY; + regs.edx = drive; + + /* call GET DISK TYPE */ + regs.eax = 0x1500; + grub_bios_interrupt (0x13, ®s); + if (regs.flags & GRUB_CPU_INT_FLAGS_CARRY) + break; + + /* check if this drive exists */ + if (!(regs.eax & 0x300)) + break; + } + + return drive; +} + +/* + * Call IBM/MS INT13 Extensions (int 13 %ah=AH) for DRIVE. DAP + * is passed for disk address packet. If an error occurs, return + * non-zero, otherwise zero. + */ + +static int +grub_biosdisk_rw_int13_extensions (int ah, int drive, void *dap) +{ + struct grub_bios_int_registers regs; + regs.eax = ah << 8; + /* compute the address of disk_address_packet */ + regs.ds = (((grub_addr_t) dap) & 0xffff0000) >> 4; + regs.esi = (((grub_addr_t) dap) & 0xffff); + regs.edx = drive; + regs.flags = GRUB_CPU_INT_FLAGS_DEFAULT; + + grub_bios_interrupt (0x13, ®s); + return (regs.eax >> 8) & 0xff; +} + +/* + * Call standard and old INT13 (int 13 %ah=AH) for DRIVE. Read/write + * NSEC sectors from COFF/HOFF/SOFF into SEGMENT. If an error occurs, + * return non-zero, otherwise zero. + */ +static int +grub_biosdisk_rw_standard (int ah, int drive, int coff, int hoff, + int soff, int nsec, int segment) +{ + int ret, i; + + /* Try 3 times. */ + for (i = 0; i < 3; i++) + { + struct grub_bios_int_registers regs; + + /* set up CHS information */ + /* set %ch to low eight bits of cylinder */ + regs.ecx = (coff << 8) & 0xff00; + /* set bits 6-7 of %cl to high two bits of cylinder */ + regs.ecx |= (coff >> 2) & 0xc0; + /* set bits 0-5 of %cl to sector */ + regs.ecx |= soff & 0x3f; + + /* set %dh to head and %dl to drive */ + regs.edx = (drive & 0xff) | ((hoff << 8) & 0xff00); + /* set %ah to AH */ + regs.eax = (ah << 8) & 0xff00; + /* set %al to NSEC */ + regs.eax |= nsec & 0xff; + + regs.ebx = 0; + regs.es = segment; + + regs.flags = GRUB_CPU_INT_FLAGS_DEFAULT; + + grub_bios_interrupt (0x13, ®s); + /* check if successful */ + if (!(regs.flags & GRUB_CPU_INT_FLAGS_CARRY)) + return 0; + + /* save return value */ + ret = regs.eax >> 8; + + /* if fail, reset the disk system */ + regs.eax = 0; + regs.edx = (drive & 0xff); + regs.flags = GRUB_CPU_INT_FLAGS_DEFAULT; + grub_bios_interrupt (0x13, ®s); + } + return ret; +} + +/* + * Check if LBA is supported for DRIVE. If it is supported, then return + * the major version of extensions, otherwise zero. + */ +static int +grub_biosdisk_check_int13_extensions (int drive) +{ + struct grub_bios_int_registers regs; + + regs.edx = drive & 0xff; + regs.eax = 0x4100; + regs.ebx = 0x55aa; + regs.flags = GRUB_CPU_INT_FLAGS_DEFAULT; + grub_bios_interrupt (0x13, ®s); + + if (regs.flags & GRUB_CPU_INT_FLAGS_CARRY) + return 0; + + if ((regs.ebx & 0xffff) != 0xaa55) + return 0; + + /* check if AH=0x42 is supported */ + if (!(regs.ecx & 1)) + return 0; + + return (regs.eax >> 8) & 0xff; +} + +/* + * Return the geometry of DRIVE in CYLINDERS, HEADS and SECTORS. If an + * error occurs, then return non-zero, otherwise zero. + */ +static int +grub_biosdisk_get_diskinfo_standard (int drive, + unsigned long *cylinders, + unsigned long *heads, + unsigned long *sectors) +{ + struct grub_bios_int_registers regs; + + regs.eax = 0x0800; + regs.edx = drive & 0xff; + + regs.flags = GRUB_CPU_INT_FLAGS_DEFAULT; + grub_bios_interrupt (0x13, ®s); + + /* Check if unsuccessful. Ignore return value if carry isn't set to + workaround some buggy BIOSes. */ + if ((regs.flags & GRUB_CPU_INT_FLAGS_CARRY) && ((regs.eax & 0xff00) != 0)) + return (regs.eax & 0xff00) >> 8; + + /* bogus BIOSes may not return an error number */ + /* 0 sectors means no disk */ + if (!(regs.ecx & 0x3f)) + /* XXX 0x60 is one of the unused error numbers */ + return 0x60; + + /* the number of heads is counted from zero */ + *heads = ((regs.edx >> 8) & 0xff) + 1; + *cylinders = (((regs.ecx >> 8) & 0xff) | ((regs.ecx << 2) & 0x0300)) + 1; + *sectors = regs.ecx & 0x3f; + return 0; +} + +static int +grub_biosdisk_get_diskinfo_real (int drive, void *drp, grub_uint16_t ax) +{ + struct grub_bios_int_registers regs; + + regs.eax = ax; + + /* compute the address of drive parameters */ + regs.esi = ((grub_addr_t) drp) & 0xf; + regs.ds = ((grub_addr_t) drp) >> 4; + regs.edx = drive & 0xff; + + regs.flags = GRUB_CPU_INT_FLAGS_DEFAULT; + grub_bios_interrupt (0x13, ®s); + + /* Check if unsuccessful. Ignore return value if carry isn't set to + workaround some buggy BIOSes. */ + if ((regs.flags & GRUB_CPU_INT_FLAGS_CARRY) && ((regs.eax & 0xff00) != 0)) + return (regs.eax & 0xff00) >> 8; + + return 0; +} + +/* + * Return the cdrom information of DRIVE in CDRP. If an error occurs, + * then return non-zero, otherwise zero. + */ +static int +grub_biosdisk_get_cdinfo_int13_extensions (int drive, void *cdrp) +{ + return grub_biosdisk_get_diskinfo_real (drive, cdrp, 0x4b01); +} + +/* + * Return the geometry of DRIVE in a drive parameters, DRP. If an error + * occurs, then return non-zero, otherwise zero. + */ +static int +grub_biosdisk_get_diskinfo_int13_extensions (int drive, void *drp) +{ + return grub_biosdisk_get_diskinfo_real (drive, drp, 0x4800); +} + +static int +grub_biosdisk_get_drive (const char *name) +{ + unsigned long drive; + + if (name[0] == 'c' && name[1] == 'd' && name[2] == 0 && cd_drive) + return cd_drive; + + if ((name[0] != 'f' && name[0] != 'h') || name[1] != 'd') + goto fail; + + drive = grub_strtoul (name + 2, 0, 10); + if (grub_errno != GRUB_ERR_NONE) + goto fail; + + if (name[0] == 'h') + drive += 0x80; + + return (int) drive ; + + fail: + grub_error (GRUB_ERR_UNKNOWN_DEVICE, "not a biosdisk"); + return -1; +} + +static int +grub_biosdisk_call_hook (grub_disk_dev_iterate_hook_t hook, void *hook_data, + int drive) +{ + char name[10]; + + if (cd_drive && drive == cd_drive) + return hook ("cd", hook_data); + + grub_snprintf (name, sizeof (name), + (drive & 0x80) ? "hd%d" : "fd%d", drive & (~0x80)); + return hook (name, hook_data); +} + +static int +grub_biosdisk_iterate (grub_disk_dev_iterate_hook_t hook, void *hook_data, + grub_disk_pull_t pull) +{ + int num_floppies; + int drive; + + /* For hard disks, attempt to read the MBR. */ + switch (pull) + { + case GRUB_DISK_PULL_NONE: + for (drive = 0x80; drive < 0x90; drive++) + { + if (grub_biosdisk_rw_standard (0x02, drive, 0, 0, 1, 1, + GRUB_MEMORY_MACHINE_SCRATCH_SEG) != 0) + { + grub_dprintf ("disk", "Read error when probing drive 0x%2x\n", drive); + break; + } + + if (grub_biosdisk_call_hook (hook, hook_data, drive)) + return 1; + } + return 0; + + case GRUB_DISK_PULL_REMOVABLE: + if (cd_drive) + { + if (grub_biosdisk_call_hook (hook, hook_data, cd_drive)) + return 1; + } + + /* For floppy disks, we can get the number safely. */ + num_floppies = grub_biosdisk_get_num_floppies (); + for (drive = 0; drive < num_floppies; drive++) + if (grub_biosdisk_call_hook (hook, hook_data, drive)) + return 1; + return 0; + default: + return 0; + } + return 0; +} + +#pragma pack(1) +typedef struct ventoy_part_table +{ + grub_uint8_t Active; // 0x00 0x80 + + grub_uint8_t StartHead; + grub_uint16_t StartSector : 6; + grub_uint16_t StartCylinder : 10; + + grub_uint8_t FsFlag; + + grub_uint8_t EndHead; + grub_uint16_t EndSector : 6; + grub_uint16_t EndCylinder : 10; + + grub_uint32_t StartSectorId; + grub_uint32_t SectorCount; +}ventoy_part_table; + +typedef struct ventoy_mbr_head +{ + grub_uint8_t BootCode[446]; + ventoy_part_table PartTbl[4]; + grub_uint8_t Byte55; + grub_uint8_t ByteAA; +}ventoy_mbr_head; +#pragma pack() + +static grub_err_t +grub_biosdisk_rw (int cmd, grub_disk_t disk, + grub_disk_addr_t sector, grub_size_t size, + unsigned segment); + +static int ventoy_is_mbr_match(ventoy_mbr_head *head) +{ + grub_uint32_t PartStartSector; + + if (head->Byte55 != 0x55 || head->ByteAA != 0xAA) { + return 0; + } + + if (head->PartTbl[2].SectorCount > 0 || head->PartTbl[3].SectorCount > 0) { + return 0; + } + + if (head->PartTbl[0].FsFlag != 0x07 || head->PartTbl[0].StartSectorId != 2048) { + return 0; + } + + if (head->PartTbl[1].Active != 0x80 || head->PartTbl[1].FsFlag != 0xEF) { + return 0; + } + + PartStartSector = head->PartTbl[0].StartSectorId + head->PartTbl[0].SectorCount; + + if (head->PartTbl[1].StartSectorId != PartStartSector || head->PartTbl[1].SectorCount != 65536) { + return 0; + } + + return 1; +} + +static grub_err_t +grub_biosdisk_open (const char *name, grub_disk_t disk) +{ + grub_uint64_t total_sectors = 0; + int drive; + struct grub_biosdisk_data *data; + + drive = grub_biosdisk_get_drive (name); + if (drive < 0) + return grub_errno; + + disk->id = drive; + + data = (struct grub_biosdisk_data *) grub_zalloc (sizeof (*data)); + if (! data) + return grub_errno; + + data->drive = drive; + + if ((cd_drive) && (drive == cd_drive)) + { + data->flags = GRUB_BIOSDISK_FLAG_LBA | GRUB_BIOSDISK_FLAG_CDROM; + data->sectors = 8; + disk->log_sector_size = 11; + /* TODO: get the correct size. */ + total_sectors = GRUB_DISK_SIZE_UNKNOWN; + } + else + { + /* HDD */ + int version; + + disk->log_sector_size = 9; + + version = grub_biosdisk_check_int13_extensions (drive); + if (version) + { + struct grub_biosdisk_drp *drp + = (struct grub_biosdisk_drp *) GRUB_MEMORY_MACHINE_SCRATCH_ADDR; + + /* Clear out the DRP. */ + grub_memset (drp, 0, sizeof (*drp)); + drp->size = sizeof (*drp); + if (! grub_biosdisk_get_diskinfo_int13_extensions (drive, drp)) + { + data->flags = GRUB_BIOSDISK_FLAG_LBA; + + if (drp->total_sectors) + total_sectors = drp->total_sectors; + else + /* Some buggy BIOSes doesn't return the total sectors + correctly but returns zero. So if it is zero, compute + it by C/H/S returned by the LBA BIOS call. */ + total_sectors = ((grub_uint64_t) drp->cylinders) + * drp->heads * drp->sectors; + if (drp->bytes_per_sector + && !(drp->bytes_per_sector & (drp->bytes_per_sector - 1)) + && drp->bytes_per_sector >= 512 + && drp->bytes_per_sector <= 16384) + { + for (disk->log_sector_size = 0; + (1 << disk->log_sector_size) < drp->bytes_per_sector; + disk->log_sector_size++); + } + } + } + } + + if (! (data->flags & GRUB_BIOSDISK_FLAG_CDROM)) + { + if (grub_biosdisk_get_diskinfo_standard (drive, + &data->cylinders, + &data->heads, + &data->sectors) != 0) + { + if (total_sectors && (data->flags & GRUB_BIOSDISK_FLAG_LBA)) + { + data->sectors = 63; + data->heads = 255; + data->cylinders + = grub_divmod64 (total_sectors + + data->heads * data->sectors - 1, + data->heads * data->sectors, 0); + } + else + { + grub_free (data); + return grub_error (GRUB_ERR_BAD_DEVICE, "%s cannot get C/H/S values", disk->name); + } + } + + if (data->sectors == 0) + data->sectors = 63; + if (data->heads == 0) + data->heads = 255; + + if (! total_sectors) + total_sectors = ((grub_uint64_t) data->cylinders) + * data->heads * data->sectors; + } + + disk->total_sectors = total_sectors; + /* Limit the max to 0x7f because of Phoenix EDD. */ + disk->max_agglomerate = 0x7f >> GRUB_DISK_CACHE_BITS; + COMPILE_TIME_ASSERT ((0x7f >> GRUB_DISK_CACHE_BITS + << (GRUB_DISK_SECTOR_BITS + GRUB_DISK_CACHE_BITS)) + + sizeof (struct grub_biosdisk_dap) + < GRUB_MEMORY_MACHINE_SCRATCH_SIZE); + + disk->data = data; + + //fixup some buggy bios + if (total_sectors > (16434495 - 2097152) && total_sectors < (16434495 + 2097152) && + (data->flags & GRUB_BIOSDISK_FLAG_LBA) > 0 && (data->flags & GRUB_BIOSDISK_FLAG_CDROM) == 0) { + if (grub_biosdisk_rw(0, disk, 0, 1, GRUB_MEMORY_MACHINE_SCRATCH_SEG) == 0) { + ventoy_mbr_head *mbr = (ventoy_mbr_head *)GRUB_MEMORY_MACHINE_SCRATCH_ADDR; + if (ventoy_is_mbr_match(mbr)) { + total_sectors = mbr->PartTbl[1].StartSectorId + mbr->PartTbl[1].SectorCount + 1; + if (disk->total_sectors < total_sectors) { + disk->total_sectors = total_sectors; + } + } + } + } + + return GRUB_ERR_NONE; +} + +static void +grub_biosdisk_close (grub_disk_t disk) +{ + grub_free (disk->data); +} + +/* For readability. */ +#define GRUB_BIOSDISK_READ 0 +#define GRUB_BIOSDISK_WRITE 1 + +#define GRUB_BIOSDISK_CDROM_RETRY_COUNT 3 + +static grub_err_t +grub_biosdisk_rw (int cmd, grub_disk_t disk, + grub_disk_addr_t sector, grub_size_t size, + unsigned segment) +{ + struct grub_biosdisk_data *data = disk->data; + + /* VirtualBox fails with sectors above 2T on CDs. + Since even BD-ROMS are never that big anyway, return error. */ + if ((data->flags & GRUB_BIOSDISK_FLAG_CDROM) + && (sector >> 32)) + return grub_error (GRUB_ERR_OUT_OF_RANGE, + N_("attempt to read or write outside of disk `%s'"), + disk->name); + + if (data->flags & GRUB_BIOSDISK_FLAG_LBA) + { + struct grub_biosdisk_dap *dap; + + dap = (struct grub_biosdisk_dap *) (GRUB_MEMORY_MACHINE_SCRATCH_ADDR + + (data->sectors + << disk->log_sector_size)); + dap->length = sizeof (*dap); + dap->reserved = 0; + dap->blocks = size; + dap->buffer = segment << 16; /* The format SEGMENT:ADDRESS. */ + dap->block = sector; + + if (data->flags & GRUB_BIOSDISK_FLAG_CDROM) + { + int i; + + if (cmd) + return grub_error (GRUB_ERR_WRITE_ERROR, N_("cannot write to CD-ROM")); + + for (i = 0; i < GRUB_BIOSDISK_CDROM_RETRY_COUNT; i++) + if (! grub_biosdisk_rw_int13_extensions (0x42, data->drive, dap)) + break; + + if (i == GRUB_BIOSDISK_CDROM_RETRY_COUNT) + return grub_error (GRUB_ERR_READ_ERROR, N_("failure reading sector 0x%llx " + "from `%s'"), + (unsigned long long) sector, + disk->name); + } + else + if (grub_biosdisk_rw_int13_extensions (cmd + 0x42, data->drive, dap)) + { + /* Fall back to the CHS mode. */ + data->flags &= ~GRUB_BIOSDISK_FLAG_LBA; + disk->total_sectors = data->cylinders * data->heads * data->sectors; + return grub_biosdisk_rw (cmd, disk, sector, size, segment); + } + } + else + { + unsigned coff, hoff, soff; + unsigned head; + + /* It is impossible to reach over 8064 MiB (a bit less than LBA24) with + the traditional CHS access. */ + if (sector > + 1024 /* cylinders */ * + 256 /* heads */ * + 63 /* spt */) + return grub_error (GRUB_ERR_OUT_OF_RANGE, + N_("attempt to read or write outside of disk `%s'"), + disk->name); + + soff = ((grub_uint32_t) sector) % data->sectors + 1; + head = ((grub_uint32_t) sector) / data->sectors; + hoff = head % data->heads; + coff = head / data->heads; + + if (coff >= data->cylinders) + return grub_error (GRUB_ERR_OUT_OF_RANGE, + N_("attempt to read or write outside of disk `%s'"), + disk->name); + + if (grub_biosdisk_rw_standard (cmd + 0x02, data->drive, + coff, hoff, soff, size, segment)) + { + switch (cmd) + { + case GRUB_BIOSDISK_READ: + return grub_error (GRUB_ERR_READ_ERROR, N_("failure reading sector 0x%llx " + "from `%s'"), + (unsigned long long) sector, + disk->name); + case GRUB_BIOSDISK_WRITE: + return grub_error (GRUB_ERR_WRITE_ERROR, N_("failure writing sector 0x%llx " + "to `%s'"), + (unsigned long long) sector, + disk->name); + } + } + } + + return GRUB_ERR_NONE; +} + +/* Return the number of sectors which can be read safely at a time. */ +static grub_size_t +get_safe_sectors (grub_disk_t disk, grub_disk_addr_t sector) +{ + grub_size_t size; + grub_uint64_t offset; + struct grub_biosdisk_data *data = disk->data; + grub_uint32_t sectors = data->sectors; + + /* OFFSET = SECTOR % SECTORS */ + grub_divmod64 (sector, sectors, &offset); + + size = sectors - offset; + + return size; +} + +static grub_err_t +grub_biosdisk_read (grub_disk_t disk, grub_disk_addr_t sector, + grub_size_t size, char *buf) +{ + while (size) + { + grub_size_t len; + + len = get_safe_sectors (disk, sector); + + if (len > size) + len = size; + + if (grub_biosdisk_rw (GRUB_BIOSDISK_READ, disk, sector, len, + GRUB_MEMORY_MACHINE_SCRATCH_SEG)) + return grub_errno; + + grub_memcpy (buf, (void *) GRUB_MEMORY_MACHINE_SCRATCH_ADDR, + len << disk->log_sector_size); + + buf += len << disk->log_sector_size; + sector += len; + size -= len; + } + + return grub_errno; +} + +static grub_err_t +grub_biosdisk_write (grub_disk_t disk, grub_disk_addr_t sector, + grub_size_t size, const char *buf) +{ + struct grub_biosdisk_data *data = disk->data; + + if (data->flags & GRUB_BIOSDISK_FLAG_CDROM) + return grub_error (GRUB_ERR_IO, N_("cannot write to CD-ROM")); + + while (size) + { + grub_size_t len; + + len = get_safe_sectors (disk, sector); + if (len > size) + len = size; + + grub_memcpy ((void *) GRUB_MEMORY_MACHINE_SCRATCH_ADDR, buf, + len << disk->log_sector_size); + + if (grub_biosdisk_rw (GRUB_BIOSDISK_WRITE, disk, sector, len, + GRUB_MEMORY_MACHINE_SCRATCH_SEG)) + return grub_errno; + + buf += len << disk->log_sector_size; + sector += len; + size -= len; + } + + return grub_errno; +} + +static struct grub_disk_dev grub_biosdisk_dev = + { + .name = "biosdisk", + .id = GRUB_DISK_DEVICE_BIOSDISK_ID, + .disk_iterate = grub_biosdisk_iterate, + .disk_open = grub_biosdisk_open, + .disk_close = grub_biosdisk_close, + .disk_read = grub_biosdisk_read, + .disk_write = grub_biosdisk_write, + .next = 0 + }; + +static void +grub_disk_biosdisk_fini (void) +{ + grub_disk_dev_unregister (&grub_biosdisk_dev); +} + +GRUB_MOD_INIT(biosdisk) +{ + struct grub_biosdisk_cdrp *cdrp + = (struct grub_biosdisk_cdrp *) GRUB_MEMORY_MACHINE_SCRATCH_ADDR; + grub_uint8_t boot_drive; + + if (grub_disk_firmware_is_tainted) + { + grub_puts_ (N_("Native disk drivers are in use. " + "Refusing to use firmware disk interface.")); + return; + } + grub_disk_firmware_fini = grub_disk_biosdisk_fini; + + grub_memset (cdrp, 0, sizeof (*cdrp)); + cdrp->size = sizeof (*cdrp); + cdrp->media_type = 0xFF; + boot_drive = (grub_boot_device >> 24); + if ((! grub_biosdisk_get_cdinfo_int13_extensions (boot_drive, cdrp)) + && ((cdrp->media_type & GRUB_BIOSDISK_CDTYPE_MASK) + == GRUB_BIOSDISK_CDTYPE_NO_EMUL)) + cd_drive = cdrp->drive_no; + /* Since diskboot.S rejects devices over 0x90 it must be a CD booted with + cdboot.S + */ + if (boot_drive >= 0x90) + cd_drive = boot_drive; + + grub_disk_dev_register (&grub_biosdisk_dev); +} + +GRUB_MOD_FINI(biosdisk) +{ + grub_disk_biosdisk_fini (); +} diff --git a/GRUB2/grub-2.04/grub-core/fs/fat.c b/GRUB2/grub-2.04/grub-core/fs/fat.c new file mode 100644 index 00000000..2b26a8cb --- /dev/null +++ b/GRUB2/grub-2.04/grub-core/fs/fat.c @@ -0,0 +1,1448 @@ +/* fat.c - FAT filesystem */ +/* + * GRUB -- GRand Unified Bootloader + * Copyright (C) 2000,2001,2002,2003,2004,2005,2007,2008,2009 Free Software Foundation, Inc. + * + * GRUB is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GRUB is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with GRUB. If not, see . + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifndef MODE_EXFAT +#include +#else +#include +#endif +#include +#include +#include +#include + +GRUB_MOD_LICENSE ("GPLv3+"); + +enum + { + GRUB_FAT_ATTR_READ_ONLY = 0x01, + GRUB_FAT_ATTR_HIDDEN = 0x02, + GRUB_FAT_ATTR_SYSTEM = 0x04, +#ifndef MODE_EXFAT + GRUB_FAT_ATTR_VOLUME_ID = 0x08, +#endif + GRUB_FAT_ATTR_DIRECTORY = 0x10, + GRUB_FAT_ATTR_ARCHIVE = 0x20, + +#ifndef MODE_EXFAT + GRUB_FAT_ATTR_LONG_NAME = (GRUB_FAT_ATTR_READ_ONLY + | GRUB_FAT_ATTR_HIDDEN + | GRUB_FAT_ATTR_SYSTEM + | GRUB_FAT_ATTR_VOLUME_ID), +#endif + GRUB_FAT_ATTR_VALID = (GRUB_FAT_ATTR_READ_ONLY + | GRUB_FAT_ATTR_HIDDEN + | GRUB_FAT_ATTR_SYSTEM + | GRUB_FAT_ATTR_DIRECTORY + | GRUB_FAT_ATTR_ARCHIVE +#ifndef MODE_EXFAT + | GRUB_FAT_ATTR_VOLUME_ID +#endif + ) + }; + +#ifdef MODE_EXFAT +typedef struct grub_exfat_bpb grub_current_fat_bpb_t; +#else +typedef struct grub_fat_bpb grub_current_fat_bpb_t; +#endif + +#ifdef MODE_EXFAT +enum + { + FLAG_CONTIGUOUS = 2 + }; +struct grub_fat_dir_entry +{ + grub_uint8_t entry_type; + union + { + grub_uint8_t placeholder[31]; + struct { + grub_uint8_t secondary_count; + grub_uint16_t checksum; + grub_uint16_t attr; + grub_uint16_t reserved1; + grub_uint32_t c_time; + grub_uint32_t m_time; + grub_uint32_t a_time; + grub_uint8_t c_time_tenth; + grub_uint8_t m_time_tenth; + grub_uint8_t a_time_tenth; + grub_uint8_t reserved2[9]; + } GRUB_PACKED file; + struct { + grub_uint8_t flags; + grub_uint8_t reserved1; + grub_uint8_t name_length; + grub_uint16_t name_hash; + grub_uint16_t reserved2; + grub_uint64_t valid_size; + grub_uint32_t reserved3; + grub_uint32_t first_cluster; + grub_uint64_t file_size; + } GRUB_PACKED stream_extension; + struct { + grub_uint8_t flags; + grub_uint16_t str[15]; + } GRUB_PACKED file_name; + struct { + grub_uint8_t character_count; + grub_uint16_t str[15]; + } GRUB_PACKED volume_label; + } GRUB_PACKED type_specific; +} GRUB_PACKED; + +struct grub_fat_dir_node +{ + grub_uint32_t attr; + grub_uint32_t first_cluster; + grub_uint64_t file_size; + grub_uint64_t valid_size; + int have_stream; + int is_contiguous; +}; + +typedef struct grub_fat_dir_node grub_fat_dir_node_t; + +#else +struct grub_fat_dir_entry +{ + grub_uint8_t name[11]; + grub_uint8_t attr; + grub_uint8_t nt_reserved; + grub_uint8_t c_time_tenth; + grub_uint16_t c_time; + grub_uint16_t c_date; + grub_uint16_t a_date; + grub_uint16_t first_cluster_high; + grub_uint16_t w_time; + grub_uint16_t w_date; + grub_uint16_t first_cluster_low; + grub_uint32_t file_size; +} GRUB_PACKED; + +struct grub_fat_long_name_entry +{ + grub_uint8_t id; + grub_uint16_t name1[5]; + grub_uint8_t attr; + grub_uint8_t reserved; + grub_uint8_t checksum; + grub_uint16_t name2[6]; + grub_uint16_t first_cluster; + grub_uint16_t name3[2]; +} GRUB_PACKED; + +typedef struct grub_fat_dir_entry grub_fat_dir_node_t; + +#endif + +struct grub_fat_data +{ + int logical_sector_bits; + grub_uint32_t num_sectors; + + grub_uint32_t fat_sector; + grub_uint32_t sectors_per_fat; + int fat_size; + + grub_uint32_t root_cluster; +#ifndef MODE_EXFAT + grub_uint32_t root_sector; + grub_uint32_t num_root_sectors; +#endif + + int cluster_bits; + grub_uint32_t cluster_eof_mark; + grub_uint32_t cluster_sector; + grub_uint32_t num_clusters; + + grub_uint32_t uuid; +}; + +struct grub_fshelp_node { + grub_disk_t disk; + struct grub_fat_data *data; + + grub_uint8_t attr; +#ifndef MODE_EXFAT + grub_uint32_t file_size; +#else + grub_uint64_t file_size; +#endif + grub_uint32_t file_cluster; + grub_uint32_t cur_cluster_num; + grub_uint32_t cur_cluster; + +#ifdef MODE_EXFAT + int is_contiguous; +#endif +}; + +static grub_dl_t my_mod; + +#ifndef MODE_EXFAT +static int +fat_log2 (unsigned x) +{ + int i; + + if (x == 0) + return -1; + + for (i = 0; (x & 1) == 0; i++) + x >>= 1; + + if (x != 1) + return -1; + + return i; +} +#endif + +static struct grub_fat_data * +grub_fat_mount (grub_disk_t disk) +{ + grub_current_fat_bpb_t bpb; + struct grub_fat_data *data = 0; + grub_uint32_t first_fat, magic; + + if (! disk) + goto fail; + + data = (struct grub_fat_data *) grub_malloc (sizeof (*data)); + if (! data) + goto fail; + + /* Read the BPB. */ + if (grub_disk_read (disk, 0, 0, sizeof (bpb), &bpb)) + goto fail; + +#ifdef MODE_EXFAT + if (grub_memcmp ((const char *) bpb.oem_name, "EXFAT ", + sizeof (bpb.oem_name)) != 0) + goto fail; +#endif + + /* Get the sizes of logical sectors and clusters. */ +#ifdef MODE_EXFAT + data->logical_sector_bits = bpb.bytes_per_sector_shift; +#else + data->logical_sector_bits = + fat_log2 (grub_le_to_cpu16 (bpb.bytes_per_sector)); +#endif + if (data->logical_sector_bits < GRUB_DISK_SECTOR_BITS + || data->logical_sector_bits >= 16) + goto fail; + data->logical_sector_bits -= GRUB_DISK_SECTOR_BITS; + +#ifdef MODE_EXFAT + data->cluster_bits = bpb.sectors_per_cluster_shift; +#else + data->cluster_bits = fat_log2 (bpb.sectors_per_cluster); +#endif + if (data->cluster_bits < 0 || data->cluster_bits > 25) + goto fail; + data->cluster_bits += data->logical_sector_bits; + + /* Get information about FATs. */ +#ifdef MODE_EXFAT + data->fat_sector = (grub_le_to_cpu32 (bpb.num_reserved_sectors) + << data->logical_sector_bits); +#else + data->fat_sector = (grub_le_to_cpu16 (bpb.num_reserved_sectors) + << data->logical_sector_bits); +#endif + if (data->fat_sector == 0) + goto fail; + +#ifdef MODE_EXFAT + data->sectors_per_fat = (grub_le_to_cpu32 (bpb.sectors_per_fat) + << data->logical_sector_bits); +#else + data->sectors_per_fat = ((bpb.sectors_per_fat_16 + ? grub_le_to_cpu16 (bpb.sectors_per_fat_16) + : grub_le_to_cpu32 (bpb.version_specific.fat32.sectors_per_fat_32)) + << data->logical_sector_bits); +#endif + if (data->sectors_per_fat == 0) + goto fail; + + /* Get the number of sectors in this volume. */ +#ifdef MODE_EXFAT + data->num_sectors = ((grub_le_to_cpu64 (bpb.num_total_sectors)) + << data->logical_sector_bits); +#else + data->num_sectors = ((bpb.num_total_sectors_16 + ? grub_le_to_cpu16 (bpb.num_total_sectors_16) + : grub_le_to_cpu32 (bpb.num_total_sectors_32)) + << data->logical_sector_bits); +#endif + if (data->num_sectors == 0) + goto fail; + + /* Get information about the root directory. */ + if (bpb.num_fats == 0) + goto fail; + +#ifndef MODE_EXFAT + data->root_sector = data->fat_sector + bpb.num_fats * data->sectors_per_fat; + data->num_root_sectors + = ((((grub_uint32_t) grub_le_to_cpu16 (bpb.num_root_entries) + * sizeof (struct grub_fat_dir_entry) + + grub_le_to_cpu16 (bpb.bytes_per_sector) - 1) + >> (data->logical_sector_bits + GRUB_DISK_SECTOR_BITS)) + << (data->logical_sector_bits)); +#endif + +#ifdef MODE_EXFAT + data->cluster_sector = (grub_le_to_cpu32 (bpb.cluster_offset) + << data->logical_sector_bits); + data->num_clusters = (grub_le_to_cpu32 (bpb.cluster_count) + << data->logical_sector_bits); +#else + data->cluster_sector = data->root_sector + data->num_root_sectors; + data->num_clusters = (((data->num_sectors - data->cluster_sector) + >> data->cluster_bits) + + 2); +#endif + + if (data->num_clusters <= 2) + goto fail; + +#ifdef MODE_EXFAT + { + /* exFAT. */ + data->root_cluster = grub_le_to_cpu32 (bpb.root_cluster); + data->fat_size = 32; + data->cluster_eof_mark = 0xffffffff; + + if ((bpb.volume_flags & grub_cpu_to_le16_compile_time (0x1)) + && bpb.num_fats > 1) + data->fat_sector += data->sectors_per_fat; + } +#else + if (! bpb.sectors_per_fat_16) + { + /* FAT32. */ + grub_uint16_t flags = grub_le_to_cpu16 (bpb.version_specific.fat32.extended_flags); + + data->root_cluster = grub_le_to_cpu32 (bpb.version_specific.fat32.root_cluster); + data->fat_size = 32; + data->cluster_eof_mark = 0x0ffffff8; + + if (flags & 0x80) + { + /* Get an active FAT. */ + unsigned active_fat = flags & 0xf; + + if (active_fat > bpb.num_fats) + goto fail; + + data->fat_sector += active_fat * data->sectors_per_fat; + } + + if (bpb.num_root_entries != 0 || bpb.version_specific.fat32.fs_version != 0) + goto fail; + } + else + { + /* FAT12 or FAT16. */ + data->root_cluster = ~0U; + + if (data->num_clusters <= 4085 + 2) + { + /* FAT12. */ + data->fat_size = 12; + data->cluster_eof_mark = 0x0ff8; + } + else + { + /* FAT16. */ + data->fat_size = 16; + data->cluster_eof_mark = 0xfff8; + } + } +#endif + + /* More sanity checks. */ + if (data->num_sectors <= data->fat_sector) + goto fail; + + if (grub_disk_read (disk, + data->fat_sector, + 0, + sizeof (first_fat), + &first_fat)) + goto fail; + + first_fat = grub_le_to_cpu32 (first_fat); + + if (data->fat_size == 32) + { + first_fat &= 0x0fffffff; + magic = 0x0fffff00; + } + else if (data->fat_size == 16) + { + first_fat &= 0x0000ffff; + magic = 0xff00; + } + else + { + first_fat &= 0x00000fff; + magic = 0x0f00; + } + + /* Serial number. */ +#ifdef MODE_EXFAT + data->uuid = grub_le_to_cpu32 (bpb.num_serial); +#else + if (bpb.sectors_per_fat_16) + data->uuid = grub_le_to_cpu32 (bpb.version_specific.fat12_or_fat16.num_serial); + else + data->uuid = grub_le_to_cpu32 (bpb.version_specific.fat32.num_serial); +#endif + +#ifndef MODE_EXFAT + /* Ignore the 3rd bit, because some BIOSes assigns 0xF0 to the media + descriptor, even if it is a so-called superfloppy (e.g. an USB key). + The check may be too strict for this kind of stupid BIOSes, as + they overwrite the media descriptor. */ + if ((first_fat | 0x8) != (magic | bpb.media | 0x8)) + goto fail; +#else + (void) magic; +#endif + + return data; + + fail: + + grub_free (data); + grub_error (GRUB_ERR_BAD_FS, "not a FAT filesystem"); + return 0; +} + +static grub_ssize_t +grub_fat_read_data (grub_disk_t disk, grub_fshelp_node_t node, + grub_disk_read_hook_t read_hook, void *read_hook_data, + grub_off_t offset, grub_size_t len, char *buf) +{ + grub_size_t size; + grub_uint32_t logical_cluster; + unsigned logical_cluster_bits; + grub_ssize_t ret = 0; + unsigned long sector; + +#ifndef MODE_EXFAT + /* This is a special case. FAT12 and FAT16 doesn't have the root directory + in clusters. */ + if (node->file_cluster == ~0U) + { + size = (node->data->num_root_sectors << GRUB_DISK_SECTOR_BITS) - offset; + if (size > len) + size = len; + + if (grub_disk_read (disk, node->data->root_sector, offset, size, buf)) + return -1; + + return size; + } +#endif + +#ifdef MODE_EXFAT + if (node->is_contiguous) + { + /* Read the data here. */ + sector = (node->data->cluster_sector + + ((node->file_cluster - 2) + << node->data->cluster_bits)); + + disk->read_hook = read_hook; + disk->read_hook_data = read_hook_data; + grub_disk_read (disk, sector + (offset >> GRUB_DISK_SECTOR_BITS), + offset & (GRUB_DISK_SECTOR_SIZE - 1), len, buf); + disk->read_hook = 0; + if (grub_errno) + return -1; + + return len; + } +#endif + + /* Calculate the logical cluster number and offset. */ + logical_cluster_bits = (node->data->cluster_bits + + GRUB_DISK_SECTOR_BITS); + logical_cluster = offset >> logical_cluster_bits; + offset &= (1ULL << logical_cluster_bits) - 1; + + if (logical_cluster < node->cur_cluster_num) + { + node->cur_cluster_num = 0; + node->cur_cluster = node->file_cluster; + } + + while (len) + { + while (logical_cluster > node->cur_cluster_num) + { + /* Find next cluster. */ + grub_uint32_t next_cluster; + grub_uint32_t fat_offset; + + switch (node->data->fat_size) + { + case 32: + fat_offset = node->cur_cluster << 2; + break; + case 16: + fat_offset = node->cur_cluster << 1; + break; + default: + /* case 12: */ + fat_offset = node->cur_cluster + (node->cur_cluster >> 1); + break; + } + + /* Read the FAT. */ + if (grub_disk_read (disk, node->data->fat_sector, fat_offset, + (node->data->fat_size + 7) >> 3, + (char *) &next_cluster)) + return -1; + + next_cluster = grub_le_to_cpu32 (next_cluster); + switch (node->data->fat_size) + { + case 16: + next_cluster &= 0xFFFF; + break; + case 12: + if (node->cur_cluster & 1) + next_cluster >>= 4; + + next_cluster &= 0x0FFF; + break; + } + + grub_dprintf ("fat", "fat_size=%d, next_cluster=%u\n", + node->data->fat_size, next_cluster); + + /* Check the end. */ + if (next_cluster >= node->data->cluster_eof_mark) + return ret; + + if (next_cluster < 2 || next_cluster >= node->data->num_clusters) + { + grub_error (GRUB_ERR_BAD_FS, "invalid cluster %u", + next_cluster); + return -1; + } + + node->cur_cluster = next_cluster; + node->cur_cluster_num++; + } + + /* Read the data here. */ + sector = (node->data->cluster_sector + + ((node->cur_cluster - 2) + << node->data->cluster_bits)); + size = (1 << logical_cluster_bits) - offset; + if (size > len) + size = len; + + disk->read_hook = read_hook; + disk->read_hook_data = read_hook_data; + grub_disk_read (disk, sector, offset, size, buf); + disk->read_hook = 0; + if (grub_errno) + return -1; + + len -= size; + buf += size; + ret += size; + logical_cluster++; + offset = 0; + } + + return ret; +} + +struct grub_fat_iterate_context +{ +#ifdef MODE_EXFAT + struct grub_fat_dir_node dir; +#else + struct grub_fat_dir_entry dir; +#endif + char *filename; + grub_uint16_t *unibuf; + grub_ssize_t offset; +}; + +static grub_err_t +grub_fat_iterate_init (struct grub_fat_iterate_context *ctxt) +{ + ctxt->offset = -sizeof (struct grub_fat_dir_entry); + +#ifndef MODE_EXFAT + /* Allocate space enough to hold a long name. */ + ctxt->filename = grub_malloc (0x40 * 13 * GRUB_MAX_UTF8_PER_UTF16 + 1); + ctxt->unibuf = (grub_uint16_t *) grub_malloc (0x40 * 13 * 2); +#else + ctxt->unibuf = grub_malloc (15 * 256 * 2); + ctxt->filename = grub_malloc (15 * 256 * GRUB_MAX_UTF8_PER_UTF16 + 1); +#endif + + if (! ctxt->filename || ! ctxt->unibuf) + { + grub_free (ctxt->filename); + grub_free (ctxt->unibuf); + return grub_errno; + } + return GRUB_ERR_NONE; +} + +static void +grub_fat_iterate_fini (struct grub_fat_iterate_context *ctxt) +{ + grub_free (ctxt->filename); + grub_free (ctxt->unibuf); +} + +#ifdef MODE_EXFAT +static grub_err_t +grub_fat_iterate_dir_next (grub_fshelp_node_t node, + struct grub_fat_iterate_context *ctxt) +{ + grub_memset (&ctxt->dir, 0, sizeof (ctxt->dir)); + while (1) + { + struct grub_fat_dir_entry dir; + + ctxt->offset += sizeof (dir); + + if (grub_fat_read_data (node->disk, node, 0, 0, ctxt->offset, sizeof (dir), + (char *) &dir) + != sizeof (dir)) + break; + + if (dir.entry_type == 0) + break; + if (!(dir.entry_type & 0x80)) + continue; + + if (dir.entry_type == 0x85) + { + unsigned i, nsec, slots = 0; + + nsec = dir.type_specific.file.secondary_count; + + ctxt->dir.attr = grub_cpu_to_le16 (dir.type_specific.file.attr); + ctxt->dir.have_stream = 0; + for (i = 0; i < nsec; i++) + { + struct grub_fat_dir_entry sec; + ctxt->offset += sizeof (sec); + if (grub_fat_read_data (node->disk, node, 0, 0, + ctxt->offset, sizeof (sec), (char *) &sec) + != sizeof (sec)) + break; + if (!(sec.entry_type & 0x80)) + continue; + if (!(sec.entry_type & 0x40)) + break; + switch (sec.entry_type) + { + case 0xc0: + ctxt->dir.first_cluster = grub_cpu_to_le32 (sec.type_specific.stream_extension.first_cluster); + ctxt->dir.valid_size + = grub_cpu_to_le64 (sec.type_specific.stream_extension.valid_size); + ctxt->dir.file_size + = grub_cpu_to_le64 (sec.type_specific.stream_extension.file_size); + ctxt->dir.have_stream = 1; + ctxt->dir.is_contiguous = !!(sec.type_specific.stream_extension.flags + & grub_cpu_to_le16_compile_time (FLAG_CONTIGUOUS)); + break; + case 0xc1: + { + int j; + for (j = 0; j < 15; j++) + ctxt->unibuf[slots * 15 + j] + = grub_le_to_cpu16 (sec.type_specific.file_name.str[j]); + slots++; + } + break; + default: + grub_dprintf ("exfat", "unknown secondary type 0x%02x\n", + sec.entry_type); + } + } + + if (i != nsec) + { + ctxt->offset -= sizeof (dir); + continue; + } + + *grub_utf16_to_utf8 ((grub_uint8_t *) ctxt->filename, ctxt->unibuf, + slots * 15) = '\0'; + + return 0; + } + /* Allocation bitmap. */ + if (dir.entry_type == 0x81) + continue; + /* Upcase table. */ + if (dir.entry_type == 0x82) + continue; + /* Volume label. */ + if (dir.entry_type == 0x83) + continue; + grub_dprintf ("exfat", "unknown primary type 0x%02x\n", + dir.entry_type); + } + return grub_errno ? : GRUB_ERR_EOF; +} + +#else + +static grub_err_t +grub_fat_iterate_dir_next (grub_fshelp_node_t node, + struct grub_fat_iterate_context *ctxt) +{ + char *filep = 0; + int checksum = -1; + int slot = -1, slots = -1; + + while (1) + { + unsigned i; + + /* Adjust the offset. */ + ctxt->offset += sizeof (ctxt->dir); + + /* Read a directory entry. */ + if (grub_fat_read_data (node->disk, node, 0, 0, + ctxt->offset, sizeof (ctxt->dir), + (char *) &ctxt->dir) + != sizeof (ctxt->dir) || ctxt->dir.name[0] == 0) + break; + + /* Handle long name entries. */ + if (ctxt->dir.attr == GRUB_FAT_ATTR_LONG_NAME) + { + struct grub_fat_long_name_entry *long_name + = (struct grub_fat_long_name_entry *) &ctxt->dir; + grub_uint8_t id = long_name->id; + + if (id & 0x40) + { + id &= 0x3f; + slots = slot = id; + checksum = long_name->checksum; + } + + if (id != slot || slot == 0 || checksum != long_name->checksum) + { + checksum = -1; + continue; + } + + slot--; + grub_memcpy (ctxt->unibuf + slot * 13, long_name->name1, 5 * 2); + grub_memcpy (ctxt->unibuf + slot * 13 + 5, long_name->name2, 6 * 2); + grub_memcpy (ctxt->unibuf + slot * 13 + 11, long_name->name3, 2 * 2); + continue; + } + + /* Check if this entry is valid. */ + if (ctxt->dir.name[0] == 0xe5 || (ctxt->dir.attr & ~GRUB_FAT_ATTR_VALID)) + continue; + + /* This is a workaround for Japanese. */ + if (ctxt->dir.name[0] == 0x05) + ctxt->dir.name[0] = 0xe5; + + if (checksum != -1 && slot == 0) + { + grub_uint8_t sum; + + for (sum = 0, i = 0; i < sizeof (ctxt->dir.name); i++) + sum = ((sum >> 1) | (sum << 7)) + ctxt->dir.name[i]; + + if (sum == checksum) + { + int u; + + for (u = 0; u < slots * 13; u++) + ctxt->unibuf[u] = grub_le_to_cpu16 (ctxt->unibuf[u]); + + *grub_utf16_to_utf8 ((grub_uint8_t *) ctxt->filename, + ctxt->unibuf, + slots * 13) = '\0'; + + return GRUB_ERR_NONE; + } + + checksum = -1; + } + + /* Convert the 8.3 file name. */ + filep = ctxt->filename; + if (ctxt->dir.attr & GRUB_FAT_ATTR_VOLUME_ID) + { + for (i = 0; i < sizeof (ctxt->dir.name) && ctxt->dir.name[i]; i++) + *filep++ = ctxt->dir.name[i]; + while (i > 0 && ctxt->dir.name[i - 1] == ' ') + { + filep--; + i--; + } + } + else + { + for (i = 0; i < 8 && ctxt->dir.name[i]; i++) + *filep++ = grub_tolower (ctxt->dir.name[i]); + while (i > 0 && ctxt->dir.name[i - 1] == ' ') + { + filep--; + i--; + } + + /* XXX should we check that dir position is 0 or 1? */ + if (i > 2 || filep[0] != '.' || (i == 2 && filep[1] != '.')) + *filep++ = '.'; + + for (i = 8; i < 11 && ctxt->dir.name[i]; i++) + *filep++ = grub_tolower (ctxt->dir.name[i]); + while (i > 8 && ctxt->dir.name[i - 1] == ' ') + { + filep--; + i--; + } + + if (i == 8) + filep--; + } + *filep = '\0'; + return GRUB_ERR_NONE; + } + + return grub_errno ? : GRUB_ERR_EOF; +} + +#endif + +static grub_err_t lookup_file (grub_fshelp_node_t node, + const char *name, + grub_fshelp_node_t *foundnode, + enum grub_fshelp_filetype *foundtype) +{ + grub_err_t err; + struct grub_fat_iterate_context ctxt; + + err = grub_fat_iterate_init (&ctxt); + if (err) + return err; + + while (!(err = grub_fat_iterate_dir_next (node, &ctxt))) + { + +#ifdef MODE_EXFAT + if (!ctxt.dir.have_stream) + continue; +#else + if (ctxt.dir.attr & GRUB_FAT_ATTR_VOLUME_ID) + continue; +#endif + + if (grub_strcasecmp (name, ctxt.filename) == 0) + { + *foundnode = grub_malloc (sizeof (struct grub_fshelp_node)); + if (!*foundnode) + return grub_errno; + (*foundnode)->attr = ctxt.dir.attr; +#ifdef MODE_EXFAT + (*foundnode)->file_size = ctxt.dir.file_size; + (*foundnode)->file_cluster = ctxt.dir.first_cluster; + (*foundnode)->is_contiguous = ctxt.dir.is_contiguous; +#else + (*foundnode)->file_size = grub_le_to_cpu32 (ctxt.dir.file_size); + (*foundnode)->file_cluster = ((grub_le_to_cpu16 (ctxt.dir.first_cluster_high) << 16) + | grub_le_to_cpu16 (ctxt.dir.first_cluster_low)); + /* If directory points to root, starting cluster is 0 */ + if (!(*foundnode)->file_cluster) + (*foundnode)->file_cluster = node->data->root_cluster; +#endif + (*foundnode)->cur_cluster_num = ~0U; + (*foundnode)->data = node->data; + (*foundnode)->disk = node->disk; + + *foundtype = ((*foundnode)->attr & GRUB_FAT_ATTR_DIRECTORY) ? GRUB_FSHELP_DIR : GRUB_FSHELP_REG; + + grub_fat_iterate_fini (&ctxt); + return GRUB_ERR_NONE; + } + } + + grub_fat_iterate_fini (&ctxt); + if (err == GRUB_ERR_EOF) + err = 0; + + return err; + +} + +static grub_err_t +grub_fat_dir (grub_device_t device, const char *path, grub_fs_dir_hook_t hook, + void *hook_data) +{ + struct grub_fat_data *data = 0; + grub_disk_t disk = device->disk; + grub_fshelp_node_t found = NULL; + grub_err_t err; + struct grub_fat_iterate_context ctxt; + + grub_dl_ref (my_mod); + + data = grub_fat_mount (disk); + if (! data) + goto fail; + + struct grub_fshelp_node root = { + .data = data, + .disk = disk, + .attr = GRUB_FAT_ATTR_DIRECTORY, + .file_size = 0, + .file_cluster = data->root_cluster, + .cur_cluster_num = ~0U, + .cur_cluster = 0, +#ifdef MODE_EXFAT + .is_contiguous = 0, +#endif + }; + + err = grub_fshelp_find_file_lookup (path, &root, &found, lookup_file, NULL, GRUB_FSHELP_DIR); + if (err) + goto fail; + + err = grub_fat_iterate_init (&ctxt); + if (err) + goto fail; + + while (!(err = grub_fat_iterate_dir_next (found, &ctxt))) + { + struct grub_dirhook_info info; + grub_memset (&info, 0, sizeof (info)); + + info.dir = !! (ctxt.dir.attr & GRUB_FAT_ATTR_DIRECTORY); + info.case_insensitive = 1; +#ifdef MODE_EXFAT + if (!ctxt.dir.have_stream) + continue; +#else + if (ctxt.dir.attr & GRUB_FAT_ATTR_VOLUME_ID) + continue; +#endif + + if (hook (ctxt.filename, &info, hook_data)) + break; + } + grub_fat_iterate_fini (&ctxt); + if (err == GRUB_ERR_EOF) + err = 0; + + fail: + if (found != &root) + grub_free (found); + + grub_free (data); + + grub_dl_unref (my_mod); + + return grub_errno; +} + +static grub_err_t +grub_fat_open (grub_file_t file, const char *name) +{ + struct grub_fat_data *data = 0; + grub_fshelp_node_t found = NULL; + grub_err_t err; + grub_disk_t disk = file->device->disk; + + grub_dl_ref (my_mod); + + data = grub_fat_mount (disk); + if (! data) + goto fail; + + struct grub_fshelp_node root = { + .data = data, + .disk = disk, + .attr = GRUB_FAT_ATTR_DIRECTORY, + .file_size = 0, + .file_cluster = data->root_cluster, + .cur_cluster_num = ~0U, + .cur_cluster = 0, +#ifdef MODE_EXFAT + .is_contiguous = 0, +#endif + }; + + err = grub_fshelp_find_file_lookup (name, &root, &found, lookup_file, NULL, GRUB_FSHELP_REG); + if (err) + goto fail; + + file->data = found; + file->size = found->file_size; + + return GRUB_ERR_NONE; + + fail: + + if (found != &root) + grub_free (found); + + grub_free (data); + + grub_dl_unref (my_mod); + + return grub_errno; +} + +static grub_ssize_t +grub_fat_read (grub_file_t file, char *buf, grub_size_t len) +{ + return grub_fat_read_data (file->device->disk, file->data, + file->read_hook, file->read_hook_data, + file->offset, len, buf); +} + +static grub_err_t +grub_fat_close (grub_file_t file) +{ + grub_fshelp_node_t node = file->data; + + grub_free (node->data); + grub_free (node); + + grub_dl_unref (my_mod); + + return grub_errno; +} + +#ifdef MODE_EXFAT +static grub_err_t +grub_fat_label (grub_device_t device, char **label) +{ + struct grub_fat_dir_entry dir; + grub_ssize_t offset = -sizeof(dir); + grub_disk_t disk = device->disk; + struct grub_fshelp_node root = { + .disk = disk, + .attr = GRUB_FAT_ATTR_DIRECTORY, + .file_size = 0, + .cur_cluster_num = ~0U, + .cur_cluster = 0, + .is_contiguous = 0, + }; + + root.data = grub_fat_mount (disk); + if (! root.data) + return grub_errno; + + root.file_cluster = root.data->root_cluster; + + *label = NULL; + + while (1) + { + offset += sizeof (dir); + + if (grub_fat_read_data (disk, &root, 0, 0, + offset, sizeof (dir), (char *) &dir) + != sizeof (dir)) + break; + + if (dir.entry_type == 0) + break; + if (!(dir.entry_type & 0x80)) + continue; + + /* Volume label. */ + if (dir.entry_type == 0x83) + { + grub_size_t chc; + grub_uint16_t t[ARRAY_SIZE (dir.type_specific.volume_label.str)]; + grub_size_t i; + *label = grub_malloc (ARRAY_SIZE (dir.type_specific.volume_label.str) + * GRUB_MAX_UTF8_PER_UTF16 + 1); + if (!*label) + { + grub_free (root.data); + return grub_errno; + } + chc = dir.type_specific.volume_label.character_count; + if (chc > ARRAY_SIZE (dir.type_specific.volume_label.str)) + chc = ARRAY_SIZE (dir.type_specific.volume_label.str); + for (i = 0; i < chc; i++) + t[i] = grub_le_to_cpu16 (dir.type_specific.volume_label.str[i]); + *grub_utf16_to_utf8 ((grub_uint8_t *) *label, t, chc) = '\0'; + } + } + + grub_free (root.data); + return grub_errno; +} + +#else + +static grub_err_t +grub_fat_label (grub_device_t device, char **label) +{ + grub_disk_t disk = device->disk; + grub_err_t err; + struct grub_fat_iterate_context ctxt; + struct grub_fshelp_node root = { + .disk = disk, + .attr = GRUB_FAT_ATTR_DIRECTORY, + .file_size = 0, + .cur_cluster_num = ~0U, + .cur_cluster = 0, + }; + + *label = 0; + + grub_dl_ref (my_mod); + + root.data = grub_fat_mount (disk); + if (! root.data) + goto fail; + + root.file_cluster = root.data->root_cluster; + + err = grub_fat_iterate_init (&ctxt); + if (err) + goto fail; + + while (!(err = grub_fat_iterate_dir_next (&root, &ctxt))) + if ((ctxt.dir.attr & ~GRUB_FAT_ATTR_ARCHIVE) == GRUB_FAT_ATTR_VOLUME_ID) + { + *label = grub_strdup (ctxt.filename); + break; + } + + grub_fat_iterate_fini (&ctxt); + + fail: + + grub_dl_unref (my_mod); + + grub_free (root.data); + + return grub_errno; +} + +#endif + +static grub_err_t +grub_fat_uuid (grub_device_t device, char **uuid) +{ + struct grub_fat_data *data; + grub_disk_t disk = device->disk; + + grub_dl_ref (my_mod); + + data = grub_fat_mount (disk); + if (data) + { + char *ptr; + *uuid = grub_xasprintf ("%04x-%04x", + (grub_uint16_t) (data->uuid >> 16), + (grub_uint16_t) data->uuid); + for (ptr = *uuid; ptr && *ptr; ptr++) + *ptr = grub_toupper (*ptr); + } + else + *uuid = NULL; + + grub_dl_unref (my_mod); + + grub_free (data); + + return grub_errno; +} + +#ifdef GRUB_UTIL +#ifndef MODE_EXFAT +grub_disk_addr_t +grub_fat_get_cluster_sector (grub_disk_t disk, grub_uint64_t *sec_per_lcn) +#else +grub_disk_addr_t + grub_exfat_get_cluster_sector (grub_disk_t disk, grub_uint64_t *sec_per_lcn) +#endif +{ + grub_disk_addr_t ret; + struct grub_fat_data *data; + data = grub_fat_mount (disk); + if (!data) + return 0; + ret = data->cluster_sector; + + *sec_per_lcn = 1ULL << data->cluster_bits; + + grub_free (data); + return ret; +} +#endif + +static struct grub_fs grub_fat_fs = + { +#ifdef MODE_EXFAT + .name = "exfat", +#else + .name = "fat", +#endif + .fs_dir = grub_fat_dir, + .fs_open = grub_fat_open, + .fs_read = grub_fat_read, + .fs_close = grub_fat_close, + .fs_label = grub_fat_label, + .fs_uuid = grub_fat_uuid, +#ifdef GRUB_UTIL +#ifdef MODE_EXFAT + /* ExFAT BPB is 30 larger than FAT32 one. */ + .reserved_first_sector = 0, +#else + .reserved_first_sector = 1, +#endif + .blocklist_install = 1, +#endif + .next = 0 + }; + +#ifdef MODE_EXFAT +GRUB_MOD_INIT(exfat) +#else +GRUB_MOD_INIT(fat) +#endif +{ + COMPILE_TIME_ASSERT (sizeof (struct grub_fat_dir_entry) == 32); + grub_fs_register (&grub_fat_fs); + my_mod = mod; +} +#ifdef MODE_EXFAT +GRUB_MOD_FINI(exfat) +#else +GRUB_MOD_FINI(fat) +#endif +{ + grub_fs_unregister (&grub_fat_fs); +} + +#ifdef MODE_EXFAT + +static int grub_fat_add_chunk(ventoy_img_chunk_list *chunk_list, grub_uint64_t sector, grub_uint64_t size, grub_uint32_t log_sector_size) +{ + ventoy_img_chunk *last_chunk; + ventoy_img_chunk *new_chunk; + + if (chunk_list->cur_chunk == 0) + { + chunk_list->chunk[0].img_start_sector = 0; + chunk_list->chunk[0].img_end_sector = (size >> 11) - 1; + chunk_list->chunk[0].disk_start_sector = sector; + chunk_list->chunk[0].disk_end_sector = sector + (size >> log_sector_size) - 1; + chunk_list->cur_chunk = 1; + return 0; + } + + last_chunk = chunk_list->chunk + chunk_list->cur_chunk - 1; + if (last_chunk->disk_end_sector + 1 == sector) + { + last_chunk->img_end_sector += (size >> 11); + last_chunk->disk_end_sector += (size >> log_sector_size); + return 0; + } + + if (chunk_list->cur_chunk == chunk_list->max_chunk) + { + new_chunk = grub_realloc(chunk_list->chunk, chunk_list->max_chunk * 2 * sizeof(ventoy_img_chunk)); + if (NULL == new_chunk) + { + return -1; + } + chunk_list->chunk = new_chunk; + chunk_list->max_chunk *= 2; + + /* issue: update last_chunk */ + last_chunk = chunk_list->chunk + chunk_list->cur_chunk - 1; + } + + new_chunk = chunk_list->chunk + chunk_list->cur_chunk; + new_chunk->img_start_sector = last_chunk->img_end_sector + 1; + new_chunk->img_end_sector = new_chunk->img_start_sector + (size >> 11) - 1; + new_chunk->disk_start_sector = sector; + new_chunk->disk_end_sector = sector + (size >> log_sector_size) - 1; + + chunk_list->cur_chunk++; + + return 0; +} + +int grub_fat_get_file_chunk(grub_uint64_t part_start, grub_file_t file, ventoy_img_chunk_list *chunk_list) +{ + grub_size_t size; + grub_uint32_t i; + grub_uint32_t logical_cluster; + unsigned logical_cluster_bits; + unsigned long sector; + grub_fshelp_node_t node; + grub_disk_t disk; + grub_uint64_t len; + + disk = file->device->disk; + node = file->data; + len = file->size; + + if (node->is_contiguous) + { + /* Read the data here. */ + sector = (node->data->cluster_sector + ((node->file_cluster - 2) << node->data->cluster_bits)); + + chunk_list->chunk[0].img_start_sector = 0; + chunk_list->chunk[0].img_end_sector = (file->size >> 11) - 1; + chunk_list->chunk[0].disk_start_sector = sector; + chunk_list->chunk[0].disk_end_sector = sector + (file->size >> disk->log_sector_size) - 1; + chunk_list->cur_chunk = 1; + + goto END; + } + + /* Calculate the logical cluster number and offset. */ + logical_cluster = 0; + logical_cluster_bits = (node->data->cluster_bits + GRUB_DISK_SECTOR_BITS); + + if (logical_cluster < node->cur_cluster_num) + { + node->cur_cluster_num = 0; + node->cur_cluster = node->file_cluster; + } + + while (len) + { + while (logical_cluster > node->cur_cluster_num) + { + /* Find next cluster. */ + grub_uint32_t next_cluster; + grub_uint32_t fat_offset; + + switch (node->data->fat_size) + { + case 32: + fat_offset = node->cur_cluster << 2; + break; + case 16: + fat_offset = node->cur_cluster << 1; + break; + default: + /* case 12: */ + fat_offset = node->cur_cluster + (node->cur_cluster >> 1); + break; + } + + /* Read the FAT. */ + if (grub_disk_read (disk, node->data->fat_sector, fat_offset, + (node->data->fat_size + 7) >> 3, + (char *) &next_cluster)) + { + return -1; + } + + next_cluster = grub_le_to_cpu32 (next_cluster); + switch (node->data->fat_size) + { + case 16: + next_cluster &= 0xFFFF; + break; + case 12: + if (node->cur_cluster & 1) + next_cluster >>= 4; + + next_cluster &= 0x0FFF; + break; + } + + grub_dprintf ("fat", "fat_size=%d, next_cluster=%u\n", node->data->fat_size, next_cluster); + + /* Check the end. */ + if (next_cluster >= node->data->cluster_eof_mark) + { + return 0; + } + + if (next_cluster < 2 || next_cluster >= node->data->num_clusters) + { + grub_error (GRUB_ERR_BAD_FS, "invalid cluster %u", next_cluster); + return -1; + } + + node->cur_cluster = next_cluster; + node->cur_cluster_num++; + } + + /* Read the data here. */ + sector = (node->data->cluster_sector + + ((node->cur_cluster - 2) + << node->data->cluster_bits)); + size = (1 << logical_cluster_bits); + if (size > len) + size = len; + + grub_fat_add_chunk(chunk_list, sector, size, disk->log_sector_size); + + len -= size; + logical_cluster++; + } + +END: + + for (i = 0; i < chunk_list->cur_chunk; i++) + { + chunk_list->chunk[i].disk_start_sector += part_start; + chunk_list->chunk[i].disk_end_sector += part_start; + } + + return 0; +} + +#endif + diff --git a/GRUB2/grub-2.04/grub-core/fs/iso9660.c b/GRUB2/grub-2.04/grub-core/fs/iso9660.c new file mode 100644 index 00000000..f0e7dcfb --- /dev/null +++ b/GRUB2/grub-2.04/grub-core/fs/iso9660.c @@ -0,0 +1,1149 @@ +/* iso9660.c - iso9660 implementation with extensions: + SUSP, Rock Ridge. */ +/* + * GRUB -- GRand Unified Bootloader + * Copyright (C) 2004,2005,2006,2007,2008,2009,2010 Free Software Foundation, Inc. + * + * GRUB is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GRUB is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with GRUB. If not, see . + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +GRUB_MOD_LICENSE ("GPLv3+"); + +static grub_uint64_t g_ventoy_last_read_pos = 0; +static grub_uint64_t g_ventoy_last_read_offset = 0; +static grub_uint64_t g_ventoy_last_read_dirent_pos = 0; +static grub_uint64_t g_ventoy_last_read_dirent_offset = 0; +static grub_uint64_t g_ventoy_last_file_dirent_pos = 0; +static grub_uint64_t g_ventoy_last_file_dirent_offset = 0; + +#define GRUB_ISO9660_FSTYPE_DIR 0040000 +#define GRUB_ISO9660_FSTYPE_REG 0100000 +#define GRUB_ISO9660_FSTYPE_SYMLINK 0120000 +#define GRUB_ISO9660_FSTYPE_MASK 0170000 + +#define GRUB_ISO9660_LOG2_BLKSZ 2 +#define GRUB_ISO9660_BLKSZ 2048 + +#define GRUB_ISO9660_RR_DOT 2 +#define GRUB_ISO9660_RR_DOTDOT 4 + +#define GRUB_ISO9660_VOLDESC_BOOT 0 +#define GRUB_ISO9660_VOLDESC_PRIMARY 1 +#define GRUB_ISO9660_VOLDESC_SUPP 2 +#define GRUB_ISO9660_VOLDESC_PART 3 +#define GRUB_ISO9660_VOLDESC_END 255 + +/* The head of a volume descriptor. */ +struct grub_iso9660_voldesc +{ + grub_uint8_t type; + grub_uint8_t magic[5]; + grub_uint8_t version; +} GRUB_PACKED; + +struct grub_iso9660_date2 +{ + grub_uint8_t year; + grub_uint8_t month; + grub_uint8_t day; + grub_uint8_t hour; + grub_uint8_t minute; + grub_uint8_t second; + grub_uint8_t offset; +} GRUB_PACKED; + +/* A directory entry. */ +struct grub_iso9660_dir +{ + grub_uint8_t len; + grub_uint8_t ext_sectors; + grub_uint32_t first_sector; + grub_uint32_t first_sector_be; + grub_uint32_t size; + grub_uint32_t size_be; + struct grub_iso9660_date2 mtime; + grub_uint8_t flags; + grub_uint8_t unused2[6]; +#define MAX_NAMELEN 255 + grub_uint8_t namelen; +} GRUB_PACKED; + +struct grub_iso9660_date +{ + grub_uint8_t year[4]; + grub_uint8_t month[2]; + grub_uint8_t day[2]; + grub_uint8_t hour[2]; + grub_uint8_t minute[2]; + grub_uint8_t second[2]; + grub_uint8_t hundredth[2]; + grub_uint8_t offset; +} GRUB_PACKED; + +/* The primary volume descriptor. Only little endian is used. */ +struct grub_iso9660_primary_voldesc +{ + struct grub_iso9660_voldesc voldesc; + grub_uint8_t unused1[33]; + grub_uint8_t volname[32]; + grub_uint8_t unused2[16]; + grub_uint8_t escape[32]; + grub_uint8_t unused3[12]; + grub_uint32_t path_table_size; + grub_uint8_t unused4[4]; + grub_uint32_t path_table; + grub_uint8_t unused5[12]; + struct grub_iso9660_dir rootdir; + grub_uint8_t unused6[624]; + struct grub_iso9660_date created; + struct grub_iso9660_date modified; +} GRUB_PACKED; + +/* A single entry in the path table. */ +struct grub_iso9660_path +{ + grub_uint8_t len; + grub_uint8_t sectors; + grub_uint32_t first_sector; + grub_uint16_t parentdir; + grub_uint8_t name[0]; +} GRUB_PACKED; + +/* An entry in the System Usage area of the directory entry. */ +struct grub_iso9660_susp_entry +{ + grub_uint8_t sig[2]; + grub_uint8_t len; + grub_uint8_t version; + grub_uint8_t data[0]; +} GRUB_PACKED; + +/* The CE entry. This is used to describe the next block where data + can be found. */ +struct grub_iso9660_susp_ce +{ + struct grub_iso9660_susp_entry entry; + grub_uint32_t blk; + grub_uint32_t blk_be; + grub_uint32_t off; + grub_uint32_t off_be; + grub_uint32_t len; + grub_uint32_t len_be; +} GRUB_PACKED; + +struct grub_iso9660_data +{ + struct grub_iso9660_primary_voldesc voldesc; + grub_disk_t disk; + int rockridge; + int susp_skip; + int joliet; + struct grub_fshelp_node *node; +}; + +struct grub_fshelp_node +{ + struct grub_iso9660_data *data; + grub_size_t have_dirents, alloc_dirents; + int have_symlink; + struct grub_iso9660_dir dirents[8]; + char symlink[0]; +}; + +enum + { + FLAG_TYPE_PLAIN = 0, + FLAG_TYPE_DIR = 2, + FLAG_TYPE = 3, + FLAG_MORE_EXTENTS = 0x80 + }; + +static grub_dl_t my_mod; + + +static grub_err_t +iso9660_to_unixtime (const struct grub_iso9660_date *i, grub_int32_t *nix) +{ + struct grub_datetime datetime; + + if (! i->year[0] && ! i->year[1] + && ! i->year[2] && ! i->year[3] + && ! i->month[0] && ! i->month[1] + && ! i->day[0] && ! i->day[1] + && ! i->hour[0] && ! i->hour[1] + && ! i->minute[0] && ! i->minute[1] + && ! i->second[0] && ! i->second[1] + && ! i->hundredth[0] && ! i->hundredth[1]) + return grub_error (GRUB_ERR_BAD_NUMBER, "empty date"); + datetime.year = (i->year[0] - '0') * 1000 + (i->year[1] - '0') * 100 + + (i->year[2] - '0') * 10 + (i->year[3] - '0'); + datetime.month = (i->month[0] - '0') * 10 + (i->month[1] - '0'); + datetime.day = (i->day[0] - '0') * 10 + (i->day[1] - '0'); + datetime.hour = (i->hour[0] - '0') * 10 + (i->hour[1] - '0'); + datetime.minute = (i->minute[0] - '0') * 10 + (i->minute[1] - '0'); + datetime.second = (i->second[0] - '0') * 10 + (i->second[1] - '0'); + + if (!grub_datetime2unixtime (&datetime, nix)) + return grub_error (GRUB_ERR_BAD_NUMBER, "incorrect date"); + *nix -= i->offset * 60 * 15; + return GRUB_ERR_NONE; +} + +static int +iso9660_to_unixtime2 (const struct grub_iso9660_date2 *i, grub_int32_t *nix) +{ + struct grub_datetime datetime; + + datetime.year = i->year + 1900; + datetime.month = i->month; + datetime.day = i->day; + datetime.hour = i->hour; + datetime.minute = i->minute; + datetime.second = i->second; + + if (!grub_datetime2unixtime (&datetime, nix)) + return 0; + *nix -= i->offset * 60 * 15; + return 1; +} + +static grub_err_t +read_node (grub_fshelp_node_t node, grub_off_t off, grub_size_t len, char *buf) +{ + grub_size_t i = 0; + + while (len > 0) + { + grub_size_t toread; + grub_err_t err; + while (i < node->have_dirents + && off >= grub_le_to_cpu32 (node->dirents[i].size)) + { + off -= grub_le_to_cpu32 (node->dirents[i].size); + i++; + } + if (i == node->have_dirents) + return grub_error (GRUB_ERR_OUT_OF_RANGE, "read out of range"); + toread = grub_le_to_cpu32 (node->dirents[i].size); + if (toread > len) + toread = len; + g_ventoy_last_read_pos = ((grub_disk_addr_t) grub_le_to_cpu32 (node->dirents[i].first_sector)) << GRUB_ISO9660_LOG2_BLKSZ; + g_ventoy_last_read_offset = off; + err = grub_disk_read (node->data->disk, g_ventoy_last_read_pos, off, toread, buf); + if (err) + return err; + len -= toread; + off += toread; + buf += toread; + } + return GRUB_ERR_NONE; +} + +/* Iterate over the susp entries, starting with block SUA_BLOCK on the + offset SUA_POS with a size of SUA_SIZE bytes. Hook is called for + every entry. */ +static grub_err_t +grub_iso9660_susp_iterate (grub_fshelp_node_t node, grub_off_t off, + grub_ssize_t sua_size, + grub_err_t (*hook) + (struct grub_iso9660_susp_entry *entry, void *hook_arg), + void *hook_arg) +{ + char *sua; + struct grub_iso9660_susp_entry *entry; + grub_err_t err; + + if (sua_size <= 0) + return GRUB_ERR_NONE; + + sua = grub_malloc (sua_size); + if (!sua) + return grub_errno; + + /* Load a part of the System Usage Area. */ + err = read_node (node, off, sua_size, sua); + if (err) + return err; + + for (entry = (struct grub_iso9660_susp_entry *) sua; (char *) entry < (char *) sua + sua_size - 1 && entry->len > 0; + entry = (struct grub_iso9660_susp_entry *) + ((char *) entry + entry->len)) + { + /* The last entry. */ + if (grub_strncmp ((char *) entry->sig, "ST", 2) == 0) + break; + + /* Additional entries are stored elsewhere. */ + if (grub_strncmp ((char *) entry->sig, "CE", 2) == 0) + { + struct grub_iso9660_susp_ce *ce; + grub_disk_addr_t ce_block; + + ce = (struct grub_iso9660_susp_ce *) entry; + sua_size = grub_le_to_cpu32 (ce->len); + off = grub_le_to_cpu32 (ce->off); + ce_block = grub_le_to_cpu32 (ce->blk) << GRUB_ISO9660_LOG2_BLKSZ; + + grub_free (sua); + sua = grub_malloc (sua_size); + if (!sua) + return grub_errno; + + /* Load a part of the System Usage Area. */ + err = grub_disk_read (node->data->disk, ce_block, off, + sua_size, sua); + if (err) + return err; + + entry = (struct grub_iso9660_susp_entry *) sua; + } + + if (hook (entry, hook_arg)) + { + grub_free (sua); + return 0; + } + } + + grub_free (sua); + return 0; +} + +static char * +grub_iso9660_convert_string (grub_uint8_t *us, int len) +{ + char *p; + int i; + grub_uint16_t t[MAX_NAMELEN / 2 + 1]; + + p = grub_malloc (len * GRUB_MAX_UTF8_PER_UTF16 + 1); + if (! p) + return NULL; + + for (i=0; isig, "ER", 2) == 0) + { + data->rockridge = 1; + return 1; + } + return 0; +} + +static grub_err_t +set_rockridge (struct grub_iso9660_data *data) +{ + int sua_pos; + int sua_size; + char *sua; + struct grub_iso9660_dir rootdir; + struct grub_iso9660_susp_entry *entry; + + data->rockridge = 0; + + /* Read the system use area and test it to see if SUSP is + supported. */ + if (grub_disk_read (data->disk, + (grub_le_to_cpu32 (data->voldesc.rootdir.first_sector) + << GRUB_ISO9660_LOG2_BLKSZ), 0, + sizeof (rootdir), (char *) &rootdir)) + return grub_error (GRUB_ERR_BAD_FS, "not a ISO9660 filesystem"); + + sua_pos = (sizeof (rootdir) + rootdir.namelen + + (rootdir.namelen % 2) - 1); + sua_size = rootdir.len - sua_pos; + + if (!sua_size) + return GRUB_ERR_NONE; + + sua = grub_malloc (sua_size); + if (! sua) + return grub_errno; + + if (grub_disk_read (data->disk, + (grub_le_to_cpu32 (data->voldesc.rootdir.first_sector) + << GRUB_ISO9660_LOG2_BLKSZ), sua_pos, + sua_size, sua)) + { + grub_free (sua); + return grub_error (GRUB_ERR_BAD_FS, "not a ISO9660 filesystem"); + } + + entry = (struct grub_iso9660_susp_entry *) sua; + + /* Test if the SUSP protocol is used on this filesystem. */ + if (grub_strncmp ((char *) entry->sig, "SP", 2) == 0) + { + struct grub_fshelp_node rootnode; + + rootnode.data = data; + rootnode.alloc_dirents = ARRAY_SIZE (rootnode.dirents); + rootnode.have_dirents = 1; + rootnode.have_symlink = 0; + rootnode.dirents[0] = data->voldesc.rootdir; + + /* The 2nd data byte stored how many bytes are skipped every time + to get to the SUA (System Usage Area). */ + data->susp_skip = entry->data[2]; + entry = (struct grub_iso9660_susp_entry *) ((char *) entry + entry->len); + + /* Iterate over the entries in the SUA area to detect + extensions. */ + if (grub_iso9660_susp_iterate (&rootnode, + sua_pos, sua_size, susp_iterate_set_rockridge, + data)) + { + grub_free (sua); + return grub_errno; + } + } + grub_free (sua); + return GRUB_ERR_NONE; +} + +static struct grub_iso9660_data * +grub_iso9660_mount (grub_disk_t disk) +{ + struct grub_iso9660_data *data = 0; + struct grub_iso9660_primary_voldesc voldesc; + int block; + + data = grub_zalloc (sizeof (struct grub_iso9660_data)); + if (! data) + return 0; + + data->disk = disk; + + block = 16; + do + { + int copy_voldesc = 0; + + /* Read the superblock. */ + if (grub_disk_read (disk, block << GRUB_ISO9660_LOG2_BLKSZ, 0, + sizeof (struct grub_iso9660_primary_voldesc), + (char *) &voldesc)) + { + grub_error (GRUB_ERR_BAD_FS, "not a ISO9660 filesystem"); + goto fail; + } + + if (grub_strncmp ((char *) voldesc.voldesc.magic, "CD001", 5) != 0) + { + grub_error (GRUB_ERR_BAD_FS, "not a ISO9660 filesystem"); + goto fail; + } + + if (voldesc.voldesc.type == GRUB_ISO9660_VOLDESC_PRIMARY) + copy_voldesc = 1; + else if (!data->rockridge + && (voldesc.voldesc.type == GRUB_ISO9660_VOLDESC_SUPP) + && (voldesc.escape[0] == 0x25) && (voldesc.escape[1] == 0x2f) + && + ((voldesc.escape[2] == 0x40) || /* UCS-2 Level 1. */ + (voldesc.escape[2] == 0x43) || /* UCS-2 Level 2. */ + (voldesc.escape[2] == 0x45))) /* UCS-2 Level 3. */ + { + copy_voldesc = 1; + data->joliet = 1; + } + + if (copy_voldesc) + { + grub_memcpy((char *) &data->voldesc, (char *) &voldesc, + sizeof (struct grub_iso9660_primary_voldesc)); + if (set_rockridge (data)) + goto fail; + } + + block++; + } while (voldesc.voldesc.type != GRUB_ISO9660_VOLDESC_END); + + return data; + + fail: + grub_free (data); + return 0; +} + + +static char * +grub_iso9660_read_symlink (grub_fshelp_node_t node) +{ + return node->have_symlink + ? grub_strdup (node->symlink + + (node->have_dirents) * sizeof (node->dirents[0]) + - sizeof (node->dirents)) : grub_strdup (""); +} + +static grub_off_t +get_node_size (grub_fshelp_node_t node) +{ + grub_off_t ret = 0; + grub_size_t i; + + for (i = 0; i < node->have_dirents; i++) + ret += grub_le_to_cpu32 (node->dirents[i].size); + return ret; +} + +struct iterate_dir_ctx +{ + char *filename; + int filename_alloc; + enum grub_fshelp_filetype type; + char *symlink; + int was_continue; +}; + + /* Extend the symlink. */ +static void +add_part (struct iterate_dir_ctx *ctx, + const char *part, + int len2) +{ + int size = ctx->symlink ? grub_strlen (ctx->symlink) : 0; + + ctx->symlink = grub_realloc (ctx->symlink, size + len2 + 1); + if (! ctx->symlink) + return; + + grub_memcpy (ctx->symlink + size, part, len2); + ctx->symlink[size + len2] = 0; +} + +static grub_err_t +susp_iterate_dir (struct grub_iso9660_susp_entry *entry, + void *_ctx) +{ + struct iterate_dir_ctx *ctx = _ctx; + + /* The filename in the rock ridge entry. */ + if (grub_strncmp ("NM", (char *) entry->sig, 2) == 0) + { + /* The flags are stored at the data position 0, here the + filename type is stored. */ + /* FIXME: Fix this slightly improper cast. */ + if (entry->data[0] & GRUB_ISO9660_RR_DOT) + ctx->filename = (char *) "."; + else if (entry->data[0] & GRUB_ISO9660_RR_DOTDOT) + ctx->filename = (char *) ".."; + else if (entry->len >= 5) + { + grub_size_t off = 0, csize = 1; + char *old; + csize = entry->len - 5; + old = ctx->filename; + if (ctx->filename_alloc) + { + off = grub_strlen (ctx->filename); + ctx->filename = grub_realloc (ctx->filename, csize + off + 1); + } + else + { + off = 0; + ctx->filename = grub_zalloc (csize + 1); + } + if (!ctx->filename) + { + ctx->filename = old; + return grub_errno; + } + ctx->filename_alloc = 1; + grub_memcpy (ctx->filename + off, (char *) &entry->data[1], csize); + ctx->filename[off + csize] = '\0'; + } + } + /* The mode information (st_mode). */ + else if (grub_strncmp ((char *) entry->sig, "PX", 2) == 0) + { + /* At position 0 of the PX record the st_mode information is + stored (little-endian). */ + grub_uint32_t mode = ((entry->data[0] + (entry->data[1] << 8)) + & GRUB_ISO9660_FSTYPE_MASK); + + switch (mode) + { + case GRUB_ISO9660_FSTYPE_DIR: + ctx->type = GRUB_FSHELP_DIR; + break; + case GRUB_ISO9660_FSTYPE_REG: + ctx->type = GRUB_FSHELP_REG; + break; + case GRUB_ISO9660_FSTYPE_SYMLINK: + ctx->type = GRUB_FSHELP_SYMLINK; + break; + default: + ctx->type = GRUB_FSHELP_UNKNOWN; + } + } + else if (grub_strncmp ("SL", (char *) entry->sig, 2) == 0) + { + unsigned int pos = 1; + + /* The symlink is not stored as a POSIX symlink, translate it. */ + while (pos + sizeof (*entry) < entry->len) + { + /* The current position is the `Component Flag'. */ + switch (entry->data[pos] & 30) + { + case 0: + { + /* The data on pos + 2 is the actual data, pos + 1 + is the length. Both are part of the `Component + Record'. */ + if (ctx->symlink && !ctx->was_continue) + add_part (ctx, "/", 1); + add_part (ctx, (char *) &entry->data[pos + 2], + entry->data[pos + 1]); + ctx->was_continue = (entry->data[pos] & 1); + break; + } + + case 2: + add_part (ctx, "./", 2); + break; + + case 4: + add_part (ctx, "../", 3); + break; + + case 8: + add_part (ctx, "/", 1); + break; + } + /* In pos + 1 the length of the `Component Record' is + stored. */ + pos += entry->data[pos + 1] + 2; + } + + /* Check if `grub_realloc' failed. */ + if (grub_errno) + return grub_errno; + } + + return 0; +} + +static int +grub_iso9660_iterate_dir (grub_fshelp_node_t dir, + grub_fshelp_iterate_dir_hook_t hook, void *hook_data) +{ + struct grub_iso9660_dir dirent; + grub_off_t offset = 0; + grub_off_t len; + struct iterate_dir_ctx ctx; + + len = get_node_size (dir); + + for (; offset < len; offset += dirent.len) + { + ctx.symlink = 0; + ctx.was_continue = 0; + + if (read_node (dir, offset, sizeof (dirent), (char *) &dirent)) + return 0; + + if ((dirent.flags & FLAG_TYPE) != FLAG_TYPE_DIR) { + g_ventoy_last_read_dirent_pos = g_ventoy_last_read_pos; + g_ventoy_last_read_dirent_offset = g_ventoy_last_read_offset; + } + + /* The end of the block, skip to the next one. */ + if (!dirent.len) + { + offset = (offset / GRUB_ISO9660_BLKSZ + 1) * GRUB_ISO9660_BLKSZ; + continue; + } + + { + char name[MAX_NAMELEN + 1]; + int nameoffset = offset + sizeof (dirent); + struct grub_fshelp_node *node; + int sua_off = (sizeof (dirent) + dirent.namelen + 1 + - (dirent.namelen % 2)); + int sua_size = dirent.len - sua_off; + + sua_off += offset + dir->data->susp_skip; + + ctx.filename = 0; + ctx.filename_alloc = 0; + ctx.type = GRUB_FSHELP_UNKNOWN; + + if (dir->data->rockridge + && grub_iso9660_susp_iterate (dir, sua_off, sua_size, + susp_iterate_dir, &ctx)) + return 0; + + /* Read the name. */ + if (read_node (dir, nameoffset, dirent.namelen, (char *) name)) + return 0; + + node = grub_malloc (sizeof (struct grub_fshelp_node)); + if (!node) + return 0; + + node->alloc_dirents = ARRAY_SIZE (node->dirents); + node->have_dirents = 1; + + /* Setup a new node. */ + node->data = dir->data; + node->have_symlink = 0; + + /* If the filetype was not stored using rockridge, use + whatever is stored in the iso9660 filesystem. */ + if (ctx.type == GRUB_FSHELP_UNKNOWN) + { + if ((dirent.flags & FLAG_TYPE) == FLAG_TYPE_DIR) + ctx.type = GRUB_FSHELP_DIR; + else + ctx.type = GRUB_FSHELP_REG; + } + + /* . and .. */ + if (!ctx.filename && dirent.namelen == 1 && name[0] == 0) + ctx.filename = (char *) "."; + + if (!ctx.filename && dirent.namelen == 1 && name[0] == 1) + ctx.filename = (char *) ".."; + + /* The filename was not stored in a rock ridge entry. Read it + from the iso9660 filesystem. */ + if (!dir->data->joliet && !ctx.filename) + { + char *ptr; + name[dirent.namelen] = '\0'; + ctx.filename = grub_strrchr (name, ';'); + if (ctx.filename) + *ctx.filename = '\0'; + /* ISO9660 names are not case-preserving. */ + ctx.type |= GRUB_FSHELP_CASE_INSENSITIVE; + for (ptr = name; *ptr; ptr++) + *ptr = grub_tolower (*ptr); + if (ptr != name && *(ptr - 1) == '.') + *(ptr - 1) = 0; + ctx.filename = name; + } + + if (dir->data->joliet && !ctx.filename) + { + char *semicolon; + + ctx.filename = grub_iso9660_convert_string + ((grub_uint8_t *) name, dirent.namelen >> 1); + + semicolon = grub_strrchr (ctx.filename, ';'); + if (semicolon) + *semicolon = '\0'; + + ctx.filename_alloc = 1; + } + + node->dirents[0] = dirent; + while (dirent.flags & FLAG_MORE_EXTENTS) + { + offset += dirent.len; + if (read_node (dir, offset, sizeof (dirent), (char *) &dirent)) + { + if (ctx.filename_alloc) + grub_free (ctx.filename); + grub_free (node); + return 0; + } + if (node->have_dirents >= node->alloc_dirents) + { + struct grub_fshelp_node *new_node; + node->alloc_dirents *= 2; + new_node = grub_realloc (node, + sizeof (struct grub_fshelp_node) + + ((node->alloc_dirents + - ARRAY_SIZE (node->dirents)) + * sizeof (node->dirents[0]))); + if (!new_node) + { + if (ctx.filename_alloc) + grub_free (ctx.filename); + grub_free (node); + return 0; + } + node = new_node; + } + node->dirents[node->have_dirents++] = dirent; + } + if (ctx.symlink) + { + if ((node->alloc_dirents - node->have_dirents) + * sizeof (node->dirents[0]) < grub_strlen (ctx.symlink) + 1) + { + struct grub_fshelp_node *new_node; + new_node = grub_realloc (node, + sizeof (struct grub_fshelp_node) + + ((node->alloc_dirents + - ARRAY_SIZE (node->dirents)) + * sizeof (node->dirents[0])) + + grub_strlen (ctx.symlink) + 1); + if (!new_node) + { + if (ctx.filename_alloc) + grub_free (ctx.filename); + grub_free (node); + return 0; + } + node = new_node; + } + node->have_symlink = 1; + grub_strcpy (node->symlink + + node->have_dirents * sizeof (node->dirents[0]) + - sizeof (node->dirents), ctx.symlink); + grub_free (ctx.symlink); + ctx.symlink = 0; + ctx.was_continue = 0; + } + if (hook (ctx.filename, ctx.type, node, hook_data)) + { + g_ventoy_last_file_dirent_pos = g_ventoy_last_read_dirent_pos; + g_ventoy_last_file_dirent_offset = g_ventoy_last_read_dirent_offset; + if (ctx.filename_alloc) + grub_free (ctx.filename); + return 1; + } + if (ctx.filename_alloc) + grub_free (ctx.filename); + } + } + + return 0; +} + + + +/* Context for grub_iso9660_dir. */ +struct grub_iso9660_dir_ctx +{ + grub_fs_dir_hook_t hook; + void *hook_data; +}; + +/* Helper for grub_iso9660_dir. */ +static int +grub_iso9660_dir_iter (const char *filename, + enum grub_fshelp_filetype filetype, + grub_fshelp_node_t node, void *data) +{ + struct grub_iso9660_dir_ctx *ctx = data; + struct grub_dirhook_info info; + + grub_memset (&info, 0, sizeof (info)); + info.dir = ((filetype & GRUB_FSHELP_TYPE_MASK) == GRUB_FSHELP_DIR); + info.mtimeset = !!iso9660_to_unixtime2 (&node->dirents[0].mtime, &info.mtime); + + grub_free (node); + return ctx->hook (filename, &info, ctx->hook_data); +} + +static grub_err_t +grub_iso9660_dir (grub_device_t device, const char *path, + grub_fs_dir_hook_t hook, void *hook_data) +{ + struct grub_iso9660_dir_ctx ctx = { hook, hook_data }; + struct grub_iso9660_data *data = 0; + struct grub_fshelp_node rootnode; + struct grub_fshelp_node *foundnode; + + grub_dl_ref (my_mod); + + data = grub_iso9660_mount (device->disk); + if (! data) + goto fail; + + rootnode.data = data; + rootnode.alloc_dirents = 0; + rootnode.have_dirents = 1; + rootnode.have_symlink = 0; + rootnode.dirents[0] = data->voldesc.rootdir; + + /* Use the fshelp function to traverse the path. */ + if (grub_fshelp_find_file (path, &rootnode, + &foundnode, + grub_iso9660_iterate_dir, + grub_iso9660_read_symlink, + GRUB_FSHELP_DIR)) + goto fail; + + /* List the files in the directory. */ + grub_iso9660_iterate_dir (foundnode, grub_iso9660_dir_iter, &ctx); + + if (foundnode != &rootnode) + grub_free (foundnode); + + fail: + grub_free (data); + + grub_dl_unref (my_mod); + + return grub_errno; +} + + +/* Open a file named NAME and initialize FILE. */ +static grub_err_t +grub_iso9660_open (struct grub_file *file, const char *name) +{ + struct grub_iso9660_data *data; + struct grub_fshelp_node rootnode; + struct grub_fshelp_node *foundnode; + + grub_dl_ref (my_mod); + + data = grub_iso9660_mount (file->device->disk); + if (!data) + goto fail; + + rootnode.data = data; + rootnode.alloc_dirents = 0; + rootnode.have_dirents = 1; + rootnode.have_symlink = 0; + rootnode.dirents[0] = data->voldesc.rootdir; + + /* Use the fshelp function to traverse the path. */ + if (grub_fshelp_find_file (name, &rootnode, + &foundnode, + grub_iso9660_iterate_dir, + grub_iso9660_read_symlink, + GRUB_FSHELP_REG)) + goto fail; + + data->node = foundnode; + file->data = data; + file->size = get_node_size (foundnode); + file->offset = 0; + + return 0; + + fail: + grub_dl_unref (my_mod); + + grub_free (data); + + return grub_errno; +} + + +static grub_ssize_t +grub_iso9660_read (grub_file_t file, char *buf, grub_size_t len) +{ + struct grub_iso9660_data *data = + (struct grub_iso9660_data *) file->data; + grub_err_t err; + + /* XXX: The file is stored in as a single extent. */ + data->disk->read_hook = file->read_hook; + data->disk->read_hook_data = file->read_hook_data; + err = read_node (data->node, file->offset, len, buf); + data->disk->read_hook = NULL; + + if (err || grub_errno) + return -1; + + return len; +} + + +static grub_err_t +grub_iso9660_close (grub_file_t file) +{ + struct grub_iso9660_data *data = + (struct grub_iso9660_data *) file->data; + grub_free (data->node); + grub_free (data); + + grub_dl_unref (my_mod); + + return GRUB_ERR_NONE; +} + + +static grub_err_t +grub_iso9660_label (grub_device_t device, char **label) +{ + struct grub_iso9660_data *data; + data = grub_iso9660_mount (device->disk); + + if (data) + { + if (data->joliet) + *label = grub_iso9660_convert_string (data->voldesc.volname, 16); + else + *label = grub_strndup ((char *) data->voldesc.volname, 32); + if (*label) + { + char *ptr; + for (ptr = *label; *ptr;ptr++); + ptr--; + while (ptr >= *label && *ptr == ' ') + *ptr-- = 0; + } + + grub_free (data); + } + else + *label = 0; + + return grub_errno; +} + + +static grub_err_t +grub_iso9660_uuid (grub_device_t device, char **uuid) +{ + struct grub_iso9660_data *data; + grub_disk_t disk = device->disk; + + grub_dl_ref (my_mod); + + data = grub_iso9660_mount (disk); + if (data) + { + if (! data->voldesc.modified.year[0] && ! data->voldesc.modified.year[1] + && ! data->voldesc.modified.year[2] && ! data->voldesc.modified.year[3] + && ! data->voldesc.modified.month[0] && ! data->voldesc.modified.month[1] + && ! data->voldesc.modified.day[0] && ! data->voldesc.modified.day[1] + && ! data->voldesc.modified.hour[0] && ! data->voldesc.modified.hour[1] + && ! data->voldesc.modified.minute[0] && ! data->voldesc.modified.minute[1] + && ! data->voldesc.modified.second[0] && ! data->voldesc.modified.second[1] + && ! data->voldesc.modified.hundredth[0] && ! data->voldesc.modified.hundredth[1]) + { + grub_error (GRUB_ERR_BAD_NUMBER, "no creation date in filesystem to generate UUID"); + *uuid = NULL; + } + else + { + *uuid = grub_xasprintf ("%c%c%c%c-%c%c-%c%c-%c%c-%c%c-%c%c-%c%c", + data->voldesc.modified.year[0], + data->voldesc.modified.year[1], + data->voldesc.modified.year[2], + data->voldesc.modified.year[3], + data->voldesc.modified.month[0], + data->voldesc.modified.month[1], + data->voldesc.modified.day[0], + data->voldesc.modified.day[1], + data->voldesc.modified.hour[0], + data->voldesc.modified.hour[1], + data->voldesc.modified.minute[0], + data->voldesc.modified.minute[1], + data->voldesc.modified.second[0], + data->voldesc.modified.second[1], + data->voldesc.modified.hundredth[0], + data->voldesc.modified.hundredth[1]); + } + } + else + *uuid = NULL; + + grub_dl_unref (my_mod); + + grub_free (data); + + return grub_errno; +} + +/* Get writing time of filesystem. */ +static grub_err_t +grub_iso9660_mtime (grub_device_t device, grub_int32_t *timebuf) +{ + struct grub_iso9660_data *data; + grub_disk_t disk = device->disk; + grub_err_t err; + + grub_dl_ref (my_mod); + + data = grub_iso9660_mount (disk); + if (!data) + { + grub_dl_unref (my_mod); + return grub_errno; + } + err = iso9660_to_unixtime (&data->voldesc.modified, timebuf); + + grub_dl_unref (my_mod); + + grub_free (data); + + return err; +} + +grub_uint64_t grub_iso9660_get_last_read_pos(grub_file_t file) +{ + (void)file; + return (g_ventoy_last_read_pos << GRUB_DISK_SECTOR_BITS); +} + +grub_uint64_t grub_iso9660_get_last_file_dirent_pos(grub_file_t file) +{ + (void)file; + return (g_ventoy_last_file_dirent_pos << GRUB_DISK_SECTOR_BITS) + g_ventoy_last_file_dirent_offset; +} + +static struct grub_fs grub_iso9660_fs = + { + .name = "iso9660", + .fs_dir = grub_iso9660_dir, + .fs_open = grub_iso9660_open, + .fs_read = grub_iso9660_read, + .fs_close = grub_iso9660_close, + .fs_label = grub_iso9660_label, + .fs_uuid = grub_iso9660_uuid, + .fs_mtime = grub_iso9660_mtime, +#ifdef GRUB_UTIL + .reserved_first_sector = 1, + .blocklist_install = 1, +#endif + .next = 0 + }; + +GRUB_MOD_INIT(iso9660) +{ + grub_fs_register (&grub_iso9660_fs); + my_mod = mod; +} + +GRUB_MOD_FINI(iso9660) +{ + grub_fs_unregister (&grub_iso9660_fs); +} diff --git a/GRUB2/grub-2.04/grub-core/fs/udf.c b/GRUB2/grub-2.04/grub-core/fs/udf.c new file mode 100644 index 00000000..c5ea54e4 --- /dev/null +++ b/GRUB2/grub-2.04/grub-core/fs/udf.c @@ -0,0 +1,1437 @@ +/* udf.c - Universal Disk Format filesystem. */ +/* + * GRUB -- GRand Unified Bootloader + * Copyright (C) 2008,2009 Free Software Foundation, Inc. + * + * GRUB is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GRUB is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with GRUB. If not, see . + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +GRUB_MOD_LICENSE ("GPLv3+"); + +#define OFFSET_OF(TYPE, MEMBER) ((grub_size_t) &((TYPE *)0)->MEMBER) + +grub_uint32_t g_last_disk_read_sector = 0; +grub_uint32_t g_last_fe_tag_ident = 0; +grub_uint32_t g_last_icb_read_sector = 0; +grub_uint32_t g_last_icb_read_sector_tag_ident = 0; +grub_uint32_t g_last_fileattr_read_sector = 0; +grub_uint32_t g_last_fileattr_read_sector_tag_ident = 0; +grub_uint32_t g_last_fileattr_offset = 0; +grub_uint64_t g_last_pd_length_offset = 0; + +#define GRUB_UDF_MAX_PDS 2 +#define GRUB_UDF_MAX_PMS 6 + +#define U16 grub_le_to_cpu16 +#define U32 grub_le_to_cpu32 +#define U64 grub_le_to_cpu64 + +#define GRUB_UDF_TAG_IDENT_PVD 0x0001 +#define GRUB_UDF_TAG_IDENT_AVDP 0x0002 +#define GRUB_UDF_TAG_IDENT_VDP 0x0003 +#define GRUB_UDF_TAG_IDENT_IUVD 0x0004 +#define GRUB_UDF_TAG_IDENT_PD 0x0005 +#define GRUB_UDF_TAG_IDENT_LVD 0x0006 +#define GRUB_UDF_TAG_IDENT_USD 0x0007 +#define GRUB_UDF_TAG_IDENT_TD 0x0008 +#define GRUB_UDF_TAG_IDENT_LVID 0x0009 + +#define GRUB_UDF_TAG_IDENT_FSD 0x0100 +#define GRUB_UDF_TAG_IDENT_FID 0x0101 +#define GRUB_UDF_TAG_IDENT_AED 0x0102 +#define GRUB_UDF_TAG_IDENT_IE 0x0103 +#define GRUB_UDF_TAG_IDENT_TE 0x0104 +#define GRUB_UDF_TAG_IDENT_FE 0x0105 +#define GRUB_UDF_TAG_IDENT_EAHD 0x0106 +#define GRUB_UDF_TAG_IDENT_USE 0x0107 +#define GRUB_UDF_TAG_IDENT_SBD 0x0108 +#define GRUB_UDF_TAG_IDENT_PIE 0x0109 +#define GRUB_UDF_TAG_IDENT_EFE 0x010A + +#define GRUB_UDF_ICBTAG_TYPE_UNDEF 0x00 +#define GRUB_UDF_ICBTAG_TYPE_USE 0x01 +#define GRUB_UDF_ICBTAG_TYPE_PIE 0x02 +#define GRUB_UDF_ICBTAG_TYPE_IE 0x03 +#define GRUB_UDF_ICBTAG_TYPE_DIRECTORY 0x04 +#define GRUB_UDF_ICBTAG_TYPE_REGULAR 0x05 +#define GRUB_UDF_ICBTAG_TYPE_BLOCK 0x06 +#define GRUB_UDF_ICBTAG_TYPE_CHAR 0x07 +#define GRUB_UDF_ICBTAG_TYPE_EA 0x08 +#define GRUB_UDF_ICBTAG_TYPE_FIFO 0x09 +#define GRUB_UDF_ICBTAG_TYPE_SOCKET 0x0A +#define GRUB_UDF_ICBTAG_TYPE_TE 0x0B +#define GRUB_UDF_ICBTAG_TYPE_SYMLINK 0x0C +#define GRUB_UDF_ICBTAG_TYPE_STREAMDIR 0x0D + +#define GRUB_UDF_ICBTAG_FLAG_AD_MASK 0x0007 +#define GRUB_UDF_ICBTAG_FLAG_AD_SHORT 0x0000 +#define GRUB_UDF_ICBTAG_FLAG_AD_LONG 0x0001 +#define GRUB_UDF_ICBTAG_FLAG_AD_EXT 0x0002 +#define GRUB_UDF_ICBTAG_FLAG_AD_IN_ICB 0x0003 + +#define GRUB_UDF_EXT_NORMAL 0x00000000 +#define GRUB_UDF_EXT_NREC_ALLOC 0x40000000 +#define GRUB_UDF_EXT_NREC_NALLOC 0x80000000 +#define GRUB_UDF_EXT_MASK 0xC0000000 + +#define GRUB_UDF_FID_CHAR_HIDDEN 0x01 +#define GRUB_UDF_FID_CHAR_DIRECTORY 0x02 +#define GRUB_UDF_FID_CHAR_DELETED 0x04 +#define GRUB_UDF_FID_CHAR_PARENT 0x08 +#define GRUB_UDF_FID_CHAR_METADATA 0x10 + +#define GRUB_UDF_STD_IDENT_BEA01 "BEA01" +#define GRUB_UDF_STD_IDENT_BOOT2 "BOOT2" +#define GRUB_UDF_STD_IDENT_CD001 "CD001" +#define GRUB_UDF_STD_IDENT_CDW02 "CDW02" +#define GRUB_UDF_STD_IDENT_NSR02 "NSR02" +#define GRUB_UDF_STD_IDENT_NSR03 "NSR03" +#define GRUB_UDF_STD_IDENT_TEA01 "TEA01" + +#define GRUB_UDF_CHARSPEC_TYPE_CS0 0x00 +#define GRUB_UDF_CHARSPEC_TYPE_CS1 0x01 +#define GRUB_UDF_CHARSPEC_TYPE_CS2 0x02 +#define GRUB_UDF_CHARSPEC_TYPE_CS3 0x03 +#define GRUB_UDF_CHARSPEC_TYPE_CS4 0x04 +#define GRUB_UDF_CHARSPEC_TYPE_CS5 0x05 +#define GRUB_UDF_CHARSPEC_TYPE_CS6 0x06 +#define GRUB_UDF_CHARSPEC_TYPE_CS7 0x07 +#define GRUB_UDF_CHARSPEC_TYPE_CS8 0x08 + +#define GRUB_UDF_PARTMAP_TYPE_1 1 +#define GRUB_UDF_PARTMAP_TYPE_2 2 + +struct grub_udf_lb_addr +{ + grub_uint32_t block_num; + grub_uint16_t part_ref; +} GRUB_PACKED; + +struct grub_udf_short_ad +{ + grub_uint32_t length; + grub_uint32_t position; +} GRUB_PACKED; + +struct grub_udf_long_ad +{ + grub_uint32_t length; + struct grub_udf_lb_addr block; + grub_uint8_t imp_use[6]; +} GRUB_PACKED; + +struct grub_udf_extent_ad +{ + grub_uint32_t length; + grub_uint32_t start; +} GRUB_PACKED; + +struct grub_udf_charspec +{ + grub_uint8_t charset_type; + grub_uint8_t charset_info[63]; +} GRUB_PACKED; + +struct grub_udf_timestamp +{ + grub_uint16_t type_and_timezone; + grub_uint16_t year; + grub_uint8_t month; + grub_uint8_t day; + grub_uint8_t hour; + grub_uint8_t minute; + grub_uint8_t second; + grub_uint8_t centi_seconds; + grub_uint8_t hundreds_of_micro_seconds; + grub_uint8_t micro_seconds; +} GRUB_PACKED; + +struct grub_udf_regid +{ + grub_uint8_t flags; + grub_uint8_t ident[23]; + grub_uint8_t ident_suffix[8]; +} GRUB_PACKED; + +struct grub_udf_tag +{ + grub_uint16_t tag_ident; + grub_uint16_t desc_version; + grub_uint8_t tag_checksum; + grub_uint8_t reserved; + grub_uint16_t tag_serial_number; + grub_uint16_t desc_crc; + grub_uint16_t desc_crc_length; + grub_uint32_t tag_location; +} GRUB_PACKED; + +struct grub_udf_fileset +{ + struct grub_udf_tag tag; + struct grub_udf_timestamp datetime; + grub_uint16_t interchange_level; + grub_uint16_t max_interchange_level; + grub_uint32_t charset_list; + grub_uint32_t max_charset_list; + grub_uint32_t fileset_num; + grub_uint32_t fileset_desc_num; + struct grub_udf_charspec vol_charset; + grub_uint8_t vol_ident[128]; + struct grub_udf_charspec fileset_charset; + grub_uint8_t fileset_ident[32]; + grub_uint8_t copyright_file_ident[32]; + grub_uint8_t abstract_file_ident[32]; + struct grub_udf_long_ad root_icb; + struct grub_udf_regid domain_ident; + struct grub_udf_long_ad next_ext; + struct grub_udf_long_ad streamdir_icb; +} GRUB_PACKED; + +struct grub_udf_icbtag +{ + grub_uint32_t prior_recorded_num_direct_entries; + grub_uint16_t strategy_type; + grub_uint16_t strategy_parameter; + grub_uint16_t num_entries; + grub_uint8_t reserved; + grub_uint8_t file_type; + struct grub_udf_lb_addr parent_idb; + grub_uint16_t flags; +} GRUB_PACKED; + +struct grub_udf_file_ident +{ + struct grub_udf_tag tag; + grub_uint16_t version_num; + grub_uint8_t characteristics; +#define MAX_FILE_IDENT_LENGTH 256 + grub_uint8_t file_ident_length; + struct grub_udf_long_ad icb; + grub_uint16_t imp_use_length; +} GRUB_PACKED; + +struct grub_udf_file_entry +{ + struct grub_udf_tag tag; + struct grub_udf_icbtag icbtag; + grub_uint32_t uid; + grub_uint32_t gid; + grub_uint32_t permissions; + grub_uint16_t link_count; + grub_uint8_t record_format; + grub_uint8_t record_display_attr; + grub_uint32_t record_length; + grub_uint64_t file_size; + grub_uint64_t blocks_recorded; + struct grub_udf_timestamp access_time; + struct grub_udf_timestamp modification_time; + struct grub_udf_timestamp attr_time; + grub_uint32_t checkpoint; + struct grub_udf_long_ad extended_attr_idb; + struct grub_udf_regid imp_ident; + grub_uint64_t unique_id; + grub_uint32_t ext_attr_length; + grub_uint32_t alloc_descs_length; + grub_uint8_t ext_attr[0]; +} GRUB_PACKED; + +struct grub_udf_extended_file_entry +{ + struct grub_udf_tag tag; + struct grub_udf_icbtag icbtag; + grub_uint32_t uid; + grub_uint32_t gid; + grub_uint32_t permissions; + grub_uint16_t link_count; + grub_uint8_t record_format; + grub_uint8_t record_display_attr; + grub_uint32_t record_length; + grub_uint64_t file_size; + grub_uint64_t object_size; + grub_uint64_t blocks_recorded; + struct grub_udf_timestamp access_time; + struct grub_udf_timestamp modification_time; + struct grub_udf_timestamp create_time; + struct grub_udf_timestamp attr_time; + grub_uint32_t checkpoint; + grub_uint32_t reserved; + struct grub_udf_long_ad extended_attr_icb; + struct grub_udf_long_ad streamdir_icb; + struct grub_udf_regid imp_ident; + grub_uint64_t unique_id; + grub_uint32_t ext_attr_length; + grub_uint32_t alloc_descs_length; + grub_uint8_t ext_attr[0]; +} GRUB_PACKED; + +struct grub_udf_vrs +{ + grub_uint8_t type; + grub_uint8_t magic[5]; + grub_uint8_t version; +} GRUB_PACKED; + +struct grub_udf_avdp +{ + struct grub_udf_tag tag; + struct grub_udf_extent_ad vds; +} GRUB_PACKED; + +struct grub_udf_pd +{ + struct grub_udf_tag tag; + grub_uint32_t seq_num; + grub_uint16_t flags; + grub_uint16_t part_num; + struct grub_udf_regid contents; + grub_uint8_t contents_use[128]; + grub_uint32_t access_type; + grub_uint32_t start; + grub_uint32_t length; +} GRUB_PACKED; + +struct grub_udf_partmap +{ + grub_uint8_t type; + grub_uint8_t length; + union + { + struct + { + grub_uint16_t seq_num; + grub_uint16_t part_num; + } type1; + + struct + { + grub_uint8_t ident[62]; + } type2; + }; +} GRUB_PACKED; + +struct grub_udf_pvd +{ + struct grub_udf_tag tag; + grub_uint32_t seq_num; + grub_uint32_t pvd_num; + grub_uint8_t ident[32]; + grub_uint16_t vol_seq_num; + grub_uint16_t max_vol_seq_num; + grub_uint16_t interchange_level; + grub_uint16_t max_interchange_level; + grub_uint32_t charset_list; + grub_uint32_t max_charset_list; + grub_uint8_t volset_ident[128]; + struct grub_udf_charspec desc_charset; + struct grub_udf_charspec expl_charset; + struct grub_udf_extent_ad vol_abstract; + struct grub_udf_extent_ad vol_copyright; + struct grub_udf_regid app_ident; + struct grub_udf_timestamp recording_time; + struct grub_udf_regid imp_ident; + grub_uint8_t imp_use[64]; + grub_uint32_t pred_vds_loc; + grub_uint16_t flags; + grub_uint8_t reserved[22]; +} GRUB_PACKED; + +struct grub_udf_lvd +{ + struct grub_udf_tag tag; + grub_uint32_t seq_num; + struct grub_udf_charspec charset; + grub_uint8_t ident[128]; + grub_uint32_t bsize; + struct grub_udf_regid domain_ident; + struct grub_udf_long_ad root_fileset; + grub_uint32_t map_table_length; + grub_uint32_t num_part_maps; + struct grub_udf_regid imp_ident; + grub_uint8_t imp_use[128]; + struct grub_udf_extent_ad integrity_seq_ext; + grub_uint8_t part_maps[1608]; +} GRUB_PACKED; + +struct grub_udf_aed +{ + struct grub_udf_tag tag; + grub_uint32_t prev_ae; + grub_uint32_t ae_len; +} GRUB_PACKED; + +struct grub_udf_data +{ + grub_disk_t disk; + struct grub_udf_pvd pvd; + struct grub_udf_lvd lvd; + struct grub_udf_pd pds[GRUB_UDF_MAX_PDS]; + struct grub_udf_partmap *pms[GRUB_UDF_MAX_PMS]; + struct grub_udf_long_ad root_icb; + int npd, npm, lbshift; +}; + +struct grub_fshelp_node +{ + struct grub_udf_data *data; + int part_ref; + union + { + struct grub_udf_file_entry fe; + struct grub_udf_extended_file_entry efe; + char raw[0]; + } block; +}; + +static inline grub_size_t +get_fshelp_size (struct grub_udf_data *data) +{ + struct grub_fshelp_node *x = NULL; + return sizeof (*x) + + (1 << (GRUB_DISK_SECTOR_BITS + + data->lbshift)) - sizeof (x->block); +} + +static grub_dl_t my_mod; + +static grub_uint32_t +grub_udf_get_block (struct grub_udf_data *data, + grub_uint16_t part_ref, grub_uint32_t block) +{ + part_ref = U16 (part_ref); + + if (part_ref >= data->npm) + { + grub_error (GRUB_ERR_BAD_FS, "invalid part ref"); + return 0; + } + + return (U32 (data->pds[data->pms[part_ref]->type1.part_num].start) + + U32 (block)); +} + +static grub_err_t +grub_udf_read_icb (struct grub_udf_data *data, + struct grub_udf_long_ad *icb, + struct grub_fshelp_node *node) +{ + grub_uint32_t block; + + block = grub_udf_get_block (data, + icb->block.part_ref, + icb->block.block_num); + + if (grub_errno) + return grub_errno; + + if (grub_disk_read (data->disk, block << data->lbshift, 0, + 1 << (GRUB_DISK_SECTOR_BITS + + data->lbshift), + &node->block)) + return grub_errno; + + g_last_disk_read_sector = block; + g_last_fe_tag_ident = U16(node->block.fe.tag.tag_ident); + + if ((U16 (node->block.fe.tag.tag_ident) != GRUB_UDF_TAG_IDENT_FE) && + (U16 (node->block.fe.tag.tag_ident) != GRUB_UDF_TAG_IDENT_EFE)) + return grub_error (GRUB_ERR_BAD_FS, "invalid fe/efe descriptor"); + + node->part_ref = icb->block.part_ref; + node->data = data; + return 0; +} + +static grub_disk_addr_t +grub_udf_read_block (grub_fshelp_node_t node, grub_disk_addr_t fileblock) +{ + char *buf = NULL; + char *ptr; + grub_ssize_t len; + grub_disk_addr_t filebytes; + + switch (U16 (node->block.fe.tag.tag_ident)) + { + case GRUB_UDF_TAG_IDENT_FE: + ptr = (char *) &node->block.fe.ext_attr[0] + U32 (node->block.fe.ext_attr_length); + len = U32 (node->block.fe.alloc_descs_length); + break; + + case GRUB_UDF_TAG_IDENT_EFE: + ptr = (char *) &node->block.efe.ext_attr[0] + U32 (node->block.efe.ext_attr_length); + len = U32 (node->block.efe.alloc_descs_length); + break; + + default: + grub_error (GRUB_ERR_BAD_FS, "invalid file entry"); + return 0; + } + + if ((U16 (node->block.fe.icbtag.flags) & GRUB_UDF_ICBTAG_FLAG_AD_MASK) + == GRUB_UDF_ICBTAG_FLAG_AD_SHORT) + { + struct grub_udf_short_ad *ad = (struct grub_udf_short_ad *) ptr; + + filebytes = fileblock * U32 (node->data->lvd.bsize); + while (len >= (grub_ssize_t) sizeof (struct grub_udf_short_ad)) + { + grub_uint32_t adlen = U32 (ad->length) & 0x3fffffff; + grub_uint32_t adtype = U32 (ad->length) >> 30; + if (adtype == 3) + { + struct grub_udf_aed *extension; + grub_disk_addr_t sec = grub_udf_get_block(node->data, + node->part_ref, + ad->position); + if (!buf) + { + buf = grub_malloc (U32 (node->data->lvd.bsize)); + if (!buf) + return 0; + } + if (grub_disk_read (node->data->disk, sec << node->data->lbshift, + 0, adlen, buf)) + goto fail; + + extension = (struct grub_udf_aed *) buf; + if (U16 (extension->tag.tag_ident) != GRUB_UDF_TAG_IDENT_AED) + { + grub_error (GRUB_ERR_BAD_FS, "invalid aed tag"); + goto fail; + } + + len = U32 (extension->ae_len); + ad = (struct grub_udf_short_ad *) + (buf + sizeof (struct grub_udf_aed)); + continue; + } + + if (filebytes < adlen) + { + grub_uint32_t ad_pos = ad->position; + grub_free (buf); + return ((U32 (ad_pos) & GRUB_UDF_EXT_MASK) ? 0 : + (grub_udf_get_block (node->data, node->part_ref, ad_pos) + + (filebytes >> (GRUB_DISK_SECTOR_BITS + + node->data->lbshift)))); + } + + filebytes -= adlen; + ad++; + len -= sizeof (struct grub_udf_short_ad); + } + } + else + { + struct grub_udf_long_ad *ad = (struct grub_udf_long_ad *) ptr; + + filebytes = fileblock * U32 (node->data->lvd.bsize); + while (len >= (grub_ssize_t) sizeof (struct grub_udf_long_ad)) + { + grub_uint32_t adlen = U32 (ad->length) & 0x3fffffff; + grub_uint32_t adtype = U32 (ad->length) >> 30; + if (adtype == 3) + { + struct grub_udf_aed *extension; + grub_disk_addr_t sec = grub_udf_get_block(node->data, + ad->block.part_ref, + ad->block.block_num); + if (!buf) + { + buf = grub_malloc (U32 (node->data->lvd.bsize)); + if (!buf) + return 0; + } + if (grub_disk_read (node->data->disk, sec << node->data->lbshift, + 0, adlen, buf)) + goto fail; + + extension = (struct grub_udf_aed *) buf; + if (U16 (extension->tag.tag_ident) != GRUB_UDF_TAG_IDENT_AED) + { + grub_error (GRUB_ERR_BAD_FS, "invalid aed tag"); + goto fail; + } + + len = U32 (extension->ae_len); + ad = (struct grub_udf_long_ad *) + (buf + sizeof (struct grub_udf_aed)); + continue; + } + + if (filebytes < adlen) + { + grub_uint32_t ad_block_num = ad->block.block_num; + grub_uint32_t ad_part_ref = ad->block.part_ref; + grub_free (buf); + return ((U32 (ad_block_num) & GRUB_UDF_EXT_MASK) ? 0 : + (grub_udf_get_block (node->data, ad_part_ref, + ad_block_num) + + (filebytes >> (GRUB_DISK_SECTOR_BITS + + node->data->lbshift)))); + } + + filebytes -= adlen; + ad++; + len -= sizeof (struct grub_udf_long_ad); + } + } + +fail: + grub_free (buf); + + return 0; +} + +static grub_ssize_t +grub_udf_read_file (grub_fshelp_node_t node, + grub_disk_read_hook_t read_hook, void *read_hook_data, + grub_off_t pos, grub_size_t len, char *buf) +{ + switch (U16 (node->block.fe.icbtag.flags) & GRUB_UDF_ICBTAG_FLAG_AD_MASK) + { + case GRUB_UDF_ICBTAG_FLAG_AD_IN_ICB: + { + char *ptr; + + ptr = ((U16 (node->block.fe.tag.tag_ident) == GRUB_UDF_TAG_IDENT_FE) ? + ((char *) &node->block.fe.ext_attr[0] + + U32 (node->block.fe.ext_attr_length)) : + ((char *) &node->block.efe.ext_attr[0] + + U32 (node->block.efe.ext_attr_length))); + + grub_memcpy (buf, ptr + pos, len); + + return len; + } + + case GRUB_UDF_ICBTAG_FLAG_AD_EXT: + grub_error (GRUB_ERR_BAD_FS, "invalid extent type"); + return 0; + } + + return grub_fshelp_read_file (node->data->disk, node, + read_hook, read_hook_data, + pos, len, buf, grub_udf_read_block, + U64 (node->block.fe.file_size), + node->data->lbshift, 0); +} + +static unsigned sblocklist[] = { 256, 512, 0 }; + +static struct grub_udf_data * +grub_udf_mount (grub_disk_t disk) +{ + struct grub_udf_data *data = 0; + struct grub_udf_fileset root_fs; + unsigned *sblklist; + grub_uint32_t block, vblock; + int i, lbshift; + + data = grub_malloc (sizeof (struct grub_udf_data)); + if (!data) + return 0; + + data->disk = disk; + + /* Search for Anchor Volume Descriptor Pointer (AVDP) + * and determine logical block size. */ + block = 0; + for (lbshift = 0; lbshift < 4; lbshift++) + { + for (sblklist = sblocklist; *sblklist; sblklist++) + { + struct grub_udf_avdp avdp; + + if (grub_disk_read (disk, *sblklist << lbshift, 0, + sizeof (struct grub_udf_avdp), &avdp)) + { + grub_error (GRUB_ERR_BAD_FS, "not an UDF filesystem"); + goto fail; + } + + if (U16 (avdp.tag.tag_ident) == GRUB_UDF_TAG_IDENT_AVDP && + U32 (avdp.tag.tag_location) == *sblklist) + { + block = U32 (avdp.vds.start); + break; + } + } + + if (block) + break; + } + + if (!block) + { + grub_error (GRUB_ERR_BAD_FS, "not an UDF filesystem"); + goto fail; + } + data->lbshift = lbshift; + + /* Search for Volume Recognition Sequence (VRS). */ + for (vblock = (32767 >> (lbshift + GRUB_DISK_SECTOR_BITS)) + 1;; + vblock += (2047 >> (lbshift + GRUB_DISK_SECTOR_BITS)) + 1) + { + struct grub_udf_vrs vrs; + + if (grub_disk_read (disk, vblock << lbshift, 0, + sizeof (struct grub_udf_vrs), &vrs)) + { + grub_error (GRUB_ERR_BAD_FS, "not an UDF filesystem"); + goto fail; + } + + if ((!grub_memcmp (vrs.magic, GRUB_UDF_STD_IDENT_NSR03, 5)) || + (!grub_memcmp (vrs.magic, GRUB_UDF_STD_IDENT_NSR02, 5))) + break; + + if ((grub_memcmp (vrs.magic, GRUB_UDF_STD_IDENT_BEA01, 5)) && + (grub_memcmp (vrs.magic, GRUB_UDF_STD_IDENT_BOOT2, 5)) && + (grub_memcmp (vrs.magic, GRUB_UDF_STD_IDENT_CD001, 5)) && + (grub_memcmp (vrs.magic, GRUB_UDF_STD_IDENT_CDW02, 5)) && + (grub_memcmp (vrs.magic, GRUB_UDF_STD_IDENT_TEA01, 5))) + { + grub_error (GRUB_ERR_BAD_FS, "not an UDF filesystem"); + goto fail; + } + } + + data->npd = data->npm = 0; + /* Locate Partition Descriptor (PD) and Logical Volume Descriptor (LVD). */ + while (1) + { + struct grub_udf_tag tag; + + if (grub_disk_read (disk, block << lbshift, 0, + sizeof (struct grub_udf_tag), &tag)) + { + grub_error (GRUB_ERR_BAD_FS, "not an UDF filesystem"); + goto fail; + } + + tag.tag_ident = U16 (tag.tag_ident); + if (tag.tag_ident == GRUB_UDF_TAG_IDENT_PVD) + { + if (grub_disk_read (disk, block << lbshift, 0, + sizeof (struct grub_udf_pvd), + &data->pvd)) + { + grub_error (GRUB_ERR_BAD_FS, "not an UDF filesystem"); + goto fail; + } + } + else if (tag.tag_ident == GRUB_UDF_TAG_IDENT_PD) + { + if (data->npd >= GRUB_UDF_MAX_PDS) + { + grub_error (GRUB_ERR_BAD_FS, "too many PDs"); + goto fail; + } + + if (grub_disk_read (disk, block << lbshift, 0, + sizeof (struct grub_udf_pd), + &data->pds[data->npd])) + { + grub_error (GRUB_ERR_BAD_FS, "not an UDF filesystem"); + goto fail; + } + + g_last_pd_length_offset = (block << lbshift) * 512 + OFFSET_OF(struct grub_udf_pd, length); + + data->npd++; + } + else if (tag.tag_ident == GRUB_UDF_TAG_IDENT_LVD) + { + int k; + + struct grub_udf_partmap *ppm; + + if (grub_disk_read (disk, block << lbshift, 0, + sizeof (struct grub_udf_lvd), + &data->lvd)) + { + grub_error (GRUB_ERR_BAD_FS, "not an UDF filesystem"); + goto fail; + } + + if (data->npm + U32 (data->lvd.num_part_maps) > GRUB_UDF_MAX_PMS) + { + grub_error (GRUB_ERR_BAD_FS, "too many partition maps"); + goto fail; + } + + ppm = (struct grub_udf_partmap *) &data->lvd.part_maps; + for (k = U32 (data->lvd.num_part_maps); k > 0; k--) + { + if (ppm->type != GRUB_UDF_PARTMAP_TYPE_1) + { + grub_error (GRUB_ERR_BAD_FS, "partmap type not supported"); + goto fail; + } + + data->pms[data->npm++] = ppm; + ppm = (struct grub_udf_partmap *) ((char *) ppm + + U32 (ppm->length)); + } + } + else if (tag.tag_ident > GRUB_UDF_TAG_IDENT_TD) + { + grub_error (GRUB_ERR_BAD_FS, "invalid tag ident"); + goto fail; + } + else if (tag.tag_ident == GRUB_UDF_TAG_IDENT_TD) + break; + + block++; + } + + for (i = 0; i < data->npm; i++) + { + int j; + + for (j = 0; j < data->npd; j++) + if (data->pms[i]->type1.part_num == data->pds[j].part_num) + { + data->pms[i]->type1.part_num = j; + break; + } + + if (j == data->npd) + { + grub_error (GRUB_ERR_BAD_FS, "can\'t find PD"); + goto fail; + } + } + + block = grub_udf_get_block (data, + data->lvd.root_fileset.block.part_ref, + data->lvd.root_fileset.block.block_num); + + if (grub_errno) + goto fail; + + if (grub_disk_read (disk, block << lbshift, 0, + sizeof (struct grub_udf_fileset), &root_fs)) + { + grub_error (GRUB_ERR_BAD_FS, "not an UDF filesystem"); + goto fail; + } + + if (U16 (root_fs.tag.tag_ident) != GRUB_UDF_TAG_IDENT_FSD) + { + grub_error (GRUB_ERR_BAD_FS, "invalid fileset descriptor"); + goto fail; + } + + data->root_icb = root_fs.root_icb; + + return data; + +fail: + grub_free (data); + return 0; +} + +#ifdef GRUB_UTIL +grub_disk_addr_t +grub_udf_get_cluster_sector (grub_disk_t disk, grub_uint64_t *sec_per_lcn) +{ + grub_disk_addr_t ret; + static struct grub_udf_data *data; + + data = grub_udf_mount (disk); + if (!data) + return 0; + + ret = U32 (data->pds[data->pms[0]->type1.part_num].start); + *sec_per_lcn = 1ULL << data->lbshift; + grub_free (data); + return ret; +} +#endif + +static char * +read_string (const grub_uint8_t *raw, grub_size_t sz, char *outbuf) +{ + grub_uint16_t *utf16 = NULL; + grub_size_t utf16len = 0; + + if (sz == 0) + return NULL; + + if (raw[0] != 8 && raw[0] != 16) + return NULL; + + if (raw[0] == 8) + { + unsigned i; + utf16len = sz - 1; + utf16 = grub_malloc (utf16len * sizeof (utf16[0])); + if (!utf16) + return NULL; + for (i = 0; i < utf16len; i++) + utf16[i] = raw[i + 1]; + } + if (raw[0] == 16) + { + unsigned i; + utf16len = (sz - 1) / 2; + utf16 = grub_malloc (utf16len * sizeof (utf16[0])); + if (!utf16) + return NULL; + for (i = 0; i < utf16len; i++) + utf16[i] = (raw[2 * i + 1] << 8) | raw[2*i + 2]; + } + if (!outbuf) + outbuf = grub_malloc (utf16len * GRUB_MAX_UTF8_PER_UTF16 + 1); + if (outbuf) + *grub_utf16_to_utf8 ((grub_uint8_t *) outbuf, utf16, utf16len) = '\0'; + grub_free (utf16); + return outbuf; +} + +static char * +read_dstring (const grub_uint8_t *raw, grub_size_t sz) +{ + grub_size_t len; + + if (raw[0] == 0) { + char *outbuf = grub_malloc (1); + if (!outbuf) + return NULL; + outbuf[0] = 0; + return outbuf; + } + + len = raw[sz - 1]; + if (len > sz - 1) + len = sz - 1; + return read_string (raw, len, NULL); +} + +static int +grub_udf_iterate_dir (grub_fshelp_node_t dir, + grub_fshelp_iterate_dir_hook_t hook, void *hook_data) +{ + grub_fshelp_node_t child; + struct grub_udf_file_ident dirent; + grub_off_t offset = 0; + + child = grub_malloc (get_fshelp_size (dir->data)); + if (!child) + return 0; + + /* The current directory is not stored. */ + grub_memcpy (child, dir, get_fshelp_size (dir->data)); + + if (hook (".", GRUB_FSHELP_DIR, child, hook_data)) + return 1; + + while (offset < U64 (dir->block.fe.file_size)) + { + if (grub_udf_read_file (dir, 0, 0, offset, sizeof (dirent), + (char *) &dirent) != sizeof (dirent)) + return 0; + + if (U16 (dirent.tag.tag_ident) != GRUB_UDF_TAG_IDENT_FID) + { + grub_error (GRUB_ERR_BAD_FS, "invalid fid tag"); + return 0; + } + + offset += sizeof (dirent) + U16 (dirent.imp_use_length); + if (!(dirent.characteristics & GRUB_UDF_FID_CHAR_DELETED)) + { + child = grub_malloc (get_fshelp_size (dir->data)); + if (!child) + return 0; + + if (grub_udf_read_icb (dir->data, &dirent.icb, child)) + return 0; + + g_last_icb_read_sector = g_last_disk_read_sector; + g_last_icb_read_sector_tag_ident = g_last_fe_tag_ident; + if (dirent.characteristics & GRUB_UDF_FID_CHAR_PARENT) + { + /* This is the parent directory. */ + if (hook ("..", GRUB_FSHELP_DIR, child, hook_data)) + return 1; + } + else + { + enum grub_fshelp_filetype type; + char *filename; + grub_uint8_t raw[MAX_FILE_IDENT_LENGTH]; + + type = ((dirent.characteristics & GRUB_UDF_FID_CHAR_DIRECTORY) ? + (GRUB_FSHELP_DIR) : (GRUB_FSHELP_REG)); + if (child->block.fe.icbtag.file_type == GRUB_UDF_ICBTAG_TYPE_SYMLINK) + type = GRUB_FSHELP_SYMLINK; + + if ((grub_udf_read_file (dir, 0, 0, offset, + dirent.file_ident_length, + (char *) raw)) + != dirent.file_ident_length) + return 0; + + filename = read_string (raw, dirent.file_ident_length, 0); + if (!filename) + grub_print_error (); + + if (filename && hook (filename, type, child, hook_data)) + { + g_last_fileattr_read_sector = g_last_icb_read_sector; + g_last_fileattr_read_sector_tag_ident = g_last_icb_read_sector_tag_ident; + g_last_fileattr_offset = (grub_uint32_t)((child->block.fe.ext_attr + child->block.fe.ext_attr_length) - (grub_uint8_t *)&(child->block.fe)); + grub_free (filename); + return 1; + } + grub_free (filename); + } + } + + /* Align to dword boundary. */ + offset = (offset + dirent.file_ident_length + 3) & (~3); + } + + return 0; +} + +static char * +grub_udf_read_symlink (grub_fshelp_node_t node) +{ + grub_size_t sz = U64 (node->block.fe.file_size); + grub_uint8_t *raw; + const grub_uint8_t *ptr; + char *out, *optr; + + if (sz < 4) + return NULL; + raw = grub_malloc (sz); + if (!raw) + return NULL; + if (grub_udf_read_file (node, NULL, NULL, 0, sz, (char *) raw) < 0) + { + grub_free (raw); + return NULL; + } + + out = grub_malloc (sz * 2 + 1); + if (!out) + { + grub_free (raw); + return NULL; + } + + optr = out; + + for (ptr = raw; ptr < raw + sz; ) + { + grub_size_t s; + if ((grub_size_t) (ptr - raw + 4) > sz) + goto fail; + if (!(ptr[2] == 0 && ptr[3] == 0)) + goto fail; + s = 4 + ptr[1]; + if ((grub_size_t) (ptr - raw + s) > sz) + goto fail; + switch (*ptr) + { + case 1: + if (ptr[1]) + goto fail; + /* Fallthrough. */ + case 2: + /* in 4 bytes. out: 1 byte. */ + optr = out; + *optr++ = '/'; + break; + case 3: + /* in 4 bytes. out: 3 bytes. */ + if (optr != out) + *optr++ = '/'; + *optr++ = '.'; + *optr++ = '.'; + break; + case 4: + /* in 4 bytes. out: 2 bytes. */ + if (optr != out) + *optr++ = '/'; + *optr++ = '.'; + break; + case 5: + /* in 4 + n bytes. out, at most: 1 + 2 * n bytes. */ + if (optr != out) + *optr++ = '/'; + if (!read_string (ptr + 4, s - 4, optr)) + goto fail; + optr += grub_strlen (optr); + break; + default: + goto fail; + } + ptr += s; + } + *optr = 0; + grub_free (raw); + return out; + + fail: + grub_free (raw); + grub_free (out); + grub_error (GRUB_ERR_BAD_FS, "invalid symlink"); + return NULL; +} + +/* Context for grub_udf_dir. */ +struct grub_udf_dir_ctx +{ + grub_fs_dir_hook_t hook; + void *hook_data; +}; + +/* Helper for grub_udf_dir. */ +static int +grub_udf_dir_iter (const char *filename, enum grub_fshelp_filetype filetype, + grub_fshelp_node_t node, void *data) +{ + struct grub_udf_dir_ctx *ctx = data; + struct grub_dirhook_info info; + const struct grub_udf_timestamp *tstamp = NULL; + + grub_memset (&info, 0, sizeof (info)); + info.dir = ((filetype & GRUB_FSHELP_TYPE_MASK) == GRUB_FSHELP_DIR); + if (U16 (node->block.fe.tag.tag_ident) == GRUB_UDF_TAG_IDENT_FE) + tstamp = &node->block.fe.modification_time; + else if (U16 (node->block.fe.tag.tag_ident) == GRUB_UDF_TAG_IDENT_EFE) + tstamp = &node->block.efe.modification_time; + + if (tstamp && (U16 (tstamp->type_and_timezone) & 0xf000) == 0x1000) + { + grub_int16_t tz; + struct grub_datetime datetime; + + datetime.year = U16 (tstamp->year); + datetime.month = tstamp->month; + datetime.day = tstamp->day; + datetime.hour = tstamp->hour; + datetime.minute = tstamp->minute; + datetime.second = tstamp->second; + + tz = U16 (tstamp->type_and_timezone) & 0xfff; + if (tz & 0x800) + tz |= 0xf000; + if (tz == -2047) + tz = 0; + + info.mtimeset = !!grub_datetime2unixtime (&datetime, &info.mtime); + + info.mtime -= 60 * tz; + } + grub_free (node); + return ctx->hook (filename, &info, ctx->hook_data); +} + +static grub_err_t +grub_udf_dir (grub_device_t device, const char *path, + grub_fs_dir_hook_t hook, void *hook_data) +{ + struct grub_udf_dir_ctx ctx = { hook, hook_data }; + struct grub_udf_data *data = 0; + struct grub_fshelp_node *rootnode = 0; + struct grub_fshelp_node *foundnode = 0; + + grub_dl_ref (my_mod); + + data = grub_udf_mount (device->disk); + if (!data) + goto fail; + + rootnode = grub_malloc (get_fshelp_size (data)); + if (!rootnode) + goto fail; + + if (grub_udf_read_icb (data, &data->root_icb, rootnode)) + goto fail; + + if (grub_fshelp_find_file (path, rootnode, + &foundnode, + grub_udf_iterate_dir, grub_udf_read_symlink, + GRUB_FSHELP_DIR)) + goto fail; + + grub_udf_iterate_dir (foundnode, grub_udf_dir_iter, &ctx); + + if (foundnode != rootnode) + grub_free (foundnode); + +fail: + grub_free (rootnode); + + grub_free (data); + + grub_dl_unref (my_mod); + + return grub_errno; +} + +static grub_err_t +grub_udf_open (struct grub_file *file, const char *name) +{ + struct grub_udf_data *data; + struct grub_fshelp_node *rootnode = 0; + struct grub_fshelp_node *foundnode; + + grub_dl_ref (my_mod); + + data = grub_udf_mount (file->device->disk); + if (!data) + goto fail; + + rootnode = grub_malloc (get_fshelp_size (data)); + if (!rootnode) + goto fail; + + if (grub_udf_read_icb (data, &data->root_icb, rootnode)) + goto fail; + + if (grub_fshelp_find_file (name, rootnode, + &foundnode, + grub_udf_iterate_dir, grub_udf_read_symlink, + GRUB_FSHELP_REG)) + goto fail; + + file->data = foundnode; + file->offset = 0; + file->size = U64 (foundnode->block.fe.file_size); + + grub_free (rootnode); + + return 0; + +fail: + grub_dl_unref (my_mod); + + grub_free (data); + grub_free (rootnode); + + return grub_errno; +} + +static grub_ssize_t +grub_udf_read (grub_file_t file, char *buf, grub_size_t len) +{ + struct grub_fshelp_node *node = (struct grub_fshelp_node *) file->data; + + return grub_udf_read_file (node, file->read_hook, file->read_hook_data, + file->offset, len, buf); +} + +static grub_err_t +grub_udf_close (grub_file_t file) +{ + if (file->data) + { + struct grub_fshelp_node *node = (struct grub_fshelp_node *) file->data; + + grub_free (node->data); + grub_free (node); + } + + grub_dl_unref (my_mod); + + return GRUB_ERR_NONE; +} + +static grub_err_t +grub_udf_label (grub_device_t device, char **label) +{ + struct grub_udf_data *data; + data = grub_udf_mount (device->disk); + + if (data) + { + *label = read_dstring (data->lvd.ident, sizeof (data->lvd.ident)); + grub_free (data); + } + else + *label = 0; + + return grub_errno; +} + +static char * +gen_uuid_from_volset (char *volset_ident) +{ + grub_size_t i; + grub_size_t len; + grub_size_t nonhexpos; + grub_uint8_t buf[17]; + char *uuid; + + len = grub_strlen (volset_ident); + if (len < 8) + return NULL; + + uuid = grub_malloc (17); + if (!uuid) + return NULL; + + if (len > 16) + len = 16; + + grub_memset (buf, 0, sizeof (buf)); + grub_memcpy (buf, volset_ident, len); + + nonhexpos = 16; + for (i = 0; i < 16; ++i) + { + if (!grub_isxdigit (buf[i])) + { + nonhexpos = i; + break; + } + } + + if (nonhexpos < 8) + { + grub_snprintf (uuid, 17, "%02x%02x%02x%02x%02x%02x%02x%02x", + buf[0], buf[1], buf[2], buf[3], + buf[4], buf[5], buf[6], buf[7]); + } + else if (nonhexpos < 16) + { + for (i = 0; i < 8; ++i) + uuid[i] = grub_tolower (buf[i]); + grub_snprintf (uuid+8, 9, "%02x%02x%02x%02x", + buf[8], buf[9], buf[10], buf[11]); + } + else + { + for (i = 0; i < 16; ++i) + uuid[i] = grub_tolower (buf[i]); + uuid[16] = 0; + } + + return uuid; +} + +static grub_err_t +grub_udf_uuid (grub_device_t device, char **uuid) +{ + char *volset_ident; + struct grub_udf_data *data; + data = grub_udf_mount (device->disk); + + if (data) + { + volset_ident = read_dstring (data->pvd.volset_ident, sizeof (data->pvd.volset_ident)); + if (volset_ident) + { + *uuid = gen_uuid_from_volset (volset_ident); + grub_free (volset_ident); + } + else + *uuid = 0; + grub_free (data); + } + else + *uuid = 0; + + return grub_errno; +} + +grub_uint64_t grub_udf_get_file_offset(grub_file_t file) +{ + grub_disk_addr_t sector; + struct grub_fshelp_node *node = (struct grub_fshelp_node *)file->data; + + sector = grub_udf_read_block(node, 0); + + return 512 * (sector << node->data->lbshift); +} + +grub_uint64_t grub_udf_get_last_pd_size_offset(void) +{ + return g_last_pd_length_offset; +} + +grub_uint64_t grub_udf_get_last_file_attr_offset +( + grub_file_t file, + grub_uint32_t *startBlock, + grub_uint64_t *fe_entry_size_offset +) +{ + grub_uint64_t attr_offset; + struct grub_fshelp_node *node; + struct grub_udf_data *data; + + node = (struct grub_fshelp_node *)file->data; + data = node->data; + + *startBlock = data->pds[data->pms[0]->type1.part_num].start; + + attr_offset = g_last_fileattr_read_sector * 2048 + g_last_fileattr_offset; + + if (GRUB_UDF_TAG_IDENT_FE == g_last_fileattr_read_sector_tag_ident) + { + *fe_entry_size_offset = g_last_fileattr_read_sector * 2048 + OFFSET_OF(struct grub_udf_file_entry, file_size); + } + else + { + *fe_entry_size_offset = g_last_fileattr_read_sector * 2048 + OFFSET_OF(struct grub_udf_extended_file_entry, file_size); + } + + return attr_offset; +} + +static struct grub_fs grub_udf_fs = { + .name = "udf", + .fs_dir = grub_udf_dir, + .fs_open = grub_udf_open, + .fs_read = grub_udf_read, + .fs_close = grub_udf_close, + .fs_label = grub_udf_label, + .fs_uuid = grub_udf_uuid, +#ifdef GRUB_UTIL + .reserved_first_sector = 1, + .blocklist_install = 1, +#endif + .next = 0 +}; + +GRUB_MOD_INIT (udf) +{ + grub_fs_register (&grub_udf_fs); + my_mod = mod; +} + +GRUB_MOD_FINI (udf) +{ + grub_fs_unregister (&grub_udf_fs); +} diff --git a/GRUB2/grub-2.04/grub-core/kern/file.c b/GRUB2/grub-2.04/grub-core/kern/file.c new file mode 100644 index 00000000..b01bfad4 --- /dev/null +++ b/GRUB2/grub-2.04/grub-core/kern/file.c @@ -0,0 +1,256 @@ +/* file.c - file I/O functions */ +/* + * GRUB -- GRand Unified Bootloader + * Copyright (C) 2002,2006,2007,2009 Free Software Foundation, Inc. + * + * GRUB is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GRUB is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with GRUB. If not, see . + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +void (*EXPORT_VAR (grub_grubnet_fini)) (void); + +grub_file_filter_t grub_file_filters[GRUB_FILE_FILTER_MAX]; + +/* Get the device part of the filename NAME. It is enclosed by parentheses. */ +char * +grub_file_get_device_name (const char *name) +{ + if (name[0] == '(') + { + char *p = grub_strchr (name, ')'); + char *ret; + + if (! p) + { + grub_error (GRUB_ERR_BAD_FILENAME, N_("missing `%c' symbol"), ')'); + return 0; + } + + ret = (char *) grub_malloc (p - name); + if (! ret) + return 0; + + grub_memcpy (ret, name + 1, p - name - 1); + ret[p - name - 1] = '\0'; + return ret; + } + + return 0; +} + +/* Support mem:xxx:size:xxx format in chainloader */ +grub_file_t grub_memfile_open(const char *name); +#define GRUB_MEMFILE_MEM "mem:" +#define GRUB_MEMFILE_SIZE "size:" + +grub_file_t grub_memfile_open(const char *name) +{ + char *size = NULL; + grub_file_t file = 0; + + file = (grub_file_t)grub_zalloc(sizeof(*file)); + if (NULL == file) + { + return 0; + } + + file->name = grub_strdup(name); + file->data = (void *)grub_strtoul(name + grub_strlen(GRUB_MEMFILE_MEM), NULL, 0); + + size = grub_strstr(name, GRUB_MEMFILE_SIZE); + file->size = (grub_off_t)grub_strtoul(size + grub_strlen(GRUB_MEMFILE_SIZE), NULL, 0); + + grub_errno = GRUB_ERR_NONE; + return file; +} + +grub_file_t +grub_file_open (const char *name, enum grub_file_type type) +{ + grub_device_t device = 0; + grub_file_t file = 0, last_file = 0; + char *device_name; + const char *file_name; + grub_file_filter_id_t filter; + + /* : mem:xxx:size:xxx format in chainloader */ + if (grub_strncmp(name, GRUB_MEMFILE_MEM, grub_strlen(GRUB_MEMFILE_MEM)) == 0) { + return grub_memfile_open(name); + } + + device_name = grub_file_get_device_name (name); + if (grub_errno) + goto fail; + + /* Get the file part of NAME. */ + file_name = (name[0] == '(') ? grub_strchr (name, ')') : NULL; + if (file_name) + file_name++; + else + file_name = name; + + device = grub_device_open (device_name); + grub_free (device_name); + if (! device) + goto fail; + + file = (grub_file_t) grub_zalloc (sizeof (*file)); + if (! file) + goto fail; + + file->device = device; + + /* In case of relative pathnames and non-Unix systems (like Windows) + * name of host files may not start with `/'. Blocklists for host files + * are meaningless as well (for a start, host disk does not allow any direct + * access - it is just a marker). So skip host disk in this case. + */ + if (device->disk && file_name[0] != '/' +#if defined(GRUB_UTIL) || defined(GRUB_MACHINE_EMU) + && grub_strcmp (device->disk->name, "host") +#endif + ) + /* This is a block list. */ + file->fs = &grub_fs_blocklist; + else + { + file->fs = grub_fs_probe (device); + if (! file->fs) + goto fail; + } + + if ((file->fs->fs_open) (file, file_name) != GRUB_ERR_NONE) + goto fail; + + file->name = grub_strdup (name); + grub_errno = GRUB_ERR_NONE; + + for (filter = 0; file && filter < ARRAY_SIZE (grub_file_filters); + filter++) + if (grub_file_filters[filter]) + { + last_file = file; + file = grub_file_filters[filter] (file, type); + if (file && file != last_file) + { + file->name = grub_strdup (name); + grub_errno = GRUB_ERR_NONE; + } + } + if (!file) + grub_file_close (last_file); + + return file; + + fail: + if (device) + grub_device_close (device); + + /* if (net) grub_net_close (net); */ + + grub_free (file); + + return 0; +} + +grub_disk_read_hook_t grub_file_progress_hook; + +grub_ssize_t +grub_file_read (grub_file_t file, void *buf, grub_size_t len) +{ + grub_ssize_t res; + grub_disk_read_hook_t read_hook; + void *read_hook_data; + + if (file->offset > file->size) + { + grub_error (GRUB_ERR_OUT_OF_RANGE, + N_("attempt to read past the end of file")); + return -1; + } + + if (len == 0) + return 0; + + if (len > file->size - file->offset) + len = file->size - file->offset; + + /* Prevent an overflow. */ + if ((grub_ssize_t) len < 0) + len >>= 1; + + if (len == 0) + return 0; + + if (grub_strncmp(file->name, GRUB_MEMFILE_MEM, grub_strlen(GRUB_MEMFILE_MEM)) == 0) { + grub_memcpy(buf, (grub_uint8_t *)(file->data) + file->offset, len); + file->offset += len; + return len; + } + + read_hook = file->read_hook; + read_hook_data = file->read_hook_data; + if (!file->read_hook) + { + file->read_hook = grub_file_progress_hook; + file->read_hook_data = file; + file->progress_offset = file->offset; + } + res = (file->fs->fs_read) (file, buf, len); + file->read_hook = read_hook; + file->read_hook_data = read_hook_data; + if (res > 0) + file->offset += res; + + return res; +} + +grub_err_t +grub_file_close (grub_file_t file) +{ + if (file->fs && file->fs->fs_close) + (file->fs->fs_close) (file); + + if (file->device) + grub_device_close (file->device); + grub_free (file->name); + grub_free (file); + return grub_errno; +} + +grub_off_t +grub_file_seek (grub_file_t file, grub_off_t offset) +{ + grub_off_t old; + + if (offset > file->size) + { + grub_error (GRUB_ERR_OUT_OF_RANGE, + N_("attempt to seek outside of the file")); + return -1; + } + + old = file->offset; + file->offset = offset; + + return old; +} diff --git a/GRUB2/grub-2.04/grub-core/kern/fs.c b/GRUB2/grub-2.04/grub-core/kern/fs.c new file mode 100644 index 00000000..3052ae9e --- /dev/null +++ b/GRUB2/grub-2.04/grub-core/kern/fs.c @@ -0,0 +1,304 @@ +/* fs.c - filesystem manager */ +/* + * GRUB -- GRand Unified Bootloader + * Copyright (C) 2002,2005,2007 Free Software Foundation, Inc. + * + * GRUB is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GRUB is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with GRUB. If not, see . + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +grub_fs_t grub_fs_list = 0; + +grub_fs_autoload_hook_t grub_fs_autoload_hook = 0; + +/* Helper for grub_fs_probe. */ +static int +probe_dummy_iter (const char *filename __attribute__ ((unused)), + const struct grub_dirhook_info *info __attribute__ ((unused)), + void *data __attribute__ ((unused))) +{ + return 1; +} + +grub_fs_t +grub_fs_probe (grub_device_t device) +{ + grub_fs_t p; + const char *first_probe; + grub_size_t len; + + if (device->disk) + { + /* Make it sure not to have an infinite recursive calls. */ + static int count = 0; + + first_probe = grub_env_get("ventoy_fs_probe"); + if (!first_probe) + { + first_probe = "iso9660"; + } + len = grub_strlen(first_probe); + + /* use iso9660 first */ + for (p = grub_fs_list; p; p = p->next) + { + if (grub_strncmp(p->name, first_probe, len) == 0) + { + break; + } + } + + if (p) + { + grub_dprintf ("fs", "Detecting %s...\n", p->name); + + /* This is evil: newly-created just mounted BtrFS after copying all + GRUB files has a very peculiar unrecoverable corruption which + will be fixed at sync but we'd rather not do a global sync and + syncing just files doesn't seem to help. Relax the check for + this time. */ +#ifdef GRUB_UTIL + if (grub_strcmp (p->name, "btrfs") == 0) + { + char *label = 0; + p->fs_uuid (device, &label); + if (label) + grub_free (label); + } + else +#endif + (p->fs_dir) (device, "/", probe_dummy_iter, NULL); + if (grub_errno == GRUB_ERR_NONE) + return p; + + grub_error_push (); + grub_dprintf ("fs", "%s detection failed.\n", p->name); + grub_error_pop (); + + if (grub_errno != GRUB_ERR_BAD_FS + && grub_errno != GRUB_ERR_OUT_OF_RANGE) + return 0; + + grub_errno = GRUB_ERR_NONE; + } + + for (p = grub_fs_list; p; p = p->next) + { + grub_dprintf ("fs", "Detecting %s...\n", p->name); + + /* This is evil: newly-created just mounted BtrFS after copying all + GRUB files has a very peculiar unrecoverable corruption which + will be fixed at sync but we'd rather not do a global sync and + syncing just files doesn't seem to help. Relax the check for + this time. */ +#ifdef GRUB_UTIL + if (grub_strcmp (p->name, "btrfs") == 0) + { + char *label = 0; + p->fs_uuid (device, &label); + if (label) + grub_free (label); + } + else +#endif + (p->fs_dir) (device, "/", probe_dummy_iter, NULL); + if (grub_errno == GRUB_ERR_NONE) + return p; + + grub_error_push (); + grub_dprintf ("fs", "%s detection failed.\n", p->name); + grub_error_pop (); + + if (grub_errno != GRUB_ERR_BAD_FS + && grub_errno != GRUB_ERR_OUT_OF_RANGE) + return 0; + + grub_errno = GRUB_ERR_NONE; + } + + /* Let's load modules automatically. */ + if (grub_fs_autoload_hook && count == 0) + { + count++; + + while (grub_fs_autoload_hook ()) + { + p = grub_fs_list; + + (p->fs_dir) (device, "/", probe_dummy_iter, NULL); + if (grub_errno == GRUB_ERR_NONE) + { + count--; + return p; + } + + if (grub_errno != GRUB_ERR_BAD_FS + && grub_errno != GRUB_ERR_OUT_OF_RANGE) + { + count--; + return 0; + } + + grub_errno = GRUB_ERR_NONE; + } + + count--; + } + } + else if (device->net && device->net->fs) + return device->net->fs; + + grub_error (GRUB_ERR_UNKNOWN_FS, N_("unknown filesystem")); + return 0; +} + + + +/* Block list support routines. */ + +struct grub_fs_block +{ + grub_disk_addr_t offset; + unsigned long length; +}; + +static grub_err_t +grub_fs_blocklist_open (grub_file_t file, const char *name) +{ + char *p = (char *) name; + unsigned num = 0; + unsigned i; + grub_disk_t disk = file->device->disk; + struct grub_fs_block *blocks; + + /* First, count the number of blocks. */ + do + { + num++; + p = grub_strchr (p, ','); + if (p) + p++; + } + while (p); + + /* Allocate a block list. */ + blocks = grub_zalloc (sizeof (struct grub_fs_block) * (num + 1)); + if (! blocks) + return 0; + + file->size = 0; + p = (char *) name; + for (i = 0; i < num; i++) + { + if (*p != '+') + { + blocks[i].offset = grub_strtoull (p, &p, 0); + if (grub_errno != GRUB_ERR_NONE || *p != '+') + { + grub_error (GRUB_ERR_BAD_FILENAME, + N_("invalid file name `%s'"), name); + goto fail; + } + } + + p++; + blocks[i].length = grub_strtoul (p, &p, 0); + if (grub_errno != GRUB_ERR_NONE + || blocks[i].length == 0 + || (*p && *p != ',' && ! grub_isspace (*p))) + { + grub_error (GRUB_ERR_BAD_FILENAME, + N_("invalid file name `%s'"), name); + goto fail; + } + + if (disk->total_sectors < blocks[i].offset + blocks[i].length) + { + grub_error (GRUB_ERR_BAD_FILENAME, "beyond the total sectors"); + goto fail; + } + + file->size += (blocks[i].length << GRUB_DISK_SECTOR_BITS); + p++; + } + + file->data = blocks; + + return GRUB_ERR_NONE; + + fail: + grub_free (blocks); + return grub_errno; +} + +static grub_ssize_t +grub_fs_blocklist_read (grub_file_t file, char *buf, grub_size_t len) +{ + struct grub_fs_block *p; + grub_disk_addr_t sector; + grub_off_t offset; + grub_ssize_t ret = 0; + + if (len > file->size - file->offset) + len = file->size - file->offset; + + sector = (file->offset >> GRUB_DISK_SECTOR_BITS); + offset = (file->offset & (GRUB_DISK_SECTOR_SIZE - 1)); + for (p = file->data; p->length && len > 0; p++) + { + if (sector < p->length) + { + grub_size_t size; + + size = len; + if (((size + offset + GRUB_DISK_SECTOR_SIZE - 1) + >> GRUB_DISK_SECTOR_BITS) > p->length - sector) + size = ((p->length - sector) << GRUB_DISK_SECTOR_BITS) - offset; + + if (grub_disk_read (file->device->disk, p->offset + sector, offset, + size, buf) != GRUB_ERR_NONE) + return -1; + + ret += size; + len -= size; + sector -= ((size + offset) >> GRUB_DISK_SECTOR_BITS); + offset = ((size + offset) & (GRUB_DISK_SECTOR_SIZE - 1)); + } + else + sector -= p->length; + } + + return ret; +} + +struct grub_fs grub_fs_blocklist = + { + .name = "blocklist", + .fs_dir = 0, + .fs_open = grub_fs_blocklist_open, + .fs_read = grub_fs_blocklist_read, + .fs_close = 0, + .next = 0 + }; diff --git a/GRUB2/grub-2.04/grub-core/kern/main.c b/GRUB2/grub-2.04/grub-core/kern/main.c new file mode 100644 index 00000000..43b2de98 --- /dev/null +++ b/GRUB2/grub-2.04/grub-core/kern/main.c @@ -0,0 +1,312 @@ +/* main.c - the kernel main routine */ +/* + * GRUB -- GRand Unified Bootloader + * Copyright (C) 2002,2003,2005,2006,2008,2009 Free Software Foundation, Inc. + * + * GRUB is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GRUB is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with GRUB. If not, see . + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef GRUB_MACHINE_PCBIOS +#include +#endif + +grub_addr_t +grub_modules_get_end (void) +{ + struct grub_module_info *modinfo; + + modinfo = (struct grub_module_info *) grub_modbase; + + /* Check if there are any modules. */ + if ((modinfo == 0) || modinfo->magic != GRUB_MODULE_MAGIC) + return grub_modbase; + + return grub_modbase + modinfo->size; +} + +/* Load all modules in core. */ +static void +grub_load_modules (void) +{ + struct grub_module_header *header; + FOR_MODULES (header) + { + /* Not an ELF module, skip. */ + if (header->type != OBJ_TYPE_ELF) + continue; + + if (! grub_dl_load_core ((char *) header + sizeof (struct grub_module_header), + (header->size - sizeof (struct grub_module_header)))) + grub_fatal ("%s", grub_errmsg); + + if (grub_errno) + grub_print_error (); + } +} + +static char *load_config; + +static void +grub_load_config (void) +{ + struct grub_module_header *header; + FOR_MODULES (header) + { + /* Not an embedded config, skip. */ + if (header->type != OBJ_TYPE_CONFIG) + continue; + + load_config = grub_malloc (header->size - sizeof (struct grub_module_header) + 1); + if (!load_config) + { + grub_print_error (); + break; + } + grub_memcpy (load_config, (char *) header + + sizeof (struct grub_module_header), + header->size - sizeof (struct grub_module_header)); + load_config[header->size - sizeof (struct grub_module_header)] = 0; + break; + } +} + +/* Write hook for the environment variables of root. Remove surrounding + parentheses, if any. */ +static char * +grub_env_write_root (struct grub_env_var *var __attribute__ ((unused)), + const char *val) +{ + /* XXX Is it better to check the existence of the device? */ + grub_size_t len = grub_strlen (val); + + if (val[0] == '(' && val[len - 1] == ')') + return grub_strndup (val + 1, len - 2); + + return grub_strdup (val); +} + +static void +grub_set_prefix_and_root (void) +{ + char *device = NULL; + char *path = NULL; + char *fwdevice = NULL; + char *fwpath = NULL; + char *prefix = NULL; + struct grub_module_header *header; + + FOR_MODULES (header) + if (header->type == OBJ_TYPE_PREFIX) + prefix = (char *) header + sizeof (struct grub_module_header); + + grub_register_variable_hook ("root", 0, grub_env_write_root); + + grub_machine_get_bootlocation (&fwdevice, &fwpath); + + if (fwdevice) + { + char *cmdpath; + + cmdpath = grub_xasprintf ("(%s)%s", fwdevice, fwpath ? : ""); + if (cmdpath) + { + grub_env_set ("cmdpath", cmdpath); + grub_env_export ("cmdpath"); + grub_free (cmdpath); + } + } + + if (prefix) + { + char *pptr = NULL; + if (prefix[0] == '(') + { + pptr = grub_strrchr (prefix, ')'); + if (pptr) + { + device = grub_strndup (prefix + 1, pptr - prefix - 1); + pptr++; + } + } + if (!pptr) + pptr = prefix; + if (pptr[0]) + path = grub_strdup (pptr); + } + + if (!device && fwdevice) + device = fwdevice; + else if (fwdevice && (device[0] == ',' || !device[0])) + { + /* We have a partition, but still need to fill in the drive. */ + char *comma, *new_device; + + for (comma = fwdevice; *comma; ) + { + if (comma[0] == '\\' && comma[1] == ',') + { + comma += 2; + continue; + } + if (*comma == ',') + break; + comma++; + } + if (*comma) + { + char *drive = grub_strndup (fwdevice, comma - fwdevice); + new_device = grub_xasprintf ("%s%s", drive, device); + grub_free (drive); + } + else + new_device = grub_xasprintf ("%s%s", fwdevice, device); + + grub_free (fwdevice); + grub_free (device); + device = new_device; + } + else + grub_free (fwdevice); + if (fwpath && !path) + { + grub_size_t len = grub_strlen (fwpath); + while (len > 1 && fwpath[len - 1] == '/') + fwpath[--len] = 0; + if (len >= sizeof (GRUB_TARGET_CPU "-" GRUB_PLATFORM) - 1 + && grub_memcmp (fwpath + len - (sizeof (GRUB_TARGET_CPU "-" GRUB_PLATFORM) - 1), GRUB_TARGET_CPU "-" GRUB_PLATFORM, + sizeof (GRUB_TARGET_CPU "-" GRUB_PLATFORM) - 1) == 0) + fwpath[len - (sizeof (GRUB_TARGET_CPU "-" GRUB_PLATFORM) - 1)] = 0; + path = fwpath; + } + else + grub_free (fwpath); + if (device) + { + char *prefix_set; + + prefix_set = grub_xasprintf ("(%s)%s", device, path ? : ""); + if (prefix_set) + { + grub_env_set ("prefix", prefix_set); + grub_free (prefix_set); + } + grub_env_set ("root", device); + } + + grub_free (device); + grub_free (path); + grub_print_error (); +} + +/* Load the normal mode module and execute the normal mode if possible. */ +static void +grub_load_normal_mode (void) +{ + /* Load the module. */ + grub_dl_load ("normal"); + + /* Print errors if any. */ + grub_print_error (); + grub_errno = 0; + + grub_command_execute ("normal", 0, 0); +} + +static void +reclaim_module_space (void) +{ + grub_addr_t modstart, modend; + + if (!grub_modbase) + return; + +#ifdef GRUB_MACHINE_PCBIOS + modstart = GRUB_MEMORY_MACHINE_DECOMPRESSION_ADDR; +#else + modstart = grub_modbase; +#endif + modend = grub_modules_get_end (); + grub_modbase = 0; + +#if GRUB_KERNEL_PRELOAD_SPACE_REUSABLE + grub_mm_init_region ((void *) modstart, modend - modstart); +#else + (void) modstart; + (void) modend; +#endif +} + +/* The main routine. */ +void __attribute__ ((noreturn)) +grub_main (void) +{ + /* First of all, initialize the machine. */ + grub_machine_init (); + + grub_boot_time ("After machine init."); + + /* Hello. */ + grub_setcolorstate (GRUB_TERM_COLOR_HIGHLIGHT); + //grub_printf ("Welcome to GRUB!\n\n"); + grub_setcolorstate (GRUB_TERM_COLOR_STANDARD); + + grub_load_config (); + + grub_boot_time ("Before loading embedded modules."); + + /* Load pre-loaded modules and free the space. */ + grub_register_exported_symbols (); +#ifdef GRUB_LINKER_HAVE_INIT + grub_arch_dl_init_linker (); +#endif + grub_load_modules (); + + grub_boot_time ("After loading embedded modules."); + + /* It is better to set the root device as soon as possible, + for convenience. */ + grub_set_prefix_and_root (); + grub_env_export ("root"); + grub_env_export ("prefix"); + + /* Reclaim space used for modules. */ + reclaim_module_space (); + + grub_boot_time ("After reclaiming module space."); + + grub_register_core_commands (); + + grub_boot_time ("Before execution of embedded config."); + + if (load_config) + grub_parser_execute (load_config); + + grub_boot_time ("After execution of embedded config. Attempt to go to normal mode"); + + grub_load_normal_mode (); + grub_rescue_run (); +} diff --git a/GRUB2/grub-2.04/grub-core/lib/cmdline.c b/GRUB2/grub-2.04/grub-core/lib/cmdline.c new file mode 100644 index 00000000..cc87e162 --- /dev/null +++ b/GRUB2/grub-2.04/grub-core/lib/cmdline.c @@ -0,0 +1,118 @@ +/* cmdline.c - linux command line handling */ +/* + * GRUB -- GRand Unified Bootloader + * Copyright (C) 2010 Free Software Foundation, Inc. + * + * GRUB is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GRUB is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with GRUB. If not, see . + */ + +#include +#include + +static unsigned int check_arg (char *c, int *has_space) +{ + int space = 0; + unsigned int size = 0; + + while (*c) + { + if (*c == '\\' || *c == '\'' || *c == '"') + size++; + else if (*c == ' ') + space = 1; + + size++; + c++; + } + + if (space) + size += 2; + + if (has_space) + *has_space = space; + + return size; +} + +unsigned int grub_loader_cmdline_size (int argc, char *argv[]) +{ + int i; + unsigned int size = 0; + + for (i = 0; i < argc; i++) + { + size += check_arg (argv[i], 0); + size++; /* Separator space or NULL. */ + } + + if (size == 0) + size = 1; + + return size; +} + +grub_err_t +grub_create_loader_cmdline (int argc, char *argv[], char *buf, + grub_size_t size, enum grub_verify_string_type type) +{ + int i, space; + unsigned int arg_size; + char *c, *orig_buf = buf; + + for (i = 0; i < argc; i++) + { + c = argv[i]; + arg_size = check_arg(argv[i], &space); + arg_size++; /* Separator space or NULL. */ + + if (size < arg_size) + break; + + size -= arg_size; + + if (space) + *buf++ = '"'; + + while (*c) + { + if (*c == '\\' && *(c+1) == 'x' && + grub_isxdigit(*(c+2)) && grub_isxdigit(*(c+3))) + { + *buf++ = *c++; + *buf++ = *c++; + *buf++ = *c++; + *buf++ = *c++; + continue; + } + else if (*c == '\\' || *c == '\'' || *c == '"') + *buf++ = '\\'; + + *buf++ = *c; + c++; + } + + if (space) + *buf++ = '"'; + + *buf++ = ' '; + } + + /* Replace last space with null. */ + if (i) + buf--; + + *buf = 0; + + return grub_verify_string (orig_buf, type); +} diff --git a/GRUB2/grub-2.04/grub-core/loader/efi/chainloader.c b/GRUB2/grub-2.04/grub-core/loader/efi/chainloader.c new file mode 100644 index 00000000..fa8a4b99 --- /dev/null +++ b/GRUB2/grub-2.04/grub-core/loader/efi/chainloader.c @@ -0,0 +1,428 @@ +/* chainloader.c - boot another boot loader */ +/* + * GRUB -- GRand Unified Bootloader + * Copyright (C) 2002,2004,2006,2007,2008 Free Software Foundation, Inc. + * + * GRUB is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GRUB is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with GRUB. If not, see . + */ + +/* TODO: support load options. */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#if defined (__i386__) || defined (__x86_64__) +#include +#include +#endif + +GRUB_MOD_LICENSE ("GPLv3+"); + +static grub_dl_t my_mod; + +static grub_efi_physical_address_t address; +static grub_efi_uintn_t pages; +static grub_efi_device_path_t *file_path; +static grub_efi_handle_t image_handle; +static grub_efi_char16_t *cmdline; + +static grub_err_t +grub_chainloader_unload (void) +{ + grub_efi_boot_services_t *b; + + b = grub_efi_system_table->boot_services; + efi_call_1 (b->unload_image, image_handle); + efi_call_2 (b->free_pages, address, pages); + + grub_free (file_path); + grub_free (cmdline); + cmdline = 0; + file_path = 0; + + grub_dl_unref (my_mod); + return GRUB_ERR_NONE; +} + +static grub_err_t +grub_chainloader_boot (void) +{ + grub_efi_boot_services_t *b; + grub_efi_status_t status; + grub_efi_uintn_t exit_data_size; + grub_efi_char16_t *exit_data = NULL; + + b = grub_efi_system_table->boot_services; + status = efi_call_3 (b->start_image, image_handle, &exit_data_size, &exit_data); + if (status != GRUB_EFI_SUCCESS) + { + if (exit_data) + { + char *buf; + + buf = grub_malloc (exit_data_size * 4 + 1); + if (buf) + { + *grub_utf16_to_utf8 ((grub_uint8_t *) buf, + exit_data, exit_data_size) = 0; + + grub_error (GRUB_ERR_BAD_OS, buf); + grub_free (buf); + } + } + else + grub_error (GRUB_ERR_BAD_OS, "unknown error"); + } + + if (exit_data) + efi_call_1 (b->free_pool, exit_data); + + grub_loader_unset (); + + return grub_errno; +} + +static void +copy_file_path (grub_efi_file_path_device_path_t *fp, + const char *str, grub_efi_uint16_t len) +{ + grub_efi_char16_t *p, *path_name; + grub_efi_uint16_t size; + + fp->header.type = GRUB_EFI_MEDIA_DEVICE_PATH_TYPE; + fp->header.subtype = GRUB_EFI_FILE_PATH_DEVICE_PATH_SUBTYPE; + + path_name = grub_malloc (len * GRUB_MAX_UTF16_PER_UTF8 * sizeof (*path_name)); + if (!path_name) + return; + + size = grub_utf8_to_utf16 (path_name, len * GRUB_MAX_UTF16_PER_UTF8, + (const grub_uint8_t *) str, len, 0); + for (p = path_name; p < path_name + size; p++) + if (*p == '/') + *p = '\\'; + + grub_memcpy (fp->path_name, path_name, size * sizeof (*fp->path_name)); + /* File Path is NULL terminated */ + fp->path_name[size++] = '\0'; + fp->header.length = size * sizeof (grub_efi_char16_t) + sizeof (*fp); + grub_free (path_name); +} + +static grub_efi_device_path_t * +make_file_path (grub_efi_device_path_t *dp, const char *filename) +{ + char *dir_start; + char *dir_end; + grub_size_t size; + grub_efi_device_path_t *d; + + dir_start = grub_strchr (filename, ')'); + if (! dir_start) + dir_start = (char *) filename; + else + dir_start++; + + dir_end = grub_strrchr (dir_start, '/'); + if (! dir_end) + { + grub_error (GRUB_ERR_BAD_FILENAME, "invalid EFI file path"); + return 0; + } + + size = 0; + d = dp; + while (1) + { + size += GRUB_EFI_DEVICE_PATH_LENGTH (d); + if ((GRUB_EFI_END_ENTIRE_DEVICE_PATH (d))) + break; + d = GRUB_EFI_NEXT_DEVICE_PATH (d); + } + + /* File Path is NULL terminated. Allocate space for 2 extra characters */ + /* FIXME why we split path in two components? */ + file_path = grub_malloc (size + + ((grub_strlen (dir_start) + 2) + * GRUB_MAX_UTF16_PER_UTF8 + * sizeof (grub_efi_char16_t)) + + sizeof (grub_efi_file_path_device_path_t) * 2); + if (! file_path) + return 0; + + grub_memcpy (file_path, dp, size); + + /* Fill the file path for the directory. */ + d = (grub_efi_device_path_t *) ((char *) file_path + + ((char *) d - (char *) dp)); + //grub_efi_print_device_path (d); + copy_file_path ((grub_efi_file_path_device_path_t *) d, + dir_start, dir_end - dir_start); + + /* Fill the file path for the file. */ + d = GRUB_EFI_NEXT_DEVICE_PATH (d); + copy_file_path ((grub_efi_file_path_device_path_t *) d, + dir_end + 1, grub_strlen (dir_end + 1)); + + /* Fill the end of device path nodes. */ + d = GRUB_EFI_NEXT_DEVICE_PATH (d); + d->type = GRUB_EFI_END_DEVICE_PATH_TYPE; + d->subtype = GRUB_EFI_END_ENTIRE_DEVICE_PATH_SUBTYPE; + d->length = sizeof (*d); + + return file_path; +} + +static grub_err_t +grub_cmd_chainloader (grub_command_t cmd __attribute__ ((unused)), + int argc, char *argv[]) +{ + grub_file_t file = 0; + grub_ssize_t size; + grub_efi_status_t status; + grub_efi_boot_services_t *b; + grub_device_t dev = 0; + grub_efi_device_path_t *dp = 0; + grub_efi_loaded_image_t *loaded_image; + char *filename; + void *boot_image = 0; + grub_efi_handle_t dev_handle = 0; + + if (argc == 0) + return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("filename expected")); + filename = argv[0]; + + grub_dl_ref (my_mod); + + /* Initialize some global variables. */ + address = 0; + image_handle = 0; + file_path = 0; + + b = grub_efi_system_table->boot_services; + + file = grub_file_open (filename, GRUB_FILE_TYPE_EFI_CHAINLOADED_IMAGE); + if (! file) + goto fail; + + /* Get the root device's device path. */ + dev = grub_device_open (0); + if (! dev) + goto fail; + + if (dev->disk) + dev_handle = grub_efidisk_get_device_handle (dev->disk); + else if (dev->net && dev->net->server) + { + grub_net_network_level_address_t addr; + struct grub_net_network_level_interface *inf; + grub_net_network_level_address_t gateway; + grub_err_t err; + + err = grub_net_resolve_address (dev->net->server, &addr); + if (err) + goto fail; + + err = grub_net_route_address (addr, &gateway, &inf); + if (err) + goto fail; + + dev_handle = grub_efinet_get_device_handle (inf->card); + } + + if (dev_handle) + dp = grub_efi_get_device_path (dev_handle); + + if (! dp) + { + grub_error (GRUB_ERR_BAD_DEVICE, "not a valid root device"); + goto fail; + } + + file_path = make_file_path (dp, filename); + if (! file_path) + goto fail; + + //grub_printf ("file path: "); + //grub_efi_print_device_path (file_path); + + size = grub_file_size (file); + if (!size) + { + grub_error (GRUB_ERR_BAD_OS, N_("premature end of file %s"), + filename); + goto fail; + } + pages = (((grub_efi_uintn_t) size + ((1 << 12) - 1)) >> 12); + + status = efi_call_4 (b->allocate_pages, GRUB_EFI_ALLOCATE_ANY_PAGES, + GRUB_EFI_LOADER_CODE, + pages, &address); + if (status != GRUB_EFI_SUCCESS) + { + grub_dprintf ("chain", "Failed to allocate %u pages\n", + (unsigned int) pages); + grub_error (GRUB_ERR_OUT_OF_MEMORY, N_("out of memory")); + goto fail; + } + + boot_image = (void *) ((grub_addr_t) address); + if (grub_file_read (file, boot_image, size) != size) + { + if (grub_errno == GRUB_ERR_NONE) + grub_error (GRUB_ERR_BAD_OS, N_("premature end of file %s"), + filename); + + goto fail; + } + +#if defined (__i386__) || defined (__x86_64__) + if (size >= (grub_ssize_t) sizeof (struct grub_macho_fat_header)) + { + struct grub_macho_fat_header *head = boot_image; + if (head->magic + == grub_cpu_to_le32_compile_time (GRUB_MACHO_FAT_EFI_MAGIC)) + { + grub_uint32_t i; + struct grub_macho_fat_arch *archs + = (struct grub_macho_fat_arch *) (head + 1); + for (i = 0; i < grub_cpu_to_le32 (head->nfat_arch); i++) + { + if (GRUB_MACHO_CPUTYPE_IS_HOST_CURRENT (archs[i].cputype)) + break; + } + if (i == grub_cpu_to_le32 (head->nfat_arch)) + { + grub_error (GRUB_ERR_BAD_OS, "no compatible arch found"); + goto fail; + } + if (grub_cpu_to_le32 (archs[i].offset) + > ~grub_cpu_to_le32 (archs[i].size) + || grub_cpu_to_le32 (archs[i].offset) + + grub_cpu_to_le32 (archs[i].size) + > (grub_size_t) size) + { + grub_error (GRUB_ERR_BAD_OS, N_("premature end of file %s"), + filename); + goto fail; + } + boot_image = (char *) boot_image + grub_cpu_to_le32 (archs[i].offset); + size = grub_cpu_to_le32 (archs[i].size); + } + } +#endif + + status = efi_call_6 (b->load_image, 0, grub_efi_image_handle, file_path, + boot_image, size, + &image_handle); + if (status != GRUB_EFI_SUCCESS) + { + if (status == GRUB_EFI_OUT_OF_RESOURCES) + grub_error (GRUB_ERR_OUT_OF_MEMORY, "out of resources"); + else + grub_error (GRUB_ERR_BAD_OS, "cannot load image"); + + goto fail; + } + + /* LoadImage does not set a device handler when the image is + loaded from memory, so it is necessary to set it explicitly here. + This is a mess. */ + loaded_image = grub_efi_get_loaded_image (image_handle); + if (! loaded_image) + { + grub_error (GRUB_ERR_BAD_OS, "no loaded image available"); + goto fail; + } + loaded_image->device_handle = dev_handle; + + if (argc > 1) + { + int i, len; + grub_efi_char16_t *p16; + + for (i = 1, len = 0; i < argc; i++) + len += grub_strlen (argv[i]) + 1; + + len *= sizeof (grub_efi_char16_t); + cmdline = p16 = grub_malloc (len); + if (! cmdline) + goto fail; + + for (i = 1; i < argc; i++) + { + char *p8; + + p8 = argv[i]; + while (*p8) + *(p16++) = *(p8++); + + *(p16++) = ' '; + } + *(--p16) = 0; + + loaded_image->load_options = cmdline; + loaded_image->load_options_size = len; + } + + grub_file_close (file); + grub_device_close (dev); + + grub_loader_set (grub_chainloader_boot, grub_chainloader_unload, 0); + return 0; + + fail: + + if (dev) + grub_device_close (dev); + + if (file) + grub_file_close (file); + + grub_free (file_path); + + if (address) + efi_call_2 (b->free_pages, address, pages); + + grub_dl_unref (my_mod); + + return grub_errno; +} + +static grub_command_t cmd; + +GRUB_MOD_INIT(chainloader) +{ + cmd = grub_register_command ("chainloader", grub_cmd_chainloader, + 0, N_("Load another boot loader.")); + my_mod = mod; +} + +GRUB_MOD_FINI(chainloader) +{ + grub_unregister_command (cmd); +} diff --git a/GRUB2/grub-2.04/grub-core/normal/menu.c b/GRUB2/grub-2.04/grub-core/normal/menu.c new file mode 100644 index 00000000..a5231818 --- /dev/null +++ b/GRUB2/grub-2.04/grub-core/normal/menu.c @@ -0,0 +1,913 @@ +/* menu.c - General supporting functionality for menus. */ +/* + * GRUB -- GRand Unified Bootloader + * Copyright (C) 2003,2004,2005,2006,2007,2008,2009,2010 Free Software Foundation, Inc. + * + * GRUB is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GRUB is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with GRUB. If not, see . + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* Time to delay after displaying an error message about a default/fallback + entry failing to boot. */ +#define DEFAULT_ENTRY_ERROR_DELAY_MS 2500 + +grub_err_t (*grub_gfxmenu_try_hook) (int entry, grub_menu_t menu, + int nested) = NULL; + +enum timeout_style { + TIMEOUT_STYLE_MENU, + TIMEOUT_STYLE_COUNTDOWN, + TIMEOUT_STYLE_HIDDEN +}; + +struct timeout_style_name { + const char *name; + enum timeout_style style; +} timeout_style_names[] = { + {"menu", TIMEOUT_STYLE_MENU}, + {"countdown", TIMEOUT_STYLE_COUNTDOWN}, + {"hidden", TIMEOUT_STYLE_HIDDEN}, + {NULL, 0} +}; + +/* Wait until the user pushes any key so that the user + can see what happened. */ +void +grub_wait_after_message (void) +{ + grub_uint64_t endtime; + grub_xputs ("\n"); + grub_printf_ (N_("Press any key to continue...")); + grub_refresh (); + + endtime = grub_get_time_ms () + 10000; + + while (grub_get_time_ms () < endtime + && grub_getkey_noblock () == GRUB_TERM_NO_KEY); + + grub_xputs ("\n"); +} + +/* Get a menu entry by its index in the entry list. */ +grub_menu_entry_t +grub_menu_get_entry (grub_menu_t menu, int no) +{ + grub_menu_entry_t e; + + for (e = menu->entry_list; e && no > 0; e = e->next, no--) + ; + + return e; +} + +/* Get the index of a menu entry associated with a given hotkey, or -1. */ +static int +get_entry_index_by_hotkey (grub_menu_t menu, int hotkey) +{ + grub_menu_entry_t entry; + int i; + + for (i = 0, entry = menu->entry_list; i < menu->size; + i++, entry = entry->next) + if (entry->hotkey == hotkey) + return i; + + return -1; +} + +/* Return the timeout style. If the variable "timeout_style" is not set or + invalid, default to TIMEOUT_STYLE_MENU. */ +static enum timeout_style +get_timeout_style (void) +{ + const char *val; + struct timeout_style_name *style_name; + + val = grub_env_get ("timeout_style"); + if (!val) + return TIMEOUT_STYLE_MENU; + + for (style_name = timeout_style_names; style_name->name; style_name++) + if (grub_strcmp (style_name->name, val) == 0) + return style_name->style; + + return TIMEOUT_STYLE_MENU; +} + +/* Return the current timeout. If the variable "timeout" is not set or + invalid, return -1. */ +int +grub_menu_get_timeout (void) +{ + const char *val; + int timeout; + + val = grub_env_get ("timeout"); + if (! val) + return -1; + + grub_error_push (); + + timeout = (int) grub_strtoul (val, 0, 0); + + /* If the value is invalid, unset the variable. */ + if (grub_errno != GRUB_ERR_NONE) + { + grub_env_unset ("timeout"); + grub_errno = GRUB_ERR_NONE; + timeout = -1; + } + + grub_error_pop (); + + return timeout; +} + +/* Set current timeout in the variable "timeout". */ +void +grub_menu_set_timeout (int timeout) +{ + /* Ignore TIMEOUT if it is zero, because it will be unset really soon. */ + if (timeout > 0) + { + char buf[16]; + + grub_snprintf (buf, sizeof (buf), "%d", timeout); + grub_env_set ("timeout", buf); + } +} + +/* Get the first entry number from the value of the environment variable NAME, + which is a space-separated list of non-negative integers. The entry number + which is returned is stripped from the value of NAME. If no entry number + can be found, -1 is returned. */ +static int +get_and_remove_first_entry_number (const char *name) +{ + const char *val; + char *tail; + int entry; + + val = grub_env_get (name); + if (! val) + return -1; + + grub_error_push (); + + entry = (int) grub_strtoul (val, &tail, 0); + + if (grub_errno == GRUB_ERR_NONE) + { + /* Skip whitespace to find the next digit. */ + while (*tail && grub_isspace (*tail)) + tail++; + grub_env_set (name, tail); + } + else + { + grub_env_unset (name); + grub_errno = GRUB_ERR_NONE; + entry = -1; + } + + grub_error_pop (); + + return entry; +} + +/* Run a menu entry. */ +static void +grub_menu_execute_entry(grub_menu_entry_t entry, int auto_boot) +{ + grub_err_t err = GRUB_ERR_NONE; + int errs_before; + grub_menu_t menu = NULL; + char *optr, *buf, *oldchosen = NULL, *olddefault = NULL; + const char *ptr, *chosen, *def; + grub_size_t sz = 0; + + if (entry->restricted) + err = grub_auth_check_authentication (entry->users); + + if (err) + { + grub_print_error (); + grub_errno = GRUB_ERR_NONE; + return; + } + + errs_before = grub_err_printed_errors; + + chosen = grub_env_get ("chosen"); + def = grub_env_get ("default"); + + if (entry->submenu) + { + grub_env_context_open (); + menu = grub_zalloc (sizeof (*menu)); + if (! menu) + return; + grub_env_set_menu (menu); + if (auto_boot) + grub_env_set ("timeout", "0"); + } + + for (ptr = entry->id; *ptr; ptr++) + sz += (*ptr == '>') ? 2 : 1; + if (chosen) + { + oldchosen = grub_strdup (chosen); + if (!oldchosen) + grub_print_error (); + } + if (def) + { + olddefault = grub_strdup (def); + if (!olddefault) + grub_print_error (); + } + sz++; + if (chosen) + sz += grub_strlen (chosen); + sz++; + buf = grub_malloc (sz); + if (!buf) + grub_print_error (); + else + { + optr = buf; + if (chosen) + { + optr = grub_stpcpy (optr, chosen); + *optr++ = '>'; + } + for (ptr = entry->id; *ptr; ptr++) + { + if (*ptr == '>') + *optr++ = '>'; + *optr++ = *ptr; + } + *optr = 0; + grub_env_set ("chosen", buf); + grub_env_export ("chosen"); + grub_free (buf); + } + + for (ptr = def; ptr && *ptr; ptr++) + { + if (ptr[0] == '>' && ptr[1] == '>') + { + ptr++; + continue; + } + if (ptr[0] == '>') + break; + } + + if (ptr && ptr[0] && ptr[1]) + grub_env_set ("default", ptr + 1); + else + grub_env_unset ("default"); + + grub_script_execute_new_scope (entry->sourcecode, entry->argc, entry->args); + + if (errs_before != grub_err_printed_errors) + grub_wait_after_message (); + + errs_before = grub_err_printed_errors; + + if (grub_errno == GRUB_ERR_NONE && grub_loader_is_loaded ()) + /* Implicit execution of boot, only if something is loaded. */ + grub_command_execute ("boot", 0, 0); + + if (errs_before != grub_err_printed_errors) + grub_wait_after_message (); + + if (entry->submenu) + { + if (menu && menu->size) + { + grub_show_menu (menu, 1, auto_boot); + grub_normal_free_menu (menu); + } + grub_env_context_close (); + } + if (oldchosen) + grub_env_set ("chosen", oldchosen); + else + grub_env_unset ("chosen"); + if (olddefault) + grub_env_set ("default", olddefault); + else + grub_env_unset ("default"); + grub_env_unset ("timeout"); +} + +/* Execute ENTRY from the menu MENU, falling back to entries specified + in the environment variable "fallback" if it fails. CALLBACK is a + pointer to a struct of function pointers which are used to allow the + caller provide feedback to the user. */ +static void +grub_menu_execute_with_fallback (grub_menu_t menu, + grub_menu_entry_t entry, + int autobooted, + grub_menu_execute_callback_t callback, + void *callback_data) +{ + int fallback_entry; + + callback->notify_booting (entry, callback_data); + + grub_menu_execute_entry (entry, 1); + + /* Deal with fallback entries. */ + while ((fallback_entry = get_and_remove_first_entry_number ("fallback")) + >= 0) + { + grub_print_error (); + grub_errno = GRUB_ERR_NONE; + + entry = grub_menu_get_entry (menu, fallback_entry); + callback->notify_fallback (entry, callback_data); + grub_menu_execute_entry (entry, 1); + /* If the function call to execute the entry returns at all, then this is + taken to indicate a boot failure. For menu entries that do something + other than actually boot an operating system, this could assume + incorrectly that something failed. */ + } + + if (!autobooted) + callback->notify_failure (callback_data); +} + +static struct grub_menu_viewer *viewers; + +static void +menu_set_chosen_entry (int entry) +{ + struct grub_menu_viewer *cur; + for (cur = viewers; cur; cur = cur->next) + cur->set_chosen_entry (entry, cur->data); +} + +static void +menu_print_timeout (int timeout) +{ + struct grub_menu_viewer *cur; + for (cur = viewers; cur; cur = cur->next) + cur->print_timeout (timeout, cur->data); +} + +static void +menu_fini (void) +{ + struct grub_menu_viewer *cur, *next; + for (cur = viewers; cur; cur = next) + { + next = cur->next; + cur->fini (cur->data); + grub_free (cur); + } + viewers = NULL; +} + +static void +menu_init (int entry, grub_menu_t menu, int nested) +{ + struct grub_term_output *term; + int gfxmenu = 0; + + FOR_ACTIVE_TERM_OUTPUTS(term) + if (term->fullscreen) + { + if (grub_env_get ("theme")) + { + if (!grub_gfxmenu_try_hook) + { + grub_dl_load ("gfxmenu"); + grub_print_error (); + } + if (grub_gfxmenu_try_hook) + { + grub_err_t err; + err = grub_gfxmenu_try_hook (entry, menu, nested); + if(!err) + { + gfxmenu = 1; + break; + } + } + else + grub_error (GRUB_ERR_BAD_MODULE, + N_("module `%s' isn't loaded"), + "gfxmenu"); + grub_print_error (); + grub_wait_after_message (); + } + grub_errno = GRUB_ERR_NONE; + term->fullscreen (); + break; + } + + FOR_ACTIVE_TERM_OUTPUTS(term) + { + grub_err_t err; + + if (grub_strcmp (term->name, "gfxterm") == 0 && gfxmenu) + continue; + + err = grub_menu_try_text (term, entry, menu, nested); + if(!err) + continue; + grub_print_error (); + grub_errno = GRUB_ERR_NONE; + } +} + +static void +clear_timeout (void) +{ + struct grub_menu_viewer *cur; + for (cur = viewers; cur; cur = cur->next) + cur->clear_timeout (cur->data); +} + +void +grub_menu_register_viewer (struct grub_menu_viewer *viewer) +{ + viewer->next = viewers; + viewers = viewer; +} + +static int +menuentry_eq (const char *id, const char *spec) +{ + const char *ptr1, *ptr2; + ptr1 = id; + ptr2 = spec; + while (1) + { + if (*ptr2 == '>' && ptr2[1] != '>' && *ptr1 == 0) + return 1; + if (*ptr2 == '>' && ptr2[1] != '>') + return 0; + if (*ptr2 == '>') + ptr2++; + if (*ptr1 != *ptr2) + return 0; + if (*ptr1 == 0) + return 1; + ptr1++; + ptr2++; + } +} + + +/* Get the entry number from the variable NAME. */ +static int +get_entry_number (grub_menu_t menu, const char *name) +{ + const char *val; + int entry; + + val = grub_env_get (name); + if (! val) + return -1; + + grub_error_push (); + + entry = (int) grub_strtoul (val, 0, 0); + + if (grub_errno == GRUB_ERR_BAD_NUMBER) + { + /* See if the variable matches the title of a menu entry. */ + grub_menu_entry_t e = menu->entry_list; + int i; + + grub_errno = GRUB_ERR_NONE; + + for (i = 0; e; i++) + { + if (menuentry_eq (e->title, val) + || menuentry_eq (e->id, val)) + { + entry = i; + break; + } + e = e->next; + } + + if (! e) + entry = -1; + } + + if (grub_errno != GRUB_ERR_NONE) + { + grub_errno = GRUB_ERR_NONE; + entry = -1; + } + + grub_error_pop (); + + return entry; +} + +/* Check whether a second has elapsed since the last tick. If so, adjust + the timer and return 1; otherwise, return 0. */ +static int +has_second_elapsed (grub_uint64_t *saved_time) +{ + grub_uint64_t current_time; + + current_time = grub_get_time_ms (); + if (current_time - *saved_time >= 1000) + { + *saved_time = current_time; + return 1; + } + else + return 0; +} + +static void +print_countdown (struct grub_term_coordinate *pos, int n) +{ + grub_term_restore_pos (pos); + /* NOTE: Do not remove the trailing space characters. + They are required to clear the line. */ + grub_printf ("%d ", n); + grub_refresh (); +} + +#define GRUB_MENU_PAGE_SIZE 10 + +/* Show the menu and handle menu entry selection. Returns the menu entry + index that should be executed or -1 if no entry should be executed (e.g., + Esc pressed to exit a sub-menu or switching menu viewers). + If the return value is not -1, then *AUTO_BOOT is nonzero iff the menu + entry to be executed is a result of an automatic default selection because + of the timeout. */ +static int +run_menu (grub_menu_t menu, int nested, int *auto_boot) +{ + grub_uint64_t saved_time; + int default_entry, current_entry; + int timeout; + enum timeout_style timeout_style; + + default_entry = get_entry_number (menu, "default"); + + /* If DEFAULT_ENTRY is not within the menu entries, fall back to + the first entry. */ + if (default_entry < 0 || default_entry >= menu->size) + default_entry = 0; + + timeout = grub_menu_get_timeout (); + if (timeout < 0) + /* If there is no timeout, the "countdown" and "hidden" styles result in + the system doing nothing and providing no or very little indication + why. Technically this is what the user asked for, but it's not very + useful and likely to be a source of confusion, so we disallow this. */ + grub_env_unset ("timeout_style"); + + timeout_style = get_timeout_style (); + + if (timeout_style == TIMEOUT_STYLE_COUNTDOWN + || timeout_style == TIMEOUT_STYLE_HIDDEN) + { + static struct grub_term_coordinate *pos; + int entry = -1; + + if (timeout_style == TIMEOUT_STYLE_COUNTDOWN && timeout) + { + pos = grub_term_save_pos (); + print_countdown (pos, timeout); + } + + /* Enter interruptible sleep until Escape or a menu hotkey is pressed, + or the timeout expires. */ + saved_time = grub_get_time_ms (); + while (1) + { + int key; + + key = grub_getkey_noblock (); + if (key != GRUB_TERM_NO_KEY) + { + entry = get_entry_index_by_hotkey (menu, key); + if (entry >= 0) + break; + } + if (key == GRUB_TERM_ESC) + { + timeout = -1; + break; + } + + if (timeout > 0 && has_second_elapsed (&saved_time)) + { + timeout--; + if (timeout_style == TIMEOUT_STYLE_COUNTDOWN) + print_countdown (pos, timeout); + } + + if (timeout == 0) + /* We will fall through to auto-booting the default entry. */ + break; + } + + grub_env_unset ("timeout"); + grub_env_unset ("timeout_style"); + if (entry >= 0) + { + *auto_boot = 0; + return entry; + } + } + + /* If timeout is 0, drawing is pointless (and ugly). */ + if (timeout == 0) + { + *auto_boot = 1; + return default_entry; + } + + current_entry = default_entry; + + refresh: + menu_init (current_entry, menu, nested); + + /* Initialize the time. */ + saved_time = grub_get_time_ms (); + + timeout = grub_menu_get_timeout (); + + if (timeout > 0) + menu_print_timeout (timeout); + else + clear_timeout (); + + while (1) + { + int c; + timeout = grub_menu_get_timeout (); + + if (grub_normal_exit_level) + return -1; + + if (timeout > 0 && has_second_elapsed (&saved_time)) + { + timeout--; + grub_menu_set_timeout (timeout); + menu_print_timeout (timeout); + } + + if (timeout == 0) + { + grub_env_unset ("timeout"); + *auto_boot = 1; + menu_fini (); + return default_entry; + } + + c = grub_getkey_noblock (); + + /* Negative values are returned on error. */ + if ((c != GRUB_TERM_NO_KEY) && (c > 0)) + { + if (timeout >= 0) + { + grub_env_unset ("timeout"); + grub_env_unset ("fallback"); + clear_timeout (); + } + + switch (c) + { + case GRUB_TERM_KEY_HOME: + case GRUB_TERM_CTRL | 'a': + current_entry = 0; + menu_set_chosen_entry (current_entry); + break; + + case GRUB_TERM_KEY_END: + case GRUB_TERM_CTRL | 'e': + current_entry = menu->size - 1; + menu_set_chosen_entry (current_entry); + break; + + case GRUB_TERM_KEY_UP: + case GRUB_TERM_CTRL | 'p': + case '^': + if (current_entry > 0) + current_entry--; + menu_set_chosen_entry (current_entry); + break; + + case GRUB_TERM_CTRL | 'n': + case GRUB_TERM_KEY_DOWN: + case 'v': + if (current_entry < menu->size - 1) + current_entry++; + menu_set_chosen_entry (current_entry); + break; + + case GRUB_TERM_CTRL | 'g': + case GRUB_TERM_KEY_PPAGE: + if (current_entry < GRUB_MENU_PAGE_SIZE) + current_entry = 0; + else + current_entry -= GRUB_MENU_PAGE_SIZE; + menu_set_chosen_entry (current_entry); + break; + + case GRUB_TERM_CTRL | 'c': + case GRUB_TERM_KEY_NPAGE: + if (current_entry + GRUB_MENU_PAGE_SIZE < menu->size) + current_entry += GRUB_MENU_PAGE_SIZE; + else + current_entry = menu->size - 1; + menu_set_chosen_entry (current_entry); + break; + + case '\n': + case '\r': + // case GRUB_TERM_KEY_RIGHT: + case GRUB_TERM_CTRL | 'f': + menu_fini (); + *auto_boot = 0; + return current_entry; + + case GRUB_TERM_ESC: + if (nested) + { + menu_fini (); + return -1; + } + break; + + case 'c': + menu_fini (); + grub_cmdline_run (1, 0); + goto refresh; + + case 'e': + menu_fini (); + { + grub_menu_entry_t e = grub_menu_get_entry (menu, current_entry); + if (e) + grub_menu_entry_run (e); + } + goto refresh; + + default: + { + int entry; + + entry = get_entry_index_by_hotkey (menu, c); + if (entry >= 0) + { + menu_fini (); + *auto_boot = 0; + return entry; + } + } + break; + } + } + } + + /* Never reach here. */ +} + +/* Callback invoked immediately before a menu entry is executed. */ +static void +notify_booting (grub_menu_entry_t entry, + void *userdata __attribute__((unused))) +{ + grub_printf (" "); + grub_printf_ (N_("Booting `%s'"), entry->title); + grub_printf ("\n\n"); +} + +/* Callback invoked when a default menu entry executed because of a timeout + has failed and an attempt will be made to execute the next fallback + entry, ENTRY. */ +static void +notify_fallback (grub_menu_entry_t entry, + void *userdata __attribute__((unused))) +{ + grub_printf ("\n "); + grub_printf_ (N_("Falling back to `%s'"), entry->title); + grub_printf ("\n\n"); + grub_millisleep (DEFAULT_ENTRY_ERROR_DELAY_MS); +} + +/* Callback invoked when a menu entry has failed and there is no remaining + fallback entry to attempt. */ +static void +notify_execution_failure (void *userdata __attribute__((unused))) +{ + if (grub_errno != GRUB_ERR_NONE) + { + grub_print_error (); + grub_errno = GRUB_ERR_NONE; + } + grub_printf ("\n "); + grub_printf_ (N_("Failed to boot both default and fallback entries.\n")); + grub_wait_after_message (); +} + +/* Callbacks used by the text menu to provide user feedback when menu entries + are executed. */ +static struct grub_menu_execute_callback execution_callback = +{ + .notify_booting = notify_booting, + .notify_fallback = notify_fallback, + .notify_failure = notify_execution_failure +}; + +static grub_err_t +show_menu (grub_menu_t menu, int nested, int autobooted) +{ + while (1) + { + int boot_entry; + grub_menu_entry_t e; + int auto_boot; + + boot_entry = run_menu (menu, nested, &auto_boot); + if (boot_entry < 0) + break; + + e = grub_menu_get_entry (menu, boot_entry); + if (! e) + continue; /* Menu is empty. */ + + grub_cls (); + + if (auto_boot) + grub_menu_execute_with_fallback (menu, e, autobooted, + &execution_callback, 0); + else + grub_menu_execute_entry (e, 0); + if (autobooted) + break; + } + + return GRUB_ERR_NONE; +} + +grub_err_t +grub_show_menu (grub_menu_t menu, int nested, int autoboot) +{ + grub_err_t err1, err2; + + while (1) + { + err1 = show_menu (menu, nested, autoboot); + autoboot = 0; + grub_print_error (); + + if (grub_normal_exit_level) + break; + + err2 = grub_auth_check_authentication (NULL); + if (err2) + { + grub_print_error (); + grub_errno = GRUB_ERR_NONE; + continue; + } + + break; + } + + return err1; +} diff --git a/GRUB2/grub-2.04/grub-core/ventoy/huffman.c b/GRUB2/grub-2.04/grub-core/ventoy/huffman.c new file mode 100644 index 00000000..1680056e --- /dev/null +++ b/GRUB2/grub-2.04/grub-core/ventoy/huffman.c @@ -0,0 +1,207 @@ +/* + * Copyright (C) 2014 Michael Brown . + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + */ + +/** + * @file + * + * Huffman alphabets + * + */ + +#include "wimboot.h" +#include "huffman.h" + +/** + * Transcribe binary value (for debugging) + * + * @v value Value + * @v bits Length of value (in bits) + * @ret string Transcribed value + */ +const char * huffman_bin ( unsigned long value, unsigned int bits ) { + static char buf[ ( 8 * sizeof ( value ) ) + 1 /* NUL */ ]; + char *out = buf; + + /* Sanity check */ + assert ( bits < sizeof ( buf ) ); + + /* Transcribe value */ + while ( bits-- ) + *(out++) = ( ( value & ( 1 << bits ) ) ? '1' : '0' ); + *out = '\0'; + + return buf; +} + +/** + * Dump Huffman alphabet (for debugging) + * + * @v alphabet Huffman alphabet + */ +static void __attribute__ (( unused )) +huffman_dump_alphabet ( struct huffman_alphabet *alphabet ) { + struct huffman_symbols *sym; + unsigned int bits; + unsigned int huf; + unsigned int i; + + (void)huf; + + /* Dump symbol table for each utilised length */ + for ( bits = 1 ; bits <= ( sizeof ( alphabet->huf ) / + sizeof ( alphabet->huf[0] ) ) ; bits++ ) { + sym = &alphabet->huf[ bits - 1 ]; + if ( sym->freq == 0 ) + continue; + huf = ( sym->start >> sym->shift ); + DBG ( "Huffman length %d start \"%s\" freq %d:", bits, + huffman_bin ( huf, sym->bits ), sym->freq ); + for ( i = 0 ; i < sym->freq ; i++ ) { + DBG ( " %03x", sym->raw[ huf + i ] ); + } + DBG ( "\n" ); + } + + /* Dump quick lookup table */ + DBG ( "Huffman quick lookup:" ); + for ( i = 0 ; i < ( sizeof ( alphabet->lookup ) / + sizeof ( alphabet->lookup[0] ) ) ; i++ ) { + DBG ( " %d", ( alphabet->lookup[i] + 1 ) ); + } + DBG ( "\n" ); +} + +/** + * Construct Huffman alphabet + * + * @v alphabet Huffman alphabet + * @v lengths Symbol length table + * @v count Number of symbols + * @ret rc Return status code + */ +int huffman_alphabet ( struct huffman_alphabet *alphabet, + uint8_t *lengths, unsigned int count ) { + struct huffman_symbols *sym; + unsigned int huf; + unsigned int cum_freq; + unsigned int bits; + unsigned int raw; + unsigned int adjustment; + unsigned int prefix; + int empty; + int complete; + + /* Clear symbol table */ + memset ( alphabet->huf, 0, sizeof ( alphabet->huf ) ); + + /* Count number of symbols with each Huffman-coded length */ + empty = 1; + for ( raw = 0 ; raw < count ; raw++ ) { + bits = lengths[raw]; + if ( bits ) { + alphabet->huf[ bits - 1 ].freq++; + empty = 0; + } + } + + /* In the degenerate case of having no symbols (i.e. an unused + * alphabet), generate a trivial alphabet with exactly two + * single-bit codes. This allows callers to avoid having to + * check for this special case. + */ + if ( empty ) + alphabet->huf[0].freq = 2; + + /* Populate Huffman-coded symbol table */ + huf = 0; + cum_freq = 0; + for ( bits = 1 ; bits <= ( sizeof ( alphabet->huf ) / + sizeof ( alphabet->huf[0] ) ) ; bits++ ) { + sym = &alphabet->huf[ bits - 1 ]; + sym->bits = bits; + sym->shift = ( HUFFMAN_BITS - bits ); + sym->start = ( huf << sym->shift ); + sym->raw = &alphabet->raw[cum_freq]; + huf += sym->freq; + if ( huf > ( 1U << bits ) ) { + DBG ( "Huffman alphabet has too many symbols with " + "lengths <=%d\n", bits ); + return -1; + } + huf <<= 1; + cum_freq += sym->freq; + } + complete = ( huf == ( 1U << bits ) ); + + /* Populate raw symbol table */ + for ( raw = 0 ; raw < count ; raw++ ) { + bits = lengths[raw]; + if ( bits ) { + sym = &alphabet->huf[ bits - 1 ]; + *(sym->raw++) = raw; + } + } + + /* Adjust Huffman-coded symbol table raw pointers and populate + * quick lookup table. + */ + for ( bits = 1 ; bits <= ( sizeof ( alphabet->huf ) / + sizeof ( alphabet->huf[0] ) ) ; bits++ ) { + sym = &alphabet->huf[ bits - 1 ]; + + /* Adjust raw pointer */ + sym->raw -= sym->freq; /* Reset to first symbol */ + adjustment = ( sym->start >> sym->shift ); + sym->raw -= adjustment; /* Adjust for quick indexing */ + + /* Populate quick lookup table */ + for ( prefix = ( sym->start >> HUFFMAN_QL_SHIFT ) ; + prefix < ( 1 << HUFFMAN_QL_BITS ) ; prefix++ ) { + alphabet->lookup[prefix] = ( bits - 1 ); + } + } + + /* Check that there are no invalid codes */ + if ( ! complete ) { + DBG ( "Huffman alphabet is incomplete\n" ); + return -1; + } + + return 0; +} + +/** + * Get Huffman symbol set + * + * @v alphabet Huffman alphabet + * @v huf Raw input value (normalised to HUFFMAN_BITS bits) + * @ret sym Huffman symbol set + */ +struct huffman_symbols * huffman_sym ( struct huffman_alphabet *alphabet, + unsigned int huf ) { + struct huffman_symbols *sym; + unsigned int lookup_index; + + /* Find symbol set for this length */ + lookup_index = ( huf >> HUFFMAN_QL_SHIFT ); + sym = &alphabet->huf[ alphabet->lookup[ lookup_index ] ]; + while ( huf < sym->start ) + sym--; + return sym; +} diff --git a/GRUB2/grub-2.04/grub-core/ventoy/huffman.h b/GRUB2/grub-2.04/grub-core/ventoy/huffman.h new file mode 100644 index 00000000..95bbae8c --- /dev/null +++ b/GRUB2/grub-2.04/grub-core/ventoy/huffman.h @@ -0,0 +1,108 @@ +#ifndef _HUFFMAN_H +#define _HUFFMAN_H + +/* + * Copyright (C) 2014 Michael Brown . + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + */ + +/** + * @file + * + * Huffman alphabets + * + */ + +/** Maximum length of a Huffman symbol (in bits) */ +#define HUFFMAN_BITS 16 + +/** Raw huffman symbol */ +typedef uint16_t huffman_raw_symbol_t; + +/** Quick lookup length for a Huffman symbol (in bits) + * + * This is a policy decision. + */ +#define HUFFMAN_QL_BITS 7 + +/** Quick lookup shift */ +#define HUFFMAN_QL_SHIFT ( HUFFMAN_BITS - HUFFMAN_QL_BITS ) + +/** A Huffman-coded set of symbols of a given length */ +struct huffman_symbols { + /** Length of Huffman-coded symbols (in bits) */ + uint8_t bits; + /** Shift to normalise symbols of this length to HUFFMAN_BITS bits */ + uint8_t shift; + /** Number of Huffman-coded symbols having this length */ + uint16_t freq; + /** First symbol of this length (normalised to HUFFMAN_BITS bits) + * + * Stored as a 32-bit value to allow the value + * (1<bits; +} + +/** + * Get Huffman symbol value + * + * @v sym Huffman symbol set + * @v huf Raw input value (normalised to HUFFMAN_BITS bits) + * @ret raw Raw symbol value + */ +static inline __attribute__ (( always_inline )) huffman_raw_symbol_t +huffman_raw ( struct huffman_symbols *sym, unsigned int huf ) { + + return sym->raw[ huf >> sym->shift ]; +} + +extern int huffman_alphabet ( struct huffman_alphabet *alphabet, + uint8_t *lengths, unsigned int count ); +extern struct huffman_symbols * +huffman_sym ( struct huffman_alphabet *alphabet, unsigned int huf ); + +#endif /* _HUFFMAN_H */ diff --git a/GRUB2/grub-2.04/grub-core/ventoy/lzx.c b/GRUB2/grub-2.04/grub-core/ventoy/lzx.c new file mode 100644 index 00000000..56dd7dd2 --- /dev/null +++ b/GRUB2/grub-2.04/grub-core/ventoy/lzx.c @@ -0,0 +1,666 @@ +/* + * Copyright (C) 2014 Michael Brown . + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + */ + +/** + * @file + * + * LZX decompression + * + * This algorithm is derived jointly from the document "[MS-PATCH]: + * LZX DELTA Compression and Decompression", available from + * + * http://msdn.microsoft.com/en-us/library/cc483133.aspx + * + * and from the file lzx-decompress.c in the wimlib source code. + * + */ + +#include "wimboot.h" +#include "huffman.h" +#include "lzx.h" + +/** Base positions, indexed by position slot */ +static unsigned int lzx_position_base[LZX_POSITION_SLOTS]; + +/** + * Attempt to accumulate bits from LZX bitstream + * + * @v lzx Decompressor + * @v bits Number of bits to accumulate + * @v norm_value Accumulated value (normalised to 16 bits) + * + * Note that there may not be sufficient accumulated bits in the + * bitstream; callers must check that sufficient bits are available + * before using the value. + */ +static int lzx_accumulate ( struct lzx *lzx, unsigned int bits ) { + const uint16_t *src16; + + /* Accumulate more bits if required */ + if ( ( lzx->bits < bits ) && + ( lzx->input.offset < lzx->input.len ) ) { + src16 = (const uint16_t *)( ( char * ) lzx->input.data + lzx->input.offset ); + lzx->input.offset += sizeof ( *src16 ); + lzx->accumulator |= ( *src16 << ( 16 - lzx->bits ) ); + lzx->bits += 16; + } + + return ( lzx->accumulator >> 16 ); +} + +/** + * Consume accumulated bits from LZX bitstream + * + * @v lzx Decompressor + * @v bits Number of bits to consume + * @ret rc Return status code + */ +static int lzx_consume ( struct lzx *lzx, unsigned int bits ) { + + /* Fail if insufficient bits are available */ + if ( lzx->bits < bits ) { + DBG ( "LZX input overrun in %#zx/%#zx out %#zx)\n", + lzx->input.offset, lzx->input.len, lzx->output.offset ); + return -1; + } + + /* Consume bits */ + lzx->accumulator <<= bits; + lzx->bits -= bits; + + return 0; +} + +/** + * Get bits from LZX bitstream + * + * @v lzx Decompressor + * @v bits Number of bits to fetch + * @ret value Value, or negative error + */ +static int lzx_getbits ( struct lzx *lzx, unsigned int bits ) { + int norm_value; + int rc; + + /* Accumulate more bits if required */ + norm_value = lzx_accumulate ( lzx, bits ); + + /* Consume bits */ + if ( ( rc = lzx_consume ( lzx, bits ) ) != 0 ) + return rc; + + return ( norm_value >> ( 16 - bits ) ); +} + +/** + * Align LZX bitstream for byte access + * + * @v lzx Decompressor + * @v bits Minimum number of padding bits + * @ret rc Return status code + */ +static int lzx_align ( struct lzx *lzx, unsigned int bits ) { + int pad; + + /* Get padding bits */ + pad = lzx_getbits ( lzx, bits ); + if ( pad < 0 ) + return pad; + + /* Consume all accumulated bits */ + lzx_consume ( lzx, lzx->bits ); + + return 0; +} + +/** + * Get bytes from LZX bitstream + * + * @v lzx Decompressor + * @v data Data buffer, or NULL + * @v len Length of data buffer + * @ret rc Return status code + */ +static int lzx_getbytes ( struct lzx *lzx, void *data, size_t len ) { + + /* Sanity check */ + if ( ( lzx->input.offset + len ) > lzx->input.len ) { + DBG ( "LZX input overrun in %#zx/%#zx out %#zx)\n", + lzx->input.offset, lzx->input.len, lzx->output.offset ); + return -1; + } + + /* Copy data */ + if ( data ) + memcpy ( data, ( lzx->input.data + lzx->input.offset ), len ); + lzx->input.offset += len; + + return 0; +} + +/** + * Decode LZX Huffman-coded symbol + * + * @v lzx Decompressor + * @v alphabet Huffman alphabet + * @ret raw Raw symbol, or negative error + */ +static int lzx_decode ( struct lzx *lzx, struct huffman_alphabet *alphabet ) { + struct huffman_symbols *sym; + int huf; + int rc; + + /* Accumulate sufficient bits */ + huf = lzx_accumulate ( lzx, HUFFMAN_BITS ); + if ( huf < 0 ) + return huf; + + /* Decode symbol */ + sym = huffman_sym ( alphabet, huf ); + + /* Consume bits */ + if ( ( rc = lzx_consume ( lzx, huffman_len ( sym ) ) ) != 0 ) + return rc; + + return huffman_raw ( sym, huf ); +} + +/** + * Generate Huffman alphabet from raw length table + * + * @v lzx Decompressor + * @v count Number of symbols + * @v bits Length of each length (in bits) + * @v lengths Lengths table to fill in + * @v alphabet Huffman alphabet to fill in + * @ret rc Return status code + */ +static int lzx_raw_alphabet ( struct lzx *lzx, unsigned int count, + unsigned int bits, uint8_t *lengths, + struct huffman_alphabet *alphabet ) { + unsigned int i; + int len; + int rc; + + /* Read lengths */ + for ( i = 0 ; i < count ; i++ ) { + len = lzx_getbits ( lzx, bits ); + if ( len < 0 ) + return len; + lengths[i] = len; + } + + /* Generate Huffman alphabet */ + if ( ( rc = huffman_alphabet ( alphabet, lengths, count ) ) != 0 ) + return rc; + + return 0; +} + +/** + * Generate pretree + * + * @v lzx Decompressor + * @v count Number of symbols + * @v lengths Lengths table to fill in + * @ret rc Return status code + */ +static int lzx_pretree ( struct lzx *lzx, unsigned int count, + uint8_t *lengths ) { + unsigned int i; + unsigned int length; + int dup = 0; + int code; + int rc; + + /* Generate pretree alphabet */ + if ( ( rc = lzx_raw_alphabet ( lzx, LZX_PRETREE_CODES, + LZX_PRETREE_BITS, lzx->pretree_lengths, + &lzx->pretree ) ) != 0 ) + return rc; + + /* Read lengths */ + for ( i = 0 ; i < count ; i++ ) { + + if ( dup ) { + + /* Duplicate previous length */ + lengths[i] = lengths[ i - 1 ]; + dup--; + + } else { + + /* Get next code */ + code = lzx_decode ( lzx, &lzx->pretree ); + if ( code < 0 ) + return code; + + /* Interpret code */ + if ( code <= 16 ) { + length = ( ( lengths[i] - code + 17 ) % 17 ); + } else if ( code == 17 ) { + length = 0; + dup = lzx_getbits ( lzx, 4 ); + if ( dup < 0 ) + return dup; + dup += 3; + } else if ( code == 18 ) { + length = 0; + dup = lzx_getbits ( lzx, 5 ); + if ( dup < 0 ) + return dup; + dup += 19; + } else if ( code == 19 ) { + length = 0; + dup = lzx_getbits ( lzx, 1 ); + if ( dup < 0 ) + return dup; + dup += 3; + code = lzx_decode ( lzx, &lzx->pretree ); + if ( code < 0 ) + return code; + length = ( ( lengths[i] - code + 17 ) % 17 ); + } else { + DBG ( "Unrecognised pretree code %d\n", code ); + return -1; + } + lengths[i] = length; + } + } + + /* Sanity check */ + if ( dup ) { + DBG ( "Pretree duplicate overrun\n" ); + return -1; + } + + return 0; +} + +/** + * Generate aligned offset Huffman alphabet + * + * @v lzx Decompressor + * @ret rc Return status code + */ +static int lzx_alignoffset_alphabet ( struct lzx *lzx ) { + int rc; + + /* Generate aligned offset alphabet */ + if ( ( rc = lzx_raw_alphabet ( lzx, LZX_ALIGNOFFSET_CODES, + LZX_ALIGNOFFSET_BITS, + lzx->alignoffset_lengths, + &lzx->alignoffset ) ) != 0 ) + return rc; + + return 0; +} + +/** + * Generate main Huffman alphabet + * + * @v lzx Decompressor + * @ret rc Return status code + */ +static int lzx_main_alphabet ( struct lzx *lzx ) { + int rc; + + /* Generate literal symbols pretree */ + if ( ( rc = lzx_pretree ( lzx, LZX_MAIN_LIT_CODES, + lzx->main_lengths.literals ) ) != 0 ) { + DBG ( "Could not construct main literal pretree\n" ); + return rc; + } + + /* Generate remaining symbols pretree */ + if ( ( rc = lzx_pretree ( lzx, ( LZX_MAIN_CODES - LZX_MAIN_LIT_CODES ), + lzx->main_lengths.remainder ) ) != 0 ) { + DBG ( "Could not construct main remainder pretree\n" ); + return rc; + } + + /* Generate Huffman alphabet */ + if ( ( rc = huffman_alphabet ( &lzx->main, lzx->main_lengths.literals, + LZX_MAIN_CODES ) ) != 0 ) { + DBG ( "Could not generate main alphabet\n" ); + return rc; + } + + return 0; +} + +/** + * Generate length Huffman alphabet + * + * @v lzx Decompressor + * @ret rc Return status code + */ +static int lzx_length_alphabet ( struct lzx *lzx ) { + int rc; + + /* Generate pretree */ + if ( ( rc = lzx_pretree ( lzx, LZX_LENGTH_CODES, + lzx->length_lengths ) ) != 0 ) { + DBG ( "Could not generate length pretree\n" ); + return rc; + } + + /* Generate Huffman alphabet */ + if ( ( rc = huffman_alphabet ( &lzx->length, lzx->length_lengths, + LZX_LENGTH_CODES ) ) != 0 ) { + DBG ( "Could not generate length alphabet\n" ); + return rc; + } + + return 0; +} + +/** + * Process LZX block header + * + * @v lzx Decompressor + * @ret rc Return status code + */ +static int lzx_block_header ( struct lzx *lzx ) { + size_t block_len; + int block_type; + int default_len; + int len_high; + int len_low; + int rc; + + /* Get block type */ + block_type = lzx_getbits ( lzx, LZX_BLOCK_TYPE_BITS ); + if ( block_type < 0 ) + return block_type; + lzx->block_type = block_type; + + /* Check block length */ + default_len = lzx_getbits ( lzx, 1 ); + if ( default_len < 0 ) + return default_len; + if ( default_len ) { + block_len = LZX_DEFAULT_BLOCK_LEN; + } else { + len_high = lzx_getbits ( lzx, 8 ); + if ( len_high < 0 ) + return len_high; + len_low = lzx_getbits ( lzx, 8 ); + if ( len_low < 0 ) + return len_low; + block_len = ( ( len_high << 8 ) | len_low ); + } + lzx->output.threshold = ( lzx->output.offset + block_len ); + + /* Handle block type */ + switch ( block_type ) { + case LZX_BLOCK_ALIGNOFFSET : + /* Generated aligned offset alphabet */ + if ( ( rc = lzx_alignoffset_alphabet ( lzx ) ) != 0 ) + return rc; + /* Fall through */ + case LZX_BLOCK_VERBATIM : + /* Generate main alphabet */ + if ( ( rc = lzx_main_alphabet ( lzx ) ) != 0 ) + return rc; + /* Generate lengths alphabet */ + if ( ( rc = lzx_length_alphabet ( lzx ) ) != 0 ) + return rc; + break; + case LZX_BLOCK_UNCOMPRESSED : + /* Align input stream */ + if ( ( rc = lzx_align ( lzx, 1 ) ) != 0 ) + return rc; + /* Read new repeated offsets */ + if ( ( rc = lzx_getbytes ( lzx, &lzx->repeated_offset, + sizeof ( lzx->repeated_offset )))!=0) + return rc; + break; + default: + DBG ( "Unrecognised block type %d\n", block_type ); + return -1; + } + + return 0; +} + +/** + * Process uncompressed data + * + * @v lzx Decompressor + * @ret rc Return status code + */ +static int lzx_uncompressed ( struct lzx *lzx ) { + void *data; + size_t len; + int rc; + + /* Copy bytes */ + data = ( lzx->output.data ? + ( lzx->output.data + lzx->output.offset ) : NULL ); + len = ( lzx->output.threshold - lzx->output.offset ); + if ( ( rc = lzx_getbytes ( lzx, data, len ) ) != 0 ) + return rc; + + /* Align input stream */ + if ( len % 2 ) + lzx->input.offset++; + + return 0; +} + +/** + * Process an LZX token + * + * @v lzx Decompressor + * @ret rc Return status code + * + * Variable names are chosen to match the LZX specification + * pseudo-code. + */ +static int lzx_token ( struct lzx *lzx ) { + unsigned int length_header; + unsigned int position_slot; + unsigned int offset_bits; + unsigned int i; + size_t match_offset; + size_t match_length; + int verbatim_bits; + int aligned_bits; + int maindata; + int length; + uint8_t *copy; + + /* Get maindata symelse*/ + maindata = lzx_decode ( lzx, &lzx->main ); + if ( maindata < 0 ) + return maindata; + + /* Check for literals */ + if ( maindata < LZX_MAIN_LIT_CODES ) { + if ( lzx->output.data ) + lzx->output.data[lzx->output.offset] = maindata; + lzx->output.offset++; + return 0; + } + maindata -= LZX_MAIN_LIT_CODES; + + /* Calculate the match length */ + length_header = ( maindata & 7 ); + if ( length_header == 7 ) { + length = lzx_decode ( lzx, &lzx->length ); + if ( length < 0 ) + return length; + } else { + length = 0; + } + match_length = ( length_header + 2 + length ); + + /* Calculate the position slot */ + position_slot = ( maindata >> 3 ); + if ( position_slot < LZX_REPEATED_OFFSETS ) { + + /* Repeated offset */ + match_offset = lzx->repeated_offset[position_slot]; + lzx->repeated_offset[position_slot] = lzx->repeated_offset[0]; + lzx->repeated_offset[0] = match_offset; + + } else { + + /* Non-repeated offset */ + offset_bits = lzx_footer_bits ( position_slot ); + if ( ( lzx->block_type == LZX_BLOCK_ALIGNOFFSET ) && + ( offset_bits >= 3 ) ) { + verbatim_bits = lzx_getbits ( lzx, ( offset_bits - 3 )); + if ( verbatim_bits < 0 ) + return verbatim_bits; + verbatim_bits <<= 3; + aligned_bits = lzx_decode ( lzx, &lzx->alignoffset ); + if ( aligned_bits < 0 ) + return aligned_bits; + } else { + verbatim_bits = lzx_getbits ( lzx, offset_bits ); + if ( verbatim_bits < 0 ) + return verbatim_bits; + aligned_bits = 0; + } + match_offset = ( lzx_position_base[position_slot] + + verbatim_bits + aligned_bits - 2 ); + + /* Update repeated offset list */ + for ( i = ( LZX_REPEATED_OFFSETS - 1 ) ; i > 0 ; i-- ) + lzx->repeated_offset[i] = lzx->repeated_offset[ i - 1 ]; + lzx->repeated_offset[0] = match_offset; + } + + /* Copy data */ + if ( match_offset > lzx->output.offset ) { + DBG ( "LZX match underrun out 0x%x offset 0x%x len 0x%x\n", + lzx->output.offset, match_offset, match_length ); + return -1; + } + if ( lzx->output.data ) { + copy = &lzx->output.data[lzx->output.offset]; + for ( i = 0 ; i < match_length ; i++ ) + copy[i] = copy[ i - match_offset ]; + } + lzx->output.offset += match_length; + + return 0; +} + +/** + * Translate E8 jump addresses + * + * @v lzx Decompressor + */ +static void lzx_translate_jumps ( struct lzx *lzx ) { + size_t offset; + int32_t *target; + + /* Sanity check */ + if ( lzx->output.offset < 10 ) + return; + + /* Scan for jump instructions */ + for ( offset = 0 ; offset < ( lzx->output.offset - 10 ) ; offset++ ) { + + /* Check for jump instruction */ + if ( lzx->output.data[offset] != 0xe8 ) + continue; + + /* Translate jump target */ + target = ( ( int32_t * ) &lzx->output.data[ offset + 1 ] ); + if ( *target >= 0 ) { + if ( *target < LZX_WIM_MAGIC_FILESIZE ) + *target -= offset; + } else { + if ( *target >= -( ( int32_t ) offset ) ) + *target += LZX_WIM_MAGIC_FILESIZE; + } + offset += sizeof ( *target ); + } +} + +/** + * Decompress LZX-compressed data + * + * @v data Compressed data + * @v len Length of compressed data + * @v buf Decompression buffer, or NULL + * @ret out_len Length of decompressed data, or negative error + */ +ssize_t lzx_decompress ( const void *data, size_t len, void *buf ) { + struct lzx lzx; + unsigned int i; + int rc; + + /* Sanity check */ + if ( len % 2 ) { + DBG ( "LZX cannot handle odd-length input data\n" ); + return -1; + } + + /* Initialise global state, if required */ + if ( ! lzx_position_base[ LZX_POSITION_SLOTS - 1 ] ) { + for ( i = 1 ; i < LZX_POSITION_SLOTS ; i++ ) { + lzx_position_base[i] = + ( lzx_position_base[i-1] + + ( 1 << lzx_footer_bits ( i - 1 ) ) ); + } + } + + /* Initialise decompressor */ + memset ( &lzx, 0, sizeof ( lzx ) ); + lzx.input.data = data; + lzx.input.len = len; + lzx.output.data = buf; + for ( i = 0 ; i < LZX_REPEATED_OFFSETS ; i++ ) + lzx.repeated_offset[i] = 1; + + /* Process blocks */ + while ( lzx.input.offset < lzx.input.len ) { + + /* Process block header */ + if ( ( rc = lzx_block_header ( &lzx ) ) != 0 ) + return rc; + + /* Process block contents */ + if ( lzx.block_type == LZX_BLOCK_UNCOMPRESSED ) { + + /* Copy uncompressed data */ + if ( ( rc = lzx_uncompressed ( &lzx ) ) != 0 ) + return rc; + + } else { + + /* Process token stream */ + while ( lzx.output.offset < lzx.output.threshold ) { + if ( ( rc = lzx_token ( &lzx ) ) != 0 ) + return rc; + } + } + } + + /* Postprocess to undo E8 jump compression */ + if ( lzx.output.data ) + lzx_translate_jumps ( &lzx ); + + return lzx.output.offset; +} diff --git a/GRUB2/grub-2.04/grub-core/ventoy/lzx.h b/GRUB2/grub-2.04/grub-core/ventoy/lzx.h new file mode 100644 index 00000000..6a4ed8fb --- /dev/null +++ b/GRUB2/grub-2.04/grub-core/ventoy/lzx.h @@ -0,0 +1,179 @@ +#ifndef _LZX_H +#define _LZX_H + +/* + * Copyright (C) 2014 Michael Brown . + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + */ + +/** + * @file + * + * LZX decompression + * + */ + +#include "huffman.h" + +/** Number of aligned offset codes */ +#define LZX_ALIGNOFFSET_CODES 8 + +/** Aligned offset code length (in bits) */ +#define LZX_ALIGNOFFSET_BITS 3 + +/** Number of pretree codes */ +#define LZX_PRETREE_CODES 20 + +/** Pretree code length (in bits) */ +#define LZX_PRETREE_BITS 4 + +/** Number of literal main codes */ +#define LZX_MAIN_LIT_CODES 256 + +/** Number of position slots */ +#define LZX_POSITION_SLOTS 30 + +/** Number of main codes */ +#define LZX_MAIN_CODES ( LZX_MAIN_LIT_CODES + ( 8 * LZX_POSITION_SLOTS ) ) + +/** Number of length codes */ +#define LZX_LENGTH_CODES 249 + +/** Block type length (in bits) */ +#define LZX_BLOCK_TYPE_BITS 3 + +/** Default block length */ +#define LZX_DEFAULT_BLOCK_LEN 32768 + +/** Number of repeated offsets */ +#define LZX_REPEATED_OFFSETS 3 + +/** Don't ask */ +#define LZX_WIM_MAGIC_FILESIZE 12000000 + +/** Block types */ +enum lzx_block_type { + /** Verbatim block */ + LZX_BLOCK_VERBATIM = 1, + /** Aligned offset block */ + LZX_BLOCK_ALIGNOFFSET = 2, + /** Uncompressed block */ + LZX_BLOCK_UNCOMPRESSED = 3, +}; + +/** An LZX input stream */ +struct lzx_input_stream { + /** Data */ + const uint8_t *data; + /** Length */ + size_t len; + /** Offset within stream */ + size_t offset; +}; + +/** An LZX output stream */ +struct lzx_output_stream { + /** Data, or NULL */ + uint8_t *data; + /** Offset within stream */ + size_t offset; + /** End of current block within stream */ + size_t threshold; +}; + +/** LZX decompressor */ +struct lzx { + /** Input stream */ + struct lzx_input_stream input; + /** Output stream */ + struct lzx_output_stream output; + /** Accumulator */ + uint32_t accumulator; + /** Number of bits in accumulator */ + unsigned int bits; + /** Block type */ + enum lzx_block_type block_type; + /** Repeated offsets */ + unsigned int repeated_offset[LZX_REPEATED_OFFSETS]; + + /** Aligned offset Huffman alphabet */ + struct huffman_alphabet alignoffset; + /** Aligned offset raw symbols + * + * Must immediately follow the aligned offset Huffman + * alphabet. + */ + huffman_raw_symbol_t alignoffset_raw[LZX_ALIGNOFFSET_CODES]; + /** Aligned offset code lengths */ + uint8_t alignoffset_lengths[LZX_ALIGNOFFSET_CODES]; + + /** Pretree Huffman alphabet */ + struct huffman_alphabet pretree; + /** Pretree raw symbols + * + * Must immediately follow the pretree Huffman alphabet. + */ + huffman_raw_symbol_t pretree_raw[LZX_PRETREE_CODES]; + /** Preetree code lengths */ + uint8_t pretree_lengths[LZX_PRETREE_CODES]; + + /** Main Huffman alphabet */ + struct huffman_alphabet main; + /** Main raw symbols + * + * Must immediately follow the main Huffman alphabet. + */ + huffman_raw_symbol_t main_raw[LZX_MAIN_CODES]; + /** Main code lengths */ + struct { + /** Literals */ + uint8_t literals[LZX_MAIN_LIT_CODES]; + /** Remaining symbols */ + uint8_t remainder[ LZX_MAIN_CODES - LZX_MAIN_LIT_CODES ]; + } __attribute__ (( packed )) main_lengths; + + /** Length Huffman alphabet */ + struct huffman_alphabet length; + /** Length raw symbols + * + * Must immediately follow the length Huffman alphabet. + */ + huffman_raw_symbol_t length_raw[LZX_LENGTH_CODES]; + /** Length code lengths */ + uint8_t length_lengths[LZX_LENGTH_CODES]; +}; + +/** + * Calculate number of footer bits for a given position slot + * + * @v position_slot Position slot + * @ret footer_bits Number of footer bits + */ +static inline unsigned int lzx_footer_bits ( unsigned int position_slot ) { + + if ( position_slot < 2 ) { + return 0; + } else if ( position_slot < 38 ) { + return ( ( position_slot / 2 ) - 1 ); + } else { + return 17; + } +} + +extern ssize_t lzx_decompress ( const void *data, size_t len, void *buf ); + +#endif /* _LZX_H */ diff --git a/GRUB2/grub-2.04/grub-core/ventoy/ventoy.c b/GRUB2/grub-2.04/grub-core/ventoy/ventoy.c new file mode 100644 index 00000000..15b7f54f --- /dev/null +++ b/GRUB2/grub-2.04/grub-core/ventoy/ventoy.c @@ -0,0 +1,1153 @@ +/****************************************************************************** + * ventoy.c + * + * Copyright (c) 2020, longpanda + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, see . + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "ventoy_def.h" + +GRUB_MOD_LICENSE ("GPLv3+"); + +int g_ventoy_debug = 0; +static int g_efi_os = 0xFF; +initrd_info *g_initrd_img_list = NULL; +initrd_info *g_initrd_img_tail = NULL; +int g_initrd_img_count = 0; +int g_valid_initrd_count = 0; + +static grub_file_t g_old_file; + +char g_img_swap_tmp_buf[1024]; + +img_info *g_ventoy_img_list = NULL; +int g_ventoy_img_count = 0; + +img_iterator_node g_img_iterator_head; + +grub_uint8_t g_ventoy_break_level = 0; +grub_uint8_t g_ventoy_debug_level = 0; +grub_uint8_t *g_ventoy_cpio_buf = NULL; +grub_uint32_t g_ventoy_cpio_size = 0; +cpio_newc_header *g_ventoy_initrd_head = NULL; +grub_uint8_t *g_ventoy_runtime_buf = NULL; + +ventoy_grub_param g_grub_param; + +ventoy_guid g_ventoy_guid = VENTOY_GUID; + +ventoy_img_chunk_list g_img_chunk_list; + +void ventoy_debug(const char *fmt, ...) +{ + va_list args; + + va_start (args, fmt); + grub_vprintf (fmt, args); + va_end (args); +} + +int ventoy_is_efi_os(void) +{ + if (g_efi_os > 1) + { + g_efi_os = (grub_strstr(GRUB_PLATFORM, "efi")) ? 1 : 0; + } + + return g_efi_os; +} + +static int ventoy_string_check(const char *str, grub_char_check_func check) +{ + if (!str) + { + return 0; + } + + for ( ; *str; str++) + { + if (!check(*str)) + { + return 0; + } + } + + return 1; +} + + +static grub_ssize_t ventoy_fs_read(grub_file_t file, char *buf, grub_size_t len) +{ + grub_memcpy(buf, (char *)file->data + file->offset, len); + return len; +} + +static grub_err_t ventoy_fs_close(grub_file_t file) +{ + grub_file_close(g_old_file); + grub_free(file->data); + + file->device = 0; + file->name = 0; + + return 0; +} + +static grub_file_t ventoy_wrapper_open(grub_file_t rawFile, enum grub_file_type type) +{ + int len; + grub_file_t file; + static struct grub_fs vtoy_fs = + { + .name = "vtoy", + .fs_dir = 0, + .fs_open = 0, + .fs_read = ventoy_fs_read, + .fs_close = ventoy_fs_close, + .fs_label = 0, + .next = 0 + }; + + if (type != 52) + { + return rawFile; + } + + file = (grub_file_t)grub_zalloc(sizeof (*file)); + if (!file) + { + return 0; + } + + file->data = grub_malloc(rawFile->size + 4096); + if (!file->data) + { + return 0; + } + + grub_file_read(rawFile, file->data, rawFile->size); + len = ventoy_fill_data(4096, (char *)file->data + rawFile->size); + + g_old_file = rawFile; + + file->size = rawFile->size + len; + file->device = rawFile->device; + file->fs = &vtoy_fs; + file->not_easily_seekable = 1; + + return file; +} + +static int ventoy_check_decimal_var(const char *name, long *value) +{ + const char *value_str = NULL; + + value_str = grub_env_get(name); + if (NULL == value_str) + { + return grub_error(GRUB_ERR_BAD_ARGUMENT, "Variable %s not found", name); + } + + if (!ventoy_is_decimal(value_str)) + { + return grub_error(GRUB_ERR_BAD_ARGUMENT, "Variable %s value '%s' is not an integer", name, value_str); + } + + *value = grub_strtol(value_str, NULL, 10); + + return GRUB_ERR_NONE; +} + +static grub_err_t ventoy_cmd_debug(grub_extcmd_context_t ctxt, int argc, char **args) +{ + if (argc != 1) + { + return grub_error(GRUB_ERR_BAD_ARGUMENT, "Usage: %s {on|off}", cmd_raw_name); + } + + if (0 == grub_strcmp(args[0], "on")) + { + g_ventoy_debug = 1; + grub_env_set("vtdebug_flag", "debug"); + } + else + { + g_ventoy_debug = 0; + grub_env_set("vtdebug_flag", ""); + } + + VENTOY_CMD_RETURN(GRUB_ERR_NONE); +} + +static grub_err_t ventoy_cmd_break(grub_extcmd_context_t ctxt, int argc, char **args) +{ + (void)ctxt; + + if (argc < 1 || (args[0][0] != '0' && args[0][0] != '1')) + { + grub_printf("Usage: %s {level} [debug]\r\n", cmd_raw_name); + grub_printf(" level:\r\n"); + grub_printf(" 01/11: busybox / (+cat log)\r\n"); + grub_printf(" 02/12: initrd / (+cat log)\r\n"); + grub_printf(" 03/13: hook / (+cat log)\r\n"); + grub_printf("\r\n"); + grub_printf(" debug:\r\n"); + grub_printf(" 0: debug is on\r\n"); + grub_printf(" 1: debug is off\r\n"); + grub_printf("\r\n"); + VENTOY_CMD_RETURN(GRUB_ERR_NONE); + } + + g_ventoy_break_level = (grub_uint8_t)grub_strtoul(args[0], NULL, 16); + + if (argc > 1 && grub_strtoul(args[1], NULL, 10) > 0) + { + g_ventoy_debug_level = 1; + } + + VENTOY_CMD_RETURN(GRUB_ERR_NONE); +} + +static grub_err_t ventoy_cmd_incr(grub_extcmd_context_t ctxt, int argc, char **args) +{ + long value_long = 0; + char buf[32]; + + if ((argc != 2) || (!ventoy_is_decimal(args[1]))) + { + return grub_error(GRUB_ERR_BAD_ARGUMENT, "Usage: %s {Variable} {Int}", cmd_raw_name); + } + + if (GRUB_ERR_NONE != ventoy_check_decimal_var(args[0], &value_long)) + { + return grub_errno; + } + + value_long += grub_strtol(args[1], NULL, 10); + + grub_snprintf(buf, sizeof(buf), "%ld", value_long); + grub_env_set(args[0], buf); + + VENTOY_CMD_RETURN(GRUB_ERR_NONE); +} + +static grub_err_t ventoy_cmd_is_udf(grub_extcmd_context_t ctxt, int argc, char **args) +{ + int i; + int rc = 1; + grub_file_t file; + grub_uint8_t buf[32]; + + (void)ctxt; + (void)argc; + (void)args; + + if (argc != 1) + { + return rc; + } + + file = ventoy_grub_file_open(VENTOY_FILE_TYPE, "%s", args[0]); + if (file == NULL) + { + debug("failed to open file <%s> for udf check\n", args[0]); + return 1; + } + + for (i = 16; i < 32; i++) + { + grub_file_seek(file, i * 2048); + grub_file_read(file, buf, sizeof(buf)); + if (buf[0] == 255) + { + break; + } + } + + i++; + grub_file_seek(file, i * 2048); + grub_file_read(file, buf, sizeof(buf)); + + if (grub_memcmp(buf + 1, "BEA01", 5) == 0) + { + i++; + grub_file_seek(file, i * 2048); + grub_file_read(file, buf, sizeof(buf)); + + if (grub_memcmp(buf + 1, "NSR02", 5) == 0 || + grub_memcmp(buf + 1, "NSR03", 5) == 0) + { + rc = 0; + } + } + + grub_file_close(file); + + debug("ISO UDF: %s\n", rc ? "NO" : "YES"); + + return rc; +} + +static grub_err_t ventoy_cmd_cmp(grub_extcmd_context_t ctxt, int argc, char **args) +{ + long value_long1 = 0; + long value_long2 = 0; + + if ((argc != 3) || (!ventoy_is_decimal(args[0])) || (!ventoy_is_decimal(args[2]))) + { + return grub_error(GRUB_ERR_BAD_ARGUMENT, "Usage: %s {Int1} { eq|ne|gt|lt|ge|le } {Int2}", cmd_raw_name); + } + + value_long1 = grub_strtol(args[0], NULL, 10); + value_long2 = grub_strtol(args[2], NULL, 10); + + if (0 == grub_strcmp(args[1], "eq")) + { + grub_errno = (value_long1 == value_long2) ? GRUB_ERR_NONE : GRUB_ERR_TEST_FAILURE; + } + else if (0 == grub_strcmp(args[1], "ne")) + { + grub_errno = (value_long1 != value_long2) ? GRUB_ERR_NONE : GRUB_ERR_TEST_FAILURE; + } + else if (0 == grub_strcmp(args[1], "gt")) + { + grub_errno = (value_long1 > value_long2) ? GRUB_ERR_NONE : GRUB_ERR_TEST_FAILURE; + } + else if (0 == grub_strcmp(args[1], "lt")) + { + grub_errno = (value_long1 < value_long2) ? GRUB_ERR_NONE : GRUB_ERR_TEST_FAILURE; + } + else if (0 == grub_strcmp(args[1], "ge")) + { + grub_errno = (value_long1 >= value_long2) ? GRUB_ERR_NONE : GRUB_ERR_TEST_FAILURE; + } + else if (0 == grub_strcmp(args[1], "le")) + { + grub_errno = (value_long1 <= value_long2) ? GRUB_ERR_NONE : GRUB_ERR_TEST_FAILURE; + } + else + { + return grub_error(GRUB_ERR_BAD_ARGUMENT, "Usage: %s {Int1} { eq ne gt lt ge le } {Int2}", cmd_raw_name); + } + + return grub_errno; +} + +static grub_err_t ventoy_cmd_device(grub_extcmd_context_t ctxt, int argc, char **args) +{ + char *pos = NULL; + char buf[128] = {0}; + + if (argc != 2) + { + return grub_error(GRUB_ERR_BAD_ARGUMENT, "Usage: %s path var", cmd_raw_name); + } + + grub_strncpy(buf, (args[0][0] == '(') ? args[0] + 1 : args[0], sizeof(buf) - 1); + pos = grub_strstr(buf, ","); + if (pos) + { + *pos = 0; + } + + grub_env_set(args[1], buf); + + VENTOY_CMD_RETURN(GRUB_ERR_NONE); +} + +static grub_err_t ventoy_cmd_check_compatible(grub_extcmd_context_t ctxt, int argc, char **args) +{ + int i; + char buf[256]; + grub_disk_t disk; + char *pos = NULL; + const char *files[] = { "ventoy.dat", "VENTOY.DAT" }; + + (void)ctxt; + + if (argc != 1) + { + return grub_error(GRUB_ERR_BAD_ARGUMENT, "Usage: %s (loop)", cmd_raw_name); + } + + for (i = 0; i < (int)ARRAY_SIZE(files); i++) + { + grub_snprintf(buf, sizeof(buf) - 1, "[ -e %s/%s ]", args[0], files[i]); + if (0 == grub_script_execute_sourcecode(buf)) + { + debug("file %s exist, ventoy_compatible YES\n", buf); + grub_env_set("ventoy_compatible", "YES"); + VENTOY_CMD_RETURN(GRUB_ERR_NONE); + } + else + { + debug("file %s NOT exist\n", buf); + } + } + + grub_snprintf(buf, sizeof(buf) - 1, "%s", args[0][0] == '(' ? (args[0] + 1) : args[0]); + pos = grub_strstr(buf, ")"); + if (pos) + { + *pos = 0; + } + + disk = grub_disk_open(buf); + if (disk) + { + grub_disk_read(disk, 16 << 2, 0, 1024, g_img_swap_tmp_buf); + grub_disk_close(disk); + + g_img_swap_tmp_buf[703] = 0; + for (i = 319; i < 703; i++) + { + if (g_img_swap_tmp_buf[i] == 'V' && + 0 == grub_strncmp(g_img_swap_tmp_buf + i, VENTOY_COMPATIBLE_STR, VENTOY_COMPATIBLE_STR_LEN)) + { + debug("Ventoy compatible string exist at %d, ventoy_compatible YES\n", i); + grub_env_set("ventoy_compatible", "YES"); + VENTOY_CMD_RETURN(GRUB_ERR_NONE); + } + } + } + else + { + debug("failed to open disk <%s>\n", buf); + } + + grub_env_set("ventoy_compatible", "NO"); + VENTOY_CMD_RETURN(GRUB_ERR_NONE); +} + +static int ventoy_cmp_img(img_info *img1, img_info *img2) +{ + char *s1, *s2; + int c1 = 0; + int c2 = 0; + + for (s1 = img1->name, s2 = img2->name; *s1 && *s2; s1++, s2++) + { + c1 = *s1; + c2 = *s2; + + if (grub_islower(c1)) + { + c1 = c1 - 'a' + 'A'; + } + + if (grub_islower(c2)) + { + c2 = c2 - 'a' + 'A'; + } + + if (c1 != c2) + { + break; + } + } + + return (c1 - c2); +} + +static void ventoy_swap_img(img_info *img1, img_info *img2) +{ + grub_memcpy(g_img_swap_tmp_buf, img1->name, sizeof(img1->name)); + grub_memcpy(img1->name, img2->name, sizeof(img1->name)); + grub_memcpy(img2->name, g_img_swap_tmp_buf, sizeof(img1->name)); + + grub_memcpy(g_img_swap_tmp_buf, img1->path, sizeof(img1->path)); + grub_memcpy(img1->path, img2->path, sizeof(img1->path)); + grub_memcpy(img2->path, g_img_swap_tmp_buf, sizeof(img1->path)); +} + +static int ventoy_img_name_valid(const char *filename, grub_size_t namelen) +{ + grub_size_t i; + + for (i = 0; i < namelen; i++) + { + if (filename[i] == ' ' || filename[i] == '\t') + { + return 0; + } + + if ((grub_uint8_t)(filename[i]) >= 127) + { + return 0; + } + } + + return 1; +} + +static int ventoy_colect_img_files(const char *filename, const struct grub_dirhook_info *info, void *data) +{ + grub_size_t len; + img_info *img; + img_info *tail; + img_iterator_node *new_node; + img_iterator_node *node = (img_iterator_node *)data; + + len = grub_strlen(filename); + + if (info->dir) + { + if ((len == 1 && filename[0] == '.') || + (len == 2 && filename[0] == '.' && filename[1] == '.')) + { + return 0; + } + + new_node = grub_malloc(sizeof(img_iterator_node)); + if (new_node) + { + new_node->tail = node->tail; + grub_snprintf(new_node->dir, sizeof(new_node->dir), "%s%s/", node->dir, filename); + + new_node->next = g_img_iterator_head.next; + g_img_iterator_head.next = new_node; + } + } + else + { + debug("Find a file %s\n", filename); + + if ((len > 4) && (0 == grub_strcasecmp(filename + len - 4, ".iso"))) + { + if (!ventoy_img_name_valid(filename, len)) + { + return 0; + } + + img = grub_zalloc(sizeof(img_info)); + if (img) + { + grub_snprintf(img->name, sizeof(img->name), "%s", filename); + grub_snprintf(img->path, sizeof(img->path), "%s%s", node->dir, filename); + + if (g_ventoy_img_list) + { + tail = *(node->tail); + img->prev = tail; + tail->next = img; + } + else + { + g_ventoy_img_list = img; + } + + *((img_info **)(node->tail)) = img; + g_ventoy_img_count++; + + debug("Add %s%s to list %d\n", node->dir, filename, g_ventoy_img_count); + } + } + } + + return 0; +} + +int ventoy_fill_data(grub_uint32_t buflen, char *buffer) +{ + int len = GRUB_UINT_MAX; + const char *value = NULL; + char name[32] = {0}; + char plat[32] = {0}; + char guidstr[32] = {0}; + ventoy_guid guid = VENTOY_GUID; + const char *fmt1 = NULL; + const char *fmt2 = NULL; + const char *fmt3 = NULL; + grub_uint32_t *puint = (grub_uint32_t *)name; + grub_uint32_t *puint2 = (grub_uint32_t *)plat; + const char fmtdata[]={ 0x39, 0x35, 0x25, 0x00, 0x35, 0x00, 0x23, 0x30, 0x30, 0x30, 0x30, 0x66, 0x66, 0x00 }; + const char fmtcode[]={ + 0x22, 0x0A, 0x2B, 0x20, 0x68, 0x62, 0x6F, 0x78, 0x20, 0x7B, 0x0A, 0x20, 0x20, 0x74, 0x6F, 0x70, + 0x20, 0x3D, 0x20, 0x25, 0x73, 0x0A, 0x20, 0x20, 0x6C, 0x65, 0x66, 0x74, 0x20, 0x3D, 0x20, 0x25, + 0x73, 0x0A, 0x20, 0x20, 0x2B, 0x20, 0x6C, 0x61, 0x62, 0x65, 0x6C, 0x20, 0x7B, 0x74, 0x65, 0x78, + 0x74, 0x20, 0x3D, 0x20, 0x22, 0x25, 0x73, 0x20, 0x25, 0x73, 0x25, 0x73, 0x22, 0x20, 0x63, 0x6F, + 0x6C, 0x6F, 0x72, 0x20, 0x3D, 0x20, 0x22, 0x25, 0x73, 0x22, 0x20, 0x61, 0x6C, 0x69, 0x67, 0x6E, + 0x20, 0x3D, 0x20, 0x22, 0x6C, 0x65, 0x66, 0x74, 0x22, 0x7D, 0x0A, 0x7D, 0x0A, 0x22, 0x00 + }; + + grub_memset(name, 0, sizeof(name)); + puint[0] = grub_swap_bytes32(0x56454e54); + puint[3] = grub_swap_bytes32(0x4f4e0000); + puint[2] = grub_swap_bytes32(0x45525349); + puint[1] = grub_swap_bytes32(0x4f595f56); + value = ventoy_get_env(name); + + grub_memset(name, 0, sizeof(name)); + puint[1] = grub_swap_bytes32(0x5f544f50); + puint[0] = grub_swap_bytes32(0x56544c45); + fmt1 = ventoy_get_env(name); + if (!fmt1) + { + fmt1 = fmtdata; + } + + grub_memset(name, 0, sizeof(name)); + puint[1] = grub_swap_bytes32(0x5f4c4654); + puint[0] = grub_swap_bytes32(0x56544c45); + fmt2 = ventoy_get_env(name); + + grub_memset(name, 0, sizeof(name)); + puint[1] = grub_swap_bytes32(0x5f434c52); + puint[0] = grub_swap_bytes32(0x56544c45); + fmt3 = ventoy_get_env(name); + + grub_memcpy(guidstr, &guid, sizeof(guid)); + + #if defined (GRUB_MACHINE_EFI) + puint2[0] = grub_swap_bytes32(0x55454649); + #else + puint2[0] = grub_swap_bytes32(0x42494f53); + #endif + + /* Easter egg :) It will be appreciated if you reserve it, but NOT mandatory. */ + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wformat-nonliteral" + len = grub_snprintf(buffer, buflen, fmtcode, + fmt1 ? fmt1 : fmtdata, + fmt2 ? fmt2 : fmtdata + 4, + value ? value : "", plat, guidstr, + fmt3 ? fmt3 : fmtdata + 6); + #pragma GCC diagnostic pop + + grub_memset(name, 0, sizeof(name)); + puint[0] = grub_swap_bytes32(0x76746f79); + puint[2] = grub_swap_bytes32(0x656e7365); + puint[1] = grub_swap_bytes32(0x5f6c6963); + ventoy_set_env(name, guidstr); + + return len; +} + +static grub_err_t ventoy_cmd_list_img(grub_extcmd_context_t ctxt, int argc, char **args) +{ + grub_fs_t fs; + grub_device_t dev = NULL; + img_info *cur = NULL; + img_info *tail = NULL; + char *device_name = NULL; + char buf[32]; + img_iterator_node *node = NULL; + + (void)ctxt; + + if (argc != 2) + { + return grub_error(GRUB_ERR_BAD_ARGUMENT, "Usage: %s {device} {cntvar}", cmd_raw_name); + } + + if (g_ventoy_img_list || g_ventoy_img_count) + { + return grub_error(GRUB_ERR_BAD_ARGUMENT, "Must clear image before list"); + } + + device_name = grub_file_get_device_name(args[0]); + if (!device_name) + { + goto fail; + } + + dev = grub_device_open(device_name); + if (!dev) + { + goto fail; + } + + fs = grub_fs_probe(dev); + if (!fs) + { + goto fail; + } + + grub_memset(&g_img_iterator_head, 0, sizeof(g_img_iterator_head)); + + g_img_iterator_head.tail = &tail; + grub_strcpy(g_img_iterator_head.dir, "/"); + + fs->fs_dir(dev, "/", ventoy_colect_img_files, &g_img_iterator_head); + + while (g_img_iterator_head.next) + { + node = g_img_iterator_head.next; + g_img_iterator_head.next = node->next; + + fs->fs_dir(dev, node->dir, ventoy_colect_img_files, node); + grub_free(node); + } + + /* sort image list by image name */ + for (cur = g_ventoy_img_list; cur; cur = cur->next) + { + for (tail = cur->next; tail; tail = tail->next) + { + if (ventoy_cmp_img(cur, tail) > 0) + { + ventoy_swap_img(cur, tail); + } + } + } + + grub_snprintf(buf, sizeof(buf), "%d", g_ventoy_img_count); + grub_env_set(args[1], buf); + +fail: + + check_free(device_name, grub_free); + check_free(dev, grub_device_close); + + VENTOY_CMD_RETURN(GRUB_ERR_NONE); +} + + +static grub_err_t ventoy_cmd_clear_img(grub_extcmd_context_t ctxt, int argc, char **args) +{ + img_info *next = NULL; + img_info *cur = g_ventoy_img_list; + + (void)ctxt; + (void)argc; + (void)args; + + while (cur) + { + next = cur->next; + grub_free(cur); + cur = next; + } + + g_ventoy_img_list = NULL; + g_ventoy_img_count = 0; + + VENTOY_CMD_RETURN(GRUB_ERR_NONE); +} + +static grub_err_t ventoy_cmd_img_name(grub_extcmd_context_t ctxt, int argc, char **args) +{ + long img_id = 0; + img_info *cur = g_ventoy_img_list; + + (void)ctxt; + + if (argc != 2 || (!ventoy_is_decimal(args[0]))) + { + return grub_error(GRUB_ERR_BAD_ARGUMENT, "Usage: %s {imageID} {var}", cmd_raw_name); + } + + img_id = grub_strtol(args[0], NULL, 10); + if (img_id >= g_ventoy_img_count) + { + return grub_error(GRUB_ERR_BAD_ARGUMENT, "No such many images %ld %ld", img_id, g_ventoy_img_count); + } + + debug("Find image %ld name \n", img_id); + + while (cur && img_id > 0) + { + img_id--; + cur = cur->next; + } + + if (!cur) + { + return grub_error(GRUB_ERR_BAD_ARGUMENT, "No such many images"); + } + + debug("image name is %s\n", cur->name); + + grub_env_set(args[1], cur->name); + + VENTOY_CMD_RETURN(GRUB_ERR_NONE); +} + +static grub_err_t ventoy_cmd_chosen_img_path(grub_extcmd_context_t ctxt, int argc, char **args) +{ + const char *name = NULL; + img_info *cur = g_ventoy_img_list; + + (void)ctxt; + + if (argc != 1) + { + return grub_error(GRUB_ERR_BAD_ARGUMENT, "Usage: %s {var}", cmd_raw_name); + } + + name = grub_env_get("chosen"); + + while (cur) + { + if (0 == grub_strcmp(name, cur->name)) + { + grub_env_set(args[0], cur->path); + break; + } + cur = cur->next; + } + + if (!cur) + { + return grub_error(GRUB_ERR_BAD_ARGUMENT, "No such image"); + } + + VENTOY_CMD_RETURN(GRUB_ERR_NONE); +} + +static int ventoy_get_disk_guid(const char *filename, grub_uint8_t *guid) +{ + grub_disk_t disk; + char *device_name; + char *pos; + char *pos2; + + device_name = grub_file_get_device_name(filename); + if (!device_name) + { + return 1; + } + + pos = device_name; + if (pos[0] == '(') + { + pos++; + } + + pos2 = grub_strstr(pos, ","); + if (!pos2) + { + pos2 = grub_strstr(pos, ")"); + } + + if (pos2) + { + *pos2 = 0; + } + + disk = grub_disk_open(pos); + if (disk) + { + grub_disk_read(disk, 0, 0x180, 16, guid); + grub_disk_close(disk); + } + else + { + return 1; + } + + grub_free(device_name); + return 0; +} + +grub_uint32_t ventoy_get_iso_boot_catlog(grub_file_t file) +{ + eltorito_descriptor desc; + + grub_memset(&desc, 0, sizeof(desc)); + grub_file_seek(file, 17 * 2048); + grub_file_read(file, &desc, sizeof(desc)); + + if (desc.type != 0 || desc.version != 1) + { + return 0; + } + + if (grub_strncmp((char *)desc.id, "CD001", 5) != 0 || + grub_strncmp((char *)desc.system_id, "EL TORITO SPECIFICATION", 23) != 0) + { + return 0; + } + + return desc.sector; +} + +int ventoy_has_efi_eltorito(grub_file_t file, grub_uint32_t sector) +{ + int i; + grub_uint8_t buf[512]; + + grub_file_seek(file, sector * 2048); + grub_file_read(file, buf, sizeof(buf)); + + if (buf[0] == 0x01 && buf[1] == 0xEF) + { + debug("%s efi eltorito in Validation Entry\n", file->name); + return 1; + } + + for (i = 64; i < (int)sizeof(buf); i += 32) + { + if ((buf[i] == 0x90 || buf[i] == 0x91) && buf[i + 1] == 0xEF) + { + debug("%s efi eltorito offset %d 0x%02x\n", file->name, i, buf[i]); + return 1; + } + } + + debug("%s does not contain efi eltorito\n", file->name); + return 0; +} + +void ventoy_fill_os_param(grub_file_t file, ventoy_os_param *param) +{ + char *pos; + grub_uint32_t i; + grub_uint8_t chksum = 0; + grub_disk_t disk; + + disk = file->device->disk; + grub_memcpy(¶m->guid, &g_ventoy_guid, sizeof(ventoy_guid)); + + param->vtoy_disk_size = disk->total_sectors * (1 << disk->log_sector_size); + param->vtoy_disk_part_id = disk->partition->number + 1; + + if (grub_strcmp(file->fs->name, "exfat") == 0) + { + param->vtoy_disk_part_type = 0; + } + else if (grub_strcmp(file->fs->name, "ntfs") == 0) + { + param->vtoy_disk_part_type = 1; + } + else + { + param->vtoy_disk_part_type = 0xFFFF; + } + + pos = grub_strstr(file->name, "/"); + if (!pos) + { + pos = file->name; + } + + grub_snprintf(param->vtoy_img_path, sizeof(param->vtoy_img_path), "%s", pos); + + ventoy_get_disk_guid(file->name, param->vtoy_disk_guid); + + param->vtoy_img_size = file->size; + + param->vtoy_reserved[0] = g_ventoy_break_level; + param->vtoy_reserved[1] = g_ventoy_debug_level; + + /* calculate checksum */ + for (i = 0; i < sizeof(ventoy_os_param); i++) + { + chksum += *((grub_uint8_t *)param + i); + } + param->chksum = (grub_uint8_t)(0x100 - chksum); + + return; +} + +static grub_err_t ventoy_cmd_img_sector(grub_extcmd_context_t ctxt, int argc, char **args) +{ + grub_file_t file; + + (void)ctxt; + (void)argc; + + file = ventoy_grub_file_open(VENTOY_FILE_TYPE, "%s", args[0]); + if (!file) + { + return grub_error(GRUB_ERR_BAD_ARGUMENT, "Can't open file %s\n", args[0]); + } + + if (g_img_chunk_list.chunk) + { + grub_free(g_img_chunk_list.chunk); + } + + /* get image chunk data */ + grub_memset(&g_img_chunk_list, 0, sizeof(g_img_chunk_list)); + g_img_chunk_list.chunk = grub_malloc(sizeof(ventoy_img_chunk) * DEFAULT_CHUNK_NUM); + if (NULL == g_img_chunk_list.chunk) + { + return grub_error(GRUB_ERR_OUT_OF_MEMORY, "Can't allocate image chunk memoty\n"); + } + + g_img_chunk_list.max_chunk = DEFAULT_CHUNK_NUM; + g_img_chunk_list.cur_chunk = 0; + + debug("get fat file chunk part start:%llu\n", (unsigned long long)file->device->disk->partition->start); + grub_fat_get_file_chunk(file->device->disk->partition->start, file, &g_img_chunk_list); + + grub_file_close(file); + + VENTOY_CMD_RETURN(GRUB_ERR_NONE); +} + +static grub_err_t ventoy_cmd_dump_img_sector(grub_extcmd_context_t ctxt, int argc, char **args) +{ + grub_uint32_t i; + ventoy_img_chunk *cur; + + (void)ctxt; + (void)argc; + (void)args; + + for (i = 0; i < g_img_chunk_list.cur_chunk; i++) + { + cur = g_img_chunk_list.chunk + i; + grub_printf("image:[%u - %u] <==> disk:[%llu - %llu]\n", + cur->img_start_sector, cur->img_end_sector, + (unsigned long long)cur->disk_start_sector, (unsigned long long)cur->disk_end_sector + ); + } + + VENTOY_CMD_RETURN(GRUB_ERR_NONE); +} + +grub_file_t ventoy_grub_file_open(enum grub_file_type type, const char *fmt, ...) +{ + va_list ap; + grub_file_t file; + char fullpath[256] = {0}; + + va_start (ap, fmt); + grub_vsnprintf(fullpath, 255, fmt, ap); + va_end (ap); + + file = grub_file_open(fullpath, type); + if (!file) + { + debug("grub_file_open failed <%s>\n", fullpath); + grub_errno = 0; + } + + return file; +} + +int ventoy_is_file_exist(const char *fmt, ...) +{ + va_list ap; + int len; + char *pos = NULL; + char buf[256] = {0}; + + grub_snprintf(buf, sizeof(buf), "%s", "[ -f "); + pos = buf + 5; + + va_start (ap, fmt); + len = grub_vsnprintf(pos, 255, fmt, ap); + va_end (ap); + + grub_strncpy(pos + len, " ]", 2); + + debug("script exec %s\n", buf); + + if (0 == grub_script_execute_sourcecode(buf)) + { + return 1; + } + + return 0; +} + +static int ventoy_env_init(void) +{ + char buf[64]; + + grub_env_set("vtdebug_flag", ""); + + ventoy_filt_register(0, ventoy_wrapper_open); + + g_grub_param.grub_env_get = grub_env_get; + grub_snprintf(buf, sizeof(buf), "%p", &g_grub_param); + grub_env_set("env_param", buf); + + return 0; +} + +static cmd_para ventoy_cmds[] = +{ + { "vt_incr", ventoy_cmd_incr, 0, NULL, "{Var} {INT}", "Increase integer variable", NULL }, + { "vt_debug", ventoy_cmd_debug, 0, NULL, "{on|off}", "turn debug on/off", NULL }, + { "vtdebug", ventoy_cmd_debug, 0, NULL, "{on|off}", "turn debug on/off", NULL }, + { "vtbreak", ventoy_cmd_break, 0, NULL, "{level}", "set debug break", NULL }, + { "vt_cmp", ventoy_cmd_cmp, 0, NULL, "{Int1} { eq|ne|gt|lt|ge|le } {Int2}", "Comare two integers", NULL }, + { "vt_device", ventoy_cmd_device, 0, NULL, "path var", "", NULL }, + { "vt_check_compatible", ventoy_cmd_check_compatible, 0, NULL, "", "", NULL }, + { "vt_list_img", ventoy_cmd_list_img, 0, NULL, "{device} {cntvar}", "find all iso file in device", NULL }, + { "vt_clear_img", ventoy_cmd_clear_img, 0, NULL, "", "clear image list", NULL }, + { "vt_img_name", ventoy_cmd_img_name, 0, NULL, "{imageID} {var}", "get image name", NULL }, + { "vt_chosen_img_path", ventoy_cmd_chosen_img_path, 0, NULL, "{var}", "get chosen img path", NULL }, + { "vt_img_sector", ventoy_cmd_img_sector, 0, NULL, "{imageName}", "", NULL }, + { "vt_dump_img_sector", ventoy_cmd_dump_img_sector, 0, NULL, "", "", NULL }, + { "vt_load_cpio", ventoy_cmd_load_cpio, 0, NULL, "", "", NULL }, + + { "vt_is_udf", ventoy_cmd_is_udf, 0, NULL, "", "", NULL }, + + { "vt_linux_parse_initrd_isolinux", ventoy_cmd_isolinux_initrd_collect, 0, NULL, "{cfgfile}", "", NULL }, + { "vt_linux_parse_initrd_grub", ventoy_cmd_grub_initrd_collect, 0, NULL, "{cfgfile}", "", NULL }, + { "vt_linux_specify_initrd_file", ventoy_cmd_specify_initrd_file, 0, NULL, "", "", NULL }, + { "vt_linux_clear_initrd", ventoy_cmd_clear_initrd_list, 0, NULL, "", "", NULL }, + { "vt_linux_dump_initrd", ventoy_cmd_dump_initrd_list, 0, NULL, "", "", NULL }, + { "vt_linux_initrd_count", ventoy_cmd_initrd_count, 0, NULL, "", "", NULL }, + { "vt_linux_locate_initrd", ventoy_cmd_linux_locate_initrd, 0, NULL, "", "", NULL }, + { "vt_linux_chain_data", ventoy_cmd_linux_chain_data, 0, NULL, "", "", NULL }, + + { "vt_windows_reset", ventoy_cmd_wimdows_reset, 0, NULL, "", "", NULL }, + { "vt_windows_locate_wim", ventoy_cmd_wimdows_locate_wim, 0, NULL, "", "", NULL }, + { "vt_windows_chain_data", ventoy_cmd_windows_chain_data, 0, NULL, "", "", NULL }, + + { "vt_load_plugin", ventoy_cmd_load_plugin, 0, NULL, "", "", NULL }, +}; + + + +GRUB_MOD_INIT(ventoy) +{ + grub_uint32_t i; + cmd_para *cur = NULL; + + ventoy_env_init(); + + for (i = 0; i < ARRAY_SIZE(ventoy_cmds); i++) + { + cur = ventoy_cmds + i; + cur->cmd = grub_register_extcmd(cur->name, cur->func, cur->flags, + cur->summary, cur->description, cur->parser); + } +} + +GRUB_MOD_FINI(ventoy) +{ + grub_uint32_t i; + + for (i = 0; i < ARRAY_SIZE(ventoy_cmds); i++) + { + grub_unregister_extcmd(ventoy_cmds[i].cmd); + } +} + diff --git a/GRUB2/grub-2.04/grub-core/ventoy/ventoy_def.h b/GRUB2/grub-2.04/grub-core/ventoy/ventoy_def.h new file mode 100644 index 00000000..4b28bc26 --- /dev/null +++ b/GRUB2/grub-2.04/grub-core/ventoy/ventoy_def.h @@ -0,0 +1,507 @@ +/****************************************************************************** + * ventoy_def.h + * + * Copyright (c) 2020, longpanda + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, see . + * + */ + +#ifndef __VENTOY_DEF_H__ +#define __VENTOY_DEF_H__ + +#define JSON_SUCCESS 0 +#define JSON_FAILED 1 +#define JSON_NOT_FOUND 2 + +#define ulonglong unsigned long long + +#define vtoy_to_upper(c) (((char)(c) >= 'a' && (char)(c) <= 'z') ? ((char)(c) - 'a' + 'A') : (char)(c)) + +#define VENTOY_CMD_RETURN(err) grub_errno = (err); return (err) +#define VENTOY_FILE_TYPE (GRUB_FILE_TYPE_NO_DECOMPRESS | GRUB_FILE_TYPE_LINUX_INITRD) + +#define ventoy_env_op1(op, a) grub_env_##op(a) +#define ventoy_env_op2(op, a, b) grub_env_##op((a), (b)) + +#define ventoy_get_env(key) ventoy_env_op1(get, key) +#define ventoy_set_env(key, val) ventoy_env_op2(set, key, val) + +typedef struct ventoy_initrd_ctx +{ + const char *path_prefix; + const char *dir_prefix; +}ventoy_initrd_ctx; + +typedef struct cmd_para +{ + const char *name; + grub_extcmd_func_t func; + grub_command_flags_t flags; + const struct grub_arg_option *parser; + + const char *summary; + const char *description; + + grub_extcmd_t cmd; +}cmd_para; + +#define ventoy_align(value, align) (((value) + ((align) - 1)) & (~((align) - 1))) + +#pragma pack(1) +typedef struct cpio_newc_header +{ + char c_magic[6]; + char c_ino[8]; + char c_mode[8]; + char c_uid[8]; + char c_gid[8]; + char c_nlink[8]; + char c_mtime[8]; + char c_filesize[8]; + char c_devmajor[8]; + char c_devminor[8]; + char c_rdevmajor[8]; + char c_rdevminor[8]; + char c_namesize[8]; + char c_check[8]; +}cpio_newc_header; +#pragma pack() + + +#define cmd_raw_name ctxt->extcmd->cmd->name +#define check_free(p, func) if (p) { func(p); p = NULL; } + +typedef int (*grub_char_check_func)(int c); +#define ventoy_is_decimal(str) ventoy_string_check(str, grub_isdigit) + + +// El Torito Boot Record Volume Descriptor +#pragma pack(1) +typedef struct eltorito_descriptor +{ + grub_uint8_t type; + grub_uint8_t id[5]; + grub_uint8_t version; + grub_uint8_t system_id[32]; + grub_uint8_t reserved[32]; + grub_uint32_t sector; +}eltorito_descriptor; + +typedef struct ventoy_iso9660_override +{ + grub_uint32_t first_sector; + grub_uint32_t first_sector_be; + grub_uint32_t size; + grub_uint32_t size_be; +}ventoy_iso9660_override; + +typedef struct ventoy_udf_override +{ + grub_uint32_t length; + grub_uint32_t position; +}ventoy_udf_override; + +#pragma pack() + + +typedef struct img_info +{ + char path[512]; + char name[256]; + + struct img_info *next; + struct img_info *prev; +}img_info; + +typedef struct img_iterator_node +{ + struct img_iterator_node *next; + img_info **tail; + char dir[400]; +}img_iterator_node; + +typedef struct initrd_info +{ + char name[256]; + + grub_uint64_t offset; + grub_uint64_t size; + + grub_uint8_t iso_type; // 0: iso9660 1:udf + grub_uint32_t udf_start_block; + + grub_uint64_t override_offset; + grub_uint32_t override_length; + char override_data[32]; + + struct initrd_info *next; + struct initrd_info *prev; +}initrd_info; + +extern initrd_info *g_initrd_img_list; +extern initrd_info *g_initrd_img_tail; +extern int g_initrd_img_count; +extern int g_valid_initrd_count; + +extern img_info *g_ventoy_img_list; +extern int g_ventoy_img_count; + +extern grub_uint8_t *g_ventoy_cpio_buf; +extern grub_uint32_t g_ventoy_cpio_size; +extern cpio_newc_header *g_ventoy_initrd_head; +extern grub_uint8_t *g_ventoy_runtime_buf; + +extern ventoy_guid g_ventoy_guid; + +extern ventoy_img_chunk_list g_img_chunk_list; + +extern int g_ventoy_debug; +void ventoy_debug(const char *fmt, ...); +#define debug(fmt, ...) if (g_ventoy_debug) ventoy_debug("[VTOY]: "fmt, __VA_ARGS__) + + + +#define FLAG_HEADER_RESERVED 0x00000001 +#define FLAG_HEADER_COMPRESSION 0x00000002 +#define FLAG_HEADER_READONLY 0x00000004 +#define FLAG_HEADER_SPANNED 0x00000008 +#define FLAG_HEADER_RESOURCE_ONLY 0x00000010 +#define FLAG_HEADER_METADATA_ONLY 0x00000020 +#define FLAG_HEADER_WRITE_IN_PROGRESS 0x00000040 +#define FLAG_HEADER_RP_FIX 0x00000080 // reparse point fixup +#define FLAG_HEADER_COMPRESS_RESERVED 0x00010000 +#define FLAG_HEADER_COMPRESS_XPRESS 0x00020000 +#define FLAG_HEADER_COMPRESS_LZX 0x00040000 + +#define RESHDR_FLAG_FREE 0x01 +#define RESHDR_FLAG_METADATA 0x02 +#define RESHDR_FLAG_COMPRESSED 0x04 +#define RESHDR_FLAG_SPANNED 0x08 + +#pragma pack(1) + +/* A WIM resource header */ +typedef struct wim_resource_header +{ + grub_uint64_t size_in_wim:56; /* Compressed length */ + grub_uint64_t flags:8; /* flags */ + grub_uint64_t offset; /* Offset */ + grub_uint64_t raw_size; /* Uncompressed length */ +}wim_resource_header; + +/* WIM resource header length mask */ +#define WIM_RESHDR_ZLEN_MASK 0x00ffffffffffffffULL + +/* WIM resource header flags */ +typedef enum wim_resource_header_flags +{ + WIM_RESHDR_METADATA = ( 0x02ULL << 56 ), /* Resource contains metadata */ + WIM_RESHDR_COMPRESSED = ( 0x04ULL << 56 ), /* Resource is compressed */ + WIM_RESHDR_PACKED_STREAMS = ( 0x10ULL << 56 ), /* Resource is compressed using packed streams */ +}wim_resource_header_flags; + +#define WIM_HEAD_SIGNATURE "MSWIM\0\0" + +/* WIM header */ +typedef struct wim_header +{ + grub_uint8_t signature[8]; /* Signature */ + grub_uint32_t header_len; /* Header length */ + grub_uint32_t version; /* Verson */ + grub_uint32_t flags; /* Flags */ + grub_uint32_t chunk_len; /* Chunk length */ + grub_uint8_t guid[16]; /* GUID */ + grub_uint16_t part; /* Part number */ + grub_uint16_t parts; /* Total number of parts */ + grub_uint32_t images; /* number of images */ + wim_resource_header lookup; /* Lookup table */ + wim_resource_header xml; /* XML data */ + wim_resource_header metadata; /* Boot metadata */ + grub_uint32_t boot_index; /* Boot index */ + wim_resource_header integrity; /* Integrity table */ + grub_uint8_t reserved[60]; /* Reserved */ +} wim_header; + +/* WIM header flags */ +typedef enum wim_header_flags +{ + WIM_HDR_XPRESS = 0x00020000, /* WIM uses Xpress compresson */ + WIM_HDR_LZX = 0x00040000, /* WIM uses LZX compression */ +}wim_header_flags; + +/* A WIM file hash */ +typedef struct wim_hash +{ + /* SHA-1 hash */ + grub_uint8_t sha1[20]; +}wim_hash; + +/* A WIM lookup table entry */ +typedef struct wim_lookup_entry +{ + wim_resource_header resource; /* Resource header */ + grub_uint16_t part; /* Part number */ + grub_uint32_t refcnt; /* Reference count */ + wim_hash hash; /* Hash */ +}wim_lookup_entry; + +/* WIM chunk length */ +#define WIM_CHUNK_LEN 32768 + +/* A WIM chunk buffer */ +typedef struct wim_chunk_buffer +{ + grub_uint8_t data[WIM_CHUNK_LEN]; /*Data */ +}wim_chunk_buffer; + +/* Security data */ +typedef struct wim_security_header +{ + grub_uint32_t len; /* Length */ + grub_uint32_t count; /* Number of entries */ +}wim_security_header; + +/* Directory entry */ +typedef struct wim_directory_entry +{ + grub_uint64_t len; /* Length */ + grub_uint32_t attributes; /* Attributes */ + grub_uint32_t security; /* Security ID */ + grub_uint64_t subdir; /* Subdirectory offset */ + grub_uint8_t reserved1[16]; /* Reserved */ + grub_uint64_t created; /* Creation time */ + grub_uint64_t accessed; /* Last access time */ + grub_uint64_t written; /* Last written time */ + wim_hash hash; /* Hash */ + grub_uint8_t reserved2[12]; /* Reserved */ + grub_uint16_t streams; /* Streams */ + grub_uint16_t short_name_len; /* Short name length */ + grub_uint16_t name_len; /* Name length */ +}wim_directory_entry; + +/** Normal file */ +#define WIM_ATTR_NORMAL 0x00000080UL + +/** No security information exists for this file */ +#define WIM_NO_SECURITY 0xffffffffUL + +#pragma pack() + + +typedef struct wim_tail +{ + grub_uint32_t wim_raw_size; + grub_uint32_t wim_align_size; + + grub_uint8_t iso_type; + grub_uint64_t file_offset; + grub_uint32_t udf_start_block; + grub_uint64_t fe_entry_size_offset; + grub_uint64_t override_offset; + grub_uint32_t override_len; + grub_uint8_t override_data[32]; + + wim_header wim_header; + + wim_hash bin_hash; + grub_uint32_t jump_exe_len; + grub_uint8_t *jump_bin_data; + grub_uint32_t bin_raw_len; + grub_uint32_t bin_align_len; + + grub_uint8_t *new_meta_data; + grub_uint32_t new_meta_len; + grub_uint32_t new_meta_align_len; + + grub_uint8_t *new_lookup_data; + grub_uint32_t new_lookup_len; + grub_uint32_t new_lookup_align_len; +}wim_tail; + + + +typedef enum _JSON_TYPE +{ + JSON_TYPE_NUMBER = 0, + JSON_TYPE_STRING, + JSON_TYPE_BOOL, + JSON_TYPE_ARRAY, + JSON_TYPE_OBJECT, + JSON_TYPE_NULL, + JSON_TYPE_BUTT +}JSON_TYPE; + + +typedef struct _VTOY_JSON +{ + struct _VTOY_JSON *pstPrev; + struct _VTOY_JSON *pstNext; + struct _VTOY_JSON *pstChild; + + JSON_TYPE enDataType; + union + { + char *pcStrVal; + int iNumVal; + grub_uint64_t lValue; + }unData; + + char *pcName; +}VTOY_JSON; + +typedef struct _JSON_PARSE +{ + char *pcKey; + void *pDataBuf; + grub_uint32_t uiBufSize; +}JSON_PARSE; + +#define JSON_NEW_ITEM(pstJson, ret) \ +{ \ + (pstJson) = (VTOY_JSON *)grub_zalloc(sizeof(VTOY_JSON)); \ + if (NULL == (pstJson)) \ + { \ + json_debug("Failed to alloc memory for json.\n"); \ + return (ret); \ + } \ +} + +typedef int (*ventoy_plugin_entry_pf)(VTOY_JSON *json, const char *isodisk); + +typedef struct plugin_entry +{ + const char *key; + ventoy_plugin_entry_pf entryfunc; +}plugin_entry; + + +void ventoy_fill_os_param(grub_file_t file, ventoy_os_param *param); +grub_err_t ventoy_cmd_isolinux_initrd_collect(grub_extcmd_context_t ctxt, int argc, char **args); +grub_err_t ventoy_cmd_grub_initrd_collect(grub_extcmd_context_t ctxt, int argc, char **args); +grub_err_t ventoy_cmd_specify_initrd_file(grub_extcmd_context_t ctxt, int argc, char **args); +grub_err_t ventoy_cmd_dump_initrd_list(grub_extcmd_context_t ctxt, int argc, char **args); +grub_err_t ventoy_cmd_clear_initrd_list(grub_extcmd_context_t ctxt, int argc, char **args); +grub_uint32_t ventoy_get_iso_boot_catlog(grub_file_t file); +int ventoy_has_efi_eltorito(grub_file_t file, grub_uint32_t sector); +grub_err_t ventoy_cmd_linux_chain_data(grub_extcmd_context_t ctxt, int argc, char **args); +grub_err_t ventoy_cmd_linux_locate_initrd(grub_extcmd_context_t ctxt, int argc, char **args); +grub_err_t ventoy_cmd_initrd_count(grub_extcmd_context_t ctxt, int argc, char **args); +grub_err_t ventoy_cmd_load_cpio(grub_extcmd_context_t ctxt, int argc, char **args); +int ventoy_cpio_newc_fill_head(void *buf, int filesize, void *filedata, const char *name); +grub_file_t ventoy_grub_file_open(enum grub_file_type type, const char *fmt, ...); +int ventoy_is_file_exist(const char *fmt, ...); +int ventoy_fill_data(grub_uint32_t buflen, char *buffer); +grub_err_t ventoy_cmd_load_plugin(grub_extcmd_context_t ctxt, int argc, char **args); +grub_err_t ventoy_cmd_wimdows_reset(grub_extcmd_context_t ctxt, int argc, char **args); +grub_err_t ventoy_cmd_wimdows_locate_wim(grub_extcmd_context_t ctxt, int argc, char **args); +grub_err_t ventoy_cmd_windows_chain_data(grub_extcmd_context_t ctxt, int argc, char **args); + +VTOY_JSON *vtoy_json_find_item +( + VTOY_JSON *pstJson, + JSON_TYPE enDataType, + const char *szKey +); +int vtoy_json_parse_value +( + char *pcNewStart, + char *pcRawStart, + VTOY_JSON *pstJson, + const char *pcData, + const char **ppcEnd +); +VTOY_JSON * vtoy_json_create(void); +int vtoy_json_parse(VTOY_JSON *pstJson, const char *szJsonData); + +int vtoy_json_scan_parse +( + const VTOY_JSON *pstJson, + grub_uint32_t uiParseNum, + JSON_PARSE *pstJsonParse +); + +int vtoy_json_scan_array +( + VTOY_JSON *pstJson, + const char *szKey, + VTOY_JSON **ppstArrayItem +); + +int vtoy_json_scan_array_ex +( + VTOY_JSON *pstJson, + const char *szKey, + VTOY_JSON **ppstArrayItem +); +int vtoy_json_scan_object +( + VTOY_JSON *pstJson, + const char *szKey, + VTOY_JSON **ppstObjectItem +); +int vtoy_json_get_int +( + VTOY_JSON *pstJson, + const char *szKey, + int *piValue +); +int vtoy_json_get_uint +( + VTOY_JSON *pstJson, + const char *szKey, + grub_uint32_t *puiValue +); +int vtoy_json_get_uint64 +( + VTOY_JSON *pstJson, + const char *szKey, + grub_uint64_t *pui64Value +); +int vtoy_json_get_bool +( + VTOY_JSON *pstJson, + const char *szKey, + grub_uint8_t *pbValue +); +int vtoy_json_get_string +( + VTOY_JSON *pstJson, + const char *szKey, + grub_uint32_t uiBufLen, + char *pcBuf +); +const char * vtoy_json_get_string_ex(VTOY_JSON *pstJson, const char *szKey); +int vtoy_json_destroy(VTOY_JSON *pstJson); + + +grub_uint32_t CalculateCrc32 +( + const void *Buffer, + grub_uint32_t Length, + grub_uint32_t InitValue +); + +static inline int ventoy_isspace (int c) +{ + return (c == '\n' || c == '\r' || c == ' ' || c == '\t'); +} + +static inline int ventoy_is_word_end(int c) +{ + return (c == 0 || c == ',' || ventoy_isspace(c)); +} + +#endif /* __VENTOY_DEF_H__ */ + diff --git a/GRUB2/grub-2.04/grub-core/ventoy/ventoy_json.c b/GRUB2/grub-2.04/grub-core/ventoy/ventoy_json.c new file mode 100644 index 00000000..8a4e8b10 --- /dev/null +++ b/GRUB2/grub-2.04/grub-core/ventoy/ventoy_json.c @@ -0,0 +1,736 @@ +/****************************************************************************** + * ventoy_json.c + * + * Copyright (c) 2020, longpanda + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, see . + * + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "ventoy_def.h" + +GRUB_MOD_LICENSE ("GPLv3+"); + +static void json_debug(const char *fmt, ...) +{ + va_list args; + + va_start (args, fmt); + grub_vprintf (fmt, args); + va_end (args); + + grub_printf("\n"); +} + +static void vtoy_json_free(VTOY_JSON *pstJsonHead) +{ + VTOY_JSON *pstNext = NULL; + + while (NULL != pstJsonHead) + { + pstNext = pstJsonHead->pstNext; + if ((pstJsonHead->enDataType < JSON_TYPE_BUTT) && (NULL != pstJsonHead->pstChild)) + { + vtoy_json_free(pstJsonHead->pstChild); + } + + grub_free(pstJsonHead); + pstJsonHead = pstNext; + } + + return; +} + +static char *vtoy_json_skip(const char *pcData) +{ + while ((NULL != pcData) && ('\0' != *pcData) && (*pcData <= 32)) + { + pcData++; + } + + return (char *)pcData; +} + +VTOY_JSON *vtoy_json_find_item +( + VTOY_JSON *pstJson, + JSON_TYPE enDataType, + const char *szKey +) +{ + while (NULL != pstJson) + { + if ((enDataType == pstJson->enDataType) && + (0 == grub_strcmp(szKey, pstJson->pcName))) + { + return pstJson; + } + pstJson = pstJson->pstNext; + } + + return NULL; +} + +static int vtoy_json_parse_number +( + VTOY_JSON *pstJson, + const char *pcData, + const char **ppcEnd +) +{ + unsigned long Value; + + Value = grub_strtoul(pcData, (char **)ppcEnd, 10); + if (*ppcEnd == pcData) + { + json_debug("Failed to parse json number %s.", pcData); + return JSON_FAILED; + } + + pstJson->enDataType = JSON_TYPE_NUMBER; + pstJson->unData.lValue = Value; + + return JSON_SUCCESS; +} + +static int vtoy_json_parse_string +( + char *pcNewStart, + char *pcRawStart, + VTOY_JSON *pstJson, + const char *pcData, + const char **ppcEnd +) +{ + grub_uint32_t uiLen = 0; + const char *pcPos = NULL; + const char *pcTmp = pcData + 1; + + *ppcEnd = pcData; + + if ('\"' != *pcData) + { + return JSON_FAILED; + } + + pcPos = grub_strchr(pcTmp, '\"'); + if ((NULL == pcPos) || (pcPos < pcTmp)) + { + json_debug("Invalid string %s.", pcData); + return JSON_FAILED; + } + + *ppcEnd = pcPos + 1; + uiLen = (grub_uint32_t)(unsigned long)(pcPos - pcTmp); + + pstJson->enDataType = JSON_TYPE_STRING; + pstJson->unData.pcStrVal = pcNewStart + (pcTmp - pcRawStart); + pstJson->unData.pcStrVal[uiLen] = '\0'; + + return JSON_SUCCESS; +} + +static int vtoy_json_parse_array +( + char *pcNewStart, + char *pcRawStart, + VTOY_JSON *pstJson, + const char *pcData, + const char **ppcEnd +) +{ + int Ret = JSON_SUCCESS; + VTOY_JSON *pstJsonChild = NULL; + VTOY_JSON *pstJsonItem = NULL; + const char *pcTmp = pcData + 1; + + *ppcEnd = pcData; + pstJson->enDataType = JSON_TYPE_ARRAY; + + if ('[' != *pcData) + { + return JSON_FAILED; + } + + pcTmp = vtoy_json_skip(pcTmp); + + if (']' == *pcTmp) + { + *ppcEnd = pcTmp + 1; + return JSON_SUCCESS; + } + + JSON_NEW_ITEM(pstJson->pstChild, JSON_FAILED); + + Ret = vtoy_json_parse_value(pcNewStart, pcRawStart, pstJson->pstChild, pcTmp, ppcEnd); + if (JSON_SUCCESS != Ret) + { + json_debug("Failed to parse array child."); + return JSON_FAILED; + } + + pstJsonChild = pstJson->pstChild; + pcTmp = vtoy_json_skip(*ppcEnd); + while ((NULL != pcTmp) && (',' == *pcTmp)) + { + JSON_NEW_ITEM(pstJsonItem, JSON_FAILED); + pstJsonChild->pstNext = pstJsonItem; + pstJsonItem->pstPrev = pstJsonChild; + pstJsonChild = pstJsonItem; + + Ret = vtoy_json_parse_value(pcNewStart, pcRawStart, pstJsonChild, vtoy_json_skip(pcTmp + 1), ppcEnd); + if (JSON_SUCCESS != Ret) + { + json_debug("Failed to parse array child."); + return JSON_FAILED; + } + pcTmp = vtoy_json_skip(*ppcEnd); + } + + if ((NULL != pcTmp) && (']' == *pcTmp)) + { + *ppcEnd = pcTmp + 1; + return JSON_SUCCESS; + } + else + { + *ppcEnd = pcTmp; + return JSON_FAILED; + } +} + +static int vtoy_json_parse_object +( + char *pcNewStart, + char *pcRawStart, + VTOY_JSON *pstJson, + const char *pcData, + const char **ppcEnd +) +{ + int Ret = JSON_SUCCESS; + VTOY_JSON *pstJsonChild = NULL; + VTOY_JSON *pstJsonItem = NULL; + const char *pcTmp = pcData + 1; + + *ppcEnd = pcData; + pstJson->enDataType = JSON_TYPE_OBJECT; + + if ('{' != *pcData) + { + return JSON_FAILED; + } + + pcTmp = vtoy_json_skip(pcTmp); + if ('}' == *pcTmp) + { + *ppcEnd = pcTmp + 1; + return JSON_SUCCESS; + } + + JSON_NEW_ITEM(pstJson->pstChild, JSON_FAILED); + + Ret = vtoy_json_parse_string(pcNewStart, pcRawStart, pstJson->pstChild, pcTmp, ppcEnd); + if (JSON_SUCCESS != Ret) + { + json_debug("Failed to parse array child."); + return JSON_FAILED; + } + + pstJsonChild = pstJson->pstChild; + pstJsonChild->pcName = pstJsonChild->unData.pcStrVal; + pstJsonChild->unData.pcStrVal = NULL; + + pcTmp = vtoy_json_skip(*ppcEnd); + if ((NULL == pcTmp) || (':' != *pcTmp)) + { + *ppcEnd = pcTmp; + return JSON_FAILED; + } + + Ret = vtoy_json_parse_value(pcNewStart, pcRawStart, pstJsonChild, vtoy_json_skip(pcTmp + 1), ppcEnd); + if (JSON_SUCCESS != Ret) + { + json_debug("Failed to parse array child."); + return JSON_FAILED; + } + + pcTmp = vtoy_json_skip(*ppcEnd); + while ((NULL != pcTmp) && (',' == *pcTmp)) + { + JSON_NEW_ITEM(pstJsonItem, JSON_FAILED); + pstJsonChild->pstNext = pstJsonItem; + pstJsonItem->pstPrev = pstJsonChild; + pstJsonChild = pstJsonItem; + + Ret = vtoy_json_parse_string(pcNewStart, pcRawStart, pstJsonChild, vtoy_json_skip(pcTmp + 1), ppcEnd); + if (JSON_SUCCESS != Ret) + { + json_debug("Failed to parse array child."); + return JSON_FAILED; + } + + pcTmp = vtoy_json_skip(*ppcEnd); + pstJsonChild->pcName = pstJsonChild->unData.pcStrVal; + pstJsonChild->unData.pcStrVal = NULL; + if ((NULL == pcTmp) || (':' != *pcTmp)) + { + *ppcEnd = pcTmp; + return JSON_FAILED; + } + + Ret = vtoy_json_parse_value(pcNewStart, pcRawStart, pstJsonChild, vtoy_json_skip(pcTmp + 1), ppcEnd); + if (JSON_SUCCESS != Ret) + { + json_debug("Failed to parse array child."); + return JSON_FAILED; + } + + pcTmp = vtoy_json_skip(*ppcEnd); + } + + if ((NULL != pcTmp) && ('}' == *pcTmp)) + { + *ppcEnd = pcTmp + 1; + return JSON_SUCCESS; + } + else + { + *ppcEnd = pcTmp; + return JSON_FAILED; + } +} + +int vtoy_json_parse_value +( + char *pcNewStart, + char *pcRawStart, + VTOY_JSON *pstJson, + const char *pcData, + const char **ppcEnd +) +{ + pcData = vtoy_json_skip(pcData); + + switch (*pcData) + { + case 'n': + { + if (0 == grub_strncmp(pcData, "null", 4)) + { + pstJson->enDataType = JSON_TYPE_NULL; + *ppcEnd = pcData + 4; + return JSON_SUCCESS; + } + break; + } + case 'f': + { + if (0 == grub_strncmp(pcData, "false", 5)) + { + pstJson->enDataType = JSON_TYPE_BOOL; + pstJson->unData.lValue = 0; + *ppcEnd = pcData + 5; + return JSON_SUCCESS; + } + break; + } + case 't': + { + if (0 == grub_strncmp(pcData, "true", 4)) + { + pstJson->enDataType = JSON_TYPE_BOOL; + pstJson->unData.lValue = 1; + *ppcEnd = pcData + 4; + return JSON_SUCCESS; + } + break; + } + case '\"': + { + return vtoy_json_parse_string(pcNewStart, pcRawStart, pstJson, pcData, ppcEnd); + } + case '[': + { + return vtoy_json_parse_array(pcNewStart, pcRawStart, pstJson, pcData, ppcEnd); + } + case '{': + { + return vtoy_json_parse_object(pcNewStart, pcRawStart, pstJson, pcData, ppcEnd); + } + case '-': + { + return vtoy_json_parse_number(pstJson, pcData, ppcEnd); + } + default : + { + if (*pcData >= '0' && *pcData <= '9') + { + return vtoy_json_parse_number(pstJson, pcData, ppcEnd); + } + } + } + + *ppcEnd = pcData; + json_debug("Invalid json data %u.", (grub_uint8_t)(*pcData)); + return JSON_FAILED; +} + +VTOY_JSON * vtoy_json_create(void) +{ + VTOY_JSON *pstJson = NULL; + + pstJson = (VTOY_JSON *)grub_zalloc(sizeof(VTOY_JSON)); + if (NULL == pstJson) + { + return NULL; + } + + return pstJson; +} + +int vtoy_json_parse(VTOY_JSON *pstJson, const char *szJsonData) +{ + grub_uint32_t uiMemSize = 0; + int Ret = JSON_SUCCESS; + char *pcNewBuf = NULL; + const char *pcEnd = NULL; + + uiMemSize = grub_strlen(szJsonData) + 1; + pcNewBuf = (char *)grub_malloc(uiMemSize); + if (NULL == pcNewBuf) + { + json_debug("Failed to alloc new buf."); + return JSON_FAILED; + } + grub_memcpy(pcNewBuf, szJsonData, uiMemSize); + pcNewBuf[uiMemSize - 1] = 0; + + Ret = vtoy_json_parse_value(pcNewBuf, (char *)szJsonData, pstJson, szJsonData, &pcEnd); + if (JSON_SUCCESS != Ret) + { + json_debug("Failed to parse json data %s start=%p, end=%p:%s.", + szJsonData, szJsonData, pcEnd, pcEnd); + return JSON_FAILED; + } + + return JSON_SUCCESS; +} + +int vtoy_json_scan_parse +( + const VTOY_JSON *pstJson, + grub_uint32_t uiParseNum, + JSON_PARSE *pstJsonParse +) +{ + grub_uint32_t i = 0; + const VTOY_JSON *pstJsonCur = NULL; + JSON_PARSE *pstCurParse = NULL; + + for (pstJsonCur = pstJson; NULL != pstJsonCur; pstJsonCur = pstJsonCur->pstNext) + { + if ((JSON_TYPE_OBJECT == pstJsonCur->enDataType) || + (JSON_TYPE_ARRAY == pstJsonCur->enDataType)) + { + continue; + } + + for (i = 0, pstCurParse = NULL; i < uiParseNum; i++) + { + if (0 == grub_strcmp(pstJsonParse[i].pcKey, pstJsonCur->pcName)) + { + pstCurParse = pstJsonParse + i; + break; + } + } + + if (NULL == pstCurParse) + { + continue; + } + + switch (pstJsonCur->enDataType) + { + case JSON_TYPE_NUMBER: + { + if (sizeof(grub_uint32_t) == pstCurParse->uiBufSize) + { + *(grub_uint32_t *)(pstCurParse->pDataBuf) = (grub_uint32_t)pstJsonCur->unData.lValue; + } + else if (sizeof(grub_uint16_t) == pstCurParse->uiBufSize) + { + *(grub_uint16_t *)(pstCurParse->pDataBuf) = (grub_uint16_t)pstJsonCur->unData.lValue; + } + else if (sizeof(grub_uint8_t) == pstCurParse->uiBufSize) + { + *(grub_uint8_t *)(pstCurParse->pDataBuf) = (grub_uint8_t)pstJsonCur->unData.lValue; + } + else if ((pstCurParse->uiBufSize > sizeof(grub_uint64_t))) + { + grub_snprintf((char *)pstCurParse->pDataBuf, pstCurParse->uiBufSize, "%llu", + (unsigned long long)(pstJsonCur->unData.lValue)); + } + else + { + json_debug("Invalid number data buf size %u.", pstCurParse->uiBufSize); + } + break; + } + case JSON_TYPE_STRING: + { + grub_strncpy((char *)pstCurParse->pDataBuf, pstJsonCur->unData.pcStrVal, pstCurParse->uiBufSize); + break; + } + case JSON_TYPE_BOOL: + { + *(grub_uint8_t *)(pstCurParse->pDataBuf) = (pstJsonCur->unData.lValue) > 0 ? 1 : 0; + break; + } + default : + { + break; + } + } + } + + return JSON_SUCCESS; +} + +int vtoy_json_scan_array +( + VTOY_JSON *pstJson, + const char *szKey, + VTOY_JSON **ppstArrayItem +) +{ + VTOY_JSON *pstJsonItem = NULL; + + pstJsonItem = vtoy_json_find_item(pstJson, JSON_TYPE_ARRAY, szKey); + if (NULL == pstJsonItem) + { + json_debug("Key %s is not found in json data.", szKey); + return JSON_NOT_FOUND; + } + + *ppstArrayItem = pstJsonItem; + + return JSON_SUCCESS; +} + +int vtoy_json_scan_array_ex +( + VTOY_JSON *pstJson, + const char *szKey, + VTOY_JSON **ppstArrayItem +) +{ + VTOY_JSON *pstJsonItem = NULL; + + pstJsonItem = vtoy_json_find_item(pstJson, JSON_TYPE_ARRAY, szKey); + if (NULL == pstJsonItem) + { + json_debug("Key %s is not found in json data.", szKey); + return JSON_NOT_FOUND; + } + + *ppstArrayItem = pstJsonItem->pstChild; + + return JSON_SUCCESS; +} + +int vtoy_json_scan_object +( + VTOY_JSON *pstJson, + const char *szKey, + VTOY_JSON **ppstObjectItem +) +{ + VTOY_JSON *pstJsonItem = NULL; + + pstJsonItem = vtoy_json_find_item(pstJson, JSON_TYPE_OBJECT, szKey); + if (NULL == pstJsonItem) + { + json_debug("Key %s is not found in json data.", szKey); + return JSON_NOT_FOUND; + } + + *ppstObjectItem = pstJsonItem; + + return JSON_SUCCESS; +} + +int vtoy_json_get_int +( + VTOY_JSON *pstJson, + const char *szKey, + int *piValue +) +{ + VTOY_JSON *pstJsonItem = NULL; + + pstJsonItem = vtoy_json_find_item(pstJson, JSON_TYPE_NUMBER, szKey); + if (NULL == pstJsonItem) + { + json_debug("Key %s is not found in json data.", szKey); + return JSON_NOT_FOUND; + } + + *piValue = (int)pstJsonItem->unData.lValue; + + return JSON_SUCCESS; +} + +int vtoy_json_get_uint +( + VTOY_JSON *pstJson, + const char *szKey, + grub_uint32_t *puiValue +) +{ + VTOY_JSON *pstJsonItem = NULL; + + pstJsonItem = vtoy_json_find_item(pstJson, JSON_TYPE_NUMBER, szKey); + if (NULL == pstJsonItem) + { + json_debug("Key %s is not found in json data.", szKey); + return JSON_NOT_FOUND; + } + + *puiValue = (grub_uint32_t)pstJsonItem->unData.lValue; + + return JSON_SUCCESS; +} + +int vtoy_json_get_uint64 +( + VTOY_JSON *pstJson, + const char *szKey, + grub_uint64_t *pui64Value +) +{ + VTOY_JSON *pstJsonItem = NULL; + + pstJsonItem = vtoy_json_find_item(pstJson, JSON_TYPE_NUMBER, szKey); + if (NULL == pstJsonItem) + { + json_debug("Key %s is not found in json data.", szKey); + return JSON_NOT_FOUND; + } + + *pui64Value = (grub_uint64_t)pstJsonItem->unData.lValue; + + return JSON_SUCCESS; +} + +int vtoy_json_get_bool +( + VTOY_JSON *pstJson, + const char *szKey, + grub_uint8_t *pbValue +) +{ + VTOY_JSON *pstJsonItem = NULL; + + pstJsonItem = vtoy_json_find_item(pstJson, JSON_TYPE_BOOL, szKey); + if (NULL == pstJsonItem) + { + json_debug("Key %s is not found in json data.", szKey); + return JSON_NOT_FOUND; + } + + *pbValue = pstJsonItem->unData.lValue > 0 ? 1 : 0; + + return JSON_SUCCESS; +} + +int vtoy_json_get_string +( + VTOY_JSON *pstJson, + const char *szKey, + grub_uint32_t uiBufLen, + char *pcBuf +) +{ + VTOY_JSON *pstJsonItem = NULL; + + pstJsonItem = vtoy_json_find_item(pstJson, JSON_TYPE_STRING, szKey); + if (NULL == pstJsonItem) + { + json_debug("Key %s is not found in json data.", szKey); + return JSON_NOT_FOUND; + } + + grub_strncpy(pcBuf, pstJsonItem->unData.pcStrVal, uiBufLen); + + return JSON_SUCCESS; +} + +const char * vtoy_json_get_string_ex(VTOY_JSON *pstJson, const char *szKey) +{ + VTOY_JSON *pstJsonItem = NULL; + + if ((NULL == pstJson) || (NULL == szKey)) + { + return NULL; + } + + pstJsonItem = vtoy_json_find_item(pstJson, JSON_TYPE_STRING, szKey); + if (NULL == pstJsonItem) + { + json_debug("Key %s is not found in json data.", szKey); + return NULL; + } + + return pstJsonItem->unData.pcStrVal; +} + +int vtoy_json_destroy(VTOY_JSON *pstJson) +{ + if (NULL == pstJson) + { + return JSON_SUCCESS; + } + + if (NULL != pstJson->pstChild) + { + vtoy_json_free(pstJson->pstChild); + } + + if (NULL != pstJson->pstNext) + { + vtoy_json_free(pstJson->pstNext); + } + + grub_free(pstJson); + + return JSON_SUCCESS; +} + diff --git a/GRUB2/grub-2.04/grub-core/ventoy/ventoy_linux.c b/GRUB2/grub-2.04/grub-core/ventoy/ventoy_linux.c new file mode 100644 index 00000000..cc35a845 --- /dev/null +++ b/GRUB2/grub-2.04/grub-core/ventoy/ventoy_linux.c @@ -0,0 +1,1050 @@ +/****************************************************************************** + * ventoy_linux.c + * + * Copyright (c) 2020, longpanda + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, see . + * + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "ventoy_def.h" + +GRUB_MOD_LICENSE ("GPLv3+"); + + +static char * ventoy_get_line(char *start) +{ + if (start == NULL) + { + return NULL; + } + + while (*start && *start != '\n') + { + start++; + } + + if (*start == 0) + { + return NULL; + } + else + { + *start = 0; + return start + 1; + } +} + +static initrd_info * ventoy_find_initrd_by_name(initrd_info *list, const char *name) +{ + initrd_info *node = list; + + while (node) + { + if (grub_strcmp(node->name, name) == 0) + { + return node; + } + node = node->next; + } + + return NULL; +} + +grub_err_t ventoy_cmd_clear_initrd_list(grub_extcmd_context_t ctxt, int argc, char **args) +{ + initrd_info *node = g_initrd_img_list; + initrd_info *next; + + (void)ctxt; + (void)argc; + (void)args; + + while (node) + { + next = node->next; + grub_free(node); + node = next; + } + + g_initrd_img_list = NULL; + g_initrd_img_tail = NULL; + g_initrd_img_count = 0; + g_valid_initrd_count = 0; + + VENTOY_CMD_RETURN(GRUB_ERR_NONE); +} + +grub_err_t ventoy_cmd_dump_initrd_list(grub_extcmd_context_t ctxt, int argc, char **args) +{ + int i = 0; + initrd_info *node = g_initrd_img_list; + + (void)ctxt; + (void)argc; + (void)args; + + grub_printf("###################\n"); + grub_printf("initrd info list: valid count:%d\n", g_valid_initrd_count); + + while (node) + { + grub_printf("%s ", node->size > 0 ? "*" : " "); + grub_printf("%02u %s offset:%llu size:%llu \n", i++, node->name, (unsigned long long)node->offset, + (unsigned long long)node->size); + node = node->next; + } + + grub_printf("###################\n"); + + VENTOY_CMD_RETURN(GRUB_ERR_NONE); +} + +static void ventoy_parse_directory(char *path, char *dir, int buflen) +{ + int end; + char *pos; + + pos = grub_strstr(path, ")"); + if (!pos) + { + pos = path; + } + + end = grub_snprintf(dir, buflen, "%s", pos + 1); + while (end > 0) + { + if (dir[end] == '/') + { + dir[end + 1] = 0; + break; + } + end--; + } +} + +static grub_err_t ventoy_isolinux_initrd_collect(grub_file_t file, const char *prefix) +{ + int i = 0; + int offset; + int prefixlen = 0; + char *buf = NULL; + char *pos = NULL; + char *start = NULL; + char *nextline = NULL; + initrd_info *img = NULL; + + prefixlen = grub_strlen(prefix); + + buf = grub_zalloc(file->size + 2); + if (!buf) + { + return 0; + } + + grub_file_read(file, buf, file->size); + + for (start = buf; start; start = nextline) + { + nextline = ventoy_get_line(start); + + while (ventoy_isspace(*start)) + { + start++; + } + + offset = 7; // strlen("initrd=") or "INITRD " or "initrd " + pos = grub_strstr(start, "initrd="); + if (pos == NULL) + { + pos = start; + + if (grub_strncmp(start, "INITRD", 6) != 0 && grub_strncmp(start, "initrd", 6) != 0) + { + if (grub_strstr(start, "xen") && + ((pos = grub_strstr(start, "--- /install.img")) != NULL || + (pos = grub_strstr(start, "--- initrd.img")) != NULL + )) + { + offset = 4; // "--- " + } + else + { + continue; + } + } + } + + pos += offset; + + while (1) + { + i = 0; + img = grub_zalloc(sizeof(initrd_info)); + if (!img) + { + break; + } + + if (*pos != '/') + { + grub_strcpy(img->name, prefix); + i = prefixlen; + } + + while (i < 255 && (0 == ventoy_is_word_end(*pos))) + { + img->name[i++] = *pos++; + } + + if (ventoy_find_initrd_by_name(g_initrd_img_list, img->name)) + { + grub_free(img); + } + else + { + if (g_initrd_img_list) + { + img->prev = g_initrd_img_tail; + g_initrd_img_tail->next = img; + } + else + { + g_initrd_img_list = img; + } + + g_initrd_img_tail = img; + g_initrd_img_count++; + } + + if (*pos == ',') + { + pos++; + } + else + { + break; + } + } + } + + grub_free(buf); + return GRUB_ERR_NONE; +} + +static int ventoy_isolinux_initrd_hook(const char *filename, const struct grub_dirhook_info *info, void *data) +{ + grub_file_t file = NULL; + ventoy_initrd_ctx *ctx = (ventoy_initrd_ctx *)data; + + (void)info; + + if (NULL == grub_strstr(filename, ".cfg") && NULL == grub_strstr(filename, ".CFG")) + { + return 0; + } + + debug("init hook dir <%s%s>\n", ctx->path_prefix, filename); + + file = ventoy_grub_file_open(VENTOY_FILE_TYPE, "%s%s", ctx->path_prefix, filename); + if (!file) + { + return 0; + } + + ventoy_isolinux_initrd_collect(file, ctx->dir_prefix); + grub_file_close(file); + + return 0; +} + +grub_err_t ventoy_cmd_isolinux_initrd_collect(grub_extcmd_context_t ctxt, int argc, char **args) +{ + grub_fs_t fs; + grub_device_t dev = NULL; + char *device_name = NULL; + ventoy_initrd_ctx ctx; + char directory[256]; + + (void)ctxt; + (void)argc; + + device_name = grub_file_get_device_name(args[0]); + if (!device_name) + { + goto end; + } + + dev = grub_device_open(device_name); + if (!dev) + { + goto end; + } + + fs = grub_fs_probe(dev); + if (!fs) + { + goto end; + } + + debug("isolinux initrd collect %s\n", args[0]); + + ventoy_parse_directory(args[0], directory, sizeof(directory) - 1); + ctx.path_prefix = args[0]; + ctx.dir_prefix = (argc > 1) ? args[1] : directory; + + debug("path_prefix=<%s> dir_prefix=<%s>\n", ctx.path_prefix, ctx.dir_prefix); + + fs->fs_dir(dev, directory, ventoy_isolinux_initrd_hook, &ctx); + +end: + check_free(device_name, grub_free); + check_free(dev, grub_device_close); + + VENTOY_CMD_RETURN(GRUB_ERR_NONE); +} + +static grub_err_t ventoy_grub_cfg_initrd_collect(const char *fileName) +{ + int i = 0; + grub_file_t file = NULL; + char *buf = NULL; + char *start = NULL; + char *nextline = NULL; + initrd_info *img = NULL; + + debug("grub initrd collect %s\n", fileName); + + file = ventoy_grub_file_open(VENTOY_FILE_TYPE, "%s", fileName); + if (!file) + { + return 0; + } + + buf = grub_zalloc(file->size + 2); + if (!buf) + { + grub_file_close(file); + return 0; + } + + grub_file_read(file, buf, file->size); + + for (start = buf; start; start = nextline) + { + nextline = ventoy_get_line(start); + + while (ventoy_isspace(*start)) + { + start++; + } + + if (grub_strncmp(start, "initrd", 6) != 0) + { + continue; + } + + start += 6; + while (*start && (!ventoy_isspace(*start))) + { + start++; + } + + while (ventoy_isspace(*start)) + { + start++; + } + + while (*start) + { + img = grub_zalloc(sizeof(initrd_info)); + if (!img) + { + break; + } + + for (i = 0; i < 255 && (0 == ventoy_is_word_end(*start)); i++) + { + img->name[i] = *start++; + } + + if (ventoy_find_initrd_by_name(g_initrd_img_list, img->name)) + { + grub_free(img); + } + else + { + if (g_initrd_img_list) + { + img->prev = g_initrd_img_tail; + g_initrd_img_tail->next = img; + } + else + { + g_initrd_img_list = img; + } + + g_initrd_img_tail = img; + g_initrd_img_count++; + } + + if (*start == ' ' || *start == '\t') + { + while (ventoy_isspace(*start)) + { + start++; + } + } + else + { + break; + } + } + } + + grub_free(buf); + grub_file_close(file); + + VENTOY_CMD_RETURN(GRUB_ERR_NONE); +} + +static int ventoy_grub_initrd_hook(const char *filename, const struct grub_dirhook_info *info, void *data) +{ + char filePath[256]; + ventoy_initrd_ctx *ctx = (ventoy_initrd_ctx *)data; + + (void)info; + + debug("ventoy_grub_initrd_hook %s\n", filename); + + if (NULL == grub_strstr(filename, ".cfg") && + NULL == grub_strstr(filename, ".CFG") && + NULL == grub_strstr(filename, ".conf")) + { + return 0; + } + + debug("init hook dir <%s%s>\n", ctx->path_prefix, filename); + + grub_snprintf(filePath, sizeof(filePath) - 1, "%s%s", ctx->dir_prefix, filename); + ventoy_grub_cfg_initrd_collect(filePath); + + return 0; +} + +grub_err_t ventoy_cmd_grub_initrd_collect(grub_extcmd_context_t ctxt, int argc, char **args) +{ + grub_fs_t fs; + grub_device_t dev = NULL; + char *device_name = NULL; + ventoy_initrd_ctx ctx; + + (void)ctxt; + (void)argc; + + if (argc != 2) + { + return 0; + } + + debug("grub initrd collect %s %s\n", args[0], args[1]); + + if (grub_strcmp(args[0], "file") == 0) + { + return ventoy_grub_cfg_initrd_collect(args[1]); + } + + device_name = grub_file_get_device_name(args[1]); + if (!device_name) + { + debug("failed to get device name %s\n", args[1]); + goto end; + } + + dev = grub_device_open(device_name); + if (!dev) + { + debug("failed to open device %s\n", device_name); + goto end; + } + + fs = grub_fs_probe(dev); + if (!fs) + { + debug("failed to probe fs %d\n", grub_errno); + goto end; + } + + ctx.dir_prefix = args[1]; + ctx.path_prefix = grub_strstr(args[1], device_name); + if (ctx.path_prefix) + { + ctx.path_prefix += grub_strlen(device_name) + 1; + } + else + { + ctx.path_prefix = args[1]; + } + + debug("ctx.path_prefix:<%s>\n", ctx.path_prefix); + + fs->fs_dir(dev, ctx.path_prefix, ventoy_grub_initrd_hook, &ctx); + +end: + check_free(device_name, grub_free); + check_free(dev, grub_device_close); + + + VENTOY_CMD_RETURN(GRUB_ERR_NONE); +} + +grub_err_t ventoy_cmd_specify_initrd_file(grub_extcmd_context_t ctxt, int argc, char **args) +{ + initrd_info *img = NULL; + + (void)ctxt; + (void)argc; + + debug("ventoy_cmd_specify_initrd_file %s\n", args[0]); + + img = grub_zalloc(sizeof(initrd_info)); + if (!img) + { + return 1; + } + + grub_strncpy(img->name, args[0], sizeof(img->name)); + if (ventoy_find_initrd_by_name(g_initrd_img_list, img->name)) + { + grub_free(img); + } + else + { + if (g_initrd_img_list) + { + img->prev = g_initrd_img_tail; + g_initrd_img_tail->next = img; + } + else + { + g_initrd_img_list = img; + } + + g_initrd_img_tail = img; + g_initrd_img_count++; + } + + VENTOY_CMD_RETURN(GRUB_ERR_NONE); +} + +static void ventoy_cpio_newc_fill_int(grub_uint32_t value, char *buf, int buflen) +{ + int i; + int len; + char intbuf[32]; + + len = grub_snprintf(intbuf, sizeof(intbuf), "%x", value); + + for (i = 0; i < buflen; i++) + { + buf[i] = '0'; + } + + if (len > buflen) + { + grub_printf("int buf len overflow %d %d\n", len, buflen); + } + else + { + grub_memcpy(buf + buflen - len, intbuf, len); + } +} + +int ventoy_cpio_newc_fill_head(void *buf, int filesize, void *filedata, const char *name) +{ + int namelen = 0; + int headlen = 0; + static grub_uint32_t cpio_ino = 0xFFFFFFF0; + cpio_newc_header *cpio = (cpio_newc_header *)buf; + + namelen = grub_strlen(name) + 1; + headlen = sizeof(cpio_newc_header) + namelen; + headlen = ventoy_align(headlen, 4); + + grub_memset(cpio, '0', sizeof(cpio_newc_header)); + grub_memset(cpio + 1, 0, headlen - sizeof(cpio_newc_header)); + + grub_memcpy(cpio->c_magic, "070701", 6); + ventoy_cpio_newc_fill_int(cpio_ino--, cpio->c_ino, 8); + ventoy_cpio_newc_fill_int(0100777, cpio->c_mode, 8); + ventoy_cpio_newc_fill_int(1, cpio->c_nlink, 8); + ventoy_cpio_newc_fill_int(filesize, cpio->c_filesize, 8); + ventoy_cpio_newc_fill_int(namelen, cpio->c_namesize, 8); + grub_memcpy(cpio + 1, name, namelen); + + if (filedata) + { + grub_memcpy((char *)cpio + headlen, filedata, filesize); + } + + return headlen; +} + +static grub_uint32_t ventoy_linux_get_virt_chunk_size(void) +{ + return (sizeof(ventoy_virt_chunk) + g_ventoy_cpio_size) * g_valid_initrd_count; +} + +static void ventoy_linux_fill_virt_data( grub_uint64_t isosize, ventoy_chain_head *chain) +{ + int id = 0; + initrd_info *node; + grub_uint64_t sector; + grub_uint32_t offset; + grub_uint32_t cpio_secs; + grub_uint32_t initrd_secs; + char *override; + ventoy_virt_chunk *cur; + char name[32]; + + override = (char *)chain + chain->virt_chunk_offset; + sector = (isosize + 2047) / 2048; + cpio_secs = g_ventoy_cpio_size / 2048; + + offset = g_valid_initrd_count * sizeof(ventoy_virt_chunk); + cur = (ventoy_virt_chunk *)override; + + for (node = g_initrd_img_list; node; node = node->next) + { + if (node->size == 0) + { + continue; + } + + initrd_secs = (grub_uint32_t)((node->size + 2047) / 2048); + + cur->mem_sector_start = sector; + cur->mem_sector_end = cur->mem_sector_start + cpio_secs; + cur->mem_sector_offset = offset; + cur->remap_sector_start = cur->mem_sector_end; + cur->remap_sector_end = cur->remap_sector_start + initrd_secs; + cur->org_sector_start = (grub_uint32_t)(node->offset / 2048); + + grub_memcpy(g_ventoy_runtime_buf, &chain->os_param, sizeof(ventoy_os_param)); + + grub_memset(name, 0, 16); + grub_snprintf(name, sizeof(name), "initrd%03d", ++id); + + grub_memcpy(g_ventoy_initrd_head + 1, name, 16); + ventoy_cpio_newc_fill_int((grub_uint32_t)node->size, g_ventoy_initrd_head->c_filesize, 8); + + grub_memcpy(override + offset, g_ventoy_cpio_buf, g_ventoy_cpio_size); + + chain->virt_img_size_in_bytes += g_ventoy_cpio_size + initrd_secs * 2048; + + offset += g_ventoy_cpio_size; + sector += cpio_secs + initrd_secs; + cur++; + } + + return; +} + +static grub_uint32_t ventoy_linux_get_override_chunk_size(void) +{ + return sizeof(ventoy_override_chunk) * g_valid_initrd_count; +} + +static void ventoy_linux_fill_override_data( grub_uint64_t isosize, void *override) +{ + initrd_info *node; + grub_uint64_t sector; + ventoy_override_chunk *cur; + + sector = (isosize + 2047) / 2048; + + cur = (ventoy_override_chunk *)override; + for (node = g_initrd_img_list; node; node = node->next) + { + if (node->size == 0) + { + continue; + } + + if (node->iso_type == 0) + { + ventoy_iso9660_override *dirent = (ventoy_iso9660_override *)node->override_data; + + node->override_length = sizeof(ventoy_iso9660_override); + dirent->first_sector = (grub_uint32_t)sector; + dirent->size = (grub_uint32_t)(node->size + g_ventoy_cpio_size); + dirent->first_sector_be = grub_swap_bytes32(dirent->first_sector); + dirent->size_be = grub_swap_bytes32(dirent->size); + + sector += (dirent->size + 2047) / 2048; + } + else + { + ventoy_udf_override *udf = (ventoy_udf_override *)node->override_data; + + node->override_length = sizeof(ventoy_udf_override); + udf->length = (grub_uint32_t)(node->size + g_ventoy_cpio_size); + udf->position = (grub_uint32_t)sector - node->udf_start_block; + + sector += (udf->length + 2047) / 2048; + } + + cur->img_offset = node->override_offset; + cur->override_size = node->override_length; + grub_memcpy(cur->override_data, node->override_data, cur->override_size); + cur++; + } + + return; +} + +grub_err_t ventoy_cmd_initrd_count(grub_extcmd_context_t ctxt, int argc, char **args) +{ + char buf[32] = {0}; + + (void)ctxt; + (void)argc; + (void)args; + + if (argc == 1) + { + grub_snprintf(buf, sizeof(buf), "%d", g_valid_initrd_count); + grub_env_set(args[0], buf); + } + + VENTOY_CMD_RETURN(GRUB_ERR_NONE); +} + +static grub_err_t ventoy_linux_locate_initrd(int filt, int *filtcnt) +{ + int data; + int sizefilt = 0; + grub_file_t file; + initrd_info *node; + + debug("ventoy_linux_locate_initrd %d\n", filt); + + g_valid_initrd_count = 0; + + for (node = g_initrd_img_list; node; node = node->next) + { + file = ventoy_grub_file_open(VENTOY_FILE_TYPE, "(loop)%s", node->name); + if (!file) + { + continue; + } + + debug("file <%s> size:%d\n", node->name, (int)file->size); + + /* initrd file too small */ + if (filt > 0 && file->size <= g_ventoy_cpio_size + 2048) + { + debug("file size too small %d\n", (int)g_ventoy_cpio_size); + grub_file_close(file); + sizefilt++; + continue; + } + + if (grub_strcmp(file->fs->name, "iso9660") == 0) + { + node->iso_type = 0; + node->override_offset = grub_iso9660_get_last_file_dirent_pos(file) + 2; + + grub_file_read(file, &data, 1); // just read for hook trigger + node->offset = grub_iso9660_get_last_read_pos(file); + } + else + { + /* TBD */ + } + + node->size = file->size; + g_valid_initrd_count++; + + grub_file_close(file); + } + + *filtcnt = sizefilt; + + VENTOY_CMD_RETURN(GRUB_ERR_NONE); +} + + +grub_err_t ventoy_cmd_linux_locate_initrd(grub_extcmd_context_t ctxt, int argc, char **args) +{ + int sizefilt = 0; + + (void)ctxt; + (void)argc; + (void)args; + + ventoy_linux_locate_initrd(1, &sizefilt); + + if (g_valid_initrd_count == 0 && sizefilt > 0) + { + ventoy_linux_locate_initrd(0, &sizefilt); + } + + VENTOY_CMD_RETURN(GRUB_ERR_NONE); +} + +grub_err_t ventoy_cmd_load_cpio(grub_extcmd_context_t ctxt, int argc, char **args) +{ + grub_uint8_t *buf; + grub_uint32_t mod; + grub_uint32_t headlen; + grub_uint32_t initrd_head_len; + grub_uint32_t padlen; + grub_uint32_t img_chunk_size; + grub_file_t file; + + (void)ctxt; + (void)argc; + + if (argc != 1) + { + return grub_error(GRUB_ERR_BAD_ARGUMENT, "Usage: %s cpiofile\n", cmd_raw_name); + } + + if (g_img_chunk_list.chunk == NULL || g_img_chunk_list.cur_chunk == 0) + { + return grub_error(GRUB_ERR_BAD_ARGUMENT, "image chunk is null\n"); + } + + img_chunk_size = g_img_chunk_list.cur_chunk * sizeof(ventoy_img_chunk); + + file = ventoy_grub_file_open(VENTOY_FILE_TYPE, "%s", args[0]); + if (!file) + { + return grub_error(GRUB_ERR_BAD_ARGUMENT, "Can't open file %s\n", args[0]); + } + + if (g_ventoy_cpio_buf) + { + grub_free(g_ventoy_cpio_buf); + g_ventoy_cpio_buf = NULL; + g_ventoy_cpio_size = 0; + } + + g_ventoy_cpio_buf = grub_malloc(file->size + 4096 + img_chunk_size); + if (NULL == g_ventoy_cpio_buf) + { + grub_file_close(file); + return grub_error(GRUB_ERR_BAD_ARGUMENT, "Can't alloc memory %llu\n", file->size + 4096 + img_chunk_size); + } + + grub_file_read(file, g_ventoy_cpio_buf, file->size); + + buf = (grub_uint8_t *)(g_ventoy_cpio_buf + file->size - 4); + while (*((grub_uint32_t *)buf) != 0x37303730) + { + buf -= 4; + } + + /* get initrd head len */ + initrd_head_len = ventoy_cpio_newc_fill_head(buf, 0, NULL, "initrd000.xx"); + + /* step1: insert image chunk data to cpio */ + headlen = ventoy_cpio_newc_fill_head(buf, img_chunk_size, g_img_chunk_list.chunk, "ventoy/ventoy_image_map"); + buf += headlen + ventoy_align(img_chunk_size, 4); + + /* step2: insert os param to cpio */ + headlen = ventoy_cpio_newc_fill_head(buf, 0, NULL, "ventoy/ventoy_os_param"); + padlen = sizeof(ventoy_os_param); + g_ventoy_cpio_size = (grub_uint32_t)(buf - g_ventoy_cpio_buf) + headlen + padlen + initrd_head_len; + mod = g_ventoy_cpio_size % 2048; + if (mod) + { + g_ventoy_cpio_size += 2048 - mod; + padlen += 2048 - mod; + } + + /* update os param data size, the data will be updated before chain boot */ + ventoy_cpio_newc_fill_int(padlen, ((cpio_newc_header *)buf)->c_filesize, 8); + g_ventoy_runtime_buf = (grub_uint8_t *)buf + headlen; + + /* step3: fill initrd cpio head, the file size will be updated before chain boot */ + g_ventoy_initrd_head = (cpio_newc_header *)(g_ventoy_runtime_buf + padlen); + ventoy_cpio_newc_fill_head(g_ventoy_initrd_head, 0, NULL, "initrd000.xx"); + + grub_file_close(file); + + VENTOY_CMD_RETURN(GRUB_ERR_NONE); +} + + +grub_err_t ventoy_cmd_linux_chain_data(grub_extcmd_context_t ctxt, int argc, char **args) +{ + int ventoy_compatible = 0; + grub_uint32_t size = 0; + grub_uint64_t isosize = 0; + grub_uint32_t boot_catlog = 0; + grub_uint32_t img_chunk_size = 0; + grub_uint32_t override_size = 0; + grub_uint32_t virt_chunk_size = 0; + grub_file_t file; + grub_disk_t disk; + const char *pLastChain = NULL; + const char *compatible; + ventoy_chain_head *chain; + char envbuf[64]; + + (void)ctxt; + (void)argc; + + compatible = grub_env_get("ventoy_compatible"); + if (compatible && compatible[0] == 'Y') + { + ventoy_compatible = 1; + } + + if ((NULL == g_img_chunk_list.chunk) || (0 == ventoy_compatible && g_ventoy_cpio_buf == NULL)) + { + grub_printf("ventoy not ready\n"); + return 1; + } + + file = ventoy_grub_file_open(VENTOY_FILE_TYPE, "%s", args[0]); + if (!file) + { + return 1; + } + + isosize = file->size; + + boot_catlog = ventoy_get_iso_boot_catlog(file); + if (boot_catlog) + { + if (ventoy_is_efi_os() && (!ventoy_has_efi_eltorito(file, boot_catlog))) + { + grub_env_set("LoadIsoEfiDriver", "on"); + } + } + else + { + if (ventoy_is_efi_os()) + { + grub_env_set("LoadIsoEfiDriver", "on"); + } + else + { + return grub_error(GRUB_ERR_BAD_ARGUMENT, "File %s is not bootable", args[0]); + } + } + + img_chunk_size = g_img_chunk_list.cur_chunk * sizeof(ventoy_img_chunk); + + if (ventoy_compatible) + { + size = sizeof(ventoy_chain_head) + img_chunk_size; + } + else + { + override_size = ventoy_linux_get_override_chunk_size(); + virt_chunk_size = ventoy_linux_get_virt_chunk_size(); + size = sizeof(ventoy_chain_head) + img_chunk_size + override_size + virt_chunk_size; + } + + pLastChain = grub_env_get("vtoy_chain_mem_addr"); + if (pLastChain) + { + chain = (ventoy_chain_head *)grub_strtoul(pLastChain, NULL, 16); + if (chain) + { + debug("free last chain memory %p\n", chain); + grub_free(chain); + } + } + + chain = grub_malloc(size); + if (!chain) + { + grub_printf("Failed to alloc chain memory size %u\n", size); + grub_file_close(file); + return 1; + } + + grub_snprintf(envbuf, sizeof(envbuf), "0x%lx", (unsigned long)chain); + grub_env_set("vtoy_chain_mem_addr", envbuf); + grub_snprintf(envbuf, sizeof(envbuf), "%u", size); + grub_env_set("vtoy_chain_mem_size", envbuf); + + grub_memset(chain, 0, sizeof(ventoy_chain_head)); + + /* part 1: os parameter */ + ventoy_fill_os_param(file, &(chain->os_param)); + + /* part 2: chain head */ + disk = file->device->disk; + chain->disk_drive = disk->id; + chain->disk_sector_size = (1 << disk->log_sector_size); + chain->real_img_size_in_bytes = file->size; + chain->virt_img_size_in_bytes = (file->size + 2047) / 2048 * 2048; + chain->boot_catalog = boot_catlog; + + if (!ventoy_is_efi_os()) + { + grub_file_seek(file, boot_catlog * 2048); + grub_file_read(file, chain->boot_catalog_sector, sizeof(chain->boot_catalog_sector)); + } + + /* part 3: image chunk */ + chain->img_chunk_offset = sizeof(ventoy_chain_head); + chain->img_chunk_num = g_img_chunk_list.cur_chunk; + grub_memcpy((char *)chain + chain->img_chunk_offset, g_img_chunk_list.chunk, img_chunk_size); + + if (ventoy_compatible) + { + return 0; + } + + if (g_valid_initrd_count == 0) + { + return 0; + } + + /* part 4: override chunk */ + chain->override_chunk_offset = chain->img_chunk_offset + img_chunk_size; + chain->override_chunk_num = g_valid_initrd_count; + ventoy_linux_fill_override_data(isosize, (char *)chain + chain->override_chunk_offset); + + /* part 5: virt chunk */ + chain->virt_chunk_offset = chain->override_chunk_offset + override_size; + chain->virt_chunk_num = g_valid_initrd_count; + ventoy_linux_fill_virt_data(isosize, chain); + + VENTOY_CMD_RETURN(GRUB_ERR_NONE); +} + diff --git a/GRUB2/grub-2.04/grub-core/ventoy/ventoy_plugin.c b/GRUB2/grub-2.04/grub-core/ventoy/ventoy_plugin.c new file mode 100644 index 00000000..cd1a1d81 --- /dev/null +++ b/GRUB2/grub-2.04/grub-core/ventoy/ventoy_plugin.c @@ -0,0 +1,151 @@ +/****************************************************************************** + * ventoy_plugin.c + * + * Copyright (c) 2020, longpanda + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, see . + * + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "ventoy_def.h" + +GRUB_MOD_LICENSE ("GPLv3+"); + +static int ventoy_plugin_theme_entry(VTOY_JSON *json, const char *isodisk) +{ + const char *value; + char filepath[256]; + + value = vtoy_json_get_string_ex(json->pstChild, "file"); + if (value) + { + grub_snprintf(filepath, sizeof(filepath), "%s/ventoy/%s", isodisk, value); + if (ventoy_is_file_exist(filepath) == 0) + { + debug("Theme file %s does not exist\n", filepath); + return 0; + } + + debug("vtoy_theme %s\n", filepath); + grub_env_set("vtoy_theme", filepath); + } + + value = vtoy_json_get_string_ex(json->pstChild, "gfxmode"); + if (value) + { + debug("vtoy_gfxmode %s\n", value); + grub_env_set("vtoy_gfxmode", value); + } + + return 0; +} + +static plugin_entry g_plugin_entries[] = +{ + { "theme", ventoy_plugin_theme_entry }, +}; + +static int ventoy_parse_plugin_config(VTOY_JSON *json, const char *isodisk) +{ + int i; + VTOY_JSON *cur = json; + + while (cur) + { + for (i = 0; i < (int)ARRAY_SIZE(g_plugin_entries); i++) + { + if (grub_strcmp(g_plugin_entries[i].key, cur->pcName) == 0) + { + debug("Plugin entry for %s\n", g_plugin_entries[i].key); + g_plugin_entries[i].entryfunc(cur, isodisk); + break; + } + } + + cur = cur->pstNext; + } + + return 0; +} + +grub_err_t ventoy_cmd_load_plugin(grub_extcmd_context_t ctxt, int argc, char **args) +{ + int ret = 0; + char *buf = NULL; + grub_file_t file; + VTOY_JSON *json = NULL; + + (void)ctxt; + (void)argc; + + file = ventoy_grub_file_open(VENTOY_FILE_TYPE, "%s/ventoy/ventoy.json", args[0]); + if (!file) + { + return GRUB_ERR_NONE; + } + + debug("json configuration file size %d\n", (int)file->size); + + buf = grub_malloc(file->size + 1); + if (!buf) + { + grub_file_close(file); + return 1; + } + + buf[file->size] = 0; + grub_file_read(file, buf, file->size); + grub_file_close(file); + + json = vtoy_json_create(); + if (!json) + { + return 1; + } + + + + ret = vtoy_json_parse(json, buf); + if (ret) + { + debug("Failed to parse json string %d\n", ret); + grub_free(buf); + return 1; + } + + ventoy_parse_plugin_config(json->pstChild, args[0]); + + vtoy_json_destroy(json); + + grub_free(buf); + + VENTOY_CMD_RETURN(GRUB_ERR_NONE); +} + diff --git a/GRUB2/grub-2.04/grub-core/ventoy/ventoy_windows.c b/GRUB2/grub-2.04/grub-core/ventoy/ventoy_windows.c new file mode 100644 index 00000000..7ec7b085 --- /dev/null +++ b/GRUB2/grub-2.04/grub-core/ventoy/ventoy_windows.c @@ -0,0 +1,931 @@ +/****************************************************************************** + * ventoy_windows.c + * + * Copyright (c) 2020, longpanda + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, see . + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "ventoy_def.h" + +GRUB_MOD_LICENSE ("GPLv3+"); + +wim_hash g_old_hash; +wim_tail g_wim_data; + +static wim_lookup_entry *g_replace_look = NULL; + +grub_ssize_t lzx_decompress ( const void *data, grub_size_t len, void *buf ); + +static int wim_name_cmp(const char *search, grub_uint16_t *name, grub_uint16_t namelen) +{ + char c1 = vtoy_to_upper(*search); + char c2 = vtoy_to_upper(*name); + + while (namelen > 0 && (c1 == c2)) + { + search++; + name++; + namelen--; + + c1 = vtoy_to_upper(*search); + c2 = vtoy_to_upper(*name); + } + + if (namelen == 0 && *search == 0) + { + return 0; + } + + return 1; +} + +static int ventoy_is_pe64(grub_uint8_t *buffer) +{ + grub_uint32_t pe_off; + + if (buffer[0] != 'M' || buffer[1] != 'Z') + { + return 0; + } + + pe_off = *(grub_uint32_t *)(buffer + 60); + + if (buffer[pe_off] != 'P' || buffer[pe_off + 1] != 'E') + { + return 0; + } + + if (*(grub_uint16_t *)(buffer + pe_off + 24) == 0x020b) + { + return 1; + } + + return 0; +} + +grub_err_t ventoy_cmd_wimdows_reset(grub_extcmd_context_t ctxt, int argc, char **args) +{ + (void)ctxt; + (void)argc; + (void)args; + + check_free(g_wim_data.jump_bin_data, grub_free); + check_free(g_wim_data.new_meta_data, grub_free); + check_free(g_wim_data.new_lookup_data, grub_free); + + grub_memset(&g_wim_data, 0, sizeof(g_wim_data)); + + return 0; +} + +static int ventoy_load_jump_exe(const char *path, grub_uint8_t **data, grub_uint32_t *size, wim_hash *hash) +{ + grub_uint32_t i; + grub_uint32_t align; + grub_file_t file; + + debug("windows load jump %s\n", path); + + file = ventoy_grub_file_open(VENTOY_FILE_TYPE, "%s", path); + if (!file) + { + debug("Can't open file %s\n", path); + return 1; + } + + align = ventoy_align((int)file->size, 2048); + + debug("file %s size:%d align:%u\n", path, (int)file->size, align); + + *size = (grub_uint32_t)file->size; + *data = (grub_uint8_t *)grub_malloc(align); + if ((*data) == NULL) + { + debug("Failed to alloc memory size %u\n", align); + goto end; + } + + grub_file_read(file, (*data), file->size); + + if (hash) + { + grub_crypto_hash(GRUB_MD_SHA1, hash->sha1, (*data), file->size); + + if (g_ventoy_debug) + { + debug("%s", "jump bin 64 hash: "); + for (i = 0; i < sizeof(hash->sha1); i++) + { + ventoy_debug("%02x ", hash->sha1[i]); + } + ventoy_debug("\n"); + } + } + +end: + + grub_file_close(file); + return 0; +} + +static int ventoy_get_override_info(grub_file_t file) +{ + grub_uint32_t start_block; + grub_uint64_t file_offset; + grub_uint64_t override_offset; + grub_uint32_t override_len; + grub_uint64_t fe_entry_size_offset; + + if (grub_strcmp(file->fs->name, "iso9660") == 0) + { + g_wim_data.iso_type = 0; + override_len = sizeof(ventoy_iso9660_override); + override_offset = grub_iso9660_get_last_file_dirent_pos(file) + 2; + + grub_file_read(file, &start_block, 1); // just read for hook trigger + file_offset = grub_iso9660_get_last_read_pos(file); + + debug("iso9660 wim size:%llu override_offset:%llu file_offset:%llu\n", + (ulonglong)file->size, (ulonglong)override_offset, (ulonglong)file_offset); + } + else + { + g_wim_data.iso_type = 1; + override_len = sizeof(ventoy_udf_override); + override_offset = grub_udf_get_last_file_attr_offset(file, &start_block, &fe_entry_size_offset); + + file_offset = grub_udf_get_file_offset(file); + + debug("UDF wim size:%llu override_offset:%llu file_offset:%llu start_block=%u\n", + (ulonglong)file->size, (ulonglong)override_offset, (ulonglong)file_offset, start_block); + } + + g_wim_data.file_offset = file_offset; + g_wim_data.udf_start_block = start_block; + g_wim_data.fe_entry_size_offset = fe_entry_size_offset; + g_wim_data.override_offset = override_offset; + g_wim_data.override_len = override_len; + + return 0; +} + +static int ventoy_read_resource(grub_file_t fp, wim_resource_header *head, void **buffer) +{ + int decompress_len = 0; + int total_decompress = 0; + grub_uint32_t i = 0; + grub_uint32_t chunk_num = 0; + grub_uint32_t chunk_size = 0; + grub_uint32_t last_chunk_size = 0; + grub_uint32_t last_decompress_size = 0; + grub_uint32_t cur_offset = 0; + grub_uint8_t *cur_dst = NULL; + grub_uint8_t *buffer_compress = NULL; + grub_uint8_t *buffer_decompress = NULL; + grub_uint32_t *chunk_offset = NULL; + + buffer_decompress = (grub_uint8_t *)grub_malloc(head->raw_size + head->size_in_wim); + if (NULL == buffer_decompress) + { + return 0; + } + + grub_file_seek(fp, head->offset); + + if (head->size_in_wim == head->raw_size) + { + grub_file_read(fp, buffer_decompress, head->size_in_wim); + *buffer = buffer_decompress; + return 0; + } + + buffer_compress = buffer_decompress + head->raw_size; + grub_file_read(fp, buffer_compress, head->size_in_wim); + + chunk_num = (head->raw_size + WIM_CHUNK_LEN - 1) / WIM_CHUNK_LEN; + cur_offset = (chunk_num - 1) * 4; + chunk_offset = (grub_uint32_t *)buffer_compress; + + cur_dst = buffer_decompress; + + for (i = 0; i < chunk_num - 1; i++) + { + chunk_size = (i == 0) ? chunk_offset[i] : chunk_offset[i] - chunk_offset[i - 1]; + + if (WIM_CHUNK_LEN == chunk_size) + { + grub_memcpy(cur_dst, buffer_compress + cur_offset, chunk_size); + decompress_len = (int)chunk_size; + } + else + { + decompress_len = (int)lzx_decompress(buffer_compress + cur_offset, chunk_size, cur_dst); + } + + //debug("chunk_size:%u decompresslen:%d\n", chunk_size, decompress_len); + + total_decompress += decompress_len; + cur_dst += decompress_len; + cur_offset += chunk_size; + } + + /* last chunk */ + last_chunk_size = (grub_uint32_t)(head->size_in_wim - cur_offset); + last_decompress_size = head->raw_size - total_decompress; + + if (last_chunk_size < WIM_CHUNK_LEN && last_chunk_size == last_decompress_size) + { + debug("Last chunk %u uncompressed\n", last_chunk_size); + grub_memcpy(cur_dst, buffer_compress + cur_offset, last_chunk_size); + decompress_len = (int)last_chunk_size; + } + else + { + decompress_len = (int)lzx_decompress(buffer_compress + cur_offset, head->size_in_wim - cur_offset, cur_dst); + } + + cur_dst += decompress_len; + total_decompress += decompress_len; + + if (cur_dst != buffer_decompress + head->raw_size) + { + debug("head->size_in_wim:%llu head->raw_size:%llu cur_dst:%p buffer_decompress:%p total_decompress:%d\n", + (ulonglong)head->size_in_wim, (ulonglong)head->raw_size, cur_dst, buffer_decompress, total_decompress); + grub_free(buffer_decompress); + return 1; + } + + *buffer = buffer_decompress; + return 0; +} + + +static wim_directory_entry * search_wim_dirent(wim_directory_entry *dir, const char *search_name) +{ + do + { + if (dir->len && dir->name_len) + { + if (wim_name_cmp(search_name, (grub_uint16_t *)(dir + 1), dir->name_len / 2) == 0) + { + return dir; + } + } + dir = (wim_directory_entry *)((grub_uint8_t *)dir + dir->len); + } while(dir->len); + + return NULL; +} + +static wim_directory_entry * search_full_wim_dirent +( + void *meta_data, + wim_directory_entry *dir, + const char **path +) +{ + wim_directory_entry *subdir = NULL; + wim_directory_entry *search = dir; + + while (*path) + { + subdir = (wim_directory_entry *)((char *)meta_data + search->subdir); + search = search_wim_dirent(subdir, *path); + if (!search) + { + debug("%s search failed\n", *path); + } + + path++; + } + return search; +} + +static wim_directory_entry * search_replace_wim_dirent(void *meta_data, wim_directory_entry *dir) +{ + wim_directory_entry *wim_dirent = NULL; + const char *winpeshl_path[] = { "Windows", "System32", "winpeshl.exe", NULL }; + const char *pecmd_path[] = { "Windows", "System32", "PECMD.exe", NULL }; + + wim_dirent = search_full_wim_dirent(meta_data, dir, winpeshl_path); + if (wim_dirent) + { + return wim_dirent; + } + + wim_dirent = search_full_wim_dirent(meta_data, dir, pecmd_path); + if (wim_dirent) + { + return wim_dirent; + } + + return NULL; +} + + +static wim_lookup_entry * ventoy_find_look_entry(wim_header *header, wim_lookup_entry *lookup, wim_hash *hash) +{ + grub_uint32_t i = 0; + + for (i = 0; i < (grub_uint32_t)header->lookup.raw_size / sizeof(wim_lookup_entry); i++) + { + if (grub_memcmp(&lookup[i].hash, hash, sizeof(wim_hash)) == 0) + { + return lookup + i; + } + } + + return NULL; +} + +static wim_lookup_entry * ventoy_find_meta_entry(wim_header *header, wim_lookup_entry *lookup) +{ + grub_uint32_t i = 0; + grub_uint32_t index = 0;; + + if ((header == NULL) || (lookup == NULL)) + { + return NULL; + } + + for (i = 0; i < (grub_uint32_t)header->lookup.raw_size / sizeof(wim_lookup_entry); i++) + { + if (lookup[i].resource.flags & RESHDR_FLAG_METADATA) + { + index++; + if (index == header->boot_index) + { + return lookup + i; + } + } + } + + return NULL; +} + +static int ventoy_update_all_hash(void *meta_data, wim_directory_entry *dir) +{ + if ((meta_data == NULL) || (dir == NULL)) + { + return 0; + } + + if (dir->len == 0) + { + return 0; + } + + do + { + if (dir->subdir == 0 && grub_memcmp(dir->hash.sha1, g_old_hash.sha1, sizeof(wim_hash)) == 0) + { + debug("find target file, name_len:%u upadte hash\n", dir->name_len); + grub_memcpy(dir->hash.sha1, &(g_wim_data.bin_hash), sizeof(wim_hash)); + } + + if (dir->subdir) + { + ventoy_update_all_hash(meta_data, (wim_directory_entry *)((char *)meta_data + dir->subdir)); + } + + dir = (wim_directory_entry *)((char *)dir + dir->len); + } while (dir->len); + + return 0; +} + +static int ventoy_cat_exe_file_data(grub_uint32_t exe_len, grub_uint8_t *exe_data) +{ + int pe64 = 0; + char file[256]; + grub_uint32_t jump_len = 0; + grub_uint32_t jump_align = 0; + grub_uint8_t *jump_data = NULL; + + pe64 = ventoy_is_pe64(exe_data); + + grub_snprintf(file, sizeof(file), "%s/vtoyjump%d.exe", grub_env_get("vtoy_path"), pe64 ? 64 : 32); + ventoy_load_jump_exe(file, &jump_data, &jump_len, NULL); + jump_align = ventoy_align(jump_len, 16); + + g_wim_data.jump_exe_len = jump_len; + g_wim_data.bin_raw_len = jump_align + sizeof(ventoy_os_param) + exe_len; + g_wim_data.bin_align_len = ventoy_align(g_wim_data.bin_raw_len, 2048); + + g_wim_data.jump_bin_data = grub_malloc(g_wim_data.bin_align_len); + if (g_wim_data.jump_bin_data) + { + grub_memcpy(g_wim_data.jump_bin_data, jump_data, jump_len); + grub_memcpy(g_wim_data.jump_bin_data + jump_align + sizeof(ventoy_os_param), exe_data, exe_len); + } + + debug("jump_exe_len:%u bin_raw_len:%u bin_align_len:%u\n", + g_wim_data.jump_exe_len, g_wim_data.bin_raw_len, g_wim_data.bin_align_len); + + return 0; +} + +static int ventoy_update_before_chain(ventoy_os_param *param) +{ + grub_uint32_t jump_align = 0; + wim_lookup_entry *meta_look = NULL; + wim_security_header *security = NULL; + wim_directory_entry *rootdir = NULL; + wim_header *head = &(g_wim_data.wim_header); + wim_lookup_entry *lookup = (wim_lookup_entry *)g_wim_data.new_lookup_data; + + jump_align = ventoy_align(g_wim_data.jump_exe_len, 16); + if (g_wim_data.jump_bin_data) + { + grub_memcpy(g_wim_data.jump_bin_data + jump_align, param, sizeof(ventoy_os_param)); + } + + grub_crypto_hash(GRUB_MD_SHA1, g_wim_data.bin_hash.sha1, g_wim_data.jump_bin_data, g_wim_data.bin_raw_len); + + security = (wim_security_header *)g_wim_data.new_meta_data; + rootdir = (wim_directory_entry *)(g_wim_data.new_meta_data + ((security->len + 7) & 0xFFFFFFF8U)); + + /* update all winpeshl.exe dirent entry's hash */ + ventoy_update_all_hash(g_wim_data.new_meta_data, rootdir); + + /* update winpeshl.exe lookup entry data (hash/offset/length) */ + if (g_replace_look) + { + debug("update replace lookup entry_id:%ld\n", ((long)g_replace_look - (long)lookup) / sizeof(wim_lookup_entry)); + g_replace_look->resource.raw_size = g_wim_data.bin_raw_len; + g_replace_look->resource.size_in_wim = g_wim_data.bin_raw_len; + g_replace_look->resource.flags = 0; + g_replace_look->resource.offset = g_wim_data.wim_align_size; + + grub_memcpy(g_replace_look->hash.sha1, g_wim_data.bin_hash.sha1, sizeof(wim_hash)); + } + + /* update metadata's hash */ + meta_look = ventoy_find_meta_entry(head, lookup); + if (meta_look) + { + debug("find meta lookup entry_id:%ld\n", ((long)meta_look - (long)lookup) / sizeof(wim_lookup_entry)); + grub_memcpy(&meta_look->resource, &head->metadata, sizeof(wim_resource_header)); + grub_crypto_hash(GRUB_MD_SHA1, meta_look->hash.sha1, g_wim_data.new_meta_data, g_wim_data.new_meta_len); + } + + return 0; +} + +grub_err_t ventoy_cmd_wimdows_locate_wim(grub_extcmd_context_t ctxt, int argc, char **args) +{ + int rc; + grub_file_t file; + grub_uint32_t exe_len; + grub_uint8_t *exe_data = NULL; + grub_uint8_t *decompress_data = NULL; + wim_lookup_entry *lookup = NULL; + wim_security_header *security = NULL; + wim_directory_entry *rootdir = NULL; + wim_directory_entry *search = NULL; + wim_header *head = &(g_wim_data.wim_header); + + (void)ctxt; + (void)argc; + + debug("windows locate wim start %s\n", args[0]); + + file = ventoy_grub_file_open(VENTOY_FILE_TYPE, "%s", args[0]); + if (!file) + { + return grub_error(GRUB_ERR_BAD_ARGUMENT, "Can't open file %s\n", args[0]); + } + + ventoy_get_override_info(file); + + grub_file_seek(file, 0); + grub_file_read(file, head, sizeof(wim_header)); + + if (grub_memcmp(head->signature, WIM_HEAD_SIGNATURE, sizeof(head->signature))) + { + debug("Not a valid wim file %s\n", (char *)head->signature); + grub_file_close(file); + return 1; + } + + if (head->flags & FLAG_HEADER_COMPRESS_XPRESS) + { + debug("Xpress compress is not supported 0x%x\n", head->flags); + grub_file_close(file); + return 1; + } + + rc = ventoy_read_resource(file, &head->metadata, (void **)&decompress_data); + if (rc) + { + grub_printf("failed to read meta data %d\n", rc); + grub_file_close(file); + return 1; + } + + security = (wim_security_header *)decompress_data; + rootdir = (wim_directory_entry *)(decompress_data + ((security->len + 7) & 0xFFFFFFF8U)); + + /* search winpeshl.exe dirent entry */ + search = search_replace_wim_dirent(decompress_data, rootdir); + if (!search) + { + debug("Failed to find replace file %p\n", search); + grub_file_close(file); + return 1; + } + + debug("find replace file at %p\n", search); + + grub_memcpy(&g_old_hash, search->hash.sha1, sizeof(wim_hash)); + + debug("read lookup offset:%llu size:%llu\n", (ulonglong)head->lookup.offset, (ulonglong)head->lookup.raw_size); + lookup = grub_malloc(head->lookup.raw_size); + grub_file_seek(file, head->lookup.offset); + grub_file_read(file, lookup, head->lookup.raw_size); + + /* find and extact winpeshl.exe */ + g_replace_look = ventoy_find_look_entry(head, lookup, &g_old_hash); + if (g_replace_look) + { + exe_len = (grub_uint32_t)g_replace_look->resource.raw_size; + debug("find replace lookup entry_id:%ld raw_size:%u\n", + ((long)g_replace_look - (long)lookup) / sizeof(wim_lookup_entry), exe_len); + + if (0 == ventoy_read_resource(file, &(g_replace_look->resource), (void **)&(exe_data))) + { + ventoy_cat_exe_file_data(exe_len, exe_data); + grub_free(exe_data); + } + else + { + debug("failed to read replace file meta data %u\n", exe_len); + } + } + else + { + debug("failed to find lookup entry for replace file 0x%02x 0x%02x\n", g_old_hash.sha1[0], g_old_hash.sha1[1]); + } + + g_wim_data.wim_raw_size = (grub_uint32_t)file->size; + g_wim_data.wim_align_size = ventoy_align(g_wim_data.wim_raw_size, 2048); + + check_free(g_wim_data.new_meta_data, grub_free); + g_wim_data.new_meta_data = decompress_data; + g_wim_data.new_meta_len = head->metadata.raw_size; + g_wim_data.new_meta_align_len = ventoy_align(g_wim_data.new_meta_len, 2048); + + check_free(g_wim_data.new_lookup_data, grub_free); + g_wim_data.new_lookup_data = (grub_uint8_t *)lookup; + g_wim_data.new_lookup_len = (grub_uint32_t)head->lookup.raw_size; + g_wim_data.new_lookup_align_len = ventoy_align(g_wim_data.new_lookup_len, 2048); + + head->metadata.flags = RESHDR_FLAG_METADATA; + head->metadata.offset = g_wim_data.wim_align_size + g_wim_data.bin_align_len; + head->metadata.size_in_wim = g_wim_data.new_meta_len; + head->metadata.raw_size = g_wim_data.new_meta_len; + + head->lookup.flags = 0; + head->lookup.offset = head->metadata.offset + g_wim_data.new_meta_align_len; + head->lookup.size_in_wim = g_wim_data.new_lookup_len; + head->lookup.raw_size = g_wim_data.new_lookup_len; + + grub_file_close(file); + + debug("%s", "windows locate wim finish\n"); + VENTOY_CMD_RETURN(GRUB_ERR_NONE); +} + +static grub_uint32_t ventoy_get_override_chunk_num(void) +{ + /* 1: block count in Partition Descriptor */ + /* 2: file_size in file_entry or extend_file_entry */ + /* 3: data_size and position in extend data short ad */ + /* 4: new wim file header */ + return 4; +} + +static void ventoy_windows_fill_override_data( grub_uint64_t isosize, void *override) +{ + grub_uint32_t data32; + grub_uint64_t data64; + grub_uint64_t sector; + grub_uint32_t new_wim_size; + ventoy_override_chunk *cur; + + sector = (isosize + 2047) / 2048; + + cur = (ventoy_override_chunk *)override; + + new_wim_size = g_wim_data.wim_align_size + g_wim_data.bin_align_len + + g_wim_data.new_meta_align_len + g_wim_data.new_lookup_align_len; + + if (g_wim_data.iso_type == 0) + { + ventoy_iso9660_override *dirent = (ventoy_iso9660_override *)g_wim_data.override_data; + + dirent->first_sector = (grub_uint32_t)sector; + dirent->size = new_wim_size; + dirent->first_sector_be = grub_swap_bytes32(dirent->first_sector); + dirent->size_be = grub_swap_bytes32(dirent->size); + } + else + { + ventoy_udf_override *udf = (ventoy_udf_override *)g_wim_data.override_data; + udf->length = new_wim_size; + udf->position = (grub_uint32_t)sector - g_wim_data.udf_start_block; + } + + //override 1: sector number in pd data + cur->img_offset = grub_udf_get_last_pd_size_offset(); + cur->override_size = 4; + data32 = sector - g_wim_data.udf_start_block + (new_wim_size / 2048); + grub_memcpy(cur->override_data, &(data32), 4); + + //override 2: filesize in file_entry + cur++; + cur->img_offset = g_wim_data.fe_entry_size_offset; + cur->override_size = 8; + data64 = new_wim_size; + grub_memcpy(cur->override_data, &(data64), 8); + + /* override 3: position and length in extend data */ + cur++; + cur->img_offset = g_wim_data.override_offset; + cur->override_size = g_wim_data.override_len; + grub_memcpy(cur->override_data, g_wim_data.override_data, cur->override_size); + + /* override 4: new wim file header */ + cur++; + cur->img_offset = g_wim_data.file_offset; + cur->override_size = sizeof(wim_header); + grub_memcpy(cur->override_data, &(g_wim_data.wim_header), cur->override_size); + + return; +} + +static void ventoy_windows_fill_virt_data( grub_uint64_t isosize, ventoy_chain_head *chain) +{ + grub_uint64_t sector; + grub_uint32_t offset; + grub_uint32_t wim_secs; + grub_uint32_t mem_secs; + char *override = NULL; + ventoy_virt_chunk *cur = NULL; + + sector = (isosize + 2047) / 2048; + offset = sizeof(ventoy_virt_chunk); + + wim_secs = g_wim_data.wim_align_size / 2048; + mem_secs = (g_wim_data.bin_align_len + g_wim_data.new_meta_align_len + g_wim_data.new_lookup_align_len) / 2048; + + override = (char *)chain + chain->virt_chunk_offset; + cur = (ventoy_virt_chunk *)override; + + cur->remap_sector_start = sector; + cur->remap_sector_end = cur->remap_sector_start + wim_secs; + cur->org_sector_start = (grub_uint32_t)(g_wim_data.file_offset / 2048); + + cur->mem_sector_start = cur->remap_sector_end; + cur->mem_sector_end = cur->mem_sector_start + mem_secs; + cur->mem_sector_offset = offset; + + grub_memcpy(override + offset, g_wim_data.jump_bin_data, g_wim_data.bin_raw_len); + offset += g_wim_data.bin_align_len; + + grub_memcpy(override + offset, g_wim_data.new_meta_data, g_wim_data.new_meta_len); + offset += g_wim_data.new_meta_align_len; + + grub_memcpy(override + offset, g_wim_data.new_lookup_data, g_wim_data.new_lookup_len); + offset += g_wim_data.new_lookup_align_len; + + chain->virt_img_size_in_bytes += g_wim_data.wim_align_size + + g_wim_data.bin_align_len + + g_wim_data.new_meta_align_len + + g_wim_data.new_lookup_align_len; + return; +} + +static int ventoy_windows_drive_map(ventoy_chain_head *chain) +{ + grub_disk_t disk; + + debug("drive map begin <%p> ...\n", chain); + + if (chain->disk_drive == 0x80) + { + disk = grub_disk_open("hd1"); + if (disk) + { + grub_disk_close(disk); + debug("drive map needed %p\n", disk); + chain->drive_map = 0x81; + } + else + { + debug("failed to open disk %s\n", "hd1"); + } + } + else + { + debug("no need to map 0x%x\n", chain->disk_drive); + } + + return 0; +} + +grub_err_t ventoy_cmd_windows_chain_data(grub_extcmd_context_t ctxt, int argc, char **args) +{ + int unknown_image = 0; + int ventoy_compatible = 0; + grub_uint32_t size = 0; + grub_uint64_t isosize = 0; + grub_uint32_t boot_catlog = 0; + grub_uint32_t img_chunk_size = 0; + grub_uint32_t override_size = 0; + grub_uint32_t virt_chunk_size = 0; + grub_file_t file; + grub_disk_t disk; + const char *pLastChain = NULL; + const char *compatible; + ventoy_chain_head *chain; + char envbuf[64]; + + (void)ctxt; + (void)argc; + + debug("chain data begin <%s> ...\n", args[0]); + + compatible = grub_env_get("ventoy_compatible"); + if (compatible && compatible[0] == 'Y') + { + ventoy_compatible = 1; + } + + if (NULL == g_img_chunk_list.chunk) + { + grub_printf("ventoy not ready\n"); + return 1; + } + + if (0 == ventoy_compatible && g_wim_data.new_meta_data == NULL) + { + unknown_image = 1; + debug("Warning: %s was not recognized by Ventoy\n", args[0]); + } + + file = ventoy_grub_file_open(VENTOY_FILE_TYPE, "%s", args[0]); + if (!file) + { + return 1; + } + + isosize = file->size; + + boot_catlog = ventoy_get_iso_boot_catlog(file); + if (boot_catlog) + { + if (ventoy_is_efi_os() && (!ventoy_has_efi_eltorito(file, boot_catlog))) + { + grub_env_set("LoadIsoEfiDriver", "on"); + } + } + else + { + if (ventoy_is_efi_os()) + { + grub_env_set("LoadIsoEfiDriver", "on"); + } + else + { + return grub_error(GRUB_ERR_BAD_ARGUMENT, "File %s is not bootable", args[0]); + } + } + + img_chunk_size = g_img_chunk_list.cur_chunk * sizeof(ventoy_img_chunk); + + if (ventoy_compatible || unknown_image) + { + size = sizeof(ventoy_chain_head) + img_chunk_size; + } + else + { + override_size = ventoy_get_override_chunk_num() * sizeof(ventoy_override_chunk); + virt_chunk_size = sizeof(ventoy_virt_chunk) + g_wim_data.bin_align_len + + g_wim_data.new_meta_align_len + g_wim_data.new_lookup_align_len;; + size = sizeof(ventoy_chain_head) + img_chunk_size + override_size + virt_chunk_size; + } + + pLastChain = grub_env_get("vtoy_chain_mem_addr"); + if (pLastChain) + { + chain = (ventoy_chain_head *)grub_strtoul(pLastChain, NULL, 16); + if (chain) + { + debug("free last chain memory %p\n", chain); + grub_free(chain); + } + } + + chain = grub_malloc(size); + if (!chain) + { + grub_printf("Failed to alloc chain memory size %u\n", size); + grub_file_close(file); + return 1; + } + + grub_snprintf(envbuf, sizeof(envbuf), "0x%lx", (unsigned long)chain); + grub_env_set("vtoy_chain_mem_addr", envbuf); + grub_snprintf(envbuf, sizeof(envbuf), "%u", size); + grub_env_set("vtoy_chain_mem_size", envbuf); + + grub_memset(chain, 0, sizeof(ventoy_chain_head)); + + /* part 1: os parameter */ + ventoy_fill_os_param(file, &(chain->os_param)); + + if (g_wim_data.jump_bin_data && g_wim_data.new_meta_data) + { + ventoy_update_before_chain(&(chain->os_param)); + } + + /* part 2: chain head */ + disk = file->device->disk; + chain->disk_drive = disk->id; + chain->disk_sector_size = (1 << disk->log_sector_size); + chain->real_img_size_in_bytes = file->size; + chain->virt_img_size_in_bytes = (file->size + 2047) / 2048 * 2048; + chain->boot_catalog = boot_catlog; + + if (!ventoy_is_efi_os()) + { + grub_file_seek(file, boot_catlog * 2048); + grub_file_read(file, chain->boot_catalog_sector, sizeof(chain->boot_catalog_sector)); + } + + /* part 3: image chunk */ + chain->img_chunk_offset = sizeof(ventoy_chain_head); + chain->img_chunk_num = g_img_chunk_list.cur_chunk; + grub_memcpy((char *)chain + chain->img_chunk_offset, g_img_chunk_list.chunk, img_chunk_size); + + if (ventoy_compatible || unknown_image) + { + return 0; + } + + if (g_wim_data.new_meta_data == NULL) + { + return 0; + } + + /* part 4: override chunk */ + chain->override_chunk_offset = chain->img_chunk_offset + img_chunk_size; + chain->override_chunk_num = ventoy_get_override_chunk_num(); + ventoy_windows_fill_override_data(isosize, (char *)chain + chain->override_chunk_offset); + + /* part 5: virt chunk */ + chain->virt_chunk_offset = chain->override_chunk_offset + override_size; + chain->virt_chunk_num = 1; + ventoy_windows_fill_virt_data(isosize, chain); + + if (ventoy_is_efi_os() == 0) + { + ventoy_windows_drive_map(chain); + } + + VENTOY_CMD_RETURN(GRUB_ERR_NONE); +} + + diff --git a/GRUB2/grub-2.04/grub-core/ventoy/wimboot.h b/GRUB2/grub-2.04/grub-core/ventoy/wimboot.h new file mode 100644 index 00000000..5a77eaed --- /dev/null +++ b/GRUB2/grub-2.04/grub-core/ventoy/wimboot.h @@ -0,0 +1,65 @@ +/****************************************************************************** + * wimboot.h + * + * Copyright (c) 2020, longpanda + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, see . + * + */ +#ifndef __WIMBOOT_H__ +#define __WIMBOOT_H__ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "ventoy_def.h" + + +#define size_t grub_size_t +#define ssize_t grub_ssize_t +#define memset grub_memset +#define memcpy grub_memcpy + +#define uint8_t grub_uint8_t +#define uint16_t grub_uint16_t +#define uint32_t grub_uint32_t +#define uint64_t grub_uint64_t +#define int32_t grub_int32_t + + + +#define assert(exp) + +//#define DBG grub_printf +#define DBG(fmt, ...) + +const char * huffman_bin ( unsigned long value, unsigned int bits ); + +#endif + diff --git a/GRUB2/grub-2.04/include/grub/ventoy.h b/GRUB2/grub-2.04/include/grub/ventoy.h new file mode 100644 index 00000000..da696c33 --- /dev/null +++ b/GRUB2/grub-2.04/include/grub/ventoy.h @@ -0,0 +1,209 @@ +/****************************************************************************** + * ventoy.h + * + * Copyright (c) 2020, longpanda + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, see . + * + */ + +#ifndef __VENTOY_H__ +#define __VENTOY_H__ + +#define COMPILE_ASSERT(expr) extern char __compile_assert[(expr) ? 1 : -1] + +#define VENTOY_COMPATIBLE_STR "VENTOY COMPATIBLE" +#define VENTOY_COMPATIBLE_STR_LEN 17 + +#define VENTOY_GUID { 0x77772020, 0x2e77, 0x6576, { 0x6e, 0x74, 0x6f, 0x79, 0x2e, 0x6e, 0x65, 0x74 }} + +#pragma pack(1) + +typedef struct ventoy_guid +{ + grub_uint32_t data1; + grub_uint16_t data2; + grub_uint16_t data3; + grub_uint8_t data4[8]; +}ventoy_guid; + + +typedef struct ventoy_image_disk_region +{ + grub_uint32_t image_sector_count; /* image sectors contained in this region (in 2048) */ + grub_uint32_t image_start_sector; /* image sector start (in 2048) */ + grub_uint64_t disk_start_sector; /* disk sector start (in 512) */ +}ventoy_image_disk_region; + +typedef struct ventoy_image_location +{ + ventoy_guid guid; + + /* image sector size, currently this value is always 2048 */ + grub_uint32_t image_sector_size; + + /* disk sector size, normally the value is 512 */ + grub_uint32_t disk_sector_size; + + grub_uint32_t region_count; + + /* + * disk region data (region_count) + * If the image file has more than one fragments in disk, + * there will be more than one region data here. + * + */ + ventoy_image_disk_region regions[1]; + + /* ventoy_image_disk_region regions[2~region_count-1] */ +}ventoy_image_location; + + +typedef struct ventoy_os_param +{ + ventoy_guid guid; // VENTOY_GUID + grub_uint8_t chksum; // checksum + + grub_uint8_t vtoy_disk_guid[16]; + grub_uint64_t vtoy_disk_size; // disk size in bytes + grub_uint16_t vtoy_disk_part_id; // begin with 1 + grub_uint16_t vtoy_disk_part_type; // 0:exfat 1:ntfs other: reserved + char vtoy_img_path[384]; // It seems to be enough, utf-8 format + grub_uint64_t vtoy_img_size; // image file size in bytes + + /* + * Ventoy will write a copy of ventoy_image_location data into runtime memory + * this is the physically address and length of that memory. + * Address 0 means no such data exist. + * Address will be aligned by 4KB. + * + */ + grub_uint64_t vtoy_img_location_addr; + grub_uint32_t vtoy_img_location_len; + + /* + * These 32 bytes are reserved by ventoy. + * + * vtoy_reserved[0]: vtoy_break_level + * vtoy_reserved[1]: vtoy_debug_level + * + */ + grub_uint8_t vtoy_reserved[32]; // Internal use by ventoy + + grub_uint8_t reserved[31]; +}ventoy_os_param; + +#pragma pack() + +// compile assert check : sizeof(ventoy_os_param) must be 512 +COMPILE_ASSERT(sizeof(ventoy_os_param) == 512); + + + + + + + +#pragma pack(4) + +typedef struct ventoy_chain_head +{ + ventoy_os_param os_param; + + grub_uint32_t disk_drive; + grub_uint32_t drive_map; + grub_uint32_t disk_sector_size; + + grub_uint64_t real_img_size_in_bytes; + grub_uint64_t virt_img_size_in_bytes; + grub_uint32_t boot_catalog; + grub_uint8_t boot_catalog_sector[2048]; + + grub_uint32_t img_chunk_offset; + grub_uint32_t img_chunk_num; + + grub_uint32_t override_chunk_offset; + grub_uint32_t override_chunk_num; + + grub_uint32_t virt_chunk_offset; + grub_uint32_t virt_chunk_num; +}ventoy_chain_head; + +typedef struct ventoy_img_chunk +{ + grub_uint32_t img_start_sector; // sector size: 2KB + grub_uint32_t img_end_sector; // included + + grub_uint64_t disk_start_sector; // in disk_sector_size + grub_uint64_t disk_end_sector; // included +}ventoy_img_chunk; + + +typedef struct ventoy_override_chunk +{ + grub_uint64_t img_offset; + grub_uint32_t override_size; + grub_uint8_t override_data[512]; +}ventoy_override_chunk; + +typedef struct ventoy_virt_chunk +{ + grub_uint32_t mem_sector_start; + grub_uint32_t mem_sector_end; + grub_uint32_t mem_sector_offset; + grub_uint32_t remap_sector_start; + grub_uint32_t remap_sector_end; + grub_uint32_t org_sector_start; +}ventoy_virt_chunk; + +#define DEFAULT_CHUNK_NUM 1024 +typedef struct ventoy_img_chunk_list +{ + grub_uint32_t max_chunk; + grub_uint32_t cur_chunk; + ventoy_img_chunk *chunk; +}ventoy_img_chunk_list; + + +#pragma pack() + +#define ventoy_filt_register grub_file_filter_register + +typedef const char * (*grub_env_get_pf)(const char *name); + +#pragma pack(1) +typedef struct ventoy_grub_param +{ + grub_env_get_pf grub_env_get; +}ventoy_grub_param; + +#pragma pack() + + + +int grub_fat_get_file_chunk(grub_uint64_t part_start, grub_file_t file, ventoy_img_chunk_list *chunk_list); +grub_uint64_t grub_iso9660_get_last_read_pos(grub_file_t file); +grub_uint64_t grub_iso9660_get_last_file_dirent_pos(grub_file_t file); +grub_uint64_t grub_udf_get_file_offset(grub_file_t file); +grub_uint64_t grub_udf_get_last_pd_size_offset(void); +grub_uint64_t grub_udf_get_last_file_attr_offset +( + grub_file_t file, + grub_uint32_t *startBlock, + grub_uint64_t *fe_entry_size_offset +); +int ventoy_is_efi_os(void); + +#endif /* __VENTOY_H__ */ + diff --git a/IMG/cpio/sbin/init b/IMG/cpio/sbin/init new file mode 100644 index 00000000..3a4a6ab9 --- /dev/null +++ b/IMG/cpio/sbin/init @@ -0,0 +1,75 @@ +#!/ventoy/busybox/tmpsh +#************************************************************************************ +# Copyright (c) 2020, longpanda +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see . +# +#************************************************************************************ + +#################################################################### +# # +# Step 1 : extract busybox & set busybox enviroment # +# # +#################################################################### + +export VTOY_ORG_PATH=$PATH +export VTOY_PATH=/ventoy +export BUSYBOX_PATH=$VTOY_PATH/busybox +export VTLOG=$VTOY_PATH/log +export FIND=$BUSYBOX_PATH/find +export GREP=$BUSYBOX_PATH/grep +export EGREP=$BUSYBOX_PATH/egrep +export CAT=$BUSYBOX_PATH/cat +export AWK=$BUSYBOX_PATH/awk +export SED=$BUSYBOX_PATH/sed +export SLEEP=$BUSYBOX_PATH/sleep +export HEAD=$BUSYBOX_PATH/head + +$BUSYBOX_PATH/tmpxz -d $BUSYBOX_PATH/busybox.xz +$BUSYBOX_PATH/busybox --install $BUSYBOX_PATH + +export PATH=$BUSYBOX_PATH/:$VTOY_PATH/tool + +export VTOY_BREAK_LEVEL=$(hexdump -n 1 -s 429 -e '1/1 "%02x"' $VTOY_PATH/ventoy_os_param) +export VTOY_DEBUG_LEVEL=$(hexdump -n 1 -s 430 -e '1/1 "%02x"' $VTOY_PATH/ventoy_os_param) + +#Fixme: busybox shell output redirect seems to have some bug in rhel5 +if uname -a | grep -q el5; then + VTOY_REDT_BUG=YES +fi + +if [ -z "$VTOY_REDT_BUG" ]; then + echo "============== VENTOY =================" >>$VTLOG +fi + +cd $VTOY_PATH +xz -d ventoy.sh.xz + +if [ -n "$VTOY_REDT_BUG" ]; then + xz -d -c hook.cpio.xz | cpio -idm + xz -d -c tool.cpio.xz | cpio -idm +else + xz -d -c hook.cpio.xz | cpio -idm 2>>$VTLOG + xz -d -c tool.cpio.xz | cpio -idm 2>>$VTLOG +fi + +rm -f *.xz +cd / + +#################################################################### +# # +# Step 2 : Hand over to ventoy init # +# # +#################################################################### +exec $BUSYBOX_PATH/sh $VTOY_PATH/init diff --git a/IMG/cpio/ventoy/busybox/busybox.xz b/IMG/cpio/ventoy/busybox/busybox.xz new file mode 100644 index 00000000..17bd64b3 Binary files /dev/null and b/IMG/cpio/ventoy/busybox/busybox.xz differ diff --git a/IMG/cpio/ventoy/busybox/tmpsh b/IMG/cpio/ventoy/busybox/tmpsh new file mode 100644 index 00000000..9944a11a Binary files /dev/null and b/IMG/cpio/ventoy/busybox/tmpsh differ diff --git a/IMG/cpio/ventoy/busybox/tmpxz b/IMG/cpio/ventoy/busybox/tmpxz new file mode 100644 index 00000000..34acebf8 Binary files /dev/null and b/IMG/cpio/ventoy/busybox/tmpxz differ diff --git a/IMG/cpio/ventoy/hook/alpine/udev_disk_hook.sh b/IMG/cpio/ventoy/hook/alpine/udev_disk_hook.sh new file mode 100644 index 00000000..930009bc --- /dev/null +++ b/IMG/cpio/ventoy/hook/alpine/udev_disk_hook.sh @@ -0,0 +1,71 @@ +#!/ventoy/busybox/sh +#************************************************************************************ +# Copyright (c) 2020, longpanda +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see . +# +#************************************************************************************ + +. /ventoy/hook/ventoy-hook-lib.sh + +if [ "$SUBSYSTEM" != "block" ] || [ "$DEVTYPE" != "partition" ]; then + exit 0 +fi + +if [ -b /dev/${MDEV:0:-1} ]; then + vtlog "/dev/${MDEV:0:-1} exist" +else + $SLEEP 2 +fi + +if is_ventoy_hook_finished || not_ventoy_disk "${MDEV:0:-1}"; then + exit 0 +fi + +PATH=$BUSYBOX_PATH:$VTOY_PATH/tool:$PATH + +# +# longpanda: +# Alpine initramfs doesn't contain dm-mod or fuse module, +# and even the worse, the libpthread.so is not included too. +# So here we directly dump the modloop squashfs file from disk to rootfs. +# Fortunately, this file is not too big (< 100MB in alpine 3.11.3). +# After that: +# 1. mount the squashfs file +# 2. find the dm-mod module from the mountpoint and insmod +# 3. unmount and delete the squashfs file +# + +vtoydm -i -f $VTOY_PATH/ventoy_image_map -d /dev/${MDEV:0:-1} > $VTOY_PATH/iso_file_list + +vtLine=$(grep '[-][-] modloop-lts ' $VTOY_PATH/iso_file_list) +sector=$(echo $vtLine | awk '{print $(NF-1)}') +length=$(echo $vtLine | awk '{print $NF}') + +vtoydm -e -f $VTOY_PATH/ventoy_image_map -d /dev/${MDEV:0:-1} -s $sector -l $length -o /vt_modloop + +mkdir -p $VTOY_PATH/mnt +mount /vt_modloop $VTOY_PATH/mnt + +KoModPath=$(find $VTOY_PATH/mnt/ -name 'dm-mod.ko*') +vtlog "insmod $KoModPath" +insmod $KoModPath + +umount $VTOY_PATH/mnt +rm -f /vt_modloop + +ventoy_udev_disk_common_hook "$MDEV" "noreplace" + +# OK finish +set_ventoy_hook_finish diff --git a/IMG/cpio/ventoy/hook/alpine/ventoy-hook.sh b/IMG/cpio/ventoy/hook/alpine/ventoy-hook.sh new file mode 100644 index 00000000..ae366cdf --- /dev/null +++ b/IMG/cpio/ventoy/hook/alpine/ventoy-hook.sh @@ -0,0 +1,24 @@ +#!/ventoy/busybox/sh +#************************************************************************************ +# Copyright (c) 2020, longpanda +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see . +# +#************************************************************************************ + +. $VTOY_PATH/hook/ventoy-os-lib.sh + +echo "-[-a-z0-9]*2 root:root 0666 @$BUSYBOX_PATH/sh $VTOY_PATH/hook/alpine/udev_disk_hook.sh" >> /mdev.conf +$CAT /etc/mdev.conf >> /mdev.conf +$BUSYBOX_PATH/mv /mdev.conf /etc/mdev.conf diff --git a/IMG/cpio/ventoy/hook/arch/ventoy-hook.sh b/IMG/cpio/ventoy/hook/arch/ventoy-hook.sh new file mode 100644 index 00000000..32ee137f --- /dev/null +++ b/IMG/cpio/ventoy/hook/arch/ventoy-hook.sh @@ -0,0 +1,34 @@ +#!/ventoy/busybox/sh +#************************************************************************************ +# Copyright (c) 2020, longpanda +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see . +# +#************************************************************************************ + +. $VTOY_PATH/hook/ventoy-os-lib.sh + +# some archlinux initramfs doesn't contain device-mapper udev rules file +ARCH_UDEV_DIR=$(ventoy_get_udev_conf_dir) +if [ -s "$ARCH_UDEV_DIR/13-dm-disk.rules" ]; then + echo 'dm-disk rule exist' >> $VTLOG +else + echo 'Copy dm-disk rule file' >> $VTLOG + $CAT $VTOY_PATH/hook/default/13-dm-disk.rules > "$ARCH_UDEV_DIR/13-dm-disk.rules" +fi + +# use default proc +ventoy_systemd_udevd_work_around + +ventoy_add_udev_rule "$VTOY_PATH/hook/default/udev_disk_hook.sh %k" diff --git a/IMG/cpio/ventoy/hook/debian/antix-disk.sh b/IMG/cpio/ventoy/hook/debian/antix-disk.sh new file mode 100644 index 00000000..31ff1ca9 --- /dev/null +++ b/IMG/cpio/ventoy/hook/debian/antix-disk.sh @@ -0,0 +1,117 @@ +#!/ventoy/busybox/sh +#************************************************************************************ +# Copyright (c) 2020, longpanda +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see . +# +#************************************************************************************ + +. /ventoy/hook/ventoy-hook-lib.sh + +vtlog "####### $0 $* ########" + +VTPATH_OLD=$PATH; PATH=$BUSYBOX_PATH:$VTOY_PATH/tool:$PATH + + +ventoy_os_install_dmsetup_by_unsquashfs() { + vtlog "ventoy_os_install_dmsetup_by_unsquashfs $*" + + vtKoPo=$(ventoy_get_module_postfix) + vtlog "vtKoPo=$vtKoPo" + + vtoydm -i -f $VTOY_PATH/ventoy_image_map -d $1 > $VTOY_PATH/iso_file_list + + vtline=$(grep '[-][-] linuxfs ' $VTOY_PATH/iso_file_list) + sector=$(echo $vtline | awk '{print $(NF-1)}') + length=$(echo $vtline | awk '{print $NF}') + + vtoydm -E -f $VTOY_PATH/ventoy_image_map -d $1 -s $sector -l $length -o $VTOY_PATH/fsdisk + + dmModPath="/usr/lib/modules/$vtKerVer/kernel/drivers/md/dm-mod.$vtKoPo" + echo $dmModPath > $VTOY_PATH/fsextract + vtoy_unsquashfs -d $VTOY_PATH/sqfs -n -q -e $VTOY_PATH/fsextract $VTOY_PATH/fsdisk + + if ! [ -e $VTOY_PATH/sqfs${dmModPath} ]; then + dmModPath="/lib/modules/$vtKerVer/kernel/drivers/md/dm-mod.$vtKoPo" + echo $dmModPath > $VTOY_PATH/fsextract + vtoy_unsquashfs -d $VTOY_PATH/sqfs -n -q -e $VTOY_PATH/fsextract $VTOY_PATH/fsdisk + fi + + if [ -e $VTOY_PATH/sqfs${dmModPath} ]; then + vtlog "success $VTOY_PATH/sqfs${dmModPath}" + insmod $VTOY_PATH/sqfs${dmModPath} + else + false + fi +} + + +ventoy_os_install_dmsetup_by_fuse() { + vtlog "ventoy_os_install_dmsetup_by_fuse $*" + + mkdir -p $VTOY_PATH/mnt/fuse $VTOY_PATH/mnt/iso $VTOY_PATH/mnt/squashfs + + vtoydm -p -f $VTOY_PATH/ventoy_image_map -d $1 > $VTOY_PATH/ventoy_dm_table + vtoy_fuse_iso -f $VTOY_PATH/ventoy_dm_table -m $VTOY_PATH/mnt/fuse + + mount -t iso9660 $VTOY_PATH/mnt/fuse/ventoy.iso $VTOY_PATH/mnt/iso + mount -t squashfs $VTOY_PATH/mnt/iso/antiX/linuxfs $VTOY_PATH/mnt/squashfs + + KoName=$(ls $VTOY_PATH/mnt/squashfs/lib/modules/$2/kernel/drivers/md/dm-mod.ko*) + vtlog "insmod $KoName" + insmod $KoName + + umount $VTOY_PATH/mnt/squashfs + umount $VTOY_PATH/mnt/iso + umount $VTOY_PATH/mnt/fuse +} + + +ventoy_os_install_dmsetup() { + vtlog "ventoy_os_install_dmsetup" + + if grep -q 'device-mapper' /proc/devices; then + vtlog "device-mapper module already loaded" + return; + fi + + vtKerVer=$(uname -r) + + if ventoy_os_install_dmsetup_by_unsquashfs $1 $vtKerVer; then + vtlog "unsquashfs success" + else + if modprobe fuse 2>>$VTLOG; then + ventoy_os_install_dmsetup_by_fuse $1 $vtKerVer + fi + fi +} + +vtdiskname=$(get_ventoy_disk_name) +if [ "$vtdiskname" = "unknown" ]; then + vtlog "ventoy disk not found" + PATH=$VTPATH_OLD + exit 0 +fi + +ventoy_os_install_dmsetup $vtdiskname + +ventoy_udev_disk_common_hook "${vtdiskname#/dev/}2" "noreplace" + +if ! [ -e $VTOY_DM_PATH ]; then + blkdev_num=$($VTOY_PATH/tool/dmsetup ls | grep ventoy | sed 's/.*(\([0-9][0-9]*\),.*\([0-9][0-9]*\).*/\1 \2/') + mknod -m 0666 $VTOY_DM_PATH b $blkdev_num +fi + +PATH=$VTPATH_OLD + diff --git a/IMG/cpio/ventoy/hook/debian/antix-hook.sh b/IMG/cpio/ventoy/hook/debian/antix-hook.sh new file mode 100644 index 00000000..66615047 --- /dev/null +++ b/IMG/cpio/ventoy/hook/debian/antix-hook.sh @@ -0,0 +1,29 @@ +#!/ventoy/busybox/sh +#************************************************************************************ +# Copyright (c) 2020, longpanda +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see . +# +#************************************************************************************ + +if $GREP -q 'FILTERED_LIST=[^a-zA-Z0-9_]*$' /init; then + $SED 's#FILTERED_LIST=[^a-zA-Z0-9_]*$#FILTERED_LIST=/dev/mapper/ventoy#' -i /init +elif $GREP -q '\[ "$FILTERED_LIST" \]' /init; then + $SED '/\[ "$FILTERED_LIST" \]/i\ FILTERED_LIST="/dev/mapper/ventoy $FILTERED_LIST"' -i /init +fi + +$SED -i "/_search_for_boot_device_/a\ $BUSYBOX_PATH/sh $VTOY_PATH/hook/debian/antix-disk.sh" /init + +# for debug +#$SED -i "/^linuxfs_error/a\exec $VTOY_PATH/busybox/sh" /init diff --git a/IMG/cpio/ventoy/hook/debian/default-hook.sh b/IMG/cpio/ventoy/hook/debian/default-hook.sh new file mode 100644 index 00000000..a8fd7ec6 --- /dev/null +++ b/IMG/cpio/ventoy/hook/debian/default-hook.sh @@ -0,0 +1,21 @@ +#!/ventoy/busybox/sh +#************************************************************************************ +# Copyright (c) 2020, longpanda +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see . +# +#************************************************************************************ + +ventoy_systemd_udevd_work_around +ventoy_add_udev_rule "$VTOY_PATH/hook/debian/udev_disk_hook.sh %k" diff --git a/IMG/cpio/ventoy/hook/debian/udev_disk_hook.sh b/IMG/cpio/ventoy/hook/debian/udev_disk_hook.sh new file mode 100644 index 00000000..7edcbe73 --- /dev/null +++ b/IMG/cpio/ventoy/hook/debian/udev_disk_hook.sh @@ -0,0 +1,111 @@ +#!/ventoy/busybox/sh +#************************************************************************************ +# Copyright (c) 2020, longpanda +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see . +# +#************************************************************************************ + +. /ventoy/hook/ventoy-hook-lib.sh + +ventoy_os_install_dmsetup() { + + vt_usb_disk=$1 + + # dump iso file location + $VTOY_PATH/tool/vtoydm -i -f $VTOY_PATH/ventoy_image_map -d ${vt_usb_disk} > $VTOY_PATH/iso_file_list + + # install dmsetup + LINE=$($GREP ' dmsetup.*\.udeb' $VTOY_PATH/iso_file_list) + if [ $? -eq 0 ]; then + install_udeb_from_line "$LINE" ${vt_usb_disk} + fi + + # install libdevmapper + LINE=$($GREP ' libdevmapper.*\.udeb' $VTOY_PATH/iso_file_list) + if [ $? -eq 0 ]; then + install_udeb_from_line "$LINE" ${vt_usb_disk} + fi + + # install md-modules + LINE=$($GREP ' md-modules.*\.udeb' $VTOY_PATH/iso_file_list) + if [ $? -eq 0 ]; then + install_udeb_from_line "$LINE" ${vt_usb_disk} + fi + + # insmod md-mod if needed + if $GREP -q 'device-mapper' /proc/devices; then + vtlog "device mapper module is loaded" + else + vtlog"device mapper module is NOT loaded, now load it..." + + VER=$($BUSYBOX_PATH/uname -r) + KO=$($FIND /lib/modules/$VER/kernel/drivers/md -name "dm-mod*") + vtlog "KO=$KO" + + insmod $KO + fi + + vtlog "dmsetup install finish, now check it..." + if dmsetup info >> $VTLOG 2>&1; then + vtlog "dmsetup work ok" + else + vtlog "dmsetup not work, now try to load eglibc ..." + + # install eglibc (some ubuntu 32 bit version need it) + LINE=$($GREP 'libc6-.*\.udeb' $VTOY_PATH/iso_file_list) + if [ $? -eq 0 ]; then + install_udeb_from_line "$LINE" ${vt_usb_disk} + fi + + if dmsetup info >> $VTLOG 2>&1; then + vtlog "dmsetup work ok after retry" + else + vtlog "dmsetup still not work after retry" + fi + fi +} + +if is_ventoy_hook_finished || not_ventoy_disk "${1:0:-1}"; then + exit 0 +fi + +dmsetup_path=$(ventoy_find_bin_path dmsetup) +if [ -z "$dmsetup_path" ]; then + ventoy_os_install_dmsetup "/dev/${1:0:-1}" +fi + +ventoy_udev_disk_common_hook $* + +# +# Some distro default only accept usb partitions as install medium. +# So if ventoy is installed on a non-USB device, we just mount /cdrom here except +# for these has boot=live or boot=casper parameter in cmdline +# +if echo $ID_BUS | $GREP -q -i usb; then + vtlog "$1 is USB device" +else + vtlog "$1 is NOT USB device (bus $ID_BUS)" + + if $EGREP -q 'boot=|casper' /proc/cmdline; then + vtlog "boot=, or casper, don't mount" + else + vtlog "No boot param, need to mount" + $BUSYBOX_PATH/mkdir /cdrom + $BUSYBOX_PATH/mount -t iso9660 $VTOY_DM_PATH /cdrom + fi +fi + +# OK finish +set_ventoy_hook_finish diff --git a/IMG/cpio/ventoy/hook/debian/ventoy-hook.sh b/IMG/cpio/ventoy/hook/debian/ventoy-hook.sh new file mode 100644 index 00000000..22e2790d --- /dev/null +++ b/IMG/cpio/ventoy/hook/debian/ventoy-hook.sh @@ -0,0 +1,31 @@ +#!/ventoy/busybox/sh +#************************************************************************************ +# Copyright (c) 2020, longpanda +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see . +# +#************************************************************************************ + +. $VTOY_PATH/hook/ventoy-os-lib.sh + +DISTRO='default' + +if [ -e /etc/initrd-release ]; then + if $EGREP -q "ID=.*antix|ID=.*mx" /etc/initrd-release; then + DISTRO='antix' + fi +fi + +echo "##### distribution = $DISTRO ######" >> $VTLOG +. $VTOY_PATH/hook/debian/${DISTRO}-hook.sh diff --git a/IMG/cpio/ventoy/hook/default/13-dm-disk.rules b/IMG/cpio/ventoy/hook/default/13-dm-disk.rules new file mode 100644 index 00000000..9be707a0 --- /dev/null +++ b/IMG/cpio/ventoy/hook/default/13-dm-disk.rules @@ -0,0 +1,42 @@ +# Copyright (C) 2009 Red Hat, Inc. All rights reserved. +# +# This file is part of LVM2. + +# Udev rules for device-mapper devices. +# +# These rules create symlinks in /dev/disk directory. +# Symlinks that depend on probing filesystem type, +# label and uuid are created only if the device is not +# suspended. + +# "add" event is processed on coldplug only! +ACTION!="add|change", GOTO="dm_end" +ENV{DM_UDEV_RULES_VSN}!="?*", GOTO="dm_end" +ENV{DM_UDEV_DISABLE_DISK_RULES_FLAG}=="1", GOTO="dm_end" + +SYMLINK+="disk/by-id/dm-name-$env{DM_NAME}" +ENV{DM_UUID}=="?*", SYMLINK+="disk/by-id/dm-uuid-$env{DM_UUID}" + +ENV{DM_SUSPENDED}=="1", GOTO="dm_end" +ENV{DM_NOSCAN}=="1", GOTO="dm_watch" + +IMPORT{builtin}="blkid" +ENV{DM_UDEV_LOW_PRIORITY_FLAG}=="1", OPTIONS="link_priority=-100" +ENV{ID_FS_USAGE}=="filesystem|other|crypto", ENV{ID_FS_UUID_ENC}=="?*", SYMLINK+="disk/by-uuid/$env{ID_FS_UUID_ENC}" +ENV{ID_FS_USAGE}=="filesystem|other", ENV{ID_FS_LABEL_ENC}=="?*", SYMLINK+="disk/by-label/$env{ID_FS_LABEL_ENC}" +ENV{ID_PART_ENTRY_UUID}=="?*", SYMLINK+="disk/by-partuuid/$env{ID_PART_ENTRY_UUID}" +ENV{ID_PART_ENTRY_SCHEME}=="gpt", ENV{ID_PART_ENTRY_NAME}=="?*", SYMLINK+="disk/by-partlabel/$env{ID_PART_ENTRY_NAME}" +ENV{ID_PART_ENTRY_SCHEME}=="gpt", ENV{ID_PART_GPT_AUTO_ROOT}=="1", SYMLINK+="gpt-auto-root" + +# Add inotify watch to track changes on this device. +# Using the watch rule is not optimal - it generates a lot of spurious +# and useless events whenever the device opened for read-write is closed. +# The best would be to generete the event directly in the tool changing +# relevant information so only relevant events will be processed +# (like creating a filesystem, changing filesystem label etc.). +# +# But let's use this until we have something better... +LABEL="dm_watch" +OPTIONS+="watch" + +LABEL="dm_end" diff --git a/IMG/cpio/ventoy/hook/default/udev_disk_hook.sh b/IMG/cpio/ventoy/hook/default/udev_disk_hook.sh new file mode 100644 index 00000000..633f29ea --- /dev/null +++ b/IMG/cpio/ventoy/hook/default/udev_disk_hook.sh @@ -0,0 +1,30 @@ +#!/ventoy/busybox/sh +#************************************************************************************ +# Copyright (c) 2020, longpanda +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see . +# +#************************************************************************************ + +. /ventoy/hook/ventoy-hook-lib.sh + +if is_ventoy_hook_finished || not_ventoy_disk "${1:0:-1}"; then + exit 0 +fi + +ventoy_udev_disk_common_hook $* + +# OK finish +set_ventoy_hook_finish + diff --git a/IMG/cpio/ventoy/hook/default/ventoy-hook.sh b/IMG/cpio/ventoy/hook/default/ventoy-hook.sh new file mode 100644 index 00000000..152dd06b --- /dev/null +++ b/IMG/cpio/ventoy/hook/default/ventoy-hook.sh @@ -0,0 +1,24 @@ +#!/ventoy/busybox/sh +#************************************************************************************ +# Copyright (c) 2020, longpanda +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see . +# +#************************************************************************************ + +. $VTOY_PATH/hook/ventoy-os-lib.sh + +ventoy_systemd_udevd_work_around + +ventoy_add_udev_rule "$VTOY_PATH/hook/default/udev_disk_hook.sh %k" diff --git a/IMG/cpio/ventoy/hook/gentoo/disk_hook.sh b/IMG/cpio/ventoy/hook/gentoo/disk_hook.sh new file mode 100644 index 00000000..3f515bff --- /dev/null +++ b/IMG/cpio/ventoy/hook/gentoo/disk_hook.sh @@ -0,0 +1,36 @@ +#!/ventoy/busybox/sh +#************************************************************************************ +# Copyright (c) 2020, longpanda +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see . +# +#************************************************************************************ + +. /ventoy/hook/ventoy-hook-lib.sh + +# Just for KVM test enviroment +$BUSYBOX_PATH/modprobe virtio_blk 2>/dev/null +$BUSYBOX_PATH/modprobe virtio_pci 2>/dev/null + +for i in 0 1 2 3 4 5 6 7 8 9; do + vtdiskname=$(get_ventoy_disk_name) + if [ "$vtdiskname" = "unknown" ]; then + vtlog "wait for disk ..." + $SLEEP 2 + else + break + fi +done + +ventoy_udev_disk_common_hook "${vtdiskname#/dev/}2" "noreplace" diff --git a/IMG/cpio/ventoy/hook/gentoo/ventoy-hook.sh b/IMG/cpio/ventoy/hook/gentoo/ventoy-hook.sh new file mode 100644 index 00000000..d9034fbf --- /dev/null +++ b/IMG/cpio/ventoy/hook/gentoo/ventoy-hook.sh @@ -0,0 +1,27 @@ +#!/ventoy/busybox/sh +#************************************************************************************ +# Copyright (c) 2020, longpanda +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see . +# +#************************************************************************************ + +. $VTOY_PATH/hook/ventoy-os-lib.sh + +if [ -d /etc/udev/rules.d ]; then + ventoy_systemd_udevd_work_around + ventoy_add_udev_rule "$VTOY_PATH/hook/default/udev_disk_hook.sh %k noreplace" +else + $SED "/mdev *-s/a\ $BUSYBOX_PATH/sh $VTOY_PATH/hook/gentoo/disk_hook.sh" -i /init +fi diff --git a/IMG/cpio/ventoy/hook/kaos/udev_disk_hook.sh b/IMG/cpio/ventoy/hook/kaos/udev_disk_hook.sh new file mode 100644 index 00000000..08ee2680 --- /dev/null +++ b/IMG/cpio/ventoy/hook/kaos/udev_disk_hook.sh @@ -0,0 +1,39 @@ +#!/ventoy/busybox/sh +#************************************************************************************ +# Copyright (c) 2020, longpanda +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see . +# +#************************************************************************************ + +. /ventoy/hook/ventoy-hook-lib.sh + +if is_ventoy_hook_finished || not_ventoy_disk "${1:0:-1}"; then + exit 0 +fi + +VTPATH_OLD=$PATH; PATH=$BUSYBOX_PATH:$VTOY_PATH/tool:$PATH + +modprobe fuse +mkdir -p $VTOY_PATH/mnt/fuse $VTOY_PATH/mnt/iso + +vtoydm -p -f $VTOY_PATH/ventoy_image_map -d "/dev/${1:0:-1}" > $VTOY_PATH/ventoy_dm_table +vtoy_fuse_iso -f $VTOY_PATH/ventoy_dm_table -m $VTOY_PATH/mnt/fuse +mount -t iso9660 $VTOY_PATH/mnt/fuse/ventoy.iso $VTOY_PATH/mnt/iso + +# OK finish +set_ventoy_hook_finish + +PATH=$VTPATH_OLD + diff --git a/IMG/cpio/ventoy/hook/kaos/ventoy-hook.sh b/IMG/cpio/ventoy/hook/kaos/ventoy-hook.sh new file mode 100644 index 00000000..c268801a --- /dev/null +++ b/IMG/cpio/ventoy/hook/kaos/ventoy-hook.sh @@ -0,0 +1,6 @@ +#!/ventoy/busybox/sh + +. $VTOY_PATH/hook/ventoy-os-lib.sh + +ventoy_systemd_udevd_work_around +ventoy_add_udev_rule "$VTOY_PATH/hook/kaos/udev_disk_hook.sh %k" diff --git a/IMG/cpio/ventoy/hook/mageia/udev_disk_hook.sh b/IMG/cpio/ventoy/hook/mageia/udev_disk_hook.sh new file mode 100644 index 00000000..b685c71d --- /dev/null +++ b/IMG/cpio/ventoy/hook/mageia/udev_disk_hook.sh @@ -0,0 +1,40 @@ +#!/ventoy/busybox/sh +#************************************************************************************ +# Copyright (c) 2020, longpanda +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see . +# +#************************************************************************************ + +. /ventoy/hook/ventoy-hook-lib.sh + +if is_ventoy_hook_finished || not_ventoy_disk "${1:0:-1}"; then + exit 0 +fi + +ventoy_udev_disk_common_hook $* + +# +# cheatcode for mageia +# +# From mageia/soft/drakx/mdk-stage1 source code, we see that the stage1 binary will search +# /tmp/syslog file to determin whether there is a DAC960 cdrom in the system. +# So we insert some string to /tmp/syslog file to cheat the stage1 program. +# +$BUSYBOX_PATH/mkdir -p /dev/rd +ventoy_copy_device_mapper "/dev/rd/ventoy" +echo 'ventoy cheatcode /dev/rd/ventoy: model' >> /tmp/syslog + +# OK finish +set_ventoy_hook_finish diff --git a/IMG/cpio/ventoy/hook/mageia/ventoy-hook.sh b/IMG/cpio/ventoy/hook/mageia/ventoy-hook.sh new file mode 100644 index 00000000..5edc8f2b --- /dev/null +++ b/IMG/cpio/ventoy/hook/mageia/ventoy-hook.sh @@ -0,0 +1,7 @@ +#!/ventoy/busybox/sh + +. $VTOY_PATH/hook/ventoy-os-lib.sh + +ventoy_systemd_udevd_work_around + +ventoy_add_udev_rule "$VTOY_PATH/hook/mageia/udev_disk_hook.sh %k noreplace" diff --git a/IMG/cpio/ventoy/hook/manjaro/ventoy-hook.sh b/IMG/cpio/ventoy/hook/manjaro/ventoy-hook.sh new file mode 100644 index 00000000..b902f984 --- /dev/null +++ b/IMG/cpio/ventoy/hook/manjaro/ventoy-hook.sh @@ -0,0 +1,33 @@ +#!/ventoy/busybox/sh +#************************************************************************************ +# Copyright (c) 2020, longpanda +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see . +# +#************************************************************************************ + +. $VTOY_PATH/hook/ventoy-os-lib.sh + +# some distro initramfs doesn't contain device-mapper udev rules file +DISTRO_UDEV_DIR=$(ventoy_get_udev_conf_dir) +if [ -s "$DISTRO_UDEV_DIR/13-dm-disk.rules" ]; then + echo 'dm-disk rule exist' >> $VTLOG +else + echo 'Copy dm-disk rule file' >> $VTLOG + $CAT $VTOY_PATH/hook/default/13-dm-disk.rules > "$DISTRO_UDEV_DIR/13-dm-disk.rules" +fi + +ventoy_systemd_udevd_work_around + +ventoy_add_udev_rule "$VTOY_PATH/hook/default/udev_disk_hook.sh %k" diff --git a/IMG/cpio/ventoy/hook/nixos/udev_disk_hook.sh b/IMG/cpio/ventoy/hook/nixos/udev_disk_hook.sh new file mode 100644 index 00000000..633f29ea --- /dev/null +++ b/IMG/cpio/ventoy/hook/nixos/udev_disk_hook.sh @@ -0,0 +1,30 @@ +#!/ventoy/busybox/sh +#************************************************************************************ +# Copyright (c) 2020, longpanda +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see . +# +#************************************************************************************ + +. /ventoy/hook/ventoy-hook-lib.sh + +if is_ventoy_hook_finished || not_ventoy_disk "${1:0:-1}"; then + exit 0 +fi + +ventoy_udev_disk_common_hook $* + +# OK finish +set_ventoy_hook_finish + diff --git a/IMG/cpio/ventoy/hook/nixos/ventoy-hook.sh b/IMG/cpio/ventoy/hook/nixos/ventoy-hook.sh new file mode 100644 index 00000000..7b01c13c --- /dev/null +++ b/IMG/cpio/ventoy/hook/nixos/ventoy-hook.sh @@ -0,0 +1,25 @@ +#!/ventoy/busybox/sh +#************************************************************************************ +# Copyright (c) 2020, longpanda +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see . +# +#************************************************************************************ + +. $VTOY_PATH/hook/ventoy-os-lib.sh + +vtRuleFile=$($FIND / -name '*.rules' -type f | $GREP udev | $HEAD -n1) + +ventoy_add_udev_rule_with_path "$VTOY_PATH/hook/default/udev_disk_hook.sh %k noreplace" "${vtRuleFile%/*}/99-ventoy.rules" + diff --git a/IMG/cpio/ventoy/hook/pclos/disk_hook.sh b/IMG/cpio/ventoy/hook/pclos/disk_hook.sh new file mode 100644 index 00000000..ca91ac84 --- /dev/null +++ b/IMG/cpio/ventoy/hook/pclos/disk_hook.sh @@ -0,0 +1,72 @@ +#!/ventoy/busybox/sh +#************************************************************************************ +# Copyright (c) 2020, longpanda +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see . +# +#************************************************************************************ + +. /ventoy/hook/ventoy-hook-lib.sh + +VTPATH_OLD=$PATH; PATH=$BUSYBOX_PATH:$VTOY_PATH/tool:$PATH + +ventoy_os_install_device_mapper_by_unsquashfs() { + vtlog "ventoy_os_install_device_mapper_by_unsquashfs $*" + + vtKoExt=$(ventoy_get_module_postfix) + vtlog "vtKoExt=$vtKoExt" + + vtoydm -i -f $VTOY_PATH/ventoy_image_map -d $1 > $VTOY_PATH/iso_file_list + + vtline=$(grep '[-][-] livecd.sqfs ' $VTOY_PATH/iso_file_list) + sector=$(echo $vtline | awk '{print $(NF-1)}') + length=$(echo $vtline | awk '{print $NF}') + + vtoydm -E -f $VTOY_PATH/ventoy_image_map -d $1 -s $sector -l $length -o $VTOY_PATH/fsdisk + + dmModPath="/lib/modules/$2/kernel/drivers/md/dm-mod.$vtKoExt" + echo $dmModPath > $VTOY_PATH/fsextract + vtoy_unsquashfs -d $VTOY_PATH/sqfs -n -q -e $VTOY_PATH/fsextract $VTOY_PATH/fsdisk + + if [ -e $VTOY_PATH/sqfs${dmModPath} ]; then + vtlog "success $VTOY_PATH/sqfs${dmModPath}" + insmod $VTOY_PATH/sqfs${dmModPath} + else + false + fi +} + + +ventoy_os_install_device_mapper() { + vtlog "ventoy_os_install_device_mapper" + + if grep -q 'device-mapper' /proc/devices; then + vtlog "device-mapper module already loaded" + return; + fi + + vtKerVer=$(uname -r) + if ventoy_os_install_device_mapper_by_unsquashfs $1 $vtKerVer; then + vtlog "unsquashfs success" + else + vterr "unsquashfs failed" + fi +} + +vtdiskname=$(get_ventoy_disk_name) +ventoy_os_install_device_mapper $vtdiskname + +ventoy_udev_disk_common_hook "${vtdiskname#/dev/}2" + +PATH=$VTPATH_OLD diff --git a/IMG/cpio/ventoy/hook/pclos/ventoy-hook.sh b/IMG/cpio/ventoy/hook/pclos/ventoy-hook.sh new file mode 100644 index 00000000..d0824533 --- /dev/null +++ b/IMG/cpio/ventoy/hook/pclos/ventoy-hook.sh @@ -0,0 +1,57 @@ +#!/ventoy/busybox/sh +#************************************************************************************ +# Copyright (c) 2020, longpanda +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see . +# +#************************************************************************************ + +. $VTOY_PATH/hook/ventoy-os-lib.sh + +# Step 1: dd initrd file to ramdisk +vtRamdiskFile=$($BUSYBOX_PATH/ls /initrd* | $HEAD -n1) +$BUSYBOX_PATH/mknod -m 0666 /ram0 b 1 0 +$BUSYBOX_PATH/dd if=$vtRamdiskFile of=/ram0 status=none +$BUSYBOX_PATH/rm -f $vtRamdiskFile + +# Step 2: mount ramdisk +$BUSYBOX_PATH/mkdir -p /ventoy_rdroot +ventoy_close_printk +$BUSYBOX_PATH/mount /ram0 /ventoy_rdroot +ventoy_restore_printk + +# Step 3: Copy ventoy tool to new root directory. +# Here we make a tmpfs mount to avoid ramdisk out of space (additional space is for log). +vtSize=$($BUSYBOX_PATH/du -m -s $VTOY_PATH | $BUSYBOX_PATH/awk '{print $1}') +let vtSize=vtSize+4 + +$BUSYBOX_PATH/mkdir -p /ventoy_rdroot/ventoy +$BUSYBOX_PATH/mount -t tmpfs -o size=${vtSize}m tmpfs /ventoy_rdroot/ventoy +$BUSYBOX_PATH/cp -a /ventoy/* /ventoy_rdroot/ventoy/ + + +# Step 4: add hook in linuxrc&rc.sysinit script file +vtLine=$($GREP -n "^find_cdrom" /ventoy_rdroot/linuxrc | $GREP -v '(' | $AWK -F: '{print $1}') +$SED "$vtLine aif test -d /ventoy; then $BUSYBOX_PATH/sh $VTOY_PATH/hook/pclos/disk_hook.sh; fi" -i /ventoy_rdroot/linuxrc +$SED "$vtLine aif test -d /initrd/ventoy; then ln -s /initrd/ventoy /ventoy; fi" -i /ventoy_rdroot/linuxrc + + +vtRcInit=$($BUSYBOX_PATH/tail /ventoy_rdroot/linuxrc | $GREP 'exec ' | $AWK '{print $2}') +if [ -e /ventoy_rdroot$vtRcInit ]; then + vtRcInit=/ventoy_rdroot$vtRcInit +else + vtRcInit=/ventoy_rdroot/etc/rc.d/rc.sysinit +fi + +echo 'exec /sbin/init' >> $vtRcInit diff --git a/IMG/cpio/ventoy/hook/rhel5/ventoy-hook.sh b/IMG/cpio/ventoy/hook/rhel5/ventoy-hook.sh new file mode 100644 index 00000000..c028991d --- /dev/null +++ b/IMG/cpio/ventoy/hook/rhel5/ventoy-hook.sh @@ -0,0 +1,23 @@ +#!/ventoy/busybox/sh +#************************************************************************************ +# Copyright (c) 2020, longpanda +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see . +# +#************************************************************************************ + +#if [ -e $VTOY_PATH/hook/rhel5/loader ]; then +# $BUSYBOX_PATH/cp -a $VTOY_PATH/hook/rhel5/loader /sbin/loader +#fi +#$BUSYBOX_PATH/cp -a $VTOY_PATH/hook/rhel5/ventoy-loader.sh $VTOY_PATH/tool/ diff --git a/IMG/cpio/ventoy/hook/rhel5/ventoy-loader.sh b/IMG/cpio/ventoy/hook/rhel5/ventoy-loader.sh new file mode 100644 index 00000000..3582ed80 --- /dev/null +++ b/IMG/cpio/ventoy/hook/rhel5/ventoy-loader.sh @@ -0,0 +1,70 @@ +#!/ventoy/busybox/sh +#************************************************************************************ +# Copyright (c) 2020, longpanda +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see . +# +#************************************************************************************ + +. /ventoy/hook/ventoy-hook-lib.sh + +ventoy_os_install_dmsetup() { + vtlog "ventoy_os_install_dmsetup $1" + + vt_usb_disk=$1 + + # dump iso file location + $VTOY_PATH/tool/vtoydm -i -f $VTOY_PATH/ventoy_image_map -d ${vt_usb_disk} > $VTOY_PATH/iso_file_list + + # install dmsetup + LINE=$($GREP 'minstg2.img' $VTOY_PATH/iso_file_list) + if [ $? -eq 0 ]; then + extract_file_from_line "$LINE" ${vt_usb_disk} /tmp/minstg2.img + + mkdir -p /tmp/ramfs/minstg2.img + mount -t squashfs /tmp/minstg2.img /tmp/ramfs/minstg2.img + + $BUSYBOX_PATH/ln -s /tmp/ramfs/minstg2.img/lib64 /lib64 + $BUSYBOX_PATH/ln -s /tmp/ramfs/minstg2.img/usr /usr + fi + + vtlog "dmsetup install finish, now check it..." + + dmsetup_path=$(ventoy_find_bin_path dmsetup) + if [ -z "$dmsetup_path" ]; then + vterr "dmsetup still not found after install" + elif $dmsetup_path info >> $VTLOG 2>&1; then + vtlog "$dmsetup_path work ok" + else + vterr "$dmsetup_path not work" + fi +} + +vtlog "##### $0 $* ########" + +vtdiskname=$(get_ventoy_disk_name) + +dmsetup_path=$(ventoy_find_bin_path dmsetup) +if [ -z "$dmsetup_path" ]; then + ventoy_os_install_dmsetup "$vtdiskname" + ventoy_udev_disk_common_hook "${vtdiskname#/dev/}2" "noreplace" + + $BUSYBOX_PATH/unlink /lib64 + $BUSYBOX_PATH/unlink /usr + umount /tmp/ramfs/minstg2.img + rm -rf /tmp/ramfs/minstg2.img + rm -f /tmp/minstg2.img +else + ventoy_udev_disk_common_hook "${vtdiskname#/dev/}2" "noreplace" +fi diff --git a/IMG/cpio/ventoy/hook/rhel6/anaconda-repo-listen.sh b/IMG/cpio/ventoy/hook/rhel6/anaconda-repo-listen.sh new file mode 100644 index 00000000..5cadb794 --- /dev/null +++ b/IMG/cpio/ventoy/hook/rhel6/anaconda-repo-listen.sh @@ -0,0 +1,20 @@ +#!/ventoy/busybox/sh +#************************************************************************************ +# Copyright (c) 2020, longpanda +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see . +# +#************************************************************************************ + +sed -i "s/^enabled.*/enabled=0/g" $2/$3 diff --git a/IMG/cpio/ventoy/hook/rhel6/udev_disk_hook.sh b/IMG/cpio/ventoy/hook/rhel6/udev_disk_hook.sh new file mode 100644 index 00000000..388c92cf --- /dev/null +++ b/IMG/cpio/ventoy/hook/rhel6/udev_disk_hook.sh @@ -0,0 +1,85 @@ +#!/ventoy/busybox/sh +#************************************************************************************ +# Copyright (c) 2020, longpanda +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see . +# +#************************************************************************************ + +. /ventoy/hook/ventoy-hook-lib.sh + +ventoy_os_install_dmsetup() { + vtlog "ventoy_os_install_dmsetup $1" + + vt_usb_disk=$1 + + $BUSYBOX_PATH/modprobe dm-mod + $BUSYBOX_PATH/modprobe linear + + # dump iso file location + $VTOY_PATH/tool/vtoydm -i -f $VTOY_PATH/ventoy_image_map -d ${vt_usb_disk} > $VTOY_PATH/iso_file_list + + # install dmsetup + LINE=$($GREP 'device-mapper-[0-9].*\.rpm' $VTOY_PATH/iso_file_list) + if [ $? -eq 0 ]; then + install_rpm_from_line "$LINE" ${vt_usb_disk} + fi + + vtlog "dmsetup install finish, now check it..." + + dmsetup_path=$(ventoy_find_bin_path dmsetup) + if [ -z "$dmsetup_path" ]; then + vterr "dmsetup still not found after install" + elif $dmsetup_path info >> $VTLOG 2>&1; then + vtlog "$dmsetup_path work ok" + else + vterr "$dmsetup_path not work" + fi +} + + +if is_ventoy_hook_finished || not_ventoy_disk "${1:0:-1}"; then + # /dev/loop7 come first + if [ "$1" = "loop7" ] && [ -b $VTOY_DM_PATH ]; then + ventoy_copy_device_mapper /dev/loop7 + fi + exit 0 +fi + +dmsetup_path=$(ventoy_find_bin_path dmsetup) +if [ -z "$dmsetup_path" ]; then + ventoy_os_install_dmsetup "/dev/${1:0:-1}" +fi + + +#some distro add there repo file to /etc/anaconda.repos.d/ which will cause error during installation +$BUSYBOX_PATH/nohup $VTOY_PATH/tool/inotifyd $VTOY_PATH/hook/rhel6/anaconda-repo-listen.sh /etc/anaconda.repos.d:n & + +ventoy_udev_disk_common_hook $* "noreplace" + +$BUSYBOX_PATH/mount $VTOY_DM_PATH /mnt/ventoy + +# +# We do a trick for rhel6 series here. +# Use /dev/loop7 and wapper it as a removable cdrom with bind mount. +# Then the anaconda installer will accept /dev/loop7 as the install medium. +# +ventoy_copy_device_mapper /dev/loop7 + +$BUSYBOX_PATH/cp -a /sys/devices/virtual/block/loop7 /tmp/ >> $VTLOG 2>&1 +echo 19 > /tmp/loop7/capability +$BUSYBOX_PATH/mount --bind /tmp/loop7 /sys/block/loop7 >> $VTLOG 2>&1 + +# OK finish +set_ventoy_hook_finish diff --git a/IMG/cpio/ventoy/hook/rhel6/ventoy-hook.sh b/IMG/cpio/ventoy/hook/rhel6/ventoy-hook.sh new file mode 100644 index 00000000..e66dbc5a --- /dev/null +++ b/IMG/cpio/ventoy/hook/rhel6/ventoy-hook.sh @@ -0,0 +1,27 @@ +#!/ventoy/busybox/sh +#************************************************************************************ +# Copyright (c) 2020, longpanda +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see . +# +#************************************************************************************ + +. $VTOY_PATH/hook/ventoy-os-lib.sh + +$BUSYBOX_PATH/mkdir -p /etc/anaconda.repos.d /mnt/ventoy +ventoy_print_yum_repo "ventoy" "file:///mnt/ventoy" > /etc/anaconda.repos.d/ventoy.repo + + +ventoy_add_udev_rule "$VTOY_PATH/hook/rhel6/udev_disk_hook.sh %k" +ventoy_add_kernel_udev_rule "loop7" "$VTOY_PATH/hook/rhel6/udev_disk_hook.sh %k" diff --git a/IMG/cpio/ventoy/hook/rhel7/ventoy-hook.sh b/IMG/cpio/ventoy/hook/rhel7/ventoy-hook.sh new file mode 100644 index 00000000..6bb0664c --- /dev/null +++ b/IMG/cpio/ventoy/hook/rhel7/ventoy-hook.sh @@ -0,0 +1,29 @@ +#!/ventoy/busybox/sh +#************************************************************************************ +# Copyright (c) 2020, longpanda +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see . +# +#************************************************************************************ + +. $VTOY_PATH/hook/ventoy-os-lib.sh + +ventoy_systemd_udevd_work_around + +ventoy_add_udev_rule "$VTOY_PATH/hook/default/udev_disk_hook.sh %k noreplace" + +# suppress write protected mount warning +if [ -e /usr/sbin/anaconda-diskroot ]; then + $SED 's/^mount $dev $repodir/mount -oro $dev $repodir/' -i /usr/sbin/anaconda-diskroot +fi diff --git a/IMG/cpio/ventoy/hook/slackware/udev_disk_hook.sh b/IMG/cpio/ventoy/hook/slackware/udev_disk_hook.sh new file mode 100644 index 00000000..9b064832 --- /dev/null +++ b/IMG/cpio/ventoy/hook/slackware/udev_disk_hook.sh @@ -0,0 +1,41 @@ +#!/ventoy/busybox/sh +#************************************************************************************ +# Copyright (c) 2020, longpanda +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see . +# +#************************************************************************************ + +. /ventoy/hook/ventoy-hook-lib.sh + +if is_ventoy_hook_finished || not_ventoy_disk "${1:0:-1}"; then + exit 0 +fi + +ventoy_udev_disk_common_hook $* + +# +# make a fake cdrom link +# +if [ -e /dev/sr3 ]; then + if ! [ -e /dev/hdp ]; then + ln -s $VTOY_DM_PATH /dev/hdp + fi +else + ln -s $VTOY_DM_PATH /dev/sr3 +fi + +# OK finish +set_ventoy_hook_finish + diff --git a/IMG/cpio/ventoy/hook/slackware/ventoy-hook.sh b/IMG/cpio/ventoy/hook/slackware/ventoy-hook.sh new file mode 100644 index 00000000..570e9098 --- /dev/null +++ b/IMG/cpio/ventoy/hook/slackware/ventoy-hook.sh @@ -0,0 +1,8 @@ +#!/ventoy/busybox/sh + +. $VTOY_PATH/hook/ventoy-os-lib.sh + +ventoy_systemd_udevd_work_around + +ventoy_add_udev_rule "$VTOY_PATH/hook/slackware/udev_disk_hook.sh %k noreplace" + diff --git a/IMG/cpio/ventoy/hook/suse/udev_disk_hook.sh b/IMG/cpio/ventoy/hook/suse/udev_disk_hook.sh new file mode 100644 index 00000000..67f36922 --- /dev/null +++ b/IMG/cpio/ventoy/hook/suse/udev_disk_hook.sh @@ -0,0 +1,60 @@ +#!/ventoy/busybox/sh +#************************************************************************************ +# Copyright (c) 2020, longpanda +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see . +# +#************************************************************************************ + +. /ventoy/hook/ventoy-hook-lib.sh + +ventoy_os_install_dmsetup() { + vtlog "ventoy_os_install_dmsetup $1" + + vt_usb_disk=$1 + + # dump iso file location + $VTOY_PATH/tool/vtoydm -i -f $VTOY_PATH/ventoy_image_map -d ${vt_usb_disk} > $VTOY_PATH/iso_file_list + + # install dmsetup + LINE=$($GREP 'device-mapper-[0-9]\..*\.rpm' $VTOY_PATH/iso_file_list) + if [ $? -eq 0 ]; then + install_rpm_from_line "$LINE" ${vt_usb_disk} + fi + + vtlog "dmsetup install finish, now check it..." + + dmsetup_path=$(ventoy_find_bin_path dmsetup) + if [ -z "$dmsetup_path" ]; then + vterr "dmsetup still not found after install" + elif $dmsetup_path info >> $VTLOG 2>&1; then + vtlog "$dmsetup_path work ok" + else + vterr "$dmsetup_path not work" + fi +} + +if is_ventoy_hook_finished || not_ventoy_disk "${1:0:-1}"; then + exit 0 +fi + +dmsetup_path=$(ventoy_find_bin_path dmsetup) +if [ -z "$dmsetup_path" ]; then + ventoy_os_install_dmsetup "/dev/${1:0:-1}" +fi + +ventoy_udev_disk_common_hook $* + +# OK finish +set_ventoy_hook_finish diff --git a/IMG/cpio/ventoy/hook/suse/ventoy-hook.sh b/IMG/cpio/ventoy/hook/suse/ventoy-hook.sh new file mode 100644 index 00000000..a281df9a --- /dev/null +++ b/IMG/cpio/ventoy/hook/suse/ventoy-hook.sh @@ -0,0 +1,24 @@ +#!/ventoy/busybox/sh +#************************************************************************************ +# Copyright (c) 2020, longpanda +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see . +# +#************************************************************************************ + +. $VTOY_PATH/hook/ventoy-os-lib.sh + +ventoy_systemd_udevd_work_around + +ventoy_add_udev_rule "$VTOY_PATH/hook/suse/udev_disk_hook.sh %k" diff --git a/IMG/cpio/ventoy/hook/tinycore/udev_disk_hook.sh b/IMG/cpio/ventoy/hook/tinycore/udev_disk_hook.sh new file mode 100644 index 00000000..6851668d --- /dev/null +++ b/IMG/cpio/ventoy/hook/tinycore/udev_disk_hook.sh @@ -0,0 +1,45 @@ +#!/ventoy/busybox/sh +#************************************************************************************ +# Copyright (c) 2020, longpanda +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see . +# +#************************************************************************************ + +. /ventoy/hook/ventoy-hook-lib.sh + +if is_ventoy_hook_finished || not_ventoy_disk "${1:0:-1}"; then + exit 0 +fi + +# TinyCore linux distro doesn't contain dmsetup, we use aoe here +sudo $BUSYBOX_PATH/modprobe aoe aoe_iflist=lo +if [ -e /sys/module/aoe ]; then + VBLADE_BIN=$(ventoy_get_vblade_bin) + sudo $VBLADE_BIN -r -f $VTOY_PATH/ventoy_image_map 9 0 lo "/dev/${1:0:-1}" & + + while ! [ -b /dev/etherd/e9.0 ]; do + vtlog 'Wait for /dev/etherd/e9.0 ....' + $SLEEP 0.1 + done + + sudo $BUSYBOX_PATH/cp -a /dev/etherd/e9.0 "/dev/$1" + + ventoy_find_bin_run rebuildfstab +else + vterr "aoe driver module load failed..." +fi + +# OK finish +set_ventoy_hook_finish diff --git a/IMG/cpio/ventoy/hook/tinycore/ventoy-hook.sh b/IMG/cpio/ventoy/hook/tinycore/ventoy-hook.sh new file mode 100644 index 00000000..b7880309 --- /dev/null +++ b/IMG/cpio/ventoy/hook/tinycore/ventoy-hook.sh @@ -0,0 +1,24 @@ +#!/ventoy/busybox/sh +#************************************************************************************ +# Copyright (c) 2020, longpanda +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see . +# +#************************************************************************************ + +. $VTOY_PATH/hook/ventoy-os-lib.sh + +ventoy_systemd_udevd_work_around + +ventoy_add_udev_rule_with_name "$VTOY_PATH/hook/tinycore/udev_disk_hook.sh %k" "90-ventoy.rules" diff --git a/IMG/cpio/ventoy/hook/ventoy-hook-lib.sh b/IMG/cpio/ventoy/hook/ventoy-hook-lib.sh new file mode 100644 index 00000000..c182a549 --- /dev/null +++ b/IMG/cpio/ventoy/hook/ventoy-hook-lib.sh @@ -0,0 +1,424 @@ +#!/ventoy/busybox/sh +#************************************************************************************ +# Copyright (c) 2020, longpanda +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see . +# +#************************************************************************************ + +VTOY_PATH=/ventoy +BUSYBOX_PATH=$VTOY_PATH/busybox +VTLOG=$VTOY_PATH/log +FIND=$BUSYBOX_PATH/find +GREP=$BUSYBOX_PATH/grep +EGREP=$BUSYBOX_PATH/egrep +CAT=$BUSYBOX_PATH/cat +AWK=$BUSYBOX_PATH/awk +SED=$BUSYBOX_PATH/sed +SLEEP=$BUSYBOX_PATH/sleep +HEAD=$BUSYBOX_PATH/head +VTOY_DM_PATH=/dev/mapper/ventoy +VTOY_DEBUG_LEVEL=$($BUSYBOX_PATH/hexdump -n 1 -s 430 -e '1/1 "%02x"' $VTOY_PATH/ventoy_os_param) + +if [ "$VTOY_DEBUG_LEVEL" = "01" ]; then + if [ -e /dev/console ]; then + VTLOG=/dev/console + fi +fi + +vtlog() { + if [ "$VTLOG" = "$VTOY_PATH/log" ]; then + echo "$*" >>$VTLOG + else + echo -e "\033[32m $* \033[0m" > $VTLOG + $SLEEP 2 + fi +} + +vterr() { + if [ "$VTLOG" = "$VTOY_PATH/log" ]; then + echo "$*" >>$VTLOG + else + echo -e "\n\033[31m $* \033[0m" > $VTLOG + $SLEEP 30 + fi +} + + +is_ventoy_hook_finished() { + [ -e $VTOY_PATH/hook_finish ] +} + +set_ventoy_hook_finish() { + echo 'Y' > $VTOY_PATH/hook_finish +} + +get_ventoy_disk_name() { + line=$($VTOY_PATH/tool/vtoydump -f /ventoy/ventoy_os_param) + if [ $? -eq 0 ]; then + echo ${line%%#*} + else + echo "unknown" + fi +} + +get_ventoy_iso_name() { + line=$($VTOY_PATH/tool/vtoydump -f /ventoy/ventoy_os_param) + if [ $? -eq 0 ]; then + echo ${line##*#} + else + echo "unknown" + fi +} + +wait_for_usb_disk_ready() { + while [ -n "Y" ]; do + usb_disk=$(get_ventoy_disk_name) + vtlog "wait_for_usb_disk_ready $usb_disk ..." + + if [ -e "${usb_disk}2" ]; then + vtlog "wait_for_usb_disk_ready $usb_disk finish" + break + else + $SLEEP 0.3 + fi + done +} + +is_ventoy_disk() { + if $VTOY_PATH/tool/vtoydump -f $VTOY_PATH/ventoy_os_param -c "$1"; then + $BUSYBOX_PATH/true + else + $BUSYBOX_PATH/false + fi +} + +not_ventoy_disk() { + if $VTOY_PATH/tool/vtoydump -f $VTOY_PATH/ventoy_os_param -c "$1"; then + $BUSYBOX_PATH/false + else + $BUSYBOX_PATH/true + fi +} + +ventoy_get_vblade_bin() { + if $VTOY_PATH/tool/vblade_64 -t >>$VTLOG 2>&1; then + echo $VTOY_PATH/tool/vblade_64 + else + echo $VTOY_PATH/tool/vblade_32 + fi +} + +ventoy_find_bin_path() { + if $BUSYBOX_PATH/which "$1" > /dev/null; then + $BUSYBOX_PATH/which "$1"; return + fi + + for vt_path in '/bin' '/sbin' '/usr/bin' '/usr/sbin' '/usr/local/bin' '/usr/local/sbin' '/root/bin'; do + if [ -e "$vt_path/$1" ]; then + echo "$vt_path/$1"; return + fi + done + + echo "" +} + + +ventoy_find_bin_run() { + vtsudo=0 + if [ "$1" = "sudo" ]; then + shift + vtsudo=1 + fi + + vtbinpath=$(ventoy_find_bin_path "$1") + if [ -n "$vtbinpath" ]; then + shift + + if [ $vtsudo -eq 0 ]; then + vtlog "$vtbinpath $*" + $vtbinpath $* + else + vtlog "sudo $vtbinpath $*" + sudo $vtbinpath $* + fi + fi +} + +ventoy_get_module_postfix() { + vtKerVer=$($BUSYBOX_PATH/uname -r) + vtLine=$($FIND /lib/modules/$vtKerVer/ -name *.ko* | $HEAD -n1) + vtComp=${vtLine##*/*.ko} + echo "ko$vtComp" +} + +ventoy_check_dm_module() { + if $GREP -q 'device-mapper' /proc/devices; then + $BUSYBOX_PATH/true; return + fi + + vtlog "device-mapper NOT found in /proc/devices, try to load kernel module" + $BUSYBOX_PATH/modprobe dm_mod >>$VTLOG 2>&1 + $BUSYBOX_PATH/modprobe dm-mod >>$VTLOG 2>&1 + + if ! $GREP -q 'device-mapper' /proc/devices; then + vtlog "modprobe failed, now try to insmod ko..." + + $FIND /lib/modules/ -name "dm-mod.ko*" | while read vtline; do + vtlog "insmode $vtline " + $BUSYBOX_PATH/insmod $vtline >>$VTLOG 2>&1 + done + fi + + if $GREP -q 'device-mapper' /proc/devices; then + vtlog "device-mapper found in /proc/devices after retry" + $BUSYBOX_PATH/true; return + else + vtlog "device-mapper still NOT found in /proc/devices after retry" + $BUSYBOX_PATH/false; return + fi +} + +create_ventoy_device_mapper() { + vtlog "create_ventoy_device_mapper $*" + + VT_DM_BIN=$(ventoy_find_bin_path dmsetup) + if [ -z "$VT_DM_BIN" ]; then + vtlog "no dmsetup avaliable, lastly try inbox dmsetup" + VT_DM_BIN=$VTOY_PATH/tool/dmsetup + fi + + vtlog "dmsetup avaliable in system $VT_DM_BIN" + + if ventoy_check_dm_module "$1"; then + vtlog "device-mapper module check success" + else + vterr "Error: no dm module avaliable" + fi + + $VTOY_PATH/tool/vtoydm -p -f $VTOY_PATH/ventoy_image_map -d $1 > $VTOY_PATH/ventoy_dm_table + if [ -z "$2" ]; then + $VT_DM_BIN create ventoy $VTOY_PATH/ventoy_dm_table >>$VTLOG 2>&1 + else + $VT_DM_BIN "$2" create ventoy $VTOY_PATH/ventoy_dm_table >>$VTLOG 2>&1 + fi +} + +wait_for_ventoy_dm_disk_label() { + DM=$($BUSYBOX_PATH/readlink $VTOY_DM_PATH) + vtlog "wait_for_ventoy_dm_disk_label $DM ..." + + for i in 0 1 2 3 4 5 6 7 8 9; do + vtlog "i=$i ####### ls /dev/disk/by-label/" + ls -l /dev/disk/by-label/ >> $VTLOG + + if ls -l /dev/disk/by-label/ | $GREP -q "$DM"; then + break + else + $SLEEP 0.3 + fi + done +} + +install_udeb_pkg() { + if ! [ -e "$1" ]; then + $BUSYBOX_PATH/false + return + fi + + if [ -d /tmp/vtoy_udeb ]; then + $BUSYBOX_PATH/rm -rf /tmp/vtoy_udeb + fi + + $BUSYBOX_PATH/mkdir -p /tmp/vtoy_udeb + $BUSYBOX_PATH/cp -a "$1" /tmp/vtoy_udeb/ + + CURDIR=$($BUSYBOX_PATH/pwd) + cd /tmp/vtoy_udeb + + $BUSYBOX_PATH/ar x "$1" + + if [ -e 'data.tar.gz' ]; then + $BUSYBOX_PATH/tar -xzf data.tar.gz -C / + elif [ -e 'data.tar.xz' ]; then + $BUSYBOX_PATH/tar -xJf data.tar.xz -C / + elif [ -e 'data.tar.bz2' ]; then + $BUSYBOX_PATH/tar -xjf data.tar.bz2 -C / + elif [ -e 'data.tar.lzma' ]; then + $BUSYBOX_PATH/tar -xaf data.tar.lzma -C / + fi + + if [ -e 'control.tar.gz' ]; then + $BUSYBOX_PATH/tar -xzf control.tar.gz -C / + elif [ -e 'control.tar.xz' ]; then + $BUSYBOX_PATH/tar -xJf control.tar.xz -C / + elif [ -e 'control.tar.bz2' ]; then + $BUSYBOX_PATH/tar -xjf control.tar.bz2 -C / + elif [ -e 'control.tar.lzma' ]; then + $BUSYBOX_PATH/tar -xaf control.tar.lzma -C / + fi + + cd $CURDIR + $BUSYBOX_PATH/rm -rf /tmp/vtoy_udeb + $BUSYBOX_PATH/true +} + + +install_udeb_from_line() { + vtlog "install_udeb_from_line $1" + + if ! [ -b "$2" ]; then + vterr "disk #$2# not exist" + return + fi + + sector=$(echo $1 | $AWK '{print $(NF-1)}') + length=$(echo $1 | $AWK '{print $NF}') + vtlog "sector=$sector length=$length" + + $VTOY_PATH/tool/vtoydm -e -f $VTOY_PATH/ventoy_image_map -d ${2} -s $sector -l $length -o /tmp/xxx.udeb + if [ -e /tmp/xxx.udeb ]; then + vtlog "extract udeb file from iso success" + else + vterr "extract udeb file from iso fail" + return + fi + + install_udeb_pkg /tmp/xxx.udeb + $BUSYBOX_PATH/rm -f /tmp/xxx.udeb +} + +extract_file_from_line() { + vtlog "extract_file_from_line $1 disk=#$2#" + if ! [ -b "$2" ]; then + vterr "disk #$2# not exist" + return + fi + + sector=$(echo $1 | $AWK '{print $(NF-1)}') + length=$(echo $1 | $AWK '{print $NF}') + vtlog "sector=$sector length=$length" + + $VTOY_PATH/tool/vtoydm -e -f $VTOY_PATH/ventoy_image_map -d ${2} -s $sector -l $length -o $3 + if [ -e $3 ]; then + vtlog "extract file from iso success" + $BUSYBOX_PATH/true + else + vterr "extract file from iso fail" + $BUSYBOX_PATH/false + fi +} + +install_rpm_from_line() { + vtlog "install_rpm_from_line $1 disk=#$2#" + + if ! [ -b "$2" ]; then + vterr "disk #$2# not exist" + return + fi + + sector=$(echo $1 | $AWK '{print $(NF-1)}') + length=$(echo $1 | $AWK '{print $NF}') + vtlog "sector=$sector length=$length" + + $VTOY_PATH/tool/vtoydm -e -f $VTOY_PATH/ventoy_image_map -d ${2} -s $sector -l $length -o /tmp/xxx.rpm + if [ -e /tmp/xxx.rpm ]; then + vtlog "extract rpm file from iso success" + else + vterr "extract rpm file from iso fail" + return + fi + + CURPWD=$($BUSYBOX_PATH/pwd) + + cd / + vtlog "install rpm..." + $BUSYBOX_PATH/rpm2cpio /tmp/xxx.rpm | $BUSYBOX_PATH/cpio -idm 2>>$VTLOG + cd $CURPWD + + $BUSYBOX_PATH/rm -f /tmp/xxx.rpm +} + +dump_whole_iso_file() { + $VTOY_PATH/tool/vtoydm -p -f $VTOY_PATH/ventoy_image_map -d $usb_disk | while read vtline; do + vtlog "dmtable line: $vtline" + vtcount=$(echo $vtline | $AWK '{print $2}') + vtoffset=$(echo $vtline | $AWK '{print $NF}') + $BUSYBOX_PATH/dd if=$usb_disk of="$1" bs=512 count=$vtcount skip=$vtoffset oflag=append conv=notrunc + done +} + +ventoy_copy_device_mapper() { + if [ -L $VTOY_DM_PATH ]; then + vtlog "replace block device link $1..." + $BUSYBOX_PATH/mv "$1" $VTOY_PATH/dev_backup_${1#/dev/} + VT_MAPPER_LINK=$($BUSYBOX_PATH/readlink $VTOY_DM_PATH) + $BUSYBOX_PATH/cp -a "/dev/mapper/$VT_MAPPER_LINK" "$1" + elif [ -b $VTOY_DM_PATH ]; then + vtlog "replace block device $1..." + $BUSYBOX_PATH/mv "$1" $VTOY_PATH/dev_backup_${1#/dev/} + $BUSYBOX_PATH/cp -a "$VTOY_DM_PATH" "$1" + else + + vtlog "$VTOY_DM_PATH not exist, now check /dev/dm-X ..." + VT_DM_BIN=$(ventoy_find_bin_path dmsetup) + if [ -z "$VT_DM_BIN" ]; then + vtlog "no dmsetup avaliable, lastly try inbox dmsetup" + VT_DM_BIN=$VTOY_PATH/tool/dmsetup + fi + + DM_VT_ID=$($VT_DM_BIN ls | $GREP ventoy | $SED 's/.*(\([0-9][0-9]*\),.*\([0-9][0-9]*\).*/\1 \2/') + vtlog "DM_VT_ID=$DM_VT_ID ..." + $BUSYBOX_PATH/mv "$1" $VTOY_PATH/dev_backup_${1#/dev/} + $BUSYBOX_PATH/mknod -m 0666 "$1" b $DM_VT_ID + fi +} + +ventoy_udev_disk_common_hook() { + + VTDISK="${1:0:-1}" + + # create device mapper for iso image file + if create_ventoy_device_mapper "/dev/$VTDISK" --readonly; then + vtlog "==== create ventoy device mapper success ====" + else + vtlog "==== create ventoy device mapper failed ====" + + $SLEEP 5 + + if $GREP -q "/dev/$VTDISK" /proc/mounts; then + $GREP "/dev/$VTDISK" /proc/mounts | while read vtLine; do + vtPart=$(echo $vtLine | $AWK '{print $1}') + vtMnt=$(echo $vtLine | $AWK '{print $2}') + vtlog "$vtPart is mounted on $vtMnt now umount it ..." + $BUSYBOX_PATH/umount $vtMnt + done + fi + + if create_ventoy_device_mapper "/dev/$VTDISK" --readonly; then + vtlog "==== create ventoy device mapper success after retry ====" + else + vtlog "==== create ventoy device mapper failed after retry ====" + return + fi + fi + + if [ "$2" = "noreplace" ]; then + vtlog "no need to replace block device" + else + ventoy_copy_device_mapper "/dev/$1" + fi +} + + diff --git a/IMG/cpio/ventoy/hook/ventoy-os-lib.sh b/IMG/cpio/ventoy/hook/ventoy-os-lib.sh new file mode 100644 index 00000000..0be5a0a7 --- /dev/null +++ b/IMG/cpio/ventoy/hook/ventoy-os-lib.sh @@ -0,0 +1,98 @@ +#!/ventoy/busybox/sh +#************************************************************************************ +# Copyright (c) 2020, longpanda +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see . +# +#************************************************************************************ + +VT_RULE_DIR_PREFIX="" +VT_PRINTK_LEVEL=0 +VT_UDEV_RULE_FILE_NAME="99-ventoy.rules" +VT_UDEV_RULE_PREFIX="ACTION==\"add\", SUBSYSTEM==\"block\"," + +ventoy_close_printk() { + VT_PRINTK_LEVEL=$($CAT /proc/sys/kernel/printk | $AWK '{print $1}') + if [ -e /proc/sys/kernel/printk ]; then + echo 0 > /proc/sys/kernel/printk + fi +} + +ventoy_restore_printk() { + if [ -e /proc/sys/kernel/printk ]; then + echo $VT_PRINTK_LEVEL > /proc/sys/kernel/printk + fi +} + +ventoy_set_rule_dir_prefix() { + VT_RULE_DIR_PREFIX=$1 +} + +ventoy_get_udev_conf_dir() { + if [ -d $VT_RULE_DIR_PREFIX/etc/udev/rules.d ]; then + VT_RULE_PATH=$VT_RULE_DIR_PREFIX/etc/udev/rules.d + elif [ -d $VT_RULE_DIR_PREFIX/lib/udev/rules.d ]; then + VT_RULE_PATH=$VT_RULE_DIR_PREFIX/lib/udev/rules.d + else + $BUSYBOX_PATH/mkdir -p $VT_RULE_DIR_PREFIX/etc/udev/rules.d + VT_RULE_PATH=$VT_RULE_DIR_PREFIX/etc/udev/rules.d + fi + echo -n "$VT_RULE_PATH" +} + +ventoy_get_udev_conf_path() { + VT_RULE_DIR=$(ventoy_get_udev_conf_dir) + echo "$VT_RULE_DIR/$VT_UDEV_RULE_FILE_NAME" +} + +ventoy_add_kernel_udev_rule() { + VT_UDEV_RULE_PATH=$(ventoy_get_udev_conf_path) + echo "KERNEL==\"$1\", $VT_UDEV_RULE_PREFIX RUN+=\"$2\"" >> $VT_UDEV_RULE_PATH +} + +ventoy_add_udev_rule_with_name() { + VT_UDEV_RULE_DIR=$(ventoy_get_udev_conf_dir) + echo "KERNEL==\"*2\", $VT_UDEV_RULE_PREFIX RUN+=\"$1\"" >> $VT_UDEV_RULE_DIR/$2 +} + +ventoy_add_udev_rule_with_path() { + echo "KERNEL==\"*2\", $VT_UDEV_RULE_PREFIX RUN+=\"$1\"" >> $2 +} + +ventoy_add_udev_rule() { + VT_UDEV_RULE_PATH=$(ventoy_get_udev_conf_path) + echo "KERNEL==\"*2\", $VT_UDEV_RULE_PREFIX RUN+=\"$1\"" >> $VT_UDEV_RULE_PATH +} + +# +# It seems there is a bug in somw version of systemd-udevd +# https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=869719 +# +ventoy_systemd_udevd_work_around() { + VTSYSTEMUDEV="$VT_RULE_DIR_PREFIX/lib/systemd/system/systemd-udevd.service" + if [ -e $VTSYSTEMUDEV ]; then + if $GREP -q 'SystemCallArchitectures.*native' $VTSYSTEMUDEV; then + $SED "s/.*\(SystemCallArchitectures.*native\)/#\1/g" -i $VTSYSTEMUDEV + fi + fi +} + +ventoy_print_yum_repo() { + echo "[$1]" + echo "name=$1" + echo "baseurl=$2" + echo "enabled=1" + echo "gpgcheck=0" + echo "priority=0" +} diff --git a/IMG/cpio/ventoy/hook/xen/udev_disk_hook.sh b/IMG/cpio/ventoy/hook/xen/udev_disk_hook.sh new file mode 100644 index 00000000..b25c1fbb --- /dev/null +++ b/IMG/cpio/ventoy/hook/xen/udev_disk_hook.sh @@ -0,0 +1,32 @@ +#!/ventoy/busybox/sh +#************************************************************************************ +# Copyright (c) 2020, longpanda +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see . +# +#************************************************************************************ + +. /ventoy/hook/ventoy-hook-lib.sh + +if is_ventoy_hook_finished || not_ventoy_disk "${1:0:-1}"; then + exit 0 +fi + +ventoy_udev_disk_common_hook $* + +# trick for xen6 +ventoy_copy_device_mapper /dev/sr7 + +# OK finish +set_ventoy_hook_finish diff --git a/IMG/cpio/ventoy/hook/xen/ventoy-hook.sh b/IMG/cpio/ventoy/hook/xen/ventoy-hook.sh new file mode 100644 index 00000000..1260ce15 --- /dev/null +++ b/IMG/cpio/ventoy/hook/xen/ventoy-hook.sh @@ -0,0 +1,24 @@ +#!/ventoy/busybox/sh +#************************************************************************************ +# Copyright (c) 2020, longpanda +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see . +# +#************************************************************************************ + +. $VTOY_PATH/hook/ventoy-os-lib.sh + +ventoy_systemd_udevd_work_around + +ventoy_add_udev_rule "$VTOY_PATH/hook/xen/udev_disk_hook.sh %k" diff --git a/IMG/cpio/ventoy/init b/IMG/cpio/ventoy/init new file mode 100644 index 00000000..bfb7adf4 --- /dev/null +++ b/IMG/cpio/ventoy/init @@ -0,0 +1,154 @@ +#!/ventoy/busybox/sh +#************************************************************************************ +# Copyright (c) 2020, longpanda +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see . +# +#************************************************************************************ + + +################################################################### +# # +# Step 1 : parse kernel debug parameter # +# # +#################################################################### +mkdir /proc; mount -t proc proc /proc +vtcmdline=$(cat /proc/cmdline) +vtkerver=$(cat /proc/version) +umount /proc; rm -rf /proc + +echo "kenel version=$vtkerver" >>$VTLOG +echo "kenel cmdline=$vtcmdline" >>$VTLOG + +#break here for debug +if [ "$VTOY_BREAK_LEVEL" = "01" ] || [ "$VTOY_BREAK_LEVEL" = "11" ]; then + sleep 5 + echo -e "\n\n\033[32m ################################################# \033[0m" + echo -e "\033[32m ################ VENTOY DEBUG ################### \033[0m" + echo -e "\033[32m ################################################# \033[0m \n" + + if [ "$VTOY_BREAK_LEVEL" = "11" ]; then + cat $VTLOG + fi + exec $BUSYBOX_PATH/sh +fi + + +#################################################################### +# # +# Step 2 : extract real initramfs to / # +# # +#################################################################### +cd / +rm -rf /init /linuxrc /sbin /dev/ /root + +ventoy_is_initrd_ramdisk() { + #As I known, PCLinuxOS use ramdisk + if echo $vtkerver | grep -i -q 'PCLinuxOS'; then + true + else + false + fi +} + +# param: file skip magic tmp +ventoy_unpack_initramfs() { + vtfile=$1; vtskip=$2; vtmagic=$3; vttmp=$4 + echo "=====ventoy_unpack_initramfs: #$*#" >> $VTLOG + + for vtx in '1F8B zcat' '1F9E zcat' '425A bzcat' '5D00 lzcat' 'FD37 xzcat' '894C lzopcat' '0221 lz4cat' '28B5 zstdcat' '3037 cat'; do + if [ "${vtx:0:4}" = "${vtmagic:0:4}" ]; then + echo "vtx=$vtx" >> $VTLOG + if [ $vtskip -eq 0 ]; then + ${vtx:5} $vtfile | (cpio -idm 2>>$VTLOG; cat > $vttmp) + else + dd if=$vtfile skip=$vtskip iflag=skip_bytes status=none | ${vtx:5} | (cpio -idm 2>>$VTLOG; cat > $vttmp) + fi + break + fi + done +} + +# param: file magic tmp +ventoy_unpack_initrd() { + vtfile=$1; vtmagic=$2; vttmp=$3 + echo "=====ventoy_unpack_initrd: #$*#" >> $VTLOG + + for vtx in '1F8B zcat' '1F9E zcat' '425A bzcat' '5D00 lzcat' 'FD37 xzcat' '894C lzopcat' '0221 lz4cat' '28B5 zstdcat' '3037 cat'; do + if [ "${vtx:0:4}" = "${vtmagic:0:4}" ]; then + echo "vtx=$vtx" >> $VTLOG + ${vtx:5} $vtfile > $vttmp + break + fi + done +} + + +# This export is for busybox cpio command +export EXTRACT_UNSAFE_SYMLINKS=1 + +for vtfile in $(ls /initrd*); do + #decompress first initrd + vtmagic=$(hexdump -n 2 -e '2/1 "%02X"' $vtfile) + + if ventoy_is_initrd_ramdisk; then + ventoy_unpack_initrd $vtfile $vtmagic ${vtfile}_tmp + mv ${vtfile}_tmp $vtfile + break + else + ventoy_unpack_initramfs $vtfile 0 $vtmagic ${vtfile}_tmp + fi + + #only for cpio,cpio,...,initrd sequence, initrd,cpio or initrd,initrd sequence is not supported + while [ -e ${vtfile}_tmp ] && [ $(stat -c '%s' ${vtfile}_tmp) -gt 512 ]; do + mv ${vtfile}_tmp $vtfile + vtdump=$(hexdump -n 512 -e '512/1 "%02X"' $vtfile) + vtmagic=$(echo $vtdump | sed 's/^\(00\)*//') + let vtoffset="(${#vtdump}-${#vtmagic})/2" + + if [ -z "$vtmagic" ]; then + echo "terminate with all zero data file" >> $VTLOG + break + fi + + ventoy_unpack_initramfs $vtfile $vtoffset ${vtmagic:0:4} ${vtfile}_tmp + done + + rm -f $vtfile ${vtfile}_tmp +done + + +#break here for debug +if [ "$VTOY_BREAK_LEVEL" = "02" ] || [ "$VTOY_BREAK_LEVEL" = "12" ]; then + sleep 5 + echo -e "\n\n\033[32m ################################################# \033[0m" + echo -e "\033[32m ################ VENTOY DEBUG ################### \033[0m" + echo -e "\033[32m ################################################# \033[0m \n" + if [ "$VTOY_BREAK_LEVEL" = "12" ]; then + cat $VTOY_PATH/log + fi + exec $BUSYBOX_PATH/sh +fi + + +#################################################################### +# # +# Step 3 : Hand over to ventoy.sh # +# # +#################################################################### +echo "Now hand over to ventoy.sh" >>$VTLOG +. $VTOY_PATH/tool/vtoytool_install.sh + +export PATH=$VTOY_ORG_PATH +exec $BUSYBOX_PATH/sh $VTOY_PATH/ventoy.sh diff --git a/IMG/cpio/ventoy/tool/ar b/IMG/cpio/ventoy/tool/ar new file mode 100644 index 00000000..fd443b2d Binary files /dev/null and b/IMG/cpio/ventoy/tool/ar differ diff --git a/IMG/cpio/ventoy/tool/inotifyd b/IMG/cpio/ventoy/tool/inotifyd new file mode 100644 index 00000000..29c70d28 Binary files /dev/null and b/IMG/cpio/ventoy/tool/inotifyd differ diff --git a/IMG/cpio/ventoy/tool/lz4cat b/IMG/cpio/ventoy/tool/lz4cat new file mode 100644 index 00000000..bccad019 Binary files /dev/null and b/IMG/cpio/ventoy/tool/lz4cat differ diff --git a/IMG/cpio/ventoy/tool/ventoy_loader.sh b/IMG/cpio/ventoy/tool/ventoy_loader.sh new file mode 100644 index 00000000..5844cbd7 --- /dev/null +++ b/IMG/cpio/ventoy/tool/ventoy_loader.sh @@ -0,0 +1,20 @@ +#!/ventoy/busybox/sh +#************************************************************************************ +# Copyright (c) 2020, longpanda +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see . +# +#************************************************************************************ + +exec /ventoy/busybox/sh diff --git a/IMG/cpio/ventoy/tool/vtoytool_install.sh b/IMG/cpio/ventoy/tool/vtoytool_install.sh new file mode 100644 index 00000000..c408d012 --- /dev/null +++ b/IMG/cpio/ventoy/tool/vtoytool_install.sh @@ -0,0 +1,54 @@ +#!/ventoy/busybox/sh +#************************************************************************************ +# Copyright (c) 2020, longpanda +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see . +# +#************************************************************************************ + +echo "#### install vtoytool #####" >> $VTLOG + +if ! [ -e $BUSYBOX_PATH/ar ]; then + $BUSYBOX_PATH/ln -s $VTOY_PATH/tool/ar $BUSYBOX_PATH/ar +fi + +for vtdir in $(ls $VTOY_PATH/tool/vtoytool/); do + echo "try $VTOY_PATH/tool/vtoytool/$vtdir/ ..." >> $VTLOG + if $VTOY_PATH/tool/vtoytool/$vtdir/vtoytool_64 --install 2>>$VTLOG; then + echo "vtoytool_64 OK" >> $VTLOG + break + fi + + if $VTOY_PATH/tool/vtoytool/$vtdir/vtoytool_32 --install 2>>$VTLOG; then + echo "vtoytool_32 OK" >> $VTLOG + break + fi +done + +if $VTOY_PATH/tool/vtoy_fuse_iso_64 -t 2>>$VTLOG; then + echo "use vtoy_fuse_iso_64" >>$VTLOG + $BUSYBOX_PATH/cp -a $VTOY_PATH/tool/vtoy_fuse_iso_64 $VTOY_PATH/tool/vtoy_fuse_iso +else + echo "use vtoy_fuse_iso_32" >>$VTLOG + $BUSYBOX_PATH/cp -a $VTOY_PATH/tool/vtoy_fuse_iso_32 $VTOY_PATH/tool/vtoy_fuse_iso +fi + +if $VTOY_PATH/tool/unsquashfs_64 -t 2>>$VTLOG; then + echo "use unsquashfs_64" >>$VTLOG + $BUSYBOX_PATH/cp -a $VTOY_PATH/tool/unsquashfs_64 $VTOY_PATH/tool/vtoy_unsquashfs +else + echo "use unsquashfs_32" >>$VTLOG + $BUSYBOX_PATH/cp -a $VTOY_PATH/tool/unsquashfs_32 $VTOY_PATH/tool/vtoy_unsquashfs +fi + diff --git a/IMG/cpio/ventoy/tool/zstdcat b/IMG/cpio/ventoy/tool/zstdcat new file mode 100644 index 00000000..e8657c6b Binary files /dev/null and b/IMG/cpio/ventoy/tool/zstdcat differ diff --git a/IMG/cpio/ventoy/ventoy.sh b/IMG/cpio/ventoy/ventoy.sh new file mode 100644 index 00000000..6426dc83 --- /dev/null +++ b/IMG/cpio/ventoy/ventoy.sh @@ -0,0 +1,203 @@ +#!/ventoy/busybox/sh +#************************************************************************************ +# Copyright (c) 2020, longpanda +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see . +# +#************************************************************************************ + +#################################################################### +# # +# Step 1 : Parse kernel parameter # +# # +#################################################################### +if ! [ -e /proc ]; then + $BUSYBOX_PATH/mkdir /proc + rmproc='Y' +fi +$BUSYBOX_PATH/mount -t proc proc /proc + +# vtinit=xxx to replace rdinit=xxx +vtcmdline=$($CAT /proc/cmdline) +for i in $vtcmdline; do + if echo $i | $GREP -q vtinit; then + user_rdinit=${i#vtinit=} + echo "user set user_rdinit=${user_rdinit}" >>$VTLOG + fi +done + + +#################################################################### +# # +# Step 2 : Do OS specific hook # +# # +#################################################################### +ventoy_get_os_type() { + echo "kernel version" >> $VTLOG + $CAT /proc/version >> $VTLOG + + # rhel5/CentOS5 and all other distributions based on them + if $GREP -q 'el5' /proc/version; then + echo 'rhel5'; return + + # rhel6/CentOS6 and all other distributions based on them + elif $GREP -q 'el6' /proc/version; then + echo 'rhel6'; return + + # rhel7/CentOS7/rhel8/CentOS8 and all other distributions based on them + elif $GREP -q 'el[78]' /proc/version; then + echo 'rhel7'; return + + # Maybe rhel9 rhel1x use the same way? Who knows! + elif $EGREP -q 'el9|el1[0-9]' /proc/version; then + echo 'rhel7'; return + + # Fedora : do the same process with rhel7 + elif $GREP -q '\.fc[0-9][0-9]\.' /proc/version; then + echo 'rhel7'; return + + # Debian : + elif $GREP -q '[Dd]ebian' /proc/version; then + echo 'debian'; return + + # Ubuntu : do the same process with debian + elif $GREP -q '[Uu]buntu' /proc/version; then + echo 'debian'; return + + # Deepin : do the same process with debian + elif $GREP -q '[Dd]eepin' /proc/version; then + echo 'debian'; return + + # SUSE + elif $GREP -q 'SUSE' /proc/version; then + echo 'suse'; return + + # ArchLinux + elif $EGREP -q 'archlinux|ARCH' /proc/version; then + echo 'arch'; return + + # gentoo + elif $EGREP -q '[Gg]entoo' /proc/version; then + echo 'gentoo'; return + + # TinyCore + elif $EGREP -q 'tinycore' /proc/version; then + echo 'tinycore'; return + + # manjaro + elif $EGREP -q 'manjaro|MANJARO' /proc/version; then + echo 'manjaro'; return + + # mageia + elif $EGREP -q 'mageia' /proc/version; then + echo 'mageia'; return + + # pclinux OS + elif $GREP -i -q 'PCLinuxOS' /proc/version; then + echo 'pclos'; return + + # KaOS + elif $GREP -i -q 'kaos' /proc/version; then + echo 'kaos'; return + + # Alpine + elif $GREP -q 'Alpine' /proc/version; then + echo 'alpine'; return + + # NixOS + elif $GREP -i -q 'NixOS' /proc/version; then + echo 'nixos'; return + + fi + + if [ -e /lib/debian-installer ]; then + echo 'debian'; return + fi + + if [ -e /etc/os-release ]; then + if $GREP -q 'XenServer' /etc/os-release; then + echo 'xen'; return + elif $GREP -q 'SUSE ' /etc/os-release; then + echo 'suse'; return + fi + fi + + if $BUSYBOX_PATH/dmesg | $GREP -q -m1 "Xen:"; then + echo 'xen'; return + fi + + + if [ -e /etc/HOSTNAME ] && $GREP -i -q 'slackware' /etc/HOSTNAME; then + echo 'slackware'; return + fi + + + echo "default" +} + +VTOS=$(ventoy_get_os_type) +echo "OS=###${VTOS}###" >>$VTLOG +if [ -e "$VTOY_PATH/hook/$VTOS/ventoy-hook.sh" ]; then + $BUSYBOX_PATH/sh "$VTOY_PATH/hook/$VTOS/ventoy-hook.sh" +fi + + +#################################################################### +# # +# Step 3 : Check for debug break # +# # +#################################################################### +if [ "$VTOY_BREAK_LEVEL" = "03" ] || [ "$VTOY_BREAK_LEVEL" = "13" ]; then + $SLEEP 5 + echo -e "\n\n\033[32m ################################################# \033[0m" + echo -e "\033[32m ################ VENTOY DEBUG ################### \033[0m" + echo -e "\033[32m ################################################# \033[0m \n" + if [ "$VTOY_BREAK_LEVEL" = "13" ]; then + $CAT $VTOY_PATH/log + fi + exec $BUSYBOX_PATH/sh +fi + + + +#################################################################### +# # +# Step 4 : Hand over to real init # +# # +#################################################################### +$BUSYBOX_PATH/umount /proc +if [ "$rmproc" = "Y" ]; then + $BUSYBOX_PATH/rm -rf /proc +fi + +cd / +unset VTOY_PATH VTLOG FIND GREP EGREP CAT AWK SED SLEEP HEAD + +for vtinit in $user_rdinit /init /sbin/init /linuxrc; do + if [ -d /ventoy_rdroot ]; then + if [ -e "/ventoy_rdroot$vtinit" ]; then + # switch_root will check /init file, this is a cheat code + echo 'switch_root' > /init + exec $BUSYBOX_PATH/switch_root /ventoy_rdroot "$vtinit" + fi + else + if [ -e "$vtinit" ];then + exec "$vtinit" + fi + fi +done + +# Should never reach here +echo -e "\n\n\033[31m ############ INIT NOT FOUND ############### \033[0m \n" +exec $BUSYBOX_PATH/sh diff --git a/IMG/mkcpio.sh b/IMG/mkcpio.sh new file mode 100644 index 00000000..517b55c4 --- /dev/null +++ b/IMG/mkcpio.sh @@ -0,0 +1,40 @@ +#!/bin/bash + +VENTOY_PATH=$PWD/../ + +rm -f ventoy.cpio + +chmod -R 777 cpio + +cp -a cpio cpio_tmp + +cd cpio_tmp +rm -f init +ln -s sbin/init init +ln -s sbin/init linuxrc + +cd ventoy + + + +find ./tool | cpio -o -H newc>tool.cpio +xz tool.cpio +rm -rf tool + +xz ventoy.sh + +find ./hook | cpio -o -H newc>hook.cpio +xz hook.cpio +rm -rf hook +cd .. + +find .| cpio -o -H newc>../ventoy.cpio + +cd .. +rm -rf cpio_tmp + +echo '======== SUCCESS =============' + +rm -f $VENTOY_PATH/INSTALL/ventoy/ventoy.cpio +cp -a ventoy.cpio $VENTOY_PATH/INSTALL/ventoy/ + diff --git a/INSTALL/EFI/BOOT/BOOTX64.EFI b/INSTALL/EFI/BOOT/BOOTX64.EFI new file mode 100644 index 00000000..9d5c2c98 Binary files /dev/null and b/INSTALL/EFI/BOOT/BOOTX64.EFI differ diff --git a/INSTALL/Ventoy2Disk.exe b/INSTALL/Ventoy2Disk.exe new file mode 100644 index 00000000..5d3c5511 Binary files /dev/null and b/INSTALL/Ventoy2Disk.exe differ diff --git a/INSTALL/Ventoy2Disk.sh b/INSTALL/Ventoy2Disk.sh new file mode 100644 index 00000000..38cd0024 --- /dev/null +++ b/INSTALL/Ventoy2Disk.sh @@ -0,0 +1,234 @@ +#!/bin/sh + +. ./tool/ventoy_lib.sh + +print_usage() { + echo 'Usage: VentoyInstaller.sh OPTION /dev/sdX' + echo ' OPTION:' + echo ' -i install ventoy to sdX (fail if disk already installed with ventoy)' + echo ' -u update ventoy in sdX' + echo ' -I force install ventoy to sdX (no matter installed or not)' + echo '' +} + +echo '' +echo '***********************************************************' +echo '* Ventoy2Disk Script *' +echo '* longpanda admin@ventoy.net *' +echo '***********************************************************' +echo '' + +vtdebug "############# Ventoy2Disk ################" + +if ! [ -e ventoy/version ]; then + vterr "Please run under the correct directory!" + exit 1 +fi + +if [ "$1" = "-i" ]; then + MODE="install" +elif [ "$1" = "-I" ]; then + MODE="install" + FORCE="Y" +elif [ "$1" = "-u" ]; then + MODE="update" +else + print_usage + exit 1 +fi + +if ! [ -b "$2" ]; then + print_usage + exit 1 +fi + +if [ -z "$SUDO_USER" ]; then + if [ "$USER" != "root" ]; then + vterr "EUID is $EUID root permission is required." + echo '' + exit 1 + fi +fi + +vtdebug "MODE=$MODE FORCE=$FORCE" + +#decompress tool +cd tool +chmod +x ./xzcat +for file in $(ls); do + if [ "$file" != "xzcat" ]; then + if [ "$file" != "ventoy_lib.sh" ]; then + ./xzcat $file > ${file%.xz} + chmod +x ${file%.xz} + fi + fi +done +cd ../ + +if ! check_tool_work_ok; then + vterr "Some tools can not run in current system. Please check log.txt for detail." + exit 1 +fi + + +DISK=$2 + +if ! [ -b "$DISK" ]; then + vterr "Disk $DISK does not exist" + exit 1 +fi + + +if [ -e /sys/class/block/${DISK#/dev/}/start ]; then + vterr "$DISK is a partition, please use the whole disk" + exit 1 +fi + +if grep "$DISK" /proc/mounts; then + vterr "$DISK is already mounted, please umount it first!" + exit 1 +fi + + +if [ "$MODE" = "install" ]; then + vtdebug "install ventoy ..." + + if ! fdisk -v >/dev/null 2>&1; then + vterr "fdisk is needed by ventoy installation, but is not found in the system." + exit 1 + fi + + version=$(get_disk_ventoy_version $DISK) + if [ $? -eq 0 ]; then + if [ -z "$FORCE" ]; then + vtwarn "$DISK already contains a Ventoy with version $version" + vtwarn "Use -u option to do a safe upgrade operation." + vtwarn "OR if you really want to reinstall ventoy to $DISK, please use -I option." + vtwarn "" + exit 1 + fi + fi + + disk_sector_num=$(cat /sys/block/${DISK#/dev/}/size) + disk_size_gb=$(expr $disk_sector_num / 2097152) + + if [ $disk_sector_num -gt 4294967296 ]; then + vterr "$DISK is over 2TB size, MBR will not work on it." + exit 1 + fi + + #Print disk info + echo "Disk : $DISK" + parted $DISK p 2>&1 | grep Model + echo "Size : $disk_size_gb GB" + echo '' + + vtwarn "Attention:" + vtwarn "You will install Ventoy to $DISK." + vtwarn "All the data on the disk $DISK will be lost!!!" + echo "" + + read -p 'Continue? (y/n)' Answer + if [ "$Answer" != "y" ]; then + if [ "$Answer" != "Y" ]; then + exit 0 + fi + fi + + echo "" + vtwarn "All the data on the disk $DISK will be lost!!!" + read -p 'Double-check. Continue? (y/n)' Answer + if [ "$Answer" != "y" ]; then + if [ "$Answer" != "Y" ]; then + exit 0 + fi + fi + + + if [ $disk_sector_num -le $VENTOY_SECTOR_NUM ]; then + vterr "No enough space in disk $DISK" + exit 1 + fi + + if ! dd if=/dev/zero of=$DISK bs=1 count=512 status=none; then + vterr "Write data to $DISK failed, please check whether it's in use." + exit 1 + fi + + format_ventoy_disk $DISK + + # format part1 + if ventoy_is_linux64; then + cmd=./tool/mkexfatfs_64 + else + cmd=./tool/mkexfatfs_32 + fi + + chmod +x ./tool/* + + # DiskSize > 32GB Cluster Size use 128KB + # DiskSize < 32GB Cluster Size use 32KB + if [ $disk_size_gb -gt 32 ]; then + cluster_sectors=256 + else + cluster_sectors=64 + fi + + $cmd -n ventoy -s $cluster_sectors ${DISK}1 + + dd status=none if=./boot/boot.img of=$DISK bs=1 count=446 + ./tool/xzcat ./boot/core.img.xz | dd status=none of=$DISK bs=512 count=2047 seek=1 + ./tool/xzcat ./ventoy/ventoy.disk.img.xz | dd status=none of=$DISK bs=512 count=$VENTOY_SECTOR_NUM seek=$part2_start_sector + + + chmod +x ./tool/vtoy_gen_uuid + ./tool/vtoy_gen_uuid | dd status=none of=${DISK} seek=384 bs=1 count=16 + + sync + + echo "" + vtinfo "Install Ventoy to $DISK successfully finished." + echo "" + +else + vtdebug "update ventoy ..." + + oldver=$(get_disk_ventoy_version $DISK) + if [ $? -ne 0 ]; then + vtwarn "$DISK does not contain ventoy or data corupted" + echo "" + vtwarn "Please use -i option if you want to install ventoy to $DISK" + echo "" + exit 1 + fi + + curver=$(cat ./ventoy/version) + + vtinfo "Upgrade operation is safe, all the data in the 1st partition (iso files and other) will be unchanged!" + echo "" + + read -p "Update Ventoy $oldver ===> $curver Continue? (y/n)" Answer + if [ "$Answer" != "y" ]; then + if [ "$Answer" != "Y" ]; then + exit 0 + fi + fi + + PART2=$(get_disk_part_name $DISK 2) + + dd status=none if=./boot/boot.img of=$DISK bs=1 count=446 + + ./tool/xzcat ./boot/core.img.xz | dd status=none of=$DISK bs=512 count=2047 seek=1 + + disk_sector_num=$(cat /sys/block/${DISK#/dev/}/size) + part2_start=$(expr $disk_sector_num - $VENTOY_SECTOR_NUM) + ./tool/xzcat ./ventoy/ventoy.disk.img.xz | dd status=none of=$DISK bs=512 count=$VENTOY_SECTOR_NUM seek=$part2_start + + sync + + echo "" + vtinfo "Update Ventoy to $DISK successfully finished." + echo "" + +fi + diff --git a/INSTALL/grub/fonts/ascii.pf2 b/INSTALL/grub/fonts/ascii.pf2 new file mode 100644 index 00000000..1eb3edcf Binary files /dev/null and b/INSTALL/grub/fonts/ascii.pf2 differ diff --git a/INSTALL/grub/grub.cfg b/INSTALL/grub/grub.cfg new file mode 100644 index 00000000..68723637 --- /dev/null +++ b/INSTALL/grub/grub.cfg @@ -0,0 +1,359 @@ +#************************************************************************************ +# Copyright (c) 2020, longpanda +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see . +# +#************************************************************************************ + +function get_os_type { + set vtoy_os=Linux + for file in "efi/microsoft" "sources/boot.wim" "boot/bcd" "bootmgr.efi" "boot/etfsboot.com"; do + if [ -e $1/$file ]; then + set vtoy_os=Windows + break + fi + done + + if [ -n "${vtdebug_flag}" ]; then + echo ISO is $vtoy_os + fi +} + +function locate_initrd { + vt_linux_locate_initrd + + if [ -n "${vtdebug_flag}" ]; then + vt_linux_dump_initrd + sleep 5 + fi +} + +function find_wim_file { + unset ventoy_wim_file + + for file in "sources/boot.wim" "sources/BOOT.WIM" "Sources/Win10PEx64.WIM" "boot/BOOT.WIM" "winpe_x64.wim"; do + if [ -e $1/$file ]; then + set ventoy_wim_file=$1/$file + break + fi + done +} + +function distro_specify_initrd_file { + if [ -e (loop)/boot/all.rdz ]; then + vt_linux_specify_initrd_file /boot/all.rdz + elif [ -e (loop)/boot/xen.gz ]; then + if [ -e (loop)/install.img ]; then + vt_linux_specify_initrd_file /install.img + fi + elif [ -d (loop)/casper ]; then + if [ -e (loop)/casper/initrd ]; then + vt_linux_specify_initrd_file /casper/initrd + fi + if [ -e (loop)/casper/initrd-oem ]; then + vt_linux_specify_initrd_file /casper/initrd-oem + fi + fi +} + +function uefi_windows_menu_func { + vt_windows_reset + + if [ "$ventoy_compatible" = "NO" ]; then + find_wim_file (loop) + if [ -n "$ventoy_wim_file" ]; then + vt_windows_locate_wim $ventoy_wim_file + fi + fi + + vt_windows_chain_data ${1}${chosen_path} + + if [ -n "$vtoy_chain_mem_addr" ]; then + terminal_output console + chainloader ${vtoy_path}/ventoy_x64.efi env_param=${env_param} isoefi=${LoadIsoEfiDriver} ${vtdebug_flag} mem:${vtoy_chain_mem_addr}:size:${vtoy_chain_mem_size} + boot + else + echo "chain empty failed" + sleep 5 + fi +} + +function uefi_linux_menu_func { + if [ "$ventoy_compatible" = "NO" ]; then + vt_load_cpio ${vtoy_path}/ventoy.cpio + + vt_linux_clear_initrd + + for file in "boot/grub/grub.cfg" "EFI/BOOT/grub.cfg" "EFI/boot/grub.cfg" "efi/boot/grub.cfg" "EFI/BOOT/BOOTX64.conf"; do + if [ -e (loop)/$file ]; then + vt_linux_parse_initrd_grub file (loop)/$file + fi + done + + vt_linux_initrd_count initrd_count + + # special process for special distros + if vt_cmp $initrd_count eq 0; then + if [ -d (loop)/loader/entries ]; then + set LoadIsoEfiDriver=on + vt_linux_parse_initrd_grub dir (loop)/loader/entries/ + elif [ -d (loop)/boot/grub ]; then + vt_linux_parse_initrd_grub dir (loop)/boot/grub/ + fi + fi + + vt_linux_initrd_count initrd_count + if vt_cmp $initrd_count eq 0; then + distro_specify_initrd_file + fi + + locate_initrd + fi + + vt_linux_chain_data ${1}${chosen_path} + + if [ -n "$vtoy_chain_mem_addr" ]; then + terminal_output console + chainloader ${vtoy_path}/ventoy_x64.efi env_param=${env_param} isoefi=${LoadIsoEfiDriver} ${vtdebug_flag} mem:${vtoy_chain_mem_addr}:size:${vtoy_chain_mem_size} + boot + else + echo "chain empty failed" + sleep 5 + fi +} + + +function uefi_iso_menu_func { + + if [ -d (loop)/ ]; then + loopback -d loop + fi + + unset LoadIsoEfiDriver + + vt_chosen_img_path chosen_path + + if vt_is_udf ${1}${chosen_path}; then + set ventoy_fs_probe=udf + else + set ventoy_fs_probe=iso9660 + fi + + loopback loop ${1}${chosen_path} + get_os_type (loop) + + vt_check_compatible (loop) + + vt_img_sector ${1}${chosen_path} + + if [ "$vtoy_os" = "Windows" ]; then + uefi_windows_menu_func $1 + else + uefi_linux_menu_func $1 + fi + + terminal_output gfxterm +} + +function legacy_windows_menu_func { + vt_windows_reset + + if [ "$ventoy_compatible" = "NO" ]; then + find_wim_file (loop) + if [ -n "$ventoy_wim_file" ]; then + vt_windows_locate_wim $ventoy_wim_file + elif [ -n "${vtdebug_flag}" ]; then + echo No wim file found + fi + fi + + vt_windows_chain_data ${1}${chosen_path} + + if [ -n "${vtdebug_flag}" ]; then + sleep 5 + fi + + if [ -n "$vtoy_chain_mem_addr" ]; then + linux16 $vtoy_path/ipxe.krn ${vtdebug_flag} ibft + initrd16 mem:${vtoy_chain_mem_addr}:size:${vtoy_chain_mem_size} + boot + else + echo "chain empty failed" + sleep 5 + fi +} + +function legacy_linux_menu_func { + if [ "$ventoy_compatible" = "NO" ]; then + + vt_load_cpio $vtoy_path/ventoy.cpio + + vt_linux_clear_initrd + + for dir in "isolinux" "boot/isolinux" "boot/x86_64/loader" "syslinux" "boot/syslinux"; do + if [ -d (loop)/$dir ]; then + vt_linux_parse_initrd_isolinux (loop)/$dir/ + fi + done + + vt_linux_initrd_count initrd_count + + # special process for special distros + if vt_cmp $initrd_count eq 0; then + #archlinux + if [ -d (loop)/arch/boot/syslinux ]; then + vt_linux_parse_initrd_isolinux (loop)/arch/boot/syslinux/ /arch/ + vt_linux_parse_initrd_isolinux (loop)/arch/boot/syslinux/ /arch/boot/syslinux/ + + #manjaro + elif [ -d (loop)/manjaro ]; then + if [ -e (loop)/boot/grub/kernels.cfg ]; then + vt_linux_parse_initrd_grub file (loop)/boot/grub/kernels.cfg + fi + elif [ -e (loop)/boot/grub/grub.cfg ]; then + vt_linux_parse_initrd_grub file (loop)/boot/grub/grub.cfg + fi + fi + + vt_linux_initrd_count initrd_count + if vt_cmp $initrd_count eq 0; then + distro_specify_initrd_file + fi + + locate_initrd + fi + + vt_linux_chain_data ${1}${chosen_path} + + if [ -n "${vtdebug_flag}" ]; then + sleep 5 + fi + + if [ -n "$vtoy_chain_mem_addr" ]; then + linux16 $vtoy_path/ipxe.krn ${vtdebug_flag} + initrd16 mem:${vtoy_chain_mem_addr}:size:${vtoy_chain_mem_size} + boot + else + echo "chain empty failed" + sleep 5 + fi +} + +function legacy_iso_menu_func { + + if [ -d (loop)/ ]; then + loopback -d loop + fi + + vt_chosen_img_path chosen_path + + if vt_is_udf ${1}${chosen_path}; then + set ventoy_fs_probe=udf + else + set ventoy_fs_probe=iso9660 + fi + + loopback loop ${1}${chosen_path} + + get_os_type (loop) + + vt_check_compatible (loop) + + vt_img_sector ${1}${chosen_path} + + if [ "$vtoy_os" = "Windows" ]; then + legacy_windows_menu_func $1 + else + legacy_linux_menu_func $1 + fi +} + + + + + +############################################################# +############################################################# +############################################################# +####### Main Process ########### +############################################################# +############################################################# +############################################################# + +set VENTOY_VERSION="1.0.00" + +#disable timeout +unset timeout + +vt_device $root vtoy_dev + +if [ "$vtoy_dev" = "tftp" ]; then + set vtoy_path=($root) + for vtid in 0 1 2 3; do + if [ -d (hd$vtid,2)/grub ]; then + set iso_path=(hd$vtid,1) + break + fi + done +else + set vtoy_path=($root)/ventoy + set iso_path=($vtoy_dev,1) +fi + +loadfont ascii + +if [ -f $iso_path/ventoy/ventoy.json ]; then + vt_load_plugin $iso_path +fi + +terminal_output gfxterm + +if [ -n "$vtoy_theme" ]; then + set theme=$vtoy_theme +else + set theme=$prefix/themes/ventoy/theme.txt +fi + +if [ -n "$vtoy_gfxmode" ]; then + set gfxmode=$vtoy_gfxmode +else + set gfxmode=1024x768 +fi + +#colect all image files (iso files) +set ventoy_img_count=0 +vt_list_img $iso_path ventoy_img_count + +#Dynamic menu for every iso file +if vt_cmp $ventoy_img_count ne 0; then + set imgid=0 + while vt_cmp $imgid lt $ventoy_img_count; do + vt_img_name $imgid img_name + menuentry "$img_name" { + if [ "$grub_platform" = "pc" ]; then + legacy_iso_menu_func $iso_path + else + uefi_iso_menu_func $iso_path + fi + } + + vt_incr imgid 1 + done +else + menuentry "No ISO files found (Press enter to reboot ...)" { + echo -e "\n Rebooting ... " + reboot + } +fi + diff --git a/INSTALL/grub/i386-pc/boot.img b/INSTALL/grub/i386-pc/boot.img new file mode 100644 index 00000000..4b6f21c3 Binary files /dev/null and b/INSTALL/grub/i386-pc/boot.img differ diff --git a/INSTALL/grub/i386-pc/core.img b/INSTALL/grub/i386-pc/core.img new file mode 100644 index 00000000..c97d4a14 Binary files /dev/null and b/INSTALL/grub/i386-pc/core.img differ diff --git a/INSTALL/grub/themes/ventoy/background.png b/INSTALL/grub/themes/ventoy/background.png new file mode 100644 index 00000000..5464b1d7 Binary files /dev/null and b/INSTALL/grub/themes/ventoy/background.png differ diff --git a/INSTALL/grub/themes/ventoy/menu_c.png b/INSTALL/grub/themes/ventoy/menu_c.png new file mode 100644 index 00000000..75c165b2 Binary files /dev/null and b/INSTALL/grub/themes/ventoy/menu_c.png differ diff --git a/INSTALL/grub/themes/ventoy/menu_e.png b/INSTALL/grub/themes/ventoy/menu_e.png new file mode 100644 index 00000000..d4c7421b Binary files /dev/null and b/INSTALL/grub/themes/ventoy/menu_e.png differ diff --git a/INSTALL/grub/themes/ventoy/menu_n.png b/INSTALL/grub/themes/ventoy/menu_n.png new file mode 100644 index 00000000..5af34692 Binary files /dev/null and b/INSTALL/grub/themes/ventoy/menu_n.png differ diff --git a/INSTALL/grub/themes/ventoy/menu_ne.png b/INSTALL/grub/themes/ventoy/menu_ne.png new file mode 100644 index 00000000..87578685 Binary files /dev/null and b/INSTALL/grub/themes/ventoy/menu_ne.png differ diff --git a/INSTALL/grub/themes/ventoy/menu_nw.png b/INSTALL/grub/themes/ventoy/menu_nw.png new file mode 100644 index 00000000..87578685 Binary files /dev/null and b/INSTALL/grub/themes/ventoy/menu_nw.png differ diff --git a/INSTALL/grub/themes/ventoy/menu_s.png b/INSTALL/grub/themes/ventoy/menu_s.png new file mode 100644 index 00000000..6ba27343 Binary files /dev/null and b/INSTALL/grub/themes/ventoy/menu_s.png differ diff --git a/INSTALL/grub/themes/ventoy/menu_se.png b/INSTALL/grub/themes/ventoy/menu_se.png new file mode 100644 index 00000000..959b6091 Binary files /dev/null and b/INSTALL/grub/themes/ventoy/menu_se.png differ diff --git a/INSTALL/grub/themes/ventoy/menu_sw.png b/INSTALL/grub/themes/ventoy/menu_sw.png new file mode 100644 index 00000000..959b6091 Binary files /dev/null and b/INSTALL/grub/themes/ventoy/menu_sw.png differ diff --git a/INSTALL/grub/themes/ventoy/menu_w.png b/INSTALL/grub/themes/ventoy/menu_w.png new file mode 100644 index 00000000..d4c7421b Binary files /dev/null and b/INSTALL/grub/themes/ventoy/menu_w.png differ diff --git a/INSTALL/grub/themes/ventoy/select_c.png b/INSTALL/grub/themes/ventoy/select_c.png new file mode 100644 index 00000000..245259aa Binary files /dev/null and b/INSTALL/grub/themes/ventoy/select_c.png differ diff --git a/INSTALL/grub/themes/ventoy/slider_c.png b/INSTALL/grub/themes/ventoy/slider_c.png new file mode 100644 index 00000000..7d630fdf Binary files /dev/null and b/INSTALL/grub/themes/ventoy/slider_c.png differ diff --git a/INSTALL/grub/themes/ventoy/slider_n.png b/INSTALL/grub/themes/ventoy/slider_n.png new file mode 100644 index 00000000..41482c90 Binary files /dev/null and b/INSTALL/grub/themes/ventoy/slider_n.png differ diff --git a/INSTALL/grub/themes/ventoy/slider_s.png b/INSTALL/grub/themes/ventoy/slider_s.png new file mode 100644 index 00000000..17adc2ab Binary files /dev/null and b/INSTALL/grub/themes/ventoy/slider_s.png differ diff --git a/INSTALL/grub/themes/ventoy/terminal_box_c.png b/INSTALL/grub/themes/ventoy/terminal_box_c.png new file mode 100644 index 00000000..d0dd52a2 Binary files /dev/null and b/INSTALL/grub/themes/ventoy/terminal_box_c.png differ diff --git a/INSTALL/grub/themes/ventoy/terminal_box_e.png b/INSTALL/grub/themes/ventoy/terminal_box_e.png new file mode 100644 index 00000000..394cbe4f Binary files /dev/null and b/INSTALL/grub/themes/ventoy/terminal_box_e.png differ diff --git a/INSTALL/grub/themes/ventoy/terminal_box_n.png b/INSTALL/grub/themes/ventoy/terminal_box_n.png new file mode 100644 index 00000000..476f8bc6 Binary files /dev/null and b/INSTALL/grub/themes/ventoy/terminal_box_n.png differ diff --git a/INSTALL/grub/themes/ventoy/terminal_box_ne.png b/INSTALL/grub/themes/ventoy/terminal_box_ne.png new file mode 100644 index 00000000..9e26959b Binary files /dev/null and b/INSTALL/grub/themes/ventoy/terminal_box_ne.png differ diff --git a/INSTALL/grub/themes/ventoy/terminal_box_nw.png b/INSTALL/grub/themes/ventoy/terminal_box_nw.png new file mode 100644 index 00000000..5c3cba87 Binary files /dev/null and b/INSTALL/grub/themes/ventoy/terminal_box_nw.png differ diff --git a/INSTALL/grub/themes/ventoy/terminal_box_s.png b/INSTALL/grub/themes/ventoy/terminal_box_s.png new file mode 100644 index 00000000..85a8901d Binary files /dev/null and b/INSTALL/grub/themes/ventoy/terminal_box_s.png differ diff --git a/INSTALL/grub/themes/ventoy/terminal_box_se.png b/INSTALL/grub/themes/ventoy/terminal_box_se.png new file mode 100644 index 00000000..d8627ee5 Binary files /dev/null and b/INSTALL/grub/themes/ventoy/terminal_box_se.png differ diff --git a/INSTALL/grub/themes/ventoy/terminal_box_sw.png b/INSTALL/grub/themes/ventoy/terminal_box_sw.png new file mode 100644 index 00000000..67c600c8 Binary files /dev/null and b/INSTALL/grub/themes/ventoy/terminal_box_sw.png differ diff --git a/INSTALL/grub/themes/ventoy/terminal_box_w.png b/INSTALL/grub/themes/ventoy/terminal_box_w.png new file mode 100644 index 00000000..d066e2db Binary files /dev/null and b/INSTALL/grub/themes/ventoy/terminal_box_w.png differ diff --git a/INSTALL/grub/themes/ventoy/theme.txt b/INSTALL/grub/themes/ventoy/theme.txt new file mode 100644 index 00000000..bf794ec6 --- /dev/null +++ b/INSTALL/grub/themes/ventoy/theme.txt @@ -0,0 +1,50 @@ + +desktop-image: "background.png" +title-text: " " +title-font: "ascii" +title-color: "#ffffff" +message-font: "ascii" +message-color: "#f2f2f2" + +terminal-box: "terminal_box_*.png" + ++ boot_menu { + left = 10% + width = 80% + top = 30% + height = 50% + + menu_pixmap_style = "menu_*.png" + + item_font = "ascii" + item_color = "#ffffff" + item_height = 30 + item_icon_space = 1 + item_spacing = 1 + item_padding = 1 + + selected_item_font = "ascii" + selected_item_color= "#f2f2f2" + selected_item_pixmap_style = "select_*.png" + + #icon_height = 30 + #icon_width = 30 + + scrollbar = true + scrollbar_width = 10 + scrollbar_thumb = "slider_*.png" +} + ++ progress_bar { + id = "__timeout__" + text = "@TIMEOUT_NOTIFICATION_SHORT@" + + left = 95% + width = 48 + top = 95% + height = 48 + + text_color = "#f2f2f2" + bar_style = "*" + highlight_style = "*" +} diff --git a/INSTALL/grub/x86_64-efi/normal.mod b/INSTALL/grub/x86_64-efi/normal.mod new file mode 100644 index 00000000..58d29ee9 Binary files /dev/null and b/INSTALL/grub/x86_64-efi/normal.mod differ diff --git a/INSTALL/tool/hexdump b/INSTALL/tool/hexdump new file mode 100644 index 00000000..0fd90c22 Binary files /dev/null and b/INSTALL/tool/hexdump differ diff --git a/INSTALL/tool/mkexfatfs_32 b/INSTALL/tool/mkexfatfs_32 new file mode 100644 index 00000000..a067639e Binary files /dev/null and b/INSTALL/tool/mkexfatfs_32 differ diff --git a/INSTALL/tool/mkexfatfs_64 b/INSTALL/tool/mkexfatfs_64 new file mode 100644 index 00000000..5d8720ca Binary files /dev/null and b/INSTALL/tool/mkexfatfs_64 differ diff --git a/INSTALL/tool/mount.exfat-fuse_32 b/INSTALL/tool/mount.exfat-fuse_32 new file mode 100644 index 00000000..0b3a5f13 Binary files /dev/null and b/INSTALL/tool/mount.exfat-fuse_32 differ diff --git a/INSTALL/tool/mount.exfat-fuse_64 b/INSTALL/tool/mount.exfat-fuse_64 new file mode 100644 index 00000000..8f945240 Binary files /dev/null and b/INSTALL/tool/mount.exfat-fuse_64 differ diff --git a/INSTALL/tool/ventoy_lib.sh b/INSTALL/tool/ventoy_lib.sh new file mode 100644 index 00000000..3562927c --- /dev/null +++ b/INSTALL/tool/ventoy_lib.sh @@ -0,0 +1,289 @@ +#!/bin/sh + +#Ventoy partition 32MB +VENTOY_PART_SIZE=33554432 +VENTOY_SECTOR_SIZE=512 +VENTOY_SECTOR_NUM=65536 + +ventoy_false() { + [ "1" = "2" ] +} + +ventoy_true() { + [ "1" = "1" ] +} + +ventoy_is_linux64() { + if [ -e /lib64 ]; then + ventoy_true + return + fi + + if [ -e /usr/lib64 ]; then + ventoy_true + return + fi + + if uname -a | egrep -q 'x86_64|amd64'; then + ventoy_true + return + fi + + ventoy_false +} + +ventoy_is_dash() { + if [ -L /bin/sh ]; then + vtdst=$(readlink /bin/sh) + if [ "$vtdst" = "dash" ]; then + ventoy_true + return + fi + fi + ventoy_false +} + +vtinfo() { + if ventoy_is_dash; then + echo "\033[32m$*\033[0m" + else + echo -e "\033[32m$*\033[0m" + fi +} + +vtwarn() { + if ventoy_is_dash; then + echo "\033[33m$*\033[0m" + else + echo -e "\033[33m$*\033[0m" + fi +} + + +vterr() { + if ventoy_is_dash; then + echo "\033[31m$*\033[0m" + else + echo -e "\033[31m$*\033[0m" + fi +} + +vtdebug() { + echo "$*" >> ./log.txt +} + +check_tool_work_ok() { + + if ventoy_is_linux64; then + vtdebug "This is linux 64" + mkexfatfs=mkexfatfs_64 + vtoyfat=vtoyfat_64 + else + vtdebug "This is linux 32" + mkexfatfs=mkexfatfs_32 + vtoyfat=vtoyfat_32 + fi + + if echo 1 | ./tool/hexdump > /dev/null; then + vtdebug "hexdump test ok ..." + else + vtdebug "hexdump test fail ..." + ventoy_false + return + fi + + if ./tool/$mkexfatfs -V > /dev/null; then + vtdebug "$mkexfatfs test ok ..." + else + vtdebug "$mkexfatfs test fail ..." + ventoy_false + return + fi + + if ./tool/$vtoyfat -T; then + vtdebug "$vtoyfat test ok ..." + else + vtdebug "$vtoyfat test fail ..." + ventoy_false + return + fi + + vtdebug "tool check success ..." + ventoy_true +} + + +get_disk_part_name() { + DISK=$1 + + if echo $DISK | grep -q "/dev/loop"; then + echo ${DISK}p${2} + elif echo $DISK | grep -q "/dev/nvme[0-9][0-9]*n[0-9]"; then + echo ${DISK}p${2} + else + echo ${DISK}${2} + fi +} + + +get_ventoy_version_from_cfg() { + if grep -q 'set.*VENTOY_VERSION=' $1; then + grep 'set.*VENTOY_VERSION=' $1 | awk -F'"' '{print $2}' + else + echo 'none' + fi +} + +is_disk_contains_ventoy() { + DISK=$1 + + PART1=$(get_disk_part_name $1 1) + PART2=$(get_disk_part_name $1 2) + + if [ -e /sys/class/block/${PART2#/dev/}/size ]; then + SIZE=$(cat /sys/class/block/${PART2#/dev/}/size) + else + SIZE=0 + fi + + if ! [ -b $PART1 ]; then + vtdebug "$PART1 not exist" + ventoy_false + return + fi + + if ! [ -b $PART2 ]; then + vtdebug "$PART2 not exist" + ventoy_false + return + fi + + PART2_TYPE=$(dd if=$DISK bs=1 count=1 skip=466 status=none | ./tool/hexdump -n1 -e '1/1 "%02X"') + if [ "$PART2_TYPE" != "EF" ]; then + vtdebug "part2 type is $PART2_TYPE not EF" + ventoy_false + return + fi + + PART1_TYPE=$(dd if=$DISK bs=1 count=1 skip=450 status=none | ./tool/hexdump -n1 -e '1/1 "%02X"') + if [ "$PART1_TYPE" != "07" ]; then + vtdebug "part1 type is $PART2_TYPE not 07" + ventoy_false + return + fi + + if [ -e /sys/class/block/${PART1#/dev/}/start ]; then + PART1_START=$(cat /sys/class/block/${PART1#/dev/}/start) + fi + + if [ "$PART1_START" != "2048" ]; then + vtdebug "part1 start is $PART1_START not 2048" + ventoy_false + return + fi + + if [ "$VENTOY_SECTOR_NUM" != "$SIZE" ]; then + vtdebug "part2 size is $SIZE not $VENTOY_SECTOR_NUM" + ventoy_false + return + fi + + ventoy_true +} + +get_disk_ventoy_version() { + + if ! is_disk_contains_ventoy $1; then + ventoy_false + return + fi + + PART2=$(get_disk_part_name $1 2) + + if ventoy_is_linux64; then + cmd=./tool/vtoyfat_64 + else + cmd=./tool/vtoyfat_32 + fi + + ParseVer=$($cmd $PART2) + if [ $? -eq 0 ]; then + vtdebug "Ventoy version in $PART2 is $ParseVer" + echo $ParseVer + ventoy_true + return + fi + + ventoy_false +} + + +format_ventoy_disk() { + DISK=$1 + PART2=$(get_disk_part_name $DISK 2) + + sector_num=$(cat /sys/block/${DISK#/dev/}/size) + + part1_start_sector=2048 + part1_end_sector=$(expr $sector_num - $VENTOY_SECTOR_NUM - 1) + export part2_start_sector=$(expr $part1_end_sector + 1) + part2_end_sector=$(expr $sector_num - 1) + + if [ -e $PART2 ]; then + echo "delete $PART2" + rm -f $PART2 + fi + + echo "" + echo "Create partitions on $DISK ..." + +fdisk $DISK >/dev/null 2>&1 </dev/null 2>&1 + partprobe >/dev/null 2>&1 + sleep 3 + + + echo 'mkfs on disk partitions ...' + while ! [ -e $PART2 ]; do + echo "wait $PART2 ..." + sleep 1 + done + + echo "create efi fat fs ..." + for i in 0 1 2 3 4 5 6 7 8 9; do + if mkfs.vfat -F 16 -n EFI $PART2; then + echo 'success' + break + else + echo "$? retry ..." + sleep 2 + fi + done +} + + + + diff --git a/INSTALL/tool/vtoy_gen_uuid b/INSTALL/tool/vtoy_gen_uuid new file mode 100644 index 00000000..8fc29eba Binary files /dev/null and b/INSTALL/tool/vtoy_gen_uuid differ diff --git a/INSTALL/tool/vtoyfat_32 b/INSTALL/tool/vtoyfat_32 new file mode 100644 index 00000000..9ff79668 Binary files /dev/null and b/INSTALL/tool/vtoyfat_32 differ diff --git a/INSTALL/tool/vtoyfat_64 b/INSTALL/tool/vtoyfat_64 new file mode 100644 index 00000000..83c9e02b Binary files /dev/null and b/INSTALL/tool/vtoyfat_64 differ diff --git a/INSTALL/tool/xzcat b/INSTALL/tool/xzcat new file mode 100644 index 00000000..012a9849 Binary files /dev/null and b/INSTALL/tool/xzcat differ diff --git a/INSTALL/ventoy/imdisk/32/imdisk.cpl b/INSTALL/ventoy/imdisk/32/imdisk.cpl new file mode 100644 index 00000000..e59193c9 Binary files /dev/null and b/INSTALL/ventoy/imdisk/32/imdisk.cpl differ diff --git a/INSTALL/ventoy/imdisk/32/imdisk.exe b/INSTALL/ventoy/imdisk/32/imdisk.exe new file mode 100644 index 00000000..c0827303 Binary files /dev/null and b/INSTALL/ventoy/imdisk/32/imdisk.exe differ diff --git a/INSTALL/ventoy/imdisk/32/imdisk.sys b/INSTALL/ventoy/imdisk/32/imdisk.sys new file mode 100644 index 00000000..17b2ac27 Binary files /dev/null and b/INSTALL/ventoy/imdisk/32/imdisk.sys differ diff --git a/INSTALL/ventoy/imdisk/64/imdisk.cpl b/INSTALL/ventoy/imdisk/64/imdisk.cpl new file mode 100644 index 00000000..13f94b29 Binary files /dev/null and b/INSTALL/ventoy/imdisk/64/imdisk.cpl differ diff --git a/INSTALL/ventoy/imdisk/64/imdisk.exe b/INSTALL/ventoy/imdisk/64/imdisk.exe new file mode 100644 index 00000000..19cb3835 Binary files /dev/null and b/INSTALL/ventoy/imdisk/64/imdisk.exe differ diff --git a/INSTALL/ventoy/imdisk/64/imdisk.sys b/INSTALL/ventoy/imdisk/64/imdisk.sys new file mode 100644 index 00000000..430229f9 Binary files /dev/null and b/INSTALL/ventoy/imdisk/64/imdisk.sys differ diff --git a/INSTALL/ventoy/ipxe.krn b/INSTALL/ventoy/ipxe.krn new file mode 100644 index 00000000..61a86375 Binary files /dev/null and b/INSTALL/ventoy/ipxe.krn differ diff --git a/INSTALL/ventoy/iso9660_x64.efi b/INSTALL/ventoy/iso9660_x64.efi new file mode 100644 index 00000000..240c33ff Binary files /dev/null and b/INSTALL/ventoy/iso9660_x64.efi differ diff --git a/INSTALL/ventoy/ventoy.cpio b/INSTALL/ventoy/ventoy.cpio new file mode 100644 index 00000000..48b4fafe Binary files /dev/null and b/INSTALL/ventoy/ventoy.cpio differ diff --git a/INSTALL/ventoy/ventoy_x64.efi b/INSTALL/ventoy/ventoy_x64.efi new file mode 100644 index 00000000..342fca4c Binary files /dev/null and b/INSTALL/ventoy/ventoy_x64.efi differ diff --git a/INSTALL/ventoy/vtoyjump32.exe b/INSTALL/ventoy/vtoyjump32.exe new file mode 100644 index 00000000..24cd8ab1 Binary files /dev/null and b/INSTALL/ventoy/vtoyjump32.exe differ diff --git a/INSTALL/ventoy/vtoyjump64.exe b/INSTALL/ventoy/vtoyjump64.exe new file mode 100644 index 00000000..f6bb9473 Binary files /dev/null and b/INSTALL/ventoy/vtoyjump64.exe differ diff --git a/IPXE/README.txt b/IPXE/README.txt new file mode 100644 index 00000000..0eabadd0 --- /dev/null +++ b/IPXE/README.txt @@ -0,0 +1,8 @@ + +========== About Source Code ============= +1. unpack ipxe_org_code/ipxe-3fe683e.tar.bz2 +2. After decompressing, delete ipxe-3fe683e/src/drivers (whole directory) +3. Merge left source code with the ipxe-3fe683e directory here + +========== Build ============= +make bin/ipxe.iso diff --git a/IPXE/ipxe-3fe683e/src/arch/x86/core/runtime.c b/IPXE/ipxe-3fe683e/src/arch/x86/core/runtime.c new file mode 100644 index 00000000..ed15de50 --- /dev/null +++ b/IPXE/ipxe-3fe683e/src/arch/x86/core/runtime.c @@ -0,0 +1,276 @@ +/* + * Copyright (C) 2011 Michael Brown . + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of the + * License, or any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + * + * You can also choose to distribute this program under the terms of + * the Unmodified Binary Distribution Licence (as given in the file + * COPYING.UBDL), provided that you have satisfied its requirements. + */ + +FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL ); + +/** @file + * + * Command line and initrd passed to iPXE at runtime + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/** Command line physical address + * + * This can be set by the prefix. + */ +uint32_t __bss16 ( cmdline_phys ); +#define cmdline_phys __use_data16 ( cmdline_phys ) + +/** initrd physical address + * + * This can be set by the prefix. + */ +uint32_t __bss16 ( initrd_phys ); +#define initrd_phys __use_data16 ( initrd_phys ) + +/** initrd length + * + * This can be set by the prefix. + */ +uint32_t __bss16 ( initrd_len ); +#define initrd_len __use_data16 ( initrd_len ) + +/** Internal copy of the command line */ +static char *cmdline_copy; + +/** Free command line image */ +static void cmdline_image_free ( struct refcnt *refcnt ) { + struct image *image = container_of ( refcnt, struct image, refcnt ); + + DBGC ( image, "RUNTIME freeing command line\n" ); + free ( cmdline_copy ); +} + +/** Embedded script representing the command line */ +static struct image cmdline_image = { + .refcnt = REF_INIT ( cmdline_image_free ), + .name = "", + .type = &script_image_type, +}; + +/** Colour for debug messages */ +#define colour &cmdline_image + +/** + * Strip unwanted cruft from command line + * + * @v cmdline Command line + * @v cruft Initial substring of cruft to strip + */ +static void cmdline_strip ( char *cmdline, const char *cruft ) { + char *strip; + char *strip_end; + + /* Find unwanted cruft, if present */ + if ( ! ( strip = strstr ( cmdline, cruft ) ) ) + return; + + /* Strip unwanted cruft */ + strip_end = strchr ( strip, ' ' ); + if ( strip_end ) { + *strip_end = '\0'; + DBGC ( colour, "RUNTIME stripping \"%s\"\n", strip ); + strcpy ( strip, ( strip_end + 1 ) ); + } else { + DBGC ( colour, "RUNTIME stripping \"%s\"\n", strip ); + *strip = '\0'; + } +} + +/** + * Initialise command line + * + * @ret rc Return status code + */ +static int cmdline_init ( void ) { + userptr_t cmdline_user; + char *cmdline; + size_t len; + int rc; + + /* Do nothing if no command line was specified */ + if ( ! cmdline_phys ) { + DBGC ( colour, "RUNTIME found no command line\n" ); + return 0; + } + cmdline_user = phys_to_user ( cmdline_phys ); + len = ( strlen_user ( cmdline_user, 0 ) + 1 /* NUL */ ); + + /* Allocate and copy command line */ + cmdline_copy = malloc ( len ); + if ( ! cmdline_copy ) { + DBGC ( colour, "RUNTIME could not allocate %zd bytes for " + "command line\n", len ); + rc = -ENOMEM; + goto err_alloc_cmdline_copy; + } + cmdline = cmdline_copy; + copy_from_user ( cmdline, cmdline_user, 0, len ); + DBGC ( colour, "RUNTIME found command line \"%s\" at %08x\n", + cmdline, cmdline_phys ); + + /* Mark command line as consumed */ + cmdline_phys = 0; + + /* Strip unwanted cruft from the command line */ + cmdline_strip ( cmdline, "BOOT_IMAGE=" ); + cmdline_strip ( cmdline, "initrd=" ); + while ( isspace ( *cmdline ) ) + cmdline++; + DBGC ( colour, "RUNTIME using command line \"%s\"\n", cmdline ); + + /* Prepare and register image */ + cmdline_image.data = virt_to_user ( cmdline ); + cmdline_image.len = strlen ( cmdline ); + if ( cmdline_image.len ) { + if ( ( rc = register_image ( &cmdline_image ) ) != 0 ) { + DBGC ( colour, "RUNTIME could not register command " + "line: %s\n", strerror ( rc ) ); + goto err_register_image; + } + } + + /* Drop our reference to the image */ + image_put ( &cmdline_image ); + + return 0; + + err_register_image: + image_put ( &cmdline_image ); + err_alloc_cmdline_copy: + return rc; +} + +/** + * Initialise initrd + * + * @ret rc Return status code + */ +static int initrd_init ( void ) { + struct image *image; + int rc; + + /* Do nothing if no initrd was specified */ + if ( ! initrd_phys ) { + DBGC ( colour, "RUNTIME found no initrd\n" ); + return 0; + } + if ( ! initrd_len ) { + DBGC ( colour, "RUNTIME found empty initrd\n" ); + return 0; + } + DBGC ( colour, "RUNTIME found initrd at [%x,%x)\n", + initrd_phys, ( initrd_phys + initrd_len ) ); + + /* Allocate image */ + image = alloc_image ( NULL ); + if ( ! image ) { + DBGC ( colour, "RUNTIME could not allocate image for " + "initrd\n" ); + rc = -ENOMEM; + goto err_alloc_image; + } + if ( ( rc = image_set_name ( image, "" ) ) != 0 ) { + DBGC ( colour, "RUNTIME could not set image name: %s\n", + strerror ( rc ) ); + goto err_set_name; + } + + /* Allocate and copy initrd content */ + image->data = umalloc ( initrd_len ); + if ( ! image->data ) { + DBGC ( colour, "RUNTIME could not allocate %d bytes for " + "initrd\n", initrd_len ); + rc = -ENOMEM; + goto err_umalloc; + } + image->len = initrd_len; + memcpy_user ( image->data, 0, phys_to_user ( initrd_phys ), 0, + initrd_len ); + + g_initrd_addr = (void *)image->data; + g_initrd_len = image->len; + g_cmdline_copy = cmdline_copy; + + + /* Mark initrd as consumed */ + initrd_phys = 0; + + /* Register image */ + if ( ( rc = register_image ( image ) ) != 0 ) { + DBGC ( colour, "RUNTIME could not register initrd: %s\n", + strerror ( rc ) ); + goto err_register_image; + } + + /* Drop our reference to the image */ + image_put ( image ); + + return 0; + + err_register_image: + err_umalloc: + err_set_name: + image_put ( image ); + err_alloc_image: + return rc; +} + +/** + * Initialise command line and initrd + * + */ +static void runtime_init ( void ) { + int rc; + + /* Initialise command line */ + if ( ( rc = cmdline_init() ) != 0 ) { + /* No way to report failure */ + return; + } + + /* Initialise initrd */ + if ( ( rc = initrd_init() ) != 0 ) { + /* No way to report failure */ + return; + } +} + +/** Command line and initrd initialisation function */ +struct startup_fn runtime_startup_fn __startup_fn ( STARTUP_NORMAL ) = { + .name = "runtime", + .startup = runtime_init, +}; diff --git a/IPXE/ipxe-3fe683e/src/arch/x86/core/ventoy_vdisk.c b/IPXE/ipxe-3fe683e/src/arch/x86/core/ventoy_vdisk.c new file mode 100644 index 00000000..b283b087 --- /dev/null +++ b/IPXE/ipxe-3fe683e/src/arch/x86/core/ventoy_vdisk.c @@ -0,0 +1,527 @@ + +FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL ); + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +int g_debug = 0; +char *g_cmdline_copy; +void *g_initrd_addr; +size_t g_initrd_len; +ventoy_chain_head *g_chain; +ventoy_img_chunk *g_chunk; +uint32_t g_img_chunk_num; +ventoy_img_chunk *g_cur_chunk; +uint32_t g_disk_sector_size; + +ventoy_override_chunk *g_override_chunk; +uint32_t g_override_chunk_num; + +ventoy_virt_chunk *g_virt_chunk; +uint32_t g_virt_chunk_num; + +ventoy_sector_flag g_sector_flag[128]; + +static struct int13_disk_address __bss16 ( ventoy_address ); +#define ventoy_address __use_data16 ( ventoy_address ) + +static uint64_t ventoy_remap_lba(uint64_t lba, uint32_t *count) +{ + uint32_t i; + uint32_t max_sectors; + ventoy_img_chunk *cur; + + if ((NULL == g_cur_chunk) || ((lba) < g_cur_chunk->img_start_sector) || ((lba) > g_cur_chunk->img_end_sector)) + { + g_cur_chunk = NULL; + for (i = 0; i < g_img_chunk_num; i++) + { + cur = g_chunk + i; + if (lba >= cur->img_start_sector && lba <= cur->img_end_sector) + { + g_cur_chunk = cur; + break; + } + } + } + + if (g_cur_chunk) + { + max_sectors = g_cur_chunk->img_end_sector - lba + 1; + if (*count > max_sectors) + { + *count = max_sectors; + } + + if (512 == g_disk_sector_size) + { + return g_cur_chunk->disk_start_sector + ((lba - g_cur_chunk->img_start_sector) << 2); + } + return g_cur_chunk->disk_start_sector + (lba - g_cur_chunk->img_start_sector) * 2048 / g_disk_sector_size; + } + return lba; +} + +static int ventoy_vdisk_read_real(uint64_t lba, unsigned int count, unsigned long buffer) +{ + uint32_t i = 0; + uint32_t left = 0; + uint32_t readcount = 0; + uint32_t tmpcount = 0; + uint16_t status = 0; + uint64_t curlba = 0; + uint64_t maplba = 0; + uint64_t start = 0; + uint64_t end = 0; + uint64_t override_start = 0; + uint64_t override_end = 0; + unsigned long phyaddr; + unsigned long databuffer = buffer; + uint8_t *override_data; + + curlba = lba; + left = count; + + while (left > 0) + { + readcount = left; + maplba = ventoy_remap_lba(curlba, &readcount); + + if (g_disk_sector_size == 512) + { + tmpcount = (readcount << 2); + } + else + { + tmpcount = (readcount * 2048) / g_disk_sector_size; + } + + phyaddr = user_to_phys(buffer, 0); + + while (tmpcount > 0) + { + /* Use INT 13, 42 to read the data from real disk */ + ventoy_address.lba = maplba; + ventoy_address.buffer.segment = (uint16_t)(phyaddr >> 4); + ventoy_address.buffer.offset = (uint16_t)(phyaddr & 0x0F); + + if (tmpcount >= 64) /* max sectors per transmit */ + { + ventoy_address.count = 64; + tmpcount -= 64; + maplba += 64; + phyaddr += 32768; + } + else + { + ventoy_address.count = tmpcount; + tmpcount = 0; + } + + __asm__ __volatile__ ( REAL_CODE ( "stc\n\t" + "sti\n\t" + "int $0x13\n\t" + "sti\n\t" /* BIOS bugs */ + "jc 1f\n\t" + "xorw %%ax, %%ax\n\t" + "\n1:\n\t" ) + : "=a" ( status ) + : "a" ( 0x4200 ), "d" ( VENTOY_BIOS_FAKE_DRIVE ), + "S" ( __from_data16 ( &ventoy_address ) ) ); + } + + curlba += readcount; + left -= readcount; + buffer += (readcount * 2048); + } + + start = lba * 2048; + if (start > g_chain->real_img_size_in_bytes) + { + goto end; + } + + end = start + count * 2048; + for (i = 0; i < g_override_chunk_num; i++) + { + override_data = g_override_chunk[i].override_data; + override_start = g_override_chunk[i].img_offset; + override_end = override_start + g_override_chunk[i].override_size; + + if (end <= override_start || start >= override_end) + { + continue; + } + + if (start <= override_start) + { + if (end <= override_end) + { + memcpy((char *)databuffer + override_start - start, override_data, end - override_start); + } + else + { + memcpy((char *)databuffer + override_start - start, override_data, override_end - override_start); + } + } + else + { + if (end <= override_end) + { + memcpy((char *)databuffer, override_data + start - override_start, end - start); + } + else + { + memcpy((char *)databuffer, override_data + start - override_start, override_end - start); + } + } + } + +end: + + return 0; +} + +int ventoy_vdisk_read(struct san_device *sandev, uint64_t lba, unsigned int count, unsigned long buffer) +{ + uint32_t i, j; + uint64_t curlba; + uint64_t lastlba = 0; + uint32_t lbacount = 0; + unsigned long lastbuffer; + uint64_t readend; + ventoy_virt_chunk *node; + ventoy_sector_flag *cur_flag; + ventoy_sector_flag *sector_flag = g_sector_flag; + struct i386_all_regs *ix86; + + if (INT13_EXTENDED_READ != sandev->int13_command) + { + DBGC(sandev, "invalid cmd %u\n", sandev->int13_command); + return 0; + } + + ix86 = (struct i386_all_regs *)sandev->x86_regptr; + + readend = (lba + count) * 2048; + if (readend < g_chain->real_img_size_in_bytes) + { + ventoy_vdisk_read_real(lba, count, buffer); + ix86->regs.dl = sandev->drive; + return 0; + } + + if (count > sizeof(g_sector_flag)) + { + sector_flag = (ventoy_sector_flag *)malloc(count * sizeof(ventoy_sector_flag)); + } + + for (curlba = lba, cur_flag = sector_flag, j = 0; j < count; j++, curlba++, cur_flag++) + { + cur_flag->flag = 0; + for (node = g_virt_chunk, i = 0; i < g_virt_chunk_num; i++, node++) + { + if (curlba >= node->mem_sector_start && curlba < node->mem_sector_end) + { + memcpy((void *)(buffer + j * 2048), + (char *)g_virt_chunk + node->mem_sector_offset + (curlba - node->mem_sector_start) * 2048, + 2048); + cur_flag->flag = 1; + break; + } + else if (curlba >= node->remap_sector_start && curlba < node->remap_sector_end) + { + cur_flag->remap_lba = node->org_sector_start + curlba - node->remap_sector_start; + cur_flag->flag = 2; + break; + } + } + } + + for (curlba = lba, cur_flag = sector_flag, j = 0; j < count; j++, curlba++, cur_flag++) + { + if (cur_flag->flag == 2) + { + if (lastlba == 0) + { + lastbuffer = buffer + j * 2048; + lastlba = cur_flag->remap_lba; + lbacount = 1; + } + else if (lastlba + lbacount == cur_flag->remap_lba) + { + lbacount++; + } + else + { + ventoy_vdisk_read_real(lastlba, lbacount, lastbuffer); + lastbuffer = buffer + j * 2048; + lastlba = cur_flag->remap_lba; + lbacount = 1; + } + } + } + + if (lbacount > 0) + { + ventoy_vdisk_read_real(lastlba, lbacount, lastbuffer); + } + + if (sector_flag != g_sector_flag) + { + free(sector_flag); + } + + ix86->regs.dl = sandev->drive; + return 0; +} + +static void ventoy_dump_img_chunk(ventoy_chain_head *chain) +{ + uint32_t i; + ventoy_img_chunk *chunk; + + chunk = (ventoy_img_chunk *)((char *)chain + chain->img_chunk_offset); + + printf("##################### ventoy_dump_img_chunk #######################\n"); + + for (i = 0; i < chain->img_chunk_num; i++) + { + printf("%2u: [ %u - %u ] <==> [ %llu - %llu ]\n", + i, chunk[i].img_start_sector, chunk[i].img_end_sector, + chunk[i].disk_start_sector, chunk[i].disk_end_sector); + } + + ventoy_debug_pause(); +} + +static void ventoy_dump_override_chunk(ventoy_chain_head *chain) +{ + uint32_t i; + ventoy_override_chunk *chunk; + + chunk = (ventoy_override_chunk *)((char *)chain + chain->override_chunk_offset); + + printf("##################### ventoy_dump_override_chunk #######################\n"); + + for (i = 0; i < g_override_chunk_num; i++) + { + printf("%2u: [ %llu, %u ]\n", i, chunk[i].img_offset, chunk[i].override_size); + } + + ventoy_debug_pause(); +} + +static void ventoy_dump_virt_chunk(ventoy_chain_head *chain) +{ + uint32_t i; + ventoy_virt_chunk *node; + + printf("##################### ventoy_dump_virt_chunk #######################\n"); + printf("virt_chunk_offset=%u\n", chain->virt_chunk_offset); + printf("virt_chunk_num=%u\n", chain->virt_chunk_num); + + node = (ventoy_virt_chunk *)((char *)chain + chain->virt_chunk_offset); + for (i = 0; i < chain->virt_chunk_num; i++, node++) + { + printf("%2u: mem:[ %u, %u, %u ] remap:[ %u, %u, %u ]\n", i, + node->mem_sector_start, + node->mem_sector_end, + node->mem_sector_offset, + node->remap_sector_start, + node->remap_sector_end, + node->org_sector_start); + } + + ventoy_debug_pause(); +} + +static void ventoy_dump_chain(ventoy_chain_head *chain) +{ + uint32_t i = 0; + uint8_t chksum = 0; + uint8_t *guid; + + guid = chain->os_param.vtoy_disk_guid; + for (i = 0; i < sizeof(ventoy_os_param); i++) + { + chksum += *((uint8_t *)(&(chain->os_param)) + i); + } + + printf("##################### ventoy_dump_chain #######################\n"); + + printf("os_param will be save at %p\n", ventoy_get_runtime_addr()); + + printf("os_param->chksum=0x%x (%s)\n", chain->os_param.chksum, chksum ? "FAILED" : "SUCCESS"); + printf("os_param->vtoy_disk_guid=%02x%02x%02x%02x\n", guid[0], guid[1], guid[2], guid[3]); + printf("os_param->vtoy_disk_size=%llu\n", chain->os_param.vtoy_disk_size); + printf("os_param->vtoy_disk_part_id=%u\n", chain->os_param.vtoy_disk_part_id); + printf("os_param->vtoy_disk_part_type=%u\n", chain->os_param.vtoy_disk_part_type); + printf("os_param->vtoy_img_path=<%s>\n", chain->os_param.vtoy_img_path); + printf("os_param->vtoy_img_size=<%llu>\n", chain->os_param.vtoy_img_size); + printf("os_param->vtoy_img_location_addr=<0x%llx>\n", chain->os_param.vtoy_img_location_addr); + printf("os_param->vtoy_img_location_len=<%u>\n", chain->os_param.vtoy_img_location_len); + ventoy_debug_pause(); + + printf("chain->disk_drive=0x%x\n", chain->disk_drive); + printf("chain->drive_map=0x%x\n", chain->drive_map); + printf("chain->disk_sector_size=%u\n", chain->disk_sector_size); + printf("chain->real_img_size_in_bytes=%llu\n", chain->real_img_size_in_bytes); + printf("chain->virt_img_size_in_bytes=%llu\n", chain->virt_img_size_in_bytes); + printf("chain->boot_catalog=%u\n", chain->boot_catalog); + printf("chain->img_chunk_offset=%u\n", chain->img_chunk_offset); + printf("chain->img_chunk_num=%u\n", chain->img_chunk_num); + printf("chain->override_chunk_offset=%u\n", chain->override_chunk_offset); + printf("chain->override_chunk_num=%u\n", chain->override_chunk_num); + printf("chain->virt_chunk_offset=%u\n", chain->virt_chunk_offset); + printf("chain->virt_chunk_num=%u\n", chain->virt_chunk_num); + ventoy_debug_pause(); + + ventoy_dump_img_chunk(chain); + ventoy_dump_override_chunk(chain); + ventoy_dump_virt_chunk(chain); +} + +static int ventoy_update_image_location(ventoy_os_param *param) +{ + uint8_t chksum = 0; + unsigned int i; + unsigned int length; + userptr_t address = 0; + ventoy_image_location *location = NULL; + ventoy_image_disk_region *region = NULL; + ventoy_img_chunk *chunk = g_chunk; + + length = sizeof(ventoy_image_location) + (g_img_chunk_num - 1) * sizeof(ventoy_image_disk_region); + + address = umalloc(length + 4096 * 2); + if (!address) + { + return 0; + } + + if (address % 4096) + { + address += 4096 - (address % 4096); + } + + param->chksum = 0; + param->vtoy_img_location_addr = user_to_phys(address, 0); + param->vtoy_img_location_len = length; + + /* update check sum */ + for (i = 0; i < sizeof(ventoy_os_param); i++) + { + chksum += *((uint8_t *)param + i); + } + param->chksum = (chksum == 0) ? 0 : (uint8_t)(0x100 - chksum); + + location = (ventoy_image_location *)(unsigned long)(address); + if (NULL == location) + { + return 0; + } + + memcpy(&location->guid, ¶m->guid, sizeof(ventoy_guid)); + location->image_sector_size = 2048; + location->disk_sector_size = g_chain->disk_sector_size; + location->region_count = g_img_chunk_num; + + region = location->regions; + + for (i = 0; i < g_img_chunk_num; i++) + { + region->image_sector_count = chunk->img_end_sector - chunk->img_start_sector + 1; + region->image_start_sector = chunk->img_start_sector; + region->disk_start_sector = chunk->disk_start_sector; + region++; + chunk++; + } + + return 0; +} + +int ventoy_boot_vdisk(void *data) +{ + uint8_t chksum = 0; + unsigned int i; + unsigned int drive; + + (void)data; + + ventoy_address.bufsize = offsetof ( typeof ( ventoy_address ), buffer_phys ); + + if (strstr(g_cmdline_copy, "debug")) + { + g_debug = 1; + printf("### ventoy chain boot begin... ###\n"); + ventoy_debug_pause(); + } + + g_chain = (ventoy_chain_head *)g_initrd_addr; + g_chunk = (ventoy_img_chunk *)((char *)g_chain + g_chain->img_chunk_offset); + g_img_chunk_num = g_chain->img_chunk_num; + g_disk_sector_size = g_chain->disk_sector_size; + g_cur_chunk = g_chunk; + + g_override_chunk = (ventoy_override_chunk *)((char *)g_chain + g_chain->override_chunk_offset); + g_override_chunk_num = g_chain->override_chunk_num; + + g_virt_chunk = (ventoy_virt_chunk *)((char *)g_chain + g_chain->virt_chunk_offset); + g_virt_chunk_num = g_chain->virt_chunk_num; + + if (g_debug) + { + for (i = 0; i < sizeof(ventoy_os_param); i++) + { + chksum += *((uint8_t *)(&(g_chain->os_param)) + i); + } + printf("os param checksum: 0x%x %s\n", g_chain->os_param.chksum, chksum ? "FAILED" : "SUCCESS"); + } + + ventoy_update_image_location(&(g_chain->os_param)); + + if (g_debug) + { + ventoy_dump_chain(g_chain); + } + + drive = ventoy_int13_hook(g_chain); + + if (g_debug) + { + printf("### ventoy chain boot before boot image ... ###\n"); + ventoy_debug_pause(); + } + + ventoy_int13_boot(drive, &(g_chain->os_param), g_cmdline_copy); + + if (g_debug) + { + printf("!!!!!!!!!! ventoy boot failed !!!!!!!!!!\n"); + ventoy_debug_pause(); + } + + return 0; +} + diff --git a/IPXE/ipxe-3fe683e/src/arch/x86/drivers/hyperv/hyperv.c b/IPXE/ipxe-3fe683e/src/arch/x86/drivers/hyperv/hyperv.c new file mode 100644 index 00000000..01e13c36 --- /dev/null +++ b/IPXE/ipxe-3fe683e/src/arch/x86/drivers/hyperv/hyperv.c @@ -0,0 +1,820 @@ +/* + * Copyright (C) 2014 Michael Brown . + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + * + * You can also choose to distribute this program under the terms of + * the Unmodified Binary Distribution Licence (as given in the file + * COPYING.UBDL), provided that you have satisfied its requirements. + */ + +FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL ); + +/** @file + * + * Hyper-V driver + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "hyperv.h" + +/** Maximum time to wait for a message response + * + * This is a policy decision. + */ +#define HV_MESSAGE_MAX_WAIT_MS 1000 + +/** Hyper-V timer frequency (fixed 10Mhz) */ +#define HV_TIMER_HZ 10000000 + +/** Hyper-V timer scale factor (used to avoid 64-bit division) */ +#define HV_TIMER_SHIFT 18 + +/** + * Convert a Hyper-V status code to an iPXE status code + * + * @v status Hyper-V status code + * @ret rc iPXE status code (before negation) + */ +#define EHV( status ) EPLATFORM ( EINFO_EPLATFORM, (status) ) + +/** + * Allocate zeroed pages + * + * @v hv Hyper-V hypervisor + * @v ... Page addresses to fill in, terminated by NULL + * @ret rc Return status code + */ +__attribute__ (( sentinel )) int +hv_alloc_pages ( struct hv_hypervisor *hv, ... ) { + va_list args; + void **page; + int i; + + /* Allocate and zero pages */ + va_start ( args, hv ); + for ( i = 0 ; ( ( page = va_arg ( args, void ** ) ) != NULL ); i++ ) { + *page = malloc_dma ( PAGE_SIZE, PAGE_SIZE ); + if ( ! *page ) + goto err_alloc; + memset ( *page, 0, PAGE_SIZE ); + } + va_end ( args ); + + return 0; + + err_alloc: + va_end ( args ); + va_start ( args, hv ); + for ( ; i >= 0 ; i-- ) { + page = va_arg ( args, void ** ); + free_dma ( *page, PAGE_SIZE ); + } + va_end ( args ); + return -ENOMEM; +} + +/** + * Free pages + * + * @v hv Hyper-V hypervisor + * @v ... Page addresses, terminated by NULL + */ +__attribute__ (( sentinel )) void +hv_free_pages ( struct hv_hypervisor *hv, ... ) { + va_list args; + void *page; + + va_start ( args, hv ); + while ( ( page = va_arg ( args, void * ) ) != NULL ) + free_dma ( page, PAGE_SIZE ); + va_end ( args ); +} + +/** + * Allocate message buffer + * + * @v hv Hyper-V hypervisor + * @ret rc Return status code + */ +static int hv_alloc_message ( struct hv_hypervisor *hv ) { + + /* Allocate buffer. Must be aligned to at least 8 bytes and + * must not cross a page boundary, so align on its own size. + */ + hv->message = malloc_dma ( sizeof ( *hv->message ), + sizeof ( *hv->message ) ); + if ( ! hv->message ) + return -ENOMEM; + + return 0; +} + +/** + * Free message buffer + * + * @v hv Hyper-V hypervisor + */ +static void hv_free_message ( struct hv_hypervisor *hv ) { + + /* Free buffer */ + free_dma ( hv->message, sizeof ( *hv->message ) ); +} + +/** + * Check whether or not we are running in Hyper-V + * + * @ret rc Return status code + */ +static int hv_check_hv ( void ) { + struct x86_features features; + uint32_t interface_id; + uint32_t discard_ebx; + uint32_t discard_ecx; + uint32_t discard_edx; + + /* Check for presence of a hypervisor (not necessarily Hyper-V) */ + x86_features ( &features ); + if ( ! ( features.intel.ecx & CPUID_FEATURES_INTEL_ECX_HYPERVISOR ) ) { + DBGC ( HV_INTERFACE_ID, "HV not running in a hypervisor\n" ); + return -ENODEV; + } + + /* Check that hypervisor is Hyper-V */ + cpuid ( HV_CPUID_INTERFACE_ID, 0, &interface_id, &discard_ebx, + &discard_ecx, &discard_edx ); + if ( interface_id != HV_INTERFACE_ID ) { + DBGC ( HV_INTERFACE_ID, "HV not running in Hyper-V (interface " + "ID %#08x)\n", interface_id ); + return -ENODEV; + } + + return 0; +} + +/** + * Check required features + * + * @v hv Hyper-V hypervisor + * @ret rc Return status code + */ +static int hv_check_features ( struct hv_hypervisor *hv ) { + uint32_t available; + uint32_t permissions; + uint32_t discard_ecx; + uint32_t discard_edx; + + /* Check that required features and privileges are available */ + cpuid ( HV_CPUID_FEATURES, 0, &available, &permissions, &discard_ecx, + &discard_edx ); + if ( ! ( available & HV_FEATURES_AVAIL_HYPERCALL_MSR ) ) { + DBGC ( hv, "HV %p has no hypercall MSRs (features %08x:%08x)\n", + hv, available, permissions ); + return -ENODEV; + } + if ( ! ( available & HV_FEATURES_AVAIL_SYNIC_MSR ) ) { + DBGC ( hv, "HV %p has no SynIC MSRs (features %08x:%08x)\n", + hv, available, permissions ); + return -ENODEV; + } + if ( ! ( permissions & HV_FEATURES_PERM_POST_MESSAGES ) ) { + DBGC ( hv, "HV %p cannot post messages (features %08x:%08x)\n", + hv, available, permissions ); + return -EACCES; + } + if ( ! ( permissions & HV_FEATURES_PERM_SIGNAL_EVENTS ) ) { + DBGC ( hv, "HV %p cannot signal events (features %08x:%08x)", + hv, available, permissions ); + return -EACCES; + } + + return 0; +} + +/** + * Check that Gen 2 UEFI firmware is not running + * + * @v hv Hyper-V hypervisor + * @ret rc Return status code + * + * We must not steal ownership from the Gen 2 UEFI firmware, since + * doing so will cause an immediate crash. Avoid this by checking for + * the guest OS identity known to be used by the Gen 2 UEFI firmware. + */ +static int hv_check_uefi ( struct hv_hypervisor *hv ) { + uint64_t guest_os_id; + + /* Check for UEFI firmware's guest OS identity */ + guest_os_id = rdmsr ( HV_X64_MSR_GUEST_OS_ID ); + if ( guest_os_id == HV_GUEST_OS_ID_UEFI ) { + DBGC ( hv, "HV %p is owned by UEFI firmware\n", hv ); + return -ENOTSUP; + } + + return 0; +} + +/** + * Map hypercall page + * + * @v hv Hyper-V hypervisor + */ +static void hv_map_hypercall ( struct hv_hypervisor *hv ) { + union { + struct { + uint32_t ebx; + uint32_t ecx; + uint32_t edx; + } __attribute__ (( packed )); + char text[ 13 /* "bbbbccccdddd" + NUL */ ]; + } vendor_id; + uint32_t build; + uint32_t version; + uint32_t discard_eax; + uint32_t discard_ecx; + uint32_t discard_edx; + uint64_t guest_os_id; + uint64_t hypercall; + + /* Report guest OS identity */ + guest_os_id = rdmsr ( HV_X64_MSR_GUEST_OS_ID ); + if ( guest_os_id != 0 ) { + DBGC ( hv, "HV %p guest OS ID MSR was %#08llx\n", + hv, guest_os_id ); + } + guest_os_id = HV_GUEST_OS_ID_IPXE; + DBGC2 ( hv, "HV %p guest OS ID MSR is %#08llx\n", hv, guest_os_id ); + wrmsr ( HV_X64_MSR_GUEST_OS_ID, guest_os_id ); + + /* Get hypervisor system identity (for debugging) */ + cpuid ( HV_CPUID_VENDOR_ID, 0, &discard_eax, &vendor_id.ebx, + &vendor_id.ecx, &vendor_id.edx ); + vendor_id.text[ sizeof ( vendor_id.text ) - 1 ] = '\0'; + cpuid ( HV_CPUID_HYPERVISOR_ID, 0, &build, &version, &discard_ecx, + &discard_edx ); + DBGC ( hv, "HV %p detected \"%s\" version %d.%d build %d\n", hv, + vendor_id.text, ( version >> 16 ), ( version & 0xffff ), build ); + + /* Map hypercall page */ + hypercall = rdmsr ( HV_X64_MSR_HYPERCALL ); + hypercall &= ( PAGE_SIZE - 1 ); + hypercall |= ( virt_to_phys ( hv->hypercall ) | HV_HYPERCALL_ENABLE ); + DBGC2 ( hv, "HV %p hypercall MSR is %#08llx\n", hv, hypercall ); + wrmsr ( HV_X64_MSR_HYPERCALL, hypercall ); +} + +/** + * Unmap hypercall page + * + * @v hv Hyper-V hypervisor + */ +static void hv_unmap_hypercall ( struct hv_hypervisor *hv ) { + uint64_t hypercall; + uint64_t guest_os_id; + + /* Unmap the hypercall page */ + hypercall = rdmsr ( HV_X64_MSR_HYPERCALL ); + hypercall &= ( ( PAGE_SIZE - 1 ) & ~HV_HYPERCALL_ENABLE ); + DBGC2 ( hv, "HV %p hypercall MSR is %#08llx\n", hv, hypercall ); + wrmsr ( HV_X64_MSR_HYPERCALL, hypercall ); + + /* Reset the guest OS identity */ + guest_os_id = 0; + DBGC2 ( hv, "HV %p guest OS ID MSR is %#08llx\n", hv, guest_os_id ); + wrmsr ( HV_X64_MSR_GUEST_OS_ID, guest_os_id ); +} + +/** + * Map synthetic interrupt controller + * + * @v hv Hyper-V hypervisor + */ +static void hv_map_synic ( struct hv_hypervisor *hv ) { + uint64_t simp; + uint64_t siefp; + uint64_t scontrol; + + /* Zero SynIC message and event pages */ + memset ( hv->synic.message, 0, PAGE_SIZE ); + memset ( hv->synic.event, 0, PAGE_SIZE ); + + /* Map SynIC message page */ + simp = rdmsr ( HV_X64_MSR_SIMP ); + simp &= ( PAGE_SIZE - 1 ); + simp |= ( virt_to_phys ( hv->synic.message ) | HV_SIMP_ENABLE ); + DBGC2 ( hv, "HV %p SIMP MSR is %#08llx\n", hv, simp ); + wrmsr ( HV_X64_MSR_SIMP, simp ); + + /* Map SynIC event page */ + siefp = rdmsr ( HV_X64_MSR_SIEFP ); + siefp &= ( PAGE_SIZE - 1 ); + siefp |= ( virt_to_phys ( hv->synic.event ) | HV_SIEFP_ENABLE ); + DBGC2 ( hv, "HV %p SIEFP MSR is %#08llx\n", hv, siefp ); + wrmsr ( HV_X64_MSR_SIEFP, siefp ); + + /* Enable SynIC */ + scontrol = rdmsr ( HV_X64_MSR_SCONTROL ); + scontrol |= HV_SCONTROL_ENABLE; + DBGC2 ( hv, "HV %p SCONTROL MSR is %#08llx\n", hv, scontrol ); + wrmsr ( HV_X64_MSR_SCONTROL, scontrol ); +} + +/** + * Unmap synthetic interrupt controller, leaving SCONTROL untouched + * + * @v hv Hyper-V hypervisor + */ +static void hv_unmap_synic_no_scontrol ( struct hv_hypervisor *hv ) { + uint64_t siefp; + uint64_t simp; + + /* Unmap SynIC event page */ + siefp = rdmsr ( HV_X64_MSR_SIEFP ); + siefp &= ( ( PAGE_SIZE - 1 ) & ~HV_SIEFP_ENABLE ); + DBGC2 ( hv, "HV %p SIEFP MSR is %#08llx\n", hv, siefp ); + wrmsr ( HV_X64_MSR_SIEFP, siefp ); + + /* Unmap SynIC message page */ + simp = rdmsr ( HV_X64_MSR_SIMP ); + simp &= ( ( PAGE_SIZE - 1 ) & ~HV_SIMP_ENABLE ); + DBGC2 ( hv, "HV %p SIMP MSR is %#08llx\n", hv, simp ); + wrmsr ( HV_X64_MSR_SIMP, simp ); +} + +/** + * Unmap synthetic interrupt controller + * + * @v hv Hyper-V hypervisor + */ +static void hv_unmap_synic ( struct hv_hypervisor *hv ) { + uint64_t scontrol; + + /* Disable SynIC */ + scontrol = rdmsr ( HV_X64_MSR_SCONTROL ); + scontrol &= ~HV_SCONTROL_ENABLE; + DBGC2 ( hv, "HV %p SCONTROL MSR is %#08llx\n", hv, scontrol ); + wrmsr ( HV_X64_MSR_SCONTROL, scontrol ); + + /* Unmap SynIC event and message pages */ + hv_unmap_synic_no_scontrol ( hv ); +} + +/** + * Enable synthetic interrupt + * + * @v hv Hyper-V hypervisor + * @v sintx Synthetic interrupt number + */ +void hv_enable_sint ( struct hv_hypervisor *hv, unsigned int sintx ) { + unsigned long msr = HV_X64_MSR_SINT ( sintx ); + uint64_t sint; + + /* Enable synthetic interrupt + * + * We have to enable the interrupt, otherwise messages will + * not be delivered (even though the documentation implies + * that polling for messages is possible). We enable AutoEOI + * and hook the interrupt to the obsolete IRQ13 (FPU + * exception) vector, which will be implemented as a no-op. + */ + sint = rdmsr ( msr ); + sint &= ~( HV_SINT_MASKED | HV_SINT_VECTOR_MASK ); + sint |= ( HV_SINT_AUTO_EOI | + HV_SINT_VECTOR ( IRQ_INT ( 13 /* See comment above */ ) ) ); + DBGC2 ( hv, "HV %p SINT%d MSR is %#08llx\n", hv, sintx, sint ); + wrmsr ( msr, sint ); +} + +/** + * Disable synthetic interrupt + * + * @v hv Hyper-V hypervisor + * @v sintx Synthetic interrupt number + */ +void hv_disable_sint ( struct hv_hypervisor *hv, unsigned int sintx ) { + unsigned long msr = HV_X64_MSR_SINT ( sintx ); + uint64_t sint; + + /* Do nothing if interrupt is already disabled */ + sint = rdmsr ( msr ); + if ( sint & HV_SINT_MASKED ) + return; + + /* Disable synthetic interrupt */ + sint &= ~HV_SINT_AUTO_EOI; + sint |= HV_SINT_MASKED; + DBGC2 ( hv, "HV %p SINT%d MSR is %#08llx\n", hv, sintx, sint ); + wrmsr ( msr, sint ); +} + +/** + * Post message + * + * @v hv Hyper-V hypervisor + * @v id Connection ID + * @v type Message type + * @v data Message + * @v len Length of message + * @ret rc Return status code + */ +int hv_post_message ( struct hv_hypervisor *hv, unsigned int id, + unsigned int type, const void *data, size_t len ) { + struct hv_post_message *msg = &hv->message->posted; + int status; + int rc; + + /* Sanity check */ + assert ( len <= sizeof ( msg->data ) ); + + /* Construct message */ + memset ( msg, 0, sizeof ( *msg ) ); + msg->id = cpu_to_le32 ( id ); + msg->type = cpu_to_le32 ( type ); + msg->len = cpu_to_le32 ( len ); + memcpy ( msg->data, data, len ); + DBGC2 ( hv, "HV %p connection %d posting message type %#08x:\n", + hv, id, type ); + DBGC2_HDA ( hv, 0, msg->data, len ); + + /* Post message */ + if ( ( status = hv_call ( hv, HV_POST_MESSAGE, msg, NULL ) ) != 0 ) { + rc = -EHV ( status ); + DBGC ( hv, "HV %p could not post message to %#08x: %s\n", + hv, id, strerror ( rc ) ); + return rc; + } + + return 0; +} + +/** + * Wait for received message + * + * @v hv Hyper-V hypervisor + * @v sintx Synthetic interrupt number + * @ret rc Return status code + */ +int hv_wait_for_message ( struct hv_hypervisor *hv, unsigned int sintx ) { + struct hv_message *msg = &hv->message->received; + struct hv_message *src = &hv->synic.message[sintx]; + unsigned int retries; + size_t len; + + /* Wait for message to arrive */ + for ( retries = 0 ; retries < HV_MESSAGE_MAX_WAIT_MS ; retries++ ) { + + /* Check for message */ + if ( src->type ) { + + /* Copy message */ + memset ( msg, 0, sizeof ( *msg ) ); + len = src->len; + assert ( len <= sizeof ( *msg ) ); + memcpy ( msg, src, + ( offsetof ( typeof ( *msg ), data ) + len ) ); + DBGC2 ( hv, "HV %p SINT%d received message type " + "%#08x:\n", hv, sintx, + le32_to_cpu ( msg->type ) ); + DBGC2_HDA ( hv, 0, msg->data, len ); + + /* Consume message */ + src->type = 0; + + return 0; + } + + /* Trigger message delivery */ + wrmsr ( HV_X64_MSR_EOM, 0 ); + + /* Delay */ + mdelay ( 1 ); + } + + DBGC ( hv, "HV %p SINT%d timed out waiting for message\n", + hv, sintx ); + return -ETIMEDOUT; +} + +/** + * Signal event + * + * @v hv Hyper-V hypervisor + * @v id Connection ID + * @v flag Flag number + * @ret rc Return status code + */ +int hv_signal_event ( struct hv_hypervisor *hv, unsigned int id, + unsigned int flag ) { + struct hv_signal_event *event = &hv->message->signalled; + int status; + int rc; + + /* Construct event */ + memset ( event, 0, sizeof ( *event ) ); + event->id = cpu_to_le32 ( id ); + event->flag = cpu_to_le16 ( flag ); + + /* Signal event */ + if ( ( status = hv_call ( hv, HV_SIGNAL_EVENT, event, NULL ) ) != 0 ) { + rc = -EHV ( status ); + DBGC ( hv, "HV %p could not signal event to %#08x: %s\n", + hv, id, strerror ( rc ) ); + return rc; + } + + return 0; +} + +/** + * Probe root device + * + * @v rootdev Root device + * @ret rc Return status code + */ +static int hv_probe ( struct root_device *rootdev ) { + struct hv_hypervisor *hv; + int rc; + + /* Check we are running in Hyper-V */ + if ( ( rc = hv_check_hv() ) != 0 ) + goto err_check_hv; + + /* Allocate and initialise structure */ + hv = zalloc ( sizeof ( *hv ) ); + if ( ! hv ) { + rc = -ENOMEM; + goto err_alloc; + } + + /* Check features */ + if ( ( rc = hv_check_features ( hv ) ) != 0 ) + goto err_check_features; + + /* Check that Gen 2 UEFI firmware is not running */ + if ( ( rc = hv_check_uefi ( hv ) ) != 0 ) + goto err_check_uefi; + + /* Allocate pages */ + if ( ( rc = hv_alloc_pages ( hv, &hv->hypercall, &hv->synic.message, + &hv->synic.event, NULL ) ) != 0 ) + goto err_alloc_pages; + + /* Allocate message buffer */ + if ( ( rc = hv_alloc_message ( hv ) ) != 0 ) + goto err_alloc_message; + + /* Map hypercall page */ + hv_map_hypercall ( hv ); + + /* Map synthetic interrupt controller */ + hv_map_synic ( hv ); + + /* Probe Hyper-V devices */ + if ( ( rc = vmbus_probe ( hv, &rootdev->dev ) ) != 0 ) + goto err_vmbus_probe; + + rootdev_set_drvdata ( rootdev, hv ); + return 0; + + vmbus_remove ( hv, &rootdev->dev ); + err_vmbus_probe: + hv_unmap_synic ( hv ); + hv_unmap_hypercall ( hv ); + hv_free_message ( hv ); + err_alloc_message: + hv_free_pages ( hv, hv->hypercall, hv->synic.message, hv->synic.event, + NULL ); + err_alloc_pages: + err_check_uefi: + err_check_features: + free ( hv ); + err_alloc: + err_check_hv: + return rc; +} + +/** + * Remove root device + * + * @v rootdev Root device + */ +static void hv_remove ( struct root_device *rootdev ) { + struct hv_hypervisor *hv = rootdev_get_drvdata ( rootdev ); + + vmbus_remove ( hv, &rootdev->dev ); + hv_unmap_synic ( hv ); + hv_unmap_hypercall ( hv ); + hv_free_message ( hv ); + hv_free_pages ( hv, hv->hypercall, hv->synic.message, hv->synic.event, + NULL ); + free ( hv ); + rootdev_set_drvdata ( rootdev, NULL ); +} + +/** Hyper-V root device driver */ +static struct root_driver hv_root_driver = { + .probe = hv_probe, + .remove = hv_remove, +}; + +/** Hyper-V root device */ +struct root_device hv_root_device __root_device = { + .dev = { .name = "Hyper-V" }, + .driver = &hv_root_driver, +}; + +/** + * Quiesce system + * + */ +static void hv_quiesce ( void ) { + struct hv_hypervisor *hv = rootdev_get_drvdata ( &hv_root_device ); + unsigned int i; + + /* Do nothing if we are not running in Hyper-V */ + if ( ! hv ) + return; + + /* The "enlightened" portions of the Windows Server 2016 boot + * process will not cleanly take ownership of an active + * Hyper-V connection. Experimentation shows that the minimum + * requirement is that we disable the SynIC message page + * (i.e. zero the SIMP MSR). + * + * We cannot perform a full shutdown of the Hyper-V + * connection. Experimentation shows that if we disable the + * SynIC (i.e. zero the SCONTROL MSR) then Windows Server 2016 + * will enter an indefinite wait loop. + * + * Attempt to create a safe handover environment by resetting + * all MSRs except for SCONTROL. + * + * Note that we do not shut down our VMBus devices, since we + * may need to unquiesce the system and continue operation. + */ + + /* Disable all synthetic interrupts */ + for ( i = 0 ; i <= HV_SINT_MAX ; i++ ) + hv_disable_sint ( hv, i ); + + /* Unmap synthetic interrupt controller, leaving SCONTROL + * enabled (see above). + */ + hv_unmap_synic_no_scontrol ( hv ); + + /* Unmap hypercall page */ + hv_unmap_hypercall ( hv ); + + DBGC ( hv, "HV %p quiesced\n", hv ); +} + +/** + * Unquiesce system + * + */ +static void hv_unquiesce ( void ) { + struct hv_hypervisor *hv = rootdev_get_drvdata ( &hv_root_device ); + uint64_t simp; + int rc; + + /* Do nothing if we are not running in Hyper-V */ + if ( ! hv ) + return; + + /* Experimentation shows that the "enlightened" portions of + * Windows Server 2016 will break our Hyper-V connection at + * some point during a SAN boot. Surprisingly it does not + * change the guest OS ID MSR, but it does leave the SynIC + * message page disabled. + * + * Our own explicit quiescing procedure will also disable the + * SynIC message page. We can therefore use the SynIC message + * page enable bit as a heuristic to determine when we need to + * reestablish our Hyper-V connection. + */ + simp = rdmsr ( HV_X64_MSR_SIMP ); + if ( simp & HV_SIMP_ENABLE ) + return; + + /* Remap hypercall page */ + hv_map_hypercall ( hv ); + + /* Remap synthetic interrupt controller */ + hv_map_synic ( hv ); + + /* Reset Hyper-V devices */ + if ( ( rc = vmbus_reset ( hv, &hv_root_device.dev ) ) != 0 ) { + DBGC ( hv, "HV %p could not unquiesce: %s\n", + hv, strerror ( rc ) ); + /* Nothing we can do */ + return; + } +} + +/** Hyper-V quiescer */ +struct quiescer hv_quiescer __quiescer = { + .quiesce = hv_quiesce, + .unquiesce = hv_unquiesce, +}; + +/** + * Probe timer + * + * @ret rc Return status code + */ +static int hv_timer_probe ( void ) { + uint32_t available; + uint32_t discard_ebx; + uint32_t discard_ecx; + uint32_t discard_edx; + int rc; + + /* Check we are running in Hyper-V */ + if ( ( rc = hv_check_hv() ) != 0 ) + return rc; + + /* Check for available reference counter */ + cpuid ( HV_CPUID_FEATURES, 0, &available, &discard_ebx, &discard_ecx, + &discard_edx ); + if ( ! ( available & HV_FEATURES_AVAIL_TIME_REF_COUNT_MSR ) ) { + DBGC ( HV_INTERFACE_ID, "HV has no time reference counter\n" ); + return -ENODEV; + } + + return 0; +} + +/** + * Get current system time in ticks + * + * @ret ticks Current time, in ticks + */ +static unsigned long hv_currticks ( void ) { + + /* Calculate time using a combination of bit shifts and + * multiplication (to avoid a 64-bit division). + */ + return ( ( rdmsr ( HV_X64_MSR_TIME_REF_COUNT ) >> HV_TIMER_SHIFT ) * + ( TICKS_PER_SEC / ( HV_TIMER_HZ >> HV_TIMER_SHIFT ) ) ); +} + +/** + * Delay for a fixed number of microseconds + * + * @v usecs Number of microseconds for which to delay + */ +static void hv_udelay ( unsigned long usecs ) { + uint32_t start; + uint32_t elapsed; + uint32_t threshold; + + /* Spin until specified number of 10MHz ticks have elapsed */ + start = rdmsr ( HV_X64_MSR_TIME_REF_COUNT ); + threshold = ( usecs * ( HV_TIMER_HZ / 1000000 ) ); + do { + elapsed = ( rdmsr ( HV_X64_MSR_TIME_REF_COUNT ) - start ); + } while ( elapsed < threshold ); +} + +/** Hyper-V timer */ +struct timer hv_timer __timer ( TIMER_PREFERRED ) = { + .name = "Hyper-V", + .probe = hv_timer_probe, + .currticks = hv_currticks, + .udelay = hv_udelay, +}; + +/* Drag in objects via hv_root_device */ +REQUIRING_SYMBOL ( hv_root_device ); + +/* Drag in netvsc driver */ +//REQUIRE_OBJECT ( netvsc ); diff --git a/IPXE/ipxe-3fe683e/src/arch/x86/drivers/xen/hvm.c b/IPXE/ipxe-3fe683e/src/arch/x86/drivers/xen/hvm.c new file mode 100644 index 00000000..1d9188e3 --- /dev/null +++ b/IPXE/ipxe-3fe683e/src/arch/x86/drivers/xen/hvm.c @@ -0,0 +1,503 @@ +/* + * Copyright (C) 2014 Michael Brown . + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + * + * You can also choose to distribute this program under the terms of + * the Unmodified Binary Distribution Licence (as given in the file + * COPYING.UBDL), provided that you have satisfied its requirements. + */ + +FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL ); + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "hvm.h" + +/** @file + * + * Xen HVM driver + * + */ + +/** + * Get CPUID base + * + * @v hvm HVM device + * @ret rc Return status code + */ +static int hvm_cpuid_base ( struct hvm_device *hvm ) { + struct { + uint32_t ebx; + uint32_t ecx; + uint32_t edx; + } __attribute__ (( packed )) signature; + uint32_t base; + uint32_t version; + uint32_t discard_eax; + uint32_t discard_ebx; + uint32_t discard_ecx; + uint32_t discard_edx; + + /* Scan for magic signature */ + for ( base = HVM_CPUID_MIN ; base <= HVM_CPUID_MAX ; + base += HVM_CPUID_STEP ) { + cpuid ( base, 0, &discard_eax, &signature.ebx, &signature.ecx, + &signature.edx ); + if ( memcmp ( &signature, HVM_CPUID_MAGIC, + sizeof ( signature ) ) == 0 ) { + hvm->cpuid_base = base; + cpuid ( ( base + HVM_CPUID_VERSION ), 0, &version, + &discard_ebx, &discard_ecx, &discard_edx ); + DBGC2 ( hvm, "HVM using CPUID base %#08x (v%d.%d)\n", + base, ( version >> 16 ), ( version & 0xffff ) ); + return 0; + } + } + + DBGC ( hvm, "HVM could not find hypervisor\n" ); + return -ENODEV; +} + +/** + * Map hypercall page(s) + * + * @v hvm HVM device + * @ret rc Return status code + */ +static int hvm_map_hypercall ( struct hvm_device *hvm ) { + uint32_t pages; + uint32_t msr; + uint32_t discard_ecx; + uint32_t discard_edx; + physaddr_t hypercall_phys; + uint32_t version; + static xen_extraversion_t extraversion; + int xenrc; + int rc; + + /* Get number of hypercall pages and MSR to use */ + cpuid ( ( hvm->cpuid_base + HVM_CPUID_PAGES ), 0, &pages, &msr, + &discard_ecx, &discard_edx ); + + /* Allocate pages */ + hvm->hypercall_len = ( pages * PAGE_SIZE ); + hvm->xen.hypercall = malloc_dma ( hvm->hypercall_len, PAGE_SIZE ); + if ( ! hvm->xen.hypercall ) { + DBGC ( hvm, "HVM could not allocate %d hypercall page(s)\n", + pages ); + return -ENOMEM; + } + hypercall_phys = virt_to_phys ( hvm->xen.hypercall ); + DBGC2 ( hvm, "HVM hypercall page(s) at [%#08lx,%#08lx) via MSR %#08x\n", + hypercall_phys, ( hypercall_phys + hvm->hypercall_len ), msr ); + + /* Write to MSR */ + wrmsr ( msr, hypercall_phys ); + + /* Check that hypercall mechanism is working */ + version = xenver_version ( &hvm->xen ); + if ( ( xenrc = xenver_extraversion ( &hvm->xen, &extraversion ) ) != 0){ + rc = -EXEN ( xenrc ); + DBGC ( hvm, "HVM could not get extraversion: %s\n", + strerror ( rc ) ); + return rc; + } + DBGC2 ( hvm, "HVM found Xen version %d.%d%s\n", + ( version >> 16 ), ( version & 0xffff ) , extraversion ); + + return 0; +} + +/** + * Unmap hypercall page(s) + * + * @v hvm HVM device + */ +static void hvm_unmap_hypercall ( struct hvm_device *hvm ) { + + /* Free pages */ + free_dma ( hvm->xen.hypercall, hvm->hypercall_len ); +} + +/** + * Allocate and map MMIO space + * + * @v hvm HVM device + * @v space Source mapping space + * @v len Length (must be a multiple of PAGE_SIZE) + * @ret mmio MMIO space address, or NULL on error + */ +static void * hvm_ioremap ( struct hvm_device *hvm, unsigned int space, + size_t len ) { + struct xen_add_to_physmap add; + struct xen_remove_from_physmap remove; + unsigned int pages = ( len / PAGE_SIZE ); + physaddr_t mmio_phys; + unsigned int i; + void *mmio; + int xenrc; + int rc; + + /* Sanity check */ + assert ( ( len % PAGE_SIZE ) == 0 ); + + /* Check for available space */ + if ( ( hvm->mmio_offset + len ) > hvm->mmio_len ) { + DBGC ( hvm, "HVM could not allocate %zd bytes of MMIO space " + "(%zd of %zd remaining)\n", len, + ( hvm->mmio_len - hvm->mmio_offset ), hvm->mmio_len ); + goto err_no_space; + } + + /* Map this space */ + mmio = ioremap ( ( hvm->mmio + hvm->mmio_offset ), len ); + if ( ! mmio ) { + DBGC ( hvm, "HVM could not map MMIO space [%08lx,%08lx)\n", + ( hvm->mmio + hvm->mmio_offset ), + ( hvm->mmio + hvm->mmio_offset + len ) ); + goto err_ioremap; + } + mmio_phys = virt_to_phys ( mmio ); + + /* Add to physical address space */ + for ( i = 0 ; i < pages ; i++ ) { + add.domid = DOMID_SELF; + add.idx = i; + add.space = space; + add.gpfn = ( ( mmio_phys / PAGE_SIZE ) + i ); + if ( ( xenrc = xenmem_add_to_physmap ( &hvm->xen, &add ) ) !=0){ + rc = -EXEN ( xenrc ); + DBGC ( hvm, "HVM could not add space %d idx %d at " + "[%08lx,%08lx): %s\n", space, i, + ( mmio_phys + ( i * PAGE_SIZE ) ), + ( mmio_phys + ( ( i + 1 ) * PAGE_SIZE ) ), + strerror ( rc ) ); + goto err_add_to_physmap; + } + } + + /* Update offset */ + hvm->mmio_offset += len; + + return mmio; + + i = pages; + err_add_to_physmap: + for ( i-- ; ( signed int ) i >= 0 ; i-- ) { + remove.domid = DOMID_SELF; + add.gpfn = ( ( mmio_phys / PAGE_SIZE ) + i ); + xenmem_remove_from_physmap ( &hvm->xen, &remove ); + } + iounmap ( mmio ); + err_ioremap: + err_no_space: + return NULL; +} + +/** + * Unmap MMIO space + * + * @v hvm HVM device + * @v mmio MMIO space address + * @v len Length (must be a multiple of PAGE_SIZE) + */ +static void hvm_iounmap ( struct hvm_device *hvm, void *mmio, size_t len ) { + struct xen_remove_from_physmap remove; + physaddr_t mmio_phys = virt_to_phys ( mmio ); + unsigned int pages = ( len / PAGE_SIZE ); + unsigned int i; + int xenrc; + int rc; + + /* Unmap this space */ + iounmap ( mmio ); + + /* Remove from physical address space */ + for ( i = 0 ; i < pages ; i++ ) { + remove.domid = DOMID_SELF; + remove.gpfn = ( ( mmio_phys / PAGE_SIZE ) + i ); + if ( ( xenrc = xenmem_remove_from_physmap ( &hvm->xen, + &remove ) ) != 0 ) { + rc = -EXEN ( xenrc ); + DBGC ( hvm, "HVM could not remove space [%08lx,%08lx): " + "%s\n", ( mmio_phys + ( i * PAGE_SIZE ) ), + ( mmio_phys + ( ( i + 1 ) * PAGE_SIZE ) ), + strerror ( rc ) ); + /* Nothing we can do about this */ + } + } +} + +/** + * Map shared info page + * + * @v hvm HVM device + * @ret rc Return status code + */ +static int hvm_map_shared_info ( struct hvm_device *hvm ) { + physaddr_t shared_info_phys; + int rc; + + /* Map shared info page */ + hvm->xen.shared = hvm_ioremap ( hvm, XENMAPSPACE_shared_info, + PAGE_SIZE ); + if ( ! hvm->xen.shared ) { + rc = -ENOMEM; + goto err_alloc; + } + shared_info_phys = virt_to_phys ( hvm->xen.shared ); + DBGC2 ( hvm, "HVM shared info page at [%#08lx,%#08lx)\n", + shared_info_phys, ( shared_info_phys + PAGE_SIZE ) ); + + /* Sanity check */ + DBGC2 ( hvm, "HVM wallclock time is %d\n", + readl ( &hvm->xen.shared->wc_sec ) ); + + return 0; + + hvm_iounmap ( hvm, hvm->xen.shared, PAGE_SIZE ); + err_alloc: + return rc; +} + +/** + * Unmap shared info page + * + * @v hvm HVM device + */ +static void hvm_unmap_shared_info ( struct hvm_device *hvm ) { + + /* Unmap shared info page */ + hvm_iounmap ( hvm, hvm->xen.shared, PAGE_SIZE ); +} + +/** + * Map grant table + * + * @v hvm HVM device + * @ret rc Return status code + */ +static int hvm_map_grant ( struct hvm_device *hvm ) { + physaddr_t grant_phys; + int rc; + + /* Initialise grant table */ + if ( ( rc = xengrant_init ( &hvm->xen ) ) != 0 ) { + DBGC ( hvm, "HVM could not initialise grant table: %s\n", + strerror ( rc ) ); + return rc; + } + + /* Map grant table */ + hvm->xen.grant.table = hvm_ioremap ( hvm, XENMAPSPACE_grant_table, + hvm->xen.grant.len ); + if ( ! hvm->xen.grant.table ) + return -ENODEV; + + grant_phys = virt_to_phys ( hvm->xen.grant.table ); + DBGC2 ( hvm, "HVM mapped grant table at [%08lx,%08lx)\n", + grant_phys, ( grant_phys + hvm->xen.grant.len ) ); + return 0; +} + +/** + * Unmap grant table + * + * @v hvm HVM device + */ +static void hvm_unmap_grant ( struct hvm_device *hvm ) { + + /* Unmap grant table */ + hvm_iounmap ( hvm, hvm->xen.grant.table, hvm->xen.grant.len ); +} + +/** + * Map XenStore + * + * @v hvm HVM device + * @ret rc Return status code + */ +static int hvm_map_xenstore ( struct hvm_device *hvm ) { + uint64_t xenstore_evtchn; + uint64_t xenstore_pfn; + physaddr_t xenstore_phys; + char *name; + int xenrc; + int rc; + + /* Get XenStore event channel */ + if ( ( xenrc = xen_hvm_get_param ( &hvm->xen, HVM_PARAM_STORE_EVTCHN, + &xenstore_evtchn ) ) != 0 ) { + rc = -EXEN ( xenrc ); + DBGC ( hvm, "HVM could not get XenStore event channel: %s\n", + strerror ( rc ) ); + return rc; + } + hvm->xen.store.port = xenstore_evtchn; + + /* Get XenStore PFN */ + if ( ( xenrc = xen_hvm_get_param ( &hvm->xen, HVM_PARAM_STORE_PFN, + &xenstore_pfn ) ) != 0 ) { + rc = -EXEN ( xenrc ); + DBGC ( hvm, "HVM could not get XenStore PFN: %s\n", + strerror ( rc ) ); + return rc; + } + xenstore_phys = ( xenstore_pfn * PAGE_SIZE ); + + /* Map XenStore */ + hvm->xen.store.intf = ioremap ( xenstore_phys, PAGE_SIZE ); + if ( ! hvm->xen.store.intf ) { + DBGC ( hvm, "HVM could not map XenStore at [%08lx,%08lx)\n", + xenstore_phys, ( xenstore_phys + PAGE_SIZE ) ); + return -ENODEV; + } + DBGC2 ( hvm, "HVM mapped XenStore at [%08lx,%08lx) with event port " + "%d\n", xenstore_phys, ( xenstore_phys + PAGE_SIZE ), + hvm->xen.store.port ); + + /* Check that XenStore is working */ + if ( ( rc = xenstore_read ( &hvm->xen, &name, "name", NULL ) ) != 0 ) { + DBGC ( hvm, "HVM could not read domain name: %s\n", + strerror ( rc ) ); + return rc; + } + DBGC2 ( hvm, "HVM running in domain \"%s\"\n", name ); + free ( name ); + + return 0; +} + +/** + * Unmap XenStore + * + * @v hvm HVM device + */ +static void hvm_unmap_xenstore ( struct hvm_device *hvm ) { + + /* Unmap XenStore */ + iounmap ( hvm->xen.store.intf ); +} + +/** + * Probe PCI device + * + * @v pci PCI device + * @ret rc Return status code + */ +static int hvm_probe ( struct pci_device *pci ) { + struct hvm_device *hvm; + int rc; + + /* Allocate and initialise structure */ + hvm = zalloc ( sizeof ( *hvm ) ); + if ( ! hvm ) { + rc = -ENOMEM; + goto err_alloc; + } + hvm->mmio = pci_bar_start ( pci, HVM_MMIO_BAR ); + hvm->mmio_len = pci_bar_size ( pci, HVM_MMIO_BAR ); + DBGC2 ( hvm, "HVM has MMIO space [%08lx,%08lx)\n", + hvm->mmio, ( hvm->mmio + hvm->mmio_len ) ); + + /* Fix up PCI device */ + adjust_pci_device ( pci ); + + /* Attach to hypervisor */ + if ( ( rc = hvm_cpuid_base ( hvm ) ) != 0 ) + goto err_cpuid_base; + if ( ( rc = hvm_map_hypercall ( hvm ) ) != 0 ) + goto err_map_hypercall; + if ( ( rc = hvm_map_shared_info ( hvm ) ) != 0 ) + goto err_map_shared_info; + if ( ( rc = hvm_map_grant ( hvm ) ) != 0 ) + goto err_map_grant; + if ( ( rc = hvm_map_xenstore ( hvm ) ) != 0 ) + goto err_map_xenstore; + + /* Probe Xen devices */ + if ( ( rc = xenbus_probe ( &hvm->xen, &pci->dev ) ) != 0 ) { + DBGC ( hvm, "HVM could not probe Xen bus: %s\n", + strerror ( rc ) ); + goto err_xenbus_probe; + } + + pci_set_drvdata ( pci, hvm ); + return 0; + + xenbus_remove ( &hvm->xen, &pci->dev ); + err_xenbus_probe: + hvm_unmap_xenstore ( hvm ); + err_map_xenstore: + hvm_unmap_grant ( hvm ); + err_map_grant: + hvm_unmap_shared_info ( hvm ); + err_map_shared_info: + hvm_unmap_hypercall ( hvm ); + err_map_hypercall: + err_cpuid_base: + free ( hvm ); + err_alloc: + return rc; +} + +/** + * Remove PCI device + * + * @v pci PCI device + */ +static void hvm_remove ( struct pci_device *pci ) { + struct hvm_device *hvm = pci_get_drvdata ( pci ); + + xenbus_remove ( &hvm->xen, &pci->dev ); + hvm_unmap_xenstore ( hvm ); + hvm_unmap_grant ( hvm ); + hvm_unmap_shared_info ( hvm ); + hvm_unmap_hypercall ( hvm ); + free ( hvm ); +} + +/** PCI device IDs */ +static struct pci_device_id hvm_ids[] = { + PCI_ROM ( 0x5853, 0x0001, "hvm", "hvm", 0 ), + PCI_ROM ( 0x5853, 0x0002, "hvm2", "hvm2", 0 ), +}; + +/** PCI driver */ +struct pci_driver hvm_driver __pci_driver = { + .ids = hvm_ids, + .id_count = ( sizeof ( hvm_ids ) / sizeof ( hvm_ids[0] ) ), + .probe = hvm_probe, + .remove = hvm_remove, +}; + +/* Drag in objects via hvm_driver */ +REQUIRING_SYMBOL ( hvm_driver ); + +/* Drag in netfront driver */ +//REQUIRE_OBJECT ( netfront ); diff --git a/IPXE/ipxe-3fe683e/src/arch/x86/interface/pcbios/hidemem.c b/IPXE/ipxe-3fe683e/src/arch/x86/interface/pcbios/hidemem.c new file mode 100644 index 00000000..a8085afd --- /dev/null +++ b/IPXE/ipxe-3fe683e/src/arch/x86/interface/pcbios/hidemem.c @@ -0,0 +1,238 @@ +/* Copyright (C) 2006 Michael Brown . + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of the + * License, or any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + * + * You can also choose to distribute this program under the terms of + * the Unmodified Binary Distribution Licence (as given in the file + * COPYING.UBDL), provided that you have satisfied its requirements. + */ + +FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL ); + +#include +#include +#include +#include +#include +#include +#include +#include + +/** Set to true if you want to test a fake E820 map */ +#define FAKE_E820 0 + +/** Alignment for hidden memory regions */ +#define ALIGN_HIDDEN 4096 /* 4kB page alignment should be enough */ + +/** + * A hidden region of iPXE + * + * This represents a region that will be edited out of the system's + * memory map. + * + * This structure is accessed by assembly code, so must not be + * changed. + */ +struct hidden_region { + /** Physical start address */ + uint64_t start; + /** Physical end address */ + uint64_t end; +}; + +/** Hidden base memory */ +extern struct hidden_region __data16 ( hidemem_base ); +#define hidemem_base __use_data16 ( hidemem_base ) + +/** Hidden umalloc memory */ +extern struct hidden_region __data16 ( hidemem_umalloc ); +#define hidemem_umalloc __use_data16 ( hidemem_umalloc ) + +/** Hidden text memory */ +extern struct hidden_region __data16 ( hidemem_textdata ); +#define hidemem_textdata __use_data16 ( hidemem_textdata ) + +/** Assembly routine in e820mangler.S */ +extern void int15(); + +/** Vector for storing original INT 15 handler */ +extern struct segoff __text16 ( int15_vector ); +#define int15_vector __use_text16 ( int15_vector ) + +/* The linker defines these symbols for us */ +extern char _textdata[]; +extern char _etextdata[]; +extern char _text16_memsz[]; +#define _text16_memsz ( ( size_t ) _text16_memsz ) +extern char _data16_memsz[]; +#define _data16_memsz ( ( size_t ) _data16_memsz ) + +/** + * Hide region of memory from system memory map + * + * @v region Hidden memory region + * @v start Start of region + * @v end End of region + */ +static void hide_region ( struct hidden_region *region, + physaddr_t start, physaddr_t end ) { + + /* Some operating systems get a nasty shock if a region of the + * E820 map seems to start on a non-page boundary. Make life + * safer by rounding out our edited region. + */ + region->start = ( start & ~( ALIGN_HIDDEN - 1 ) ); + region->end = ( ( end + ALIGN_HIDDEN - 1 ) & ~( ALIGN_HIDDEN - 1 ) ); + + DBG ( "Hiding region [%llx,%llx)\n", region->start, region->end ); +} + +/** + * Hide used base memory + * + */ +void hide_basemem ( void ) { + /* Hide from the top of free base memory to 640kB. Don't use + * hide_region(), because we don't want this rounded to the + * nearest page boundary. + */ + hidemem_base.start = ( get_fbms() * 1024 ); +} + +/** + * Hide umalloc() region + * + */ +void hide_umalloc ( physaddr_t start, physaddr_t end ) { + assert ( end <= virt_to_phys ( _textdata ) ); + hide_region ( &hidemem_umalloc, start, end ); +} + +/** + * Hide .text and .data + * + */ +void hide_textdata ( void ) { +/* Deleted by longpanda */ +#if 0 + hide_region ( &hidemem_textdata, virt_to_phys ( _textdata ), + virt_to_phys ( _etextdata ) ); +#endif +} + +/** + * Hide Etherboot + * + * Installs an INT 15 handler to edit Etherboot out of the memory map + * returned by the BIOS. + */ +static void hide_etherboot ( void ) { + struct memory_map memmap; + unsigned int rm_ds_top; + unsigned int rm_cs_top; + unsigned int fbms; + + /* Dump memory map before mangling */ + DBG ( "Hiding iPXE from system memory map\n" ); + get_memmap ( &memmap ); + + /* Hook in fake E820 map, if we're testing one */ + if ( FAKE_E820 ) { + DBG ( "Hooking in fake E820 map\n" ); + fake_e820(); + get_memmap ( &memmap ); + } + + /* Initialise the hidden regions */ + hide_basemem(); + hide_umalloc ( virt_to_phys ( _textdata ), virt_to_phys ( _textdata ) ); + hide_textdata(); + + /* Some really moronic BIOSes bring up the PXE stack via the + * UNDI loader entry point and then don't bother to unload it + * before overwriting the code and data segments. If this + * happens, we really don't want to leave INT 15 hooked, + * because that will cause any loaded OS to die horribly as + * soon as it attempts to fetch the system memory map. + * + * We use a heuristic to guess whether or not we are being + * loaded sensibly. + */ + rm_cs_top = ( ( ( rm_cs << 4 ) + _text16_memsz + 1024 - 1 ) >> 10 ); + rm_ds_top = ( ( ( rm_ds << 4 ) + _data16_memsz + 1024 - 1 ) >> 10 ); + fbms = get_fbms(); + if ( ( rm_cs_top < fbms ) && ( rm_ds_top < fbms ) ) { + DBG ( "Detected potentially unsafe UNDI load at CS=%04x " + "DS=%04x FBMS=%dkB\n", rm_cs, rm_ds, fbms ); + DBG ( "Disabling INT 15 memory hiding\n" ); + return; + } + + /* Hook INT 15 */ + hook_bios_interrupt ( 0x15, ( intptr_t ) int15, &int15_vector ); + + /* Dump memory map after mangling */ + DBG ( "Hidden iPXE from system memory map\n" ); + get_memmap ( &memmap ); +} + +/** + * Unhide Etherboot + * + * Uninstalls the INT 15 handler installed by hide_etherboot(), if + * possible. + */ +static void unhide_etherboot ( int flags __unused ) { + struct memory_map memmap; + int rc; + + /* If we have more than one hooked interrupt at this point, it + * means that some other vector is still hooked, in which case + * we can't safely unhook INT 15 because we need to keep our + * memory protected. (We expect there to be at least one + * hooked interrupt, because INT 15 itself is still hooked). + */ + if ( hooked_bios_interrupts > 1 ) { + DBG ( "Cannot unhide: %d interrupt vectors still hooked\n", + hooked_bios_interrupts ); + return; + } + + /* Try to unhook INT 15 */ + if ( ( rc = unhook_bios_interrupt ( 0x15, ( intptr_t ) int15, + &int15_vector ) ) != 0 ) { + DBG ( "Cannot unhook INT15: %s\n", strerror ( rc ) ); + /* Leave it hooked; there's nothing else we can do, + * and it should be intrinsically safe (though + * wasteful of RAM). + */ + } + + /* Unhook fake E820 map, if used */ + if ( FAKE_E820 ) + unfake_e820(); + + /* Dump memory map after unhiding */ + DBG ( "Unhidden iPXE from system memory map\n" ); + get_memmap ( &memmap ); +} + +/** Hide Etherboot startup function */ +struct startup_fn hide_etherboot_startup_fn __startup_fn ( STARTUP_EARLY ) = { + .name = "hidemem", + .startup = hide_etherboot, + .shutdown = unhide_etherboot, +}; diff --git a/IPXE/ipxe-3fe683e/src/arch/x86/interface/pcbios/int13.c b/IPXE/ipxe-3fe683e/src/arch/x86/interface/pcbios/int13.c new file mode 100644 index 00000000..fe8c4b42 --- /dev/null +++ b/IPXE/ipxe-3fe683e/src/arch/x86/interface/pcbios/int13.c @@ -0,0 +1,53 @@ +/* + * Copyright (C) 2010 Michael Brown . + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of the + * License, or any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + * + * You can also choose to distribute this program under the terms of + * the Unmodified Binary Distribution Licence (as given in the file + * COPYING.UBDL), provided that you have satisfied its requirements. + */ + +FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL ); + +#include +#include + +static int null_san_hook ( unsigned int drive __unused, + struct uri **uris __unused, + unsigned int count __unused, + unsigned int flags __unused ) { + return -EOPNOTSUPP; +} + +static void null_san_unhook ( unsigned int drive __unused ) { + /* Do nothing */ +} + +static int null_san_boot ( unsigned int drive __unused, + const char *filename __unused ) { + return -EOPNOTSUPP; +} + +static int null_san_describe ( void ) { + return -EOPNOTSUPP; +} + +PROVIDE_SANBOOT ( pcbios, san_hook, null_san_hook ); +PROVIDE_SANBOOT ( pcbios, san_unhook, null_san_unhook ); +PROVIDE_SANBOOT ( pcbios, san_boot, null_san_boot ); +PROVIDE_SANBOOT ( pcbios, san_describe, null_san_describe ); + diff --git a/IPXE/ipxe-3fe683e/src/arch/x86/interface/pcbios/ventoy_int13.c b/IPXE/ipxe-3fe683e/src/arch/x86/interface/pcbios/ventoy_int13.c new file mode 100644 index 00000000..c71f9f63 --- /dev/null +++ b/IPXE/ipxe-3fe683e/src/arch/x86/interface/pcbios/ventoy_int13.c @@ -0,0 +1,1527 @@ +/* + * Copyright (C) 2006 Michael Brown . + * Copyright (C) 2020 longpanda . + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of the + * License, or any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + * + * You can also choose to distribute this program under the terms of + * the Unmodified Binary Distribution Licence (as given in the file + * COPYING.UBDL), provided that you have satisfied its requirements. + */ + +FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL ); + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "ventoy_int13.h" + +static unsigned int g_drive_map1 = 0; +static unsigned int g_drive_map2 = 0; + +/** @file + * + * INT 13 emulation + * + * This module provides a mechanism for exporting block devices via + * the BIOS INT 13 disk interrupt interface. + * + */ + +/** INT 13 SAN device private data */ +struct int13_data { + /** BIOS natural drive number (0x00-0xff) + * + * This is the drive number that would have been assigned by + * 'naturally' appending the drive to the end of the BIOS + * drive list. + * + * If the emulated drive replaces a preexisting drive, this is + * the drive number that the preexisting drive gets remapped + * to. + */ + unsigned int natural_drive; + + /** Number of cylinders + * + * The cylinder number field in an INT 13 call is ten bits + * wide, giving a maximum of 1024 cylinders. Conventionally, + * when the 7.8GB limit of a CHS address is exceeded, it is + * the number of cylinders that is increased beyond the + * addressable limit. + */ + unsigned int cylinders; + /** Number of heads + * + * The head number field in an INT 13 call is eight bits wide, + * giving a maximum of 256 heads. However, apparently all + * versions of MS-DOS up to and including Win95 fail with 256 + * heads, so the maximum encountered in practice is 255. + */ + unsigned int heads; + /** Number of sectors per track + * + * The sector number field in an INT 13 call is six bits wide, + * giving a maximum of 63 sectors, since sector numbering + * (unlike head and cylinder numbering) starts at 1, not 0. + */ + unsigned int sectors_per_track; + + /** Address of El Torito boot catalog (if any) */ + unsigned int boot_catalog; + /** Status of last operation */ + int last_status; +}; + +/** Vector for chaining to other INT 13 handlers */ +static struct segoff __text16 ( int13_vector ); +#define int13_vector __use_text16 ( int13_vector ) + +/** Assembly wrapper */ +extern void int13_wrapper ( void ); + +/** Dummy floppy disk parameter table */ +static struct int13_fdd_parameters __data16 ( int13_fdd_params ) = { + /* 512 bytes per sector */ + .bytes_per_sector = 0x02, + /* Highest sectors per track that we ever return */ + .sectors_per_track = 48, +}; +#define int13_fdd_params __use_data16 ( int13_fdd_params ) + +/** + * Equipment word + * + * This is a cached copy of the BIOS Data Area equipment word at + * 40:10. + */ +static uint16_t equipment_word; + +/** + * Number of BIOS floppy disk drives + * + * This is derived from the equipment word. It is held in .text16 to + * allow for easy access by the INT 13,08 wrapper. + */ +static uint8_t __text16 ( num_fdds ); +#define num_fdds __use_text16 ( num_fdds ) + +/** + * Number of BIOS hard disk drives + * + * This is a cached copy of the BIOS Data Area number of hard disk + * drives at 40:75. It is held in .text16 to allow for easy access by + * the INT 13,08 wrapper. + */ +static uint8_t __text16 ( num_drives ); +#define num_drives __use_text16 ( num_drives ) +static struct san_device *g_sandev; + +/** + * Calculate SAN device capacity (limited to 32 bits) + * + * @v sandev SAN device + * @ret blocks Number of blocks + */ +static inline uint32_t int13_capacity32 ( struct san_device *sandev ) { + uint64_t capacity = sandev_capacity ( sandev ); + return ( ( capacity <= 0xffffffffUL ) ? capacity : 0xffffffff ); +} + +/** + * Test if SAN device is a floppy disk drive + * + * @v sandev SAN device + * @ret is_fdd SAN device is a floppy disk drive + */ +static inline int int13_is_fdd ( struct san_device *sandev ) { + (void)sandev; + return 0; +} + +#if 0 +/** + * Guess INT 13 hard disk drive geometry + * + * @v sandev SAN device + * @v scratch Scratch area for single-sector reads + * @ret heads Guessed number of heads + * @ret sectors Guessed number of sectors per track + * @ret rc Return status code + * + * Guesses the drive geometry by inspecting the partition table. + */ +static int int13_guess_geometry_hdd ( struct san_device *sandev, void *scratch, + unsigned int *heads, + unsigned int *sectors ) { + struct master_boot_record *mbr = scratch; + struct partition_table_entry *partition; + unsigned int i; + unsigned int start_cylinder; + unsigned int start_head; + unsigned int start_sector; + unsigned int end_head; + unsigned int end_sector; + int rc; + + /* Read partition table */ + if ( ( rc = sandev_read ( sandev, 0, 1, virt_to_user ( mbr ) ) ) != 0 ) { + DBGC ( sandev, "INT13 drive %02x could not read " + "partition table to guess geometry: %s\n", + sandev->drive, strerror ( rc ) ); + return rc; + } + DBGC2 ( sandev, "INT13 drive %02x has MBR:\n", sandev->drive ); + DBGC2_HDA ( sandev, 0, mbr, sizeof ( *mbr ) ); + DBGC ( sandev, "INT13 drive %02x has signature %08x\n", + sandev->drive, mbr->signature ); + + /* Scan through partition table and modify guesses for + * heads and sectors_per_track if we find any used + * partitions. + */ + *heads = 0; + *sectors = 0; + for ( i = 0 ; i < 4 ; i++ ) { + + /* Skip empty partitions */ + partition = &mbr->partitions[i]; + if ( ! partition->type ) + continue; + + /* If partition starts on cylinder 0 then we can + * unambiguously determine the number of sectors. + */ + start_cylinder = PART_CYLINDER ( partition->chs_start ); + start_head = PART_HEAD ( partition->chs_start ); + start_sector = PART_SECTOR ( partition->chs_start ); + if ( ( start_cylinder == 0 ) && ( start_head != 0 ) ) { + *sectors = ( ( partition->start + 1 - start_sector ) / + start_head ); + DBGC ( sandev, "INT13 drive %02x guessing C/H/S " + "xx/xx/%d based on partition %d\n", + sandev->drive, *sectors, ( i + 1 ) ); + } + + /* If partition ends on a higher head or sector number + * than our current guess, then increase the guess. + */ + end_head = PART_HEAD ( partition->chs_end ); + end_sector = PART_SECTOR ( partition->chs_end ); + if ( ( end_head + 1 ) > *heads ) { + *heads = ( end_head + 1 ); + DBGC ( sandev, "INT13 drive %02x guessing C/H/S " + "xx/%d/xx based on partition %d\n", + sandev->drive, *heads, ( i + 1 ) ); + } + if ( end_sector > *sectors ) { + *sectors = end_sector; + DBGC ( sandev, "INT13 drive %02x guessing C/H/S " + "xx/xx/%d based on partition %d\n", + sandev->drive, *sectors, ( i + 1 ) ); + } + } + + /* Default guess is xx/255/63 */ + if ( ! *heads ) + *heads = 255; + if ( ! *sectors ) + *sectors = 63; + + return 0; +} + +/** Recognised floppy disk geometries */ +static const struct int13_fdd_geometry int13_fdd_geometries[] = { + INT13_FDD_GEOMETRY ( 40, 1, 8 ), + INT13_FDD_GEOMETRY ( 40, 1, 9 ), + INT13_FDD_GEOMETRY ( 40, 2, 8 ), + INT13_FDD_GEOMETRY ( 40, 1, 9 ), + INT13_FDD_GEOMETRY ( 80, 2, 8 ), + INT13_FDD_GEOMETRY ( 80, 2, 9 ), + INT13_FDD_GEOMETRY ( 80, 2, 15 ), + INT13_FDD_GEOMETRY ( 80, 2, 18 ), + INT13_FDD_GEOMETRY ( 80, 2, 20 ), + INT13_FDD_GEOMETRY ( 80, 2, 21 ), + INT13_FDD_GEOMETRY ( 82, 2, 21 ), + INT13_FDD_GEOMETRY ( 83, 2, 21 ), + INT13_FDD_GEOMETRY ( 80, 2, 22 ), + INT13_FDD_GEOMETRY ( 80, 2, 23 ), + INT13_FDD_GEOMETRY ( 80, 2, 24 ), + INT13_FDD_GEOMETRY ( 80, 2, 36 ), + INT13_FDD_GEOMETRY ( 80, 2, 39 ), + INT13_FDD_GEOMETRY ( 80, 2, 40 ), + INT13_FDD_GEOMETRY ( 80, 2, 44 ), + INT13_FDD_GEOMETRY ( 80, 2, 48 ), +}; + +/** + * Guess INT 13 floppy disk drive geometry + * + * @v sandev SAN device + * @ret heads Guessed number of heads + * @ret sectors Guessed number of sectors per track + * @ret rc Return status code + * + * Guesses the drive geometry by inspecting the disk size. + */ +static int int13_guess_geometry_fdd ( struct san_device *sandev, + unsigned int *heads, + unsigned int *sectors ) { + unsigned int blocks = sandev_capacity ( sandev ); + const struct int13_fdd_geometry *geometry; + unsigned int cylinders; + unsigned int i; + + /* Look for a match against a known geometry */ + for ( i = 0 ; i < ( sizeof ( int13_fdd_geometries ) / + sizeof ( int13_fdd_geometries[0] ) ) ; i++ ) { + geometry = &int13_fdd_geometries[i]; + cylinders = INT13_FDD_CYLINDERS ( geometry ); + *heads = INT13_FDD_HEADS ( geometry ); + *sectors = INT13_FDD_SECTORS ( geometry ); + if ( ( cylinders * (*heads) * (*sectors) ) == blocks ) { + DBGC ( sandev, "INT13 drive %02x guessing C/H/S " + "%d/%d/%d based on size %dK\n", sandev->drive, + cylinders, *heads, *sectors, ( blocks / 2 ) ); + return 0; + } + } + + /* Otherwise, assume a partial disk image in the most common + * format (1440K, 80/2/18). + */ + *heads = 2; + *sectors = 18; + DBGC ( sandev, "INT13 drive %02x guessing C/H/S xx/%d/%d based on size " + "%dK\n", sandev->drive, *heads, *sectors, ( blocks / 2 ) ); + return 0; +} + +/** + * Guess INT 13 drive geometry + * + * @v sandev SAN device + * @v scratch Scratch area for single-sector reads + * @ret rc Return status code + */ +static int int13_guess_geometry ( struct san_device *sandev, void *scratch ) { + struct int13_data *int13 = sandev->priv; + unsigned int guessed_heads; + unsigned int guessed_sectors; + unsigned int blocks; + unsigned int blocks_per_cyl; + int rc; + + /* Guess geometry according to drive type */ + if ( int13_is_fdd ( sandev ) ) { + if ( ( rc = int13_guess_geometry_fdd ( sandev, &guessed_heads, + &guessed_sectors )) != 0) + return rc; + } else { + if ( ( rc = int13_guess_geometry_hdd ( sandev, scratch, + &guessed_heads, + &guessed_sectors )) != 0) + return rc; + } + + /* Apply guesses if no geometry already specified */ + if ( ! int13->heads ) + int13->heads = guessed_heads; + if ( ! int13->sectors_per_track ) + int13->sectors_per_track = guessed_sectors; + if ( ! int13->cylinders ) { + /* Avoid attempting a 64-bit divide on a 32-bit system */ + blocks = int13_capacity32 ( sandev ); + blocks_per_cyl = ( int13->heads * int13->sectors_per_track ); + assert ( blocks_per_cyl != 0 ); + int13->cylinders = ( blocks / blocks_per_cyl ); + if ( int13->cylinders > 1024 ) + int13->cylinders = 1024; + } + + return 0; +} +#endif /* #if 0 */ + +/** + * Update BIOS drive count + */ +void int13_sync_num_drives ( void ) { + struct san_device *sandev; + struct int13_data *int13; + uint8_t *counter; + uint8_t max_drive; + uint8_t required; + + /* Get current drive counts */ + get_real ( equipment_word, BDA_SEG, BDA_EQUIPMENT_WORD ); + get_real ( num_drives, BDA_SEG, BDA_NUM_DRIVES ); + num_fdds = ( ( equipment_word & 0x0001 ) ? + ( ( ( equipment_word >> 6 ) & 0x3 ) + 1 ) : 0 ); + + /* Ensure count is large enough to cover all of our SAN devices */ + for_each_sandev ( sandev ) { + int13 = sandev->priv; + counter = ( int13_is_fdd ( sandev ) ? &num_fdds : &num_drives ); + max_drive = sandev->drive; + if ( max_drive < int13->natural_drive ) + max_drive = int13->natural_drive; + required = ( ( max_drive & 0x7f ) + 1 ); + if ( *counter < required ) { + *counter = required; + DBGC ( sandev, "INT13 drive %02x added to drive count: " + "%d HDDs, %d FDDs\n", + sandev->drive, num_drives, num_fdds ); + } + } + + /* Update current drive count */ + equipment_word &= ~( ( 0x3 << 6 ) | 0x0001 ); + if ( num_fdds ) { + equipment_word |= ( 0x0001 | + ( ( ( num_fdds - 1 ) & 0x3 ) << 6 ) ); + } + put_real ( equipment_word, BDA_SEG, BDA_EQUIPMENT_WORD ); + put_real ( num_drives, BDA_SEG, BDA_NUM_DRIVES ); +} + +/** + * Check number of drives + */ +void int13_check_num_drives ( void ) { + uint16_t check_equipment_word; + uint8_t check_num_drives; + + get_real ( check_equipment_word, BDA_SEG, BDA_EQUIPMENT_WORD ); + get_real ( check_num_drives, BDA_SEG, BDA_NUM_DRIVES ); + if ( ( check_equipment_word != equipment_word ) || + ( check_num_drives != num_drives ) ) { + int13_sync_num_drives(); + } +} + +/** + * INT 13, 00 - Reset disk system + * + * @v sandev SAN device + * @ret status Status code + */ +static int int13_reset ( struct san_device *sandev, + struct i386_all_regs *ix86 __unused ) { + int rc; + + DBGC2 ( sandev, "Reset drive\n" ); + + /* Reset SAN device */ + if ( ( rc = sandev_reset ( sandev ) ) != 0 ) + return -INT13_STATUS_RESET_FAILED; + + return 0; +} + +/** + * INT 13, 01 - Get status of last operation + * + * @v sandev SAN device + * @ret status Status code + */ +static int int13_get_last_status ( struct san_device *sandev, + struct i386_all_regs *ix86 __unused ) { + struct int13_data *int13 = sandev->priv; + + DBGC2 ( sandev, "Get status of last operation\n" ); + return int13->last_status; +} + +/** + * Read / write sectors + * + * @v sandev SAN device + * @v al Number of sectors to read or write (must be nonzero) + * @v ch Low bits of cylinder number + * @v cl (bits 7:6) High bits of cylinder number + * @v cl (bits 5:0) Sector number + * @v dh Head number + * @v es:bx Data buffer + * @v sandev_rw SAN device read/write method + * @ret status Status code + * @ret al Number of sectors read or written + */ +static int int13_rw_sectors ( struct san_device *sandev, + struct i386_all_regs *ix86, + int ( * sandev_rw ) ( struct san_device *sandev, + uint64_t lba, + unsigned int count, + userptr_t buffer ) ) { + struct int13_data *int13 = sandev->priv; + unsigned int cylinder, head, sector; + unsigned long lba; + unsigned int count; + userptr_t buffer; + int rc; + + /* Validate blocksize */ + if ( sandev_blksize ( sandev ) != INT13_BLKSIZE ) { + DBGC ( sandev, "\nINT 13 drive %02x invalid blocksize (%zd) " + "for non-extended read/write\n", + sandev->drive, sandev_blksize ( sandev ) ); + return -INT13_STATUS_INVALID; + } + + /* Calculate parameters */ + cylinder = ( ( ( ix86->regs.cl & 0xc0 ) << 2 ) | ix86->regs.ch ); + head = ix86->regs.dh; + sector = ( ix86->regs.cl & 0x3f ); + if ( ( cylinder >= int13->cylinders ) || + ( head >= int13->heads ) || + ( sector < 1 ) || ( sector > int13->sectors_per_track ) ) { + DBGC ( sandev, "C/H/S %d/%d/%d out of range for geometry " + "%d/%d/%d\n", cylinder, head, sector, int13->cylinders, + int13->heads, int13->sectors_per_track ); + return -INT13_STATUS_INVALID; + } + lba = ( ( ( ( cylinder * int13->heads ) + head ) + * int13->sectors_per_track ) + sector - 1 ); + count = ix86->regs.al; + buffer = real_to_user ( ix86->segs.es, ix86->regs.bx ); + + DBGC2 ( sandev, "C/H/S %d/%d/%d = LBA %08lx <-> %04x:%04x (count %d)\n", + cylinder, head, sector, lba, ix86->segs.es, ix86->regs.bx, + count ); + + /* Read from / write to block device */ + if ( ( rc = sandev_rw ( sandev, lba, count, buffer ) ) != 0 ){ + DBGC ( sandev, "INT13 drive %02x I/O failed: %s\n", + sandev->drive, strerror ( rc ) ); + return -INT13_STATUS_READ_ERROR; + } + + return 0; +} + +/** + * INT 13, 02 - Read sectors + * + * @v sandev SAN device + * @v al Number of sectors to read (must be nonzero) + * @v ch Low bits of cylinder number + * @v cl (bits 7:6) High bits of cylinder number + * @v cl (bits 5:0) Sector number + * @v dh Head number + * @v es:bx Data buffer + * @ret status Status code + * @ret al Number of sectors read + */ +static int int13_read_sectors ( struct san_device *sandev, + struct i386_all_regs *ix86 ) { + + DBGC2 ( sandev, "Read: " ); + return int13_rw_sectors ( sandev, ix86, sandev_read ); +} + +/** + * INT 13, 03 - Write sectors + * + * @v sandev SAN device + * @v al Number of sectors to write (must be nonzero) + * @v ch Low bits of cylinder number + * @v cl (bits 7:6) High bits of cylinder number + * @v cl (bits 5:0) Sector number + * @v dh Head number + * @v es:bx Data buffer + * @ret status Status code + * @ret al Number of sectors written + */ +static int int13_write_sectors ( struct san_device *sandev, + struct i386_all_regs *ix86 ) { + + DBGC2 ( sandev, "Write: " ); + return int13_rw_sectors ( sandev, ix86, sandev_write ); +} + +/** + * INT 13, 08 - Get drive parameters + * + * @v sandev SAN device + * @ret status Status code + * @ret ch Low bits of maximum cylinder number + * @ret cl (bits 7:6) High bits of maximum cylinder number + * @ret cl (bits 5:0) Maximum sector number + * @ret dh Maximum head number + * @ret dl Number of drives + */ +static int int13_get_parameters ( struct san_device *sandev, + struct i386_all_regs *ix86 ) { + struct int13_data *int13 = sandev->priv; + unsigned int max_cylinder = int13->cylinders - 1; + unsigned int max_head = int13->heads - 1; + unsigned int max_sector = int13->sectors_per_track; /* sic */ + + DBGC2 ( sandev, "Get drive parameters\n" ); + + /* Validate blocksize */ + if ( sandev_blksize ( sandev ) != INT13_BLKSIZE ) { + DBGC ( sandev, "\nINT 13 drive %02x invalid blocksize (%zd) " + "for non-extended parameters\n", + sandev->drive, sandev_blksize ( sandev ) ); + return -INT13_STATUS_INVALID; + } + + /* Common parameters */ + ix86->regs.ch = ( max_cylinder & 0xff ); + ix86->regs.cl = ( ( ( max_cylinder >> 8 ) << 6 ) | max_sector ); + ix86->regs.dh = max_head; + ix86->regs.dl = ( int13_is_fdd ( sandev ) ? num_fdds : num_drives ); + + /* Floppy-specific parameters */ + if ( int13_is_fdd ( sandev ) ) { + ix86->regs.bl = INT13_FDD_TYPE_1M44; + ix86->segs.es = rm_ds; + ix86->regs.di = __from_data16 ( &int13_fdd_params ); + } + + return 0; +} + +/** + * INT 13, 15 - Get disk type + * + * @v sandev SAN device + * @ret ah Type code + * @ret cx:dx Sector count + * @ret status Status code / disk type + */ +static int int13_get_disk_type ( struct san_device *sandev, + struct i386_all_regs *ix86 ) { + uint32_t blocks; + + DBGC2 ( sandev, "Get disk type\n" ); + + if ( int13_is_fdd ( sandev ) ) { + return INT13_DISK_TYPE_FDD; + } else { + blocks = int13_capacity32 ( sandev ); + ix86->regs.cx = ( blocks >> 16 ); + ix86->regs.dx = ( blocks & 0xffff ); + return INT13_DISK_TYPE_HDD; + } +} + +/** + * INT 13, 41 - Extensions installation check + * + * @v sandev SAN device + * @v bx 0x55aa + * @ret bx 0xaa55 + * @ret cx Extensions API support bitmap + * @ret status Status code / API version + */ +static int int13_extension_check ( struct san_device *sandev __unused, + struct i386_all_regs *ix86 ) { + + if ( ix86->regs.bx == 0x55aa ) { + DBGC2 ( sandev, "INT13 extensions installation check\n" ); + ix86->regs.bx = 0xaa55; + ix86->regs.cx = ( INT13_EXTENSION_LINEAR | + INT13_EXTENSION_EDD | + INT13_EXTENSION_64BIT ); + return INT13_EXTENSION_VER_3_0; + } else { + return -INT13_STATUS_INVALID; + } +} + +/** + * Extended read / write + * + * @v sandev SAN device + * @v ds:si Disk address packet + * @v sandev_rw SAN device read/write method + * @ret status Status code + */ +static int int13_extended_rw ( struct san_device *sandev, + struct i386_all_regs *ix86, + int ( * sandev_rw ) ( struct san_device *sandev, + uint64_t lba, + unsigned int count, + userptr_t buffer ) ) { + struct int13_disk_address addr; + uint8_t bufsize; + uint64_t lba; + unsigned long count; + userptr_t buffer; + int rc; + + /* Extended reads are not allowed on floppy drives. + * ELTORITO.SYS seems to assume that we are really a CD-ROM if + * we support extended reads for a floppy drive. + */ + if ( int13_is_fdd ( sandev ) ) + return -INT13_STATUS_INVALID; + + /* Get buffer size */ + get_real ( bufsize, ix86->segs.ds, + ( ix86->regs.si + offsetof ( typeof ( addr ), bufsize ) ) ); + if ( bufsize < offsetof ( typeof ( addr ), buffer_phys ) ) { + DBGC2 ( sandev, "\n", bufsize ); + return -INT13_STATUS_INVALID; + } + + /* Read parameters from disk address structure */ + memset ( &addr, 0, sizeof ( addr ) ); + copy_from_real ( &addr, ix86->segs.ds, ix86->regs.si, bufsize ); + lba = addr.lba; + DBGC2 ( sandev, "LBA %08llx <-> ", ( ( unsigned long long ) lba ) ); + if ( ( addr.count == 0xff ) || + ( ( addr.buffer.segment == 0xffff ) && + ( addr.buffer.offset == 0xffff ) ) ) { + buffer = phys_to_user ( addr.buffer_phys ); + DBGC2 ( sandev, "%08llx", + ( ( unsigned long long ) addr.buffer_phys ) ); + } else { + buffer = real_to_user ( addr.buffer.segment, + addr.buffer.offset ); + DBGC2 ( sandev, "%04x:%04x", addr.buffer.segment, + addr.buffer.offset ); + } + if ( addr.count <= 0x7f ) { + count = addr.count; + } else if ( addr.count == 0xff ) { + count = addr.long_count; + } else { + DBGC2 ( sandev, " \n", addr.count ); + return -INT13_STATUS_INVALID; + } + DBGC2 ( sandev, " (count %ld)\n", count ); + + /* Read from / write to block device */ + if ( ( rc = sandev_rw ( sandev, lba, count, buffer ) ) != 0 ) { + DBGC ( sandev, "INT13 drive %02x extended I/O failed: %s\n", + sandev->drive, strerror ( rc ) ); + /* Record that no blocks were transferred successfully */ + addr.count = 0; + put_real ( addr.count, ix86->segs.ds, + ( ix86->regs.si + + offsetof ( typeof ( addr ), count ) ) ); + return -INT13_STATUS_READ_ERROR; + } + + copy_to_real (ix86->segs.ds, ix86->regs.si, &addr, bufsize ); + + return 0; +} + +/** + * INT 13, 42 - Extended read + * + * @v sandev SAN device + * @v ds:si Disk address packet + * @ret status Status code + */ +static int int13_extended_read ( struct san_device *sandev, + struct i386_all_regs *ix86 ) { + + DBGC2 ( sandev, "Extended read: " ); + return int13_extended_rw ( sandev, ix86, sandev_read ); +} + +/** + * INT 13, 43 - Extended write + * + * @v sandev SAN device + * @v ds:si Disk address packet + * @ret status Status code + */ +static int int13_extended_write ( struct san_device *sandev, + struct i386_all_regs *ix86 ) { + + DBGC2 ( sandev, "Extended write: " ); + return int13_extended_rw ( sandev, ix86, sandev_write ); +} + +/** + * INT 13, 44 - Verify sectors + * + * @v sandev SAN device + * @v ds:si Disk address packet + * @ret status Status code + */ +static int int13_extended_verify ( struct san_device *sandev, + struct i386_all_regs *ix86 ) { + struct int13_disk_address addr; + uint64_t lba; + unsigned long count; + + /* Read parameters from disk address structure */ + if ( DBG_EXTRA ) { + copy_from_real ( &addr, ix86->segs.ds, ix86->regs.si, + sizeof ( addr )); + lba = addr.lba; + count = addr.count; + DBGC2 ( sandev, "Verify: LBA %08llx (count %ld)\n", + ( ( unsigned long long ) lba ), count ); + } + + /* We have no mechanism for verifying sectors */ + return -INT13_STATUS_INVALID; +} + +/** + * INT 13, 44 - Extended seek + * + * @v sandev SAN device + * @v ds:si Disk address packet + * @ret status Status code + */ +static int int13_extended_seek ( struct san_device *sandev, + struct i386_all_regs *ix86 ) { + struct int13_disk_address addr; + uint64_t lba; + unsigned long count; + + /* Read parameters from disk address structure */ + if ( DBG_EXTRA ) { + copy_from_real ( &addr, ix86->segs.ds, ix86->regs.si, + sizeof ( addr )); + lba = addr.lba; + count = addr.count; + DBGC2 ( sandev, "Seek: LBA %08llx (count %ld)\n", + ( ( unsigned long long ) lba ), count ); + } + + /* Ignore and return success */ + return 0; +} + +/** + * Build device path information + * + * @v sandev SAN device + * @v dpi Device path information + * @ret rc Return status code + */ +static int int13_device_path_info ( struct san_device *sandev, + struct edd_device_path_information *dpi ) { + struct san_path *sanpath; + struct device *device; + struct device_description *desc; + unsigned int i; + uint8_t sum = 0; + int rc; + return -ECANCELED; + /* Reopen block device if necessary */ + if ( sandev_needs_reopen ( sandev ) && + ( ( rc = sandev_reopen ( sandev ) ) != 0 ) ) + return rc; + sanpath = sandev->active; + assert ( sanpath != NULL ); + + /* Get underlying hardware device */ + device = identify_device ( &sanpath->block ); + if ( ! device ) { + DBGC ( sandev, "INT13 drive %02x cannot identify hardware " + "device\n", sandev->drive ); + return -ENODEV; + } + + /* Fill in bus type and interface path */ + desc = &device->desc; + switch ( desc->bus_type ) { + case BUS_TYPE_PCI: + dpi->host_bus_type.type = EDD_BUS_TYPE_PCI; + dpi->interface_path.pci.bus = PCI_BUS ( desc->location ); + dpi->interface_path.pci.slot = PCI_SLOT ( desc->location ); + dpi->interface_path.pci.function = PCI_FUNC ( desc->location ); + dpi->interface_path.pci.channel = 0xff; /* unused */ + break; + default: + DBGC ( sandev, "INT13 drive %02x unrecognised bus type %d\n", + sandev->drive, desc->bus_type ); + return -ENOTSUP; + } + + /* Get EDD block device description */ + if ( ( rc = edd_describe ( &sanpath->block, &dpi->interface_type, + &dpi->device_path ) ) != 0 ) { + DBGC ( sandev, "INT13 drive %02x cannot identify block device: " + "%s\n", sandev->drive, strerror ( rc ) ); + return rc; + } + + /* Fill in common fields and fix checksum */ + dpi->key = EDD_DEVICE_PATH_INFO_KEY; + dpi->len = sizeof ( *dpi ); + for ( i = 0 ; i < sizeof ( *dpi ) ; i++ ) + sum += *( ( ( uint8_t * ) dpi ) + i ); + dpi->checksum -= sum; + + return 0; +} + +/** + * INT 13, 48 - Get extended parameters + * + * @v sandev SAN device + * @v ds:si Drive parameter table + * @ret status Status code + */ +static int int13_get_extended_parameters ( struct san_device *sandev, + struct i386_all_regs *ix86 ) { + struct int13_data *int13 = sandev->priv; + struct int13_disk_parameters params; + struct segoff address; + size_t len = sizeof ( params ); + uint16_t bufsize; + int rc; + + /* Get buffer size */ + get_real ( bufsize, ix86->segs.ds, + ( ix86->regs.si + offsetof ( typeof ( params ), bufsize ))); + + DBGC2 ( sandev, "Get extended drive parameters to %04x:%04x+%02x\n", + ix86->segs.ds, ix86->regs.si, bufsize ); + + /* Build drive parameters */ + memset ( ¶ms, 0, sizeof ( params ) ); + params.flags = INT13_FL_DMA_TRANSPARENT; + if ( ( int13->cylinders < 1024 ) && + ( sandev_capacity ( sandev ) <= INT13_MAX_CHS_SECTORS ) ) { + params.flags |= INT13_FL_CHS_VALID; + } + params.cylinders = int13->cylinders; + params.heads = int13->heads; + params.sectors_per_track = int13->sectors_per_track; + params.sectors = sandev_capacity ( sandev ); + params.sector_size = sandev_blksize ( sandev ); + memset ( ¶ms.dpte, 0xff, sizeof ( params.dpte ) ); + if ( ( rc = int13_device_path_info ( sandev, ¶ms.dpi ) ) != 0 ) { + DBGC ( sandev, "INT13 drive %02x could not provide device " + "path information: %s\n", + sandev->drive, strerror ( rc ) ); + len = offsetof ( typeof ( params ), dpi ); + } + + /* Calculate returned "buffer size" (which will be less than + * the length actually copied if device path information is + * present). + */ + if ( bufsize < offsetof ( typeof ( params ), dpte ) ) + return -INT13_STATUS_INVALID; + if ( bufsize < offsetof ( typeof ( params ), dpi ) ) { + params.bufsize = offsetof ( typeof ( params ), dpte ); + } else { + params.bufsize = offsetof ( typeof ( params ), dpi ); + } + + DBGC ( sandev, "INT 13 drive %02x described using extended " + "parameters:\n", sandev->drive ); + address.segment = ix86->segs.ds; + address.offset = ix86->regs.si; + DBGC_HDA ( sandev, address, ¶ms, len ); + + /* Return drive parameters */ + if ( len > bufsize ) + len = bufsize; + copy_to_real ( ix86->segs.ds, ix86->regs.si, ¶ms, len ); + + return 0; +} + +/** + * INT 13, 4b - Get status or terminate CD-ROM emulation + * + * @v sandev SAN device + * @v ds:si Specification packet + * @ret status Status code + */ +static int int13_cdrom_status_terminate ( struct san_device *sandev, + struct i386_all_regs *ix86 ) { + struct int13_cdrom_specification specification; + + DBGC2 ( sandev, "Get CD-ROM emulation status to %04x:%04x%s\n", + ix86->segs.ds, ix86->regs.si, + ( ix86->regs.al ? "" : " and terminate" ) ); + + /* Fail if we are not a CD-ROM */ + if ( ! sandev->is_cdrom ) { + DBGC ( sandev, "INT13 drive %02x is not a CD-ROM\n", + sandev->drive ); + return -INT13_STATUS_INVALID; + } + + /* Build specification packet */ + memset ( &specification, 0, sizeof ( specification ) ); + specification.size = sizeof ( specification ); + specification.drive = sandev->drive; + + /* Return specification packet */ + copy_to_real ( ix86->segs.ds, ix86->regs.si, &specification, + sizeof ( specification ) ); + + return 0; +} + + +/** + * INT 13, 4d - Read CD-ROM boot catalog + * + * @v sandev SAN device + * @v ds:si Command packet + * @ret status Status code + */ +static int int13_cdrom_read_boot_catalog ( struct san_device *sandev, + struct i386_all_regs *ix86 ) { + struct int13_data *int13 = sandev->priv; + struct int13_cdrom_boot_catalog_command command; + unsigned int start; + int rc; + + /* Read parameters from command packet */ + copy_from_real ( &command, ix86->segs.ds, ix86->regs.si, + sizeof ( command ) ); + DBGC2 ( sandev, "Read CD-ROM boot catalog to %08x\n", command.buffer ); + + /* Fail if we have no boot catalog */ + if ( ! int13->boot_catalog ) { + DBGC ( sandev, "INT13 drive %02x has no boot catalog\n", + sandev->drive ); + return -INT13_STATUS_INVALID; + } + start = ( int13->boot_catalog + command.start ); + + /* Read from boot catalog */ + if ( ( rc = sandev_read ( sandev, start, command.count, + phys_to_user ( command.buffer ) ) ) != 0 ) { + DBGC ( sandev, "INT13 drive %02x could not read boot catalog: " + "%s\n", sandev->drive, strerror ( rc ) ); + return -INT13_STATUS_READ_ERROR; + } + + return 0; +} + + + +/** + * INT 13 handler + * + */ +static __asmcall void int13 ( struct i386_all_regs *ix86 ) { + int command = ix86->regs.ah; + unsigned int bios_drive = ix86->regs.dl; + struct san_device *sandev; + struct int13_data *int13; + int status; + + /* We simulate a cdrom, so no need to sync hd drive number */ + //int13_check_num_drives(); + + if (bios_drive == VENTOY_BIOS_FAKE_DRIVE) + { + ix86->regs.dl = g_sandev->exdrive; + return; + } + + // drive swap + if (g_drive_map1 >= 0x80 && g_drive_map2 >= 0x80) + { + if (bios_drive == g_drive_map1) + { + ix86->regs.dl = g_drive_map2; + return; + } + else if (bios_drive == g_drive_map2) + { + ix86->regs.dl = g_drive_map1; + return; + } + } + + for_each_sandev ( sandev ) { + + int13 = sandev->priv; + if ( bios_drive != sandev->drive ) { + /* Remap any accesses to this drive's natural number */ + if ( bios_drive == int13->natural_drive ) { + DBGC2 ( sandev, "INT13,%02x (%02x) remapped to " + "(%02x)\n", ix86->regs.ah, + bios_drive, sandev->drive ); + ix86->regs.dl = sandev->drive; + return; + } else if ( ( ( bios_drive & 0x7f ) == 0x7f ) && + ( command == INT13_CDROM_STATUS_TERMINATE ) + && sandev->is_cdrom ) { + + /* Catch non-drive-specific CD-ROM calls */ + } else { + return; + } + } + + sandev->int13_command = command; + sandev->x86_regptr = ix86; + + DBGC2 ( sandev, "INT13,%02x (%02x): ", + ix86->regs.ah, bios_drive ); + + switch ( command ) { + case INT13_RESET: + status = int13_reset ( sandev, ix86 ); + break; + case INT13_GET_LAST_STATUS: + status = int13_get_last_status ( sandev, ix86 ); + break; + case INT13_READ_SECTORS: + status = int13_read_sectors ( sandev, ix86 ); + break; + case INT13_WRITE_SECTORS: + status = int13_write_sectors ( sandev, ix86 ); + break; + case INT13_GET_PARAMETERS: + status = int13_get_parameters ( sandev, ix86 ); + break; + case INT13_GET_DISK_TYPE: + status = int13_get_disk_type ( sandev, ix86 ); + break; + case INT13_EXTENSION_CHECK: + status = int13_extension_check ( sandev, ix86 ); + break; + case INT13_EXTENDED_READ: + status = int13_extended_read ( sandev, ix86 ); + break; + case INT13_EXTENDED_WRITE: + status = int13_extended_write ( sandev, ix86 ); + break; + case INT13_EXTENDED_VERIFY: + status = int13_extended_verify ( sandev, ix86 ); + break; + case INT13_EXTENDED_SEEK: + status = int13_extended_seek ( sandev, ix86 ); + break; + case INT13_GET_EXTENDED_PARAMETERS: + status = int13_get_extended_parameters ( sandev, ix86 ); + break; + case INT13_CDROM_STATUS_TERMINATE: + status = int13_cdrom_status_terminate ( sandev, ix86 ); + break; + case INT13_CDROM_READ_BOOT_CATALOG: + status = int13_cdrom_read_boot_catalog ( sandev, ix86 ); + break; + default: + DBGC2 ( sandev, "*** Unrecognised INT13 ***\n" ); + status = -INT13_STATUS_INVALID; + break; + } + + /* Store status for INT 13,01 */ + int13->last_status = status; + + /* Negative status indicates an error */ + if ( status < 0 ) { + status = -status; + DBGC ( sandev, "INT13,%02x (%02x) failed with status " + "%02x\n", ix86->regs.ah, sandev->drive, status ); + } else { + ix86->flags &= ~CF; + } + ix86->regs.ah = status; + + /* Set OF to indicate to wrapper not to chain this call */ + ix86->flags |= OF; + + return; + } +} + +/** + * Hook INT 13 handler + * + */ +static void int13_hook_vector ( void ) { + /* Assembly wrapper to call int13(). int13() sets OF if we + * should not chain to the previous handler. (The wrapper + * clears CF and OF before calling int13()). + */ + __asm__ __volatile__ ( + TEXT16_CODE ( "\nint13_wrapper:\n\t" + /* Preserve %ax and %dx for future reference */ + "pushw %%bp\n\t" + "movw %%sp, %%bp\n\t" + "pushw %%ax\n\t" + "pushw %%dx\n\t" + /* Clear OF, set CF, call int13() */ + "orb $0, %%al\n\t" + "stc\n\t" + VIRT_CALL ( int13 ) + /* Chain if OF not set */ + "jo 1f\n\t" + "pushfw\n\t" + "lcall *%%cs:int13_vector\n\t" + "\n1:\n\t" + /* Overwrite flags for iret */ + "pushfw\n\t" + "popw 6(%%bp)\n\t" + /* Fix up %dl: + * + * INT 13,15 : do nothing if hard disk + * INT 13,08 : load with number of drives + * all others: restore original value + */ + "cmpb $0x15, -1(%%bp)\n\t" + "jne 2f\n\t" + "testb $0x80, -4(%%bp)\n\t" + "jnz 3f\n\t" + "\n2:\n\t" + "movb -4(%%bp), %%dl\n\t" + "cmpb $0x08, -1(%%bp)\n\t" + "jne 3f\n\t" + "testb $0x80, %%dl\n\t" + "movb %%cs:num_drives, %%dl\n\t" + "jnz 3f\n\t" + "movb %%cs:num_fdds, %%dl\n\t" + /* Return */ + "\n3:\n\t" + "movw %%bp, %%sp\n\t" + "popw %%bp\n\t" + "iret\n\t" ) : : ); + + hook_bios_interrupt ( 0x13, ( intptr_t ) int13_wrapper, &int13_vector ); +} + + + +/** + * Load and verify master boot record from INT 13 drive + * + * @v drive Drive number + * @v address Boot code address to fill in + * @ret rc Return status code + */ +static int int13_load_mbr ( unsigned int drive, struct segoff *address ) { + uint16_t status; + int discard_b, discard_c, discard_d; + uint16_t magic; + + /* Use INT 13, 02 to read the MBR */ + address->segment = 0; + address->offset = 0x7c00; + __asm__ __volatile__ ( REAL_CODE ( "pushw %%es\n\t" + "pushl %%ebx\n\t" + "popw %%bx\n\t" + "popw %%es\n\t" + "stc\n\t" + "sti\n\t" + "int $0x13\n\t" + "sti\n\t" /* BIOS bugs */ + "jc 1f\n\t" + "xorw %%ax, %%ax\n\t" + "\n1:\n\t" + "popw %%es\n\t" ) + : "=a" ( status ), "=b" ( discard_b ), + "=c" ( discard_c ), "=d" ( discard_d ) + : "a" ( 0x0201 ), "b" ( *address ), + "c" ( 1 ), "d" ( drive ) ); + if ( status ) { + DBG ( "INT13 drive %02x could not read MBR (status %04x)\n", + drive, status ); + return -EIO; + } + + /* Check magic signature */ + get_real ( magic, address->segment, + ( address->offset + + offsetof ( struct master_boot_record, magic ) ) ); + if ( magic != INT13_MBR_MAGIC ) { + DBG ( "INT13 drive %02x does not contain a valid MBR\n", + drive ); + return -ENOEXEC; + } + + return 0; +} + +/** El Torito boot catalog command packet */ +static struct int13_cdrom_boot_catalog_command __data16 ( eltorito_cmd ) = { + .size = sizeof ( struct int13_cdrom_boot_catalog_command ), + .count = 1, + .buffer = 0x7c00, + .start = 0, +}; +#define eltorito_cmd __use_data16 ( eltorito_cmd ) + +/** El Torito disk address packet */ +static struct int13_disk_address __bss16 ( eltorito_address ); +#define eltorito_address __use_data16 ( eltorito_address ) + +/** + * Load and verify El Torito boot record from INT 13 drive + * + * @v drive Drive number + * @v address Boot code address to fill in + * @ret rc Return status code + */ +static int int13_load_eltorito ( unsigned int drive, struct segoff *address ) { + struct { + struct eltorito_validation_entry valid; + struct eltorito_boot_entry boot; + } __attribute__ (( packed )) catalog; + uint16_t status; + + if (g_sandev && g_sandev->drive == drive) + { + copy_to_user(phys_to_user ( eltorito_cmd.buffer ), 0, g_sandev->boot_catalog_sector, sizeof(g_sandev->boot_catalog_sector)); + } + else + { + /* Use INT 13, 4d to read the boot catalog */ + __asm__ __volatile__ ( REAL_CODE ( "stc\n\t" + "sti\n\t" + "int $0x13\n\t" + "sti\n\t" /* BIOS bugs */ + "jc 1f\n\t" + "xorw %%ax, %%ax\n\t" + "\n1:\n\t" ) + : "=a" ( status ) + : "a" ( 0x4d00 ), "d" ( drive ), + "S" ( __from_data16 ( &eltorito_cmd ) ) ); + if ( status ) { + DBG ( "INT13 drive %02x could not read El Torito boot catalog " + "(status %04x)\n", drive, status ); + return -EIO; + } + } + + copy_from_user ( &catalog, phys_to_user ( eltorito_cmd.buffer ), 0, + sizeof ( catalog ) ); + + /* Sanity checks */ + if ( catalog.valid.platform_id != ELTORITO_PLATFORM_X86 ) { + DBG ( "INT13 drive %02x El Torito specifies unknown platform " + "%02x\n", drive, catalog.valid.platform_id ); + return -ENOEXEC; + } + if ( catalog.boot.indicator != ELTORITO_BOOTABLE ) { + DBG ( "INT13 drive %02x El Torito is not bootable\n", drive ); + return -ENOEXEC; + } + if ( catalog.boot.media_type != ELTORITO_NO_EMULATION ) { + DBG ( "INT13 drive %02x El Torito requires emulation " + "type %02x\n", drive, catalog.boot.media_type ); + return -ENOTSUP; + } + DBG ( "INT13 drive %02x El Torito boot image at LBA %08x (count %d)\n", + drive, catalog.boot.start, catalog.boot.length ); + address->segment = ( catalog.boot.load_segment ? + catalog.boot.load_segment : 0x7c0 ); + address->offset = 0; + DBG ( "INT13 drive %02x El Torito boot image loads at %04x:%04x\n", + drive, address->segment, address->offset ); + + /* Use INT 13, 42 to read the boot image */ + eltorito_address.bufsize = + offsetof ( typeof ( eltorito_address ), buffer_phys ); + eltorito_address.count = catalog.boot.length; + eltorito_address.buffer = *address; + eltorito_address.lba = catalog.boot.start; + __asm__ __volatile__ ( REAL_CODE ( "stc\n\t" + "sti\n\t" + "int $0x13\n\t" + "sti\n\t" /* BIOS bugs */ + "jc 1f\n\t" + "xorw %%ax, %%ax\n\t" + "\n1:\n\t" ) + : "=a" ( status ) + : "a" ( 0x4200 ), "d" ( drive ), + "S" ( __from_data16 ( &eltorito_address ) ) ); + if ( status ) { + DBG ( "INT13 drive %02x could not read El Torito boot image " + "(status %04x)\n", drive, status ); + return -EIO; + } + + return 0; +} + +/** + * Hook INT 13 SAN device + * + * @v drive Drive number + * @v uris List of URIs + * @v count Number of URIs + * @v flags Flags + * @ret drive Drive number, or negative error + * + * Registers the drive with the INT 13 emulation subsystem, and hooks + * the INT 13 interrupt vector (if not already hooked). + */ +unsigned int ventoy_int13_hook (ventoy_chain_head *chain) +{ + unsigned int blocks; + unsigned int blocks_per_cyl; + unsigned int natural_drive; + struct int13_data *int13; + + /* We simulate a cdrom, so no need to sync hd drive number */ + //int13_sync_num_drives(); + + /* hook will copy num_drives to dl when int13 08 was called, so must initialize it's value */ + get_real(num_drives, BDA_SEG, BDA_NUM_DRIVES); + + //natural_drive = num_drives | 0x80; + natural_drive = 0xE0; /* just set a cdrom drive number 224 */ + + if (chain->disk_drive >= 0x80 && chain->drive_map >= 0x80) + { + g_drive_map1 = chain->disk_drive; + g_drive_map2 = chain->drive_map; + } + + /* a fake sandev */ + g_sandev = zalloc(sizeof(struct san_device) + sizeof(struct int13_data)); + g_sandev->priv = int13 = (struct int13_data *)(g_sandev + 1); + g_sandev->drive = int13->natural_drive = natural_drive; + g_sandev->is_cdrom = 1; + g_sandev->blksize_shift = 2; + g_sandev->capacity.blksize = 512; + g_sandev->capacity.blocks = chain->virt_img_size_in_bytes / 512; + g_sandev->exdrive = chain->disk_drive; + int13->boot_catalog = chain->boot_catalog; + memcpy(g_sandev->boot_catalog_sector, chain->boot_catalog_sector, sizeof(chain->boot_catalog_sector)); + + + /* Apply guesses if no geometry already specified */ + if ( ! int13->heads ) + int13->heads = 255; + if ( ! int13->sectors_per_track ) + int13->sectors_per_track = 63; + if ( ! int13->cylinders ) { + /* Avoid attempting a 64-bit divide on a 32-bit system */ + blocks = int13_capacity32 ( g_sandev ); + blocks_per_cyl = ( int13->heads * int13->sectors_per_track ); + + int13->cylinders = ( blocks / blocks_per_cyl ); + if ( int13->cylinders > 1024 ) + int13->cylinders = 1024; + } + + /* Hook INT 13 vector if not already hooked */ + int13_hook_vector(); + + /* Update BIOS drive count */ + //int13_sync_num_drives(); + + return natural_drive; +} + +static uint8_t __bss16_array ( xbftab, [512 + 128]) + __attribute__ (( aligned ( 16 ) )); +#define xbftab __use_data16 ( xbftab ) + +void * ventoy_get_runtime_addr(void) +{ + return (void *)user_to_phys((userptr_t)(&xbftab), 0); +} + +/** + * Attempt to boot from an INT 13 drive + * + * @v drive Drive number + * @v filename Filename (or NULL to use default) + * @ret rc Return status code + * + * This boots from the specified INT 13 drive by loading the Master + * Boot Record to 0000:7c00 and jumping to it. INT 18 is hooked to + * capture an attempt by the MBR to boot the next device. (This is + * the closest thing to a return path from an MBR). + * + * Note that this function can never return success, by definition. + */ +int ventoy_int13_boot ( unsigned int drive, void *imginfo, const char *cmdline) { + //struct memory_map memmap; + int rc; + int headlen; + struct segoff address; + struct acpi_header *acpi = NULL; + struct ibft_table *ibft = NULL; + + /* Look for a usable boot sector */ + if ( ( ( rc = int13_load_eltorito ( drive, &address ) ) != 0 ) && + ( ( rc = int13_load_mbr ( drive, &address ) ) != 0 )) + return rc; + + if (imginfo) + { + if (strstr(cmdline, "ibft")) + { + headlen = 80; + ibft = (struct ibft_table *)(&xbftab); + acpi = &(ibft->acpi); + memset(ibft, 0, headlen); + + acpi->signature = IBFT_SIG; + acpi->length = headlen + sizeof(ventoy_os_param); + acpi->revision = 1; + strncpy(acpi->oem_id, "ventoy", sizeof(acpi->oem_id)); + strncpy(acpi->oem_table_id, "runtime", sizeof(acpi->oem_table_id)); + memcpy((uint8_t *)ibft + headlen, imginfo, sizeof(ventoy_os_param)); + acpi_fix_checksum(acpi); + } + else + { + memcpy((&xbftab), imginfo, sizeof(ventoy_os_param)); + } + } + + /* Dump out memory map prior to boot, if memmap debugging is + * enabled. Not required for program flow, but we have so + * many problems that turn out to be memory-map related that + * it's worth doing. + */ + //get_memmap ( &memmap ); + + DBGC(g_sandev, "start to boot ...\n"); + + /* Jump to boot sector */ + if ( ( rc = call_bootsector ( address.segment, address.offset, + drive ) ) != 0 ) { + return rc; + } + + return -ECANCELED; /* -EIMPOSSIBLE */ +} + diff --git a/IPXE/ipxe-3fe683e/src/arch/x86/interface/pcbios/ventoy_int13.h b/IPXE/ipxe-3fe683e/src/arch/x86/interface/pcbios/ventoy_int13.h new file mode 100644 index 00000000..e6fe5455 --- /dev/null +++ b/IPXE/ipxe-3fe683e/src/arch/x86/interface/pcbios/ventoy_int13.h @@ -0,0 +1,48 @@ + +#ifndef __VENTOY_INT13_H__ +#define __VENTOY_INT13_H__ + +#undef for_each_sandev +#define for_each_sandev( sandev ) sandev = g_sandev; if (sandev) + +int ventoy_vdisk_read(struct san_device*sandev, uint64_t lba, unsigned int count, unsigned long buffer); + +static inline int ventoy_sandev_write ( struct san_device *sandev, uint64_t lba, unsigned int count, unsigned long buffer ) +{ + (void)sandev; + (void)lba; + (void)count; + (void)buffer; + DBGC(sandev, "ventoy_sandev_write\n"); + return 0; +} + +static inline int ventoy_sandev_reset (void *sandev) +{ + (void)sandev; + DBGC(sandev, "ventoy_sandev_reset\n"); + return 0; +} + +#define sandev_reset ventoy_sandev_reset +#define sandev_read ventoy_vdisk_read +#define sandev_write ventoy_sandev_write + +#undef ECANCELED +#define ECANCELED 0x0b +#undef ENODEV +#define ENODEV 0x2c +#undef ENOTSUP +#define ENOTSUP 0x3c +#undef ENOMEM +#define ENOMEM 0x31 +#undef EIO +#define EIO 0x1d +#undef ENOEXEC +#define ENOEXEC 0x2e +#undef ENOSPC +#define ENOSPC 0x34 + + +#endif /* __VENTOY_INT13_H__ */ + diff --git a/IPXE/ipxe-3fe683e/src/config/settings.h b/IPXE/ipxe-3fe683e/src/config/settings.h new file mode 100644 index 00000000..8c22e1fa --- /dev/null +++ b/IPXE/ipxe-3fe683e/src/config/settings.h @@ -0,0 +1,24 @@ +#ifndef CONFIG_SETTINGS_H +#define CONFIG_SETTINGS_H + +/** @file + * + * Configuration settings sources + * + */ + +FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL ); + +//#define PCI_SETTINGS /* PCI device settings */ +//#define CPUID_SETTINGS /* CPUID settings */ +//#define MEMMAP_SETTINGS /* Memory map settings */ +//#define VMWARE_SETTINGS /* VMware GuestInfo settings */ +//#define VRAM_SETTINGS /* Video RAM dump settings */ +//#define ACPI_SETTINGS /* ACPI settings */ + +#include +#include NAMED_CONFIG(settings.h) +#include +#include LOCAL_NAMED_CONFIG(settings.h) + +#endif /* CONFIG_SETTINGS_H */ diff --git a/IPXE/ipxe-3fe683e/src/core/device.c b/IPXE/ipxe-3fe683e/src/core/device.c new file mode 100644 index 00000000..d3909b44 --- /dev/null +++ b/IPXE/ipxe-3fe683e/src/core/device.c @@ -0,0 +1,142 @@ +/* + * Copyright (C) 2006 Michael Brown . + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of the + * License, or any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + * + * You can also choose to distribute this program under the terms of + * the Unmodified Binary Distribution Licence (as given in the file + * COPYING.UBDL), provided that you have satisfied its requirements. + */ + +FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL ); + +#include +#include +#include +#include +#include +#include + +/** + * @file + * + * Device model + * + */ + +/** Registered root devices */ +static LIST_HEAD ( devices ); + +/** Device removal inhibition counter */ +int device_keep_count = 0; + +/** + * Probe a root device + * + * @v rootdev Root device + * @ret rc Return status code + */ +static int rootdev_probe ( struct root_device *rootdev ) { + int rc; + + DBG ( "Adding %s root bus\n", rootdev->dev.name ); + if ( ( rc = rootdev->driver->probe ( rootdev ) ) != 0 ) { + DBG ( "Failed to add %s root bus: %s\n", + rootdev->dev.name, strerror ( rc ) ); + return rc; + } + + return 0; +} + +/** + * Remove a root device + * + * @v rootdev Root device + */ +static void rootdev_remove ( struct root_device *rootdev ) { + rootdev->driver->remove ( rootdev ); + DBG ( "Removed %s root bus\n", rootdev->dev.name ); +} + +/** + * Probe all devices + * + * This initiates probing for all devices in the system. After this + * call, the device hierarchy will be populated, and all hardware + * should be ready to use. + */ +static void probe_devices ( void ) { + struct root_device *rootdev; + int rc; + + for_each_table_entry ( rootdev, ROOT_DEVICES ) { + list_add ( &rootdev->dev.siblings, &devices ); + INIT_LIST_HEAD ( &rootdev->dev.children ); + if ( ( rc = rootdev_probe ( rootdev ) ) != 0 ) + list_del ( &rootdev->dev.siblings ); + } +} + +/** + * Remove all devices + * + */ +static void remove_devices ( int booting __unused ) { + struct root_device *rootdev; + struct root_device *tmp; + + if ( device_keep_count != 0 ) { + DBG ( "Refusing to remove devices on shutdown\n" ); + return; + } + + list_for_each_entry_safe ( rootdev, tmp, &devices, dev.siblings ) { + rootdev_remove ( rootdev ); + list_del ( &rootdev->dev.siblings ); + } +} + +//struct startup_fn startup_devices __startup_fn ( STARTUP_NORMAL ) = { +struct startup_fn startup_devices = { + .name = "devices", + .startup = probe_devices, + .shutdown = remove_devices, +}; + +/** + * Identify a device behind an interface + * + * @v intf Interface + * @ret device Device, or NULL + */ +struct device * identify_device ( struct interface *intf ) { + struct interface *dest; + identify_device_TYPE ( void * ) *op = + intf_get_dest_op ( intf, identify_device, &dest ); + void *object = intf_object ( dest ); + void *device; + + if ( op ) { + device = op ( object ); + } else { + /* Default is to return NULL */ + device = NULL; + } + + intf_put ( dest ); + return device; +} diff --git a/IPXE/ipxe-3fe683e/src/core/main.c b/IPXE/ipxe-3fe683e/src/core/main.c new file mode 100644 index 00000000..6a60ad33 --- /dev/null +++ b/IPXE/ipxe-3fe683e/src/core/main.c @@ -0,0 +1,47 @@ +/************************************************************************** +iPXE - Network Bootstrap Program + +Literature dealing with the network protocols: + ARP - RFC826 + RARP - RFC903 + UDP - RFC768 + BOOTP - RFC951, RFC2132 (vendor extensions) + DHCP - RFC2131, RFC2132 (options) + TFTP - RFC1350, RFC2347 (options), RFC2348 (blocksize), RFC2349 (tsize) + RPC - RFC1831, RFC1832 (XDR), RFC1833 (rpcbind/portmapper) + +**************************************************************************/ + +FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL ); + +#include +#include +#include +#include +#include +#include + +/** + * Main entry point + * + * @ret rc Return status code + */ +__asmcall int main ( void ) { + int rc; + + /* Perform one-time-only initialisation (e.g. heap) */ + initialise(); + + /* Some devices take an unreasonably long time to initialise */ + //printf ( "%s initialising devices...", product_short_name ); + startup(); + //printf ( "ok\n" ); + + /* Attempt to boot */ + if ( ( rc = ventoy_boot_vdisk ( NULL ) ) != 0 ) + goto err_ipxe; + + err_ipxe: + shutdown_exit(); + return rc; +} diff --git a/IPXE/ipxe-3fe683e/src/core/ventoy_dummy.c b/IPXE/ipxe-3fe683e/src/core/ventoy_dummy.c new file mode 100644 index 00000000..ee7d114e --- /dev/null +++ b/IPXE/ipxe-3fe683e/src/core/ventoy_dummy.c @@ -0,0 +1,201 @@ +/* + * Copyright (C) 2017 Michael Brown . + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of the + * License, or any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + * + * You can also choose to distribute this program under the terms of + * the Unmodified Binary Distribution Licence (as given in the file + * COPYING.UBDL), provided that you have satisfied its requirements. + */ + +FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL ); + +/** + * @file + * + * SAN booting + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +unsigned long pci_bar_size ( struct pci_device *pci, unsigned int reg ) +{ + (void)pci; + (void)reg; + + return 0; +} + +unsigned long pci_bar_start ( struct pci_device *pci, unsigned int reg ) +{ + (void)pci; + (void)reg; + return 0; +} + +void adjust_pci_device ( struct pci_device *pci ) +{ + (void)pci; +} + +/* + * obj_netfront + * obj_netvsc + * + * ibft_model + */ + +int scsi_parse_lun ( const char *lun_string, struct scsi_lun *lun ) +{ + (void)lun_string; + (void)lun; + return 0; +} + +void scsi_parse_sense ( const void *data, size_t len, + struct scsi_sns_descriptor *sense ) +{ + (void)data; + (void)len; + (void)sense; + + return; +} + +void scsi_response ( struct interface *intf, struct scsi_rsp *response ) +{ + (void)intf; + (void)response; +} +int scsi_open ( struct interface *block, struct interface *scsi, + struct scsi_lun *lun ) +{ + (void)block; + (void)scsi; + (void)lun; + + return 0; +} + +int scsi_command ( struct interface *control, struct interface *data, + struct scsi_cmd *command ) +{ + (void)control; + (void)data; + (void)command; + + return 0; +} + + +int ata_open ( struct interface *block, struct interface *ata, + unsigned int device, unsigned int max_count ) +{ + (void)block; + (void)ata; + (void)device; + (void)max_count; + + return 0; +} + +int ata_command ( struct interface *control, struct interface *data, + struct ata_cmd *command ) +{ + (void)control; + (void)data; + (void)command; + + return 0; +} + +#if 0 +static uint32_t mCrcTable[256] = +{ + 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, + 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, + 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, + 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, + 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, + 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, + 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, + 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, + 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, + 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, + 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, + 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, + 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, + 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, + 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, + 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, + 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, + 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, + 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, + 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, + 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, + 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, + 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, + 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, + 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, + 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, + 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, + 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, + 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, + 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, + 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, + 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D +}; + +uint32_t CalculateCrc32 +( + const void *Buffer, + uint32_t Length, + uint32_t InitValue +) +{ + uint32_t Crc = 0; + uint32_t Index = 0; + const uint8_t *Ptr = (const uint8_t *)Buffer; + + Crc = InitValue ^ 0xffffffff; + for (Index = 0; Index < Length; Index++, Ptr++) + { + Crc = (Crc >> 8) ^ mCrcTable[(uint8_t) Crc ^ *Ptr]; + } + + return (Crc ^ 0xffffffff); +} + +#endif + diff --git a/IPXE/ipxe-3fe683e/src/core/vsprintf.c b/IPXE/ipxe-3fe683e/src/core/vsprintf.c new file mode 100644 index 00000000..4a231b46 --- /dev/null +++ b/IPXE/ipxe-3fe683e/src/core/vsprintf.c @@ -0,0 +1,501 @@ +/* + * Copyright (C) 2006 Michael Brown . + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of the + * License, or any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + * + * You can also choose to distribute this program under the terms of + * the Unmodified Binary Distribution Licence (as given in the file + * COPYING.UBDL), provided that you have satisfied its requirements. + */ + +FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL ); + +#include +#include +#include +#include +#include +#include + +/** @file */ + +#define CHAR_LEN 0 /**< "hh" length modifier */ +#define SHORT_LEN 1 /**< "h" length modifier */ +#define INT_LEN 2 /**< no length modifier */ +#define LONG_LEN 3 /**< "l" length modifier */ +#define LONGLONG_LEN 4 /**< "ll" length modifier */ +#define SIZE_T_LEN 5 /**< "z" length modifier */ + +static uint8_t type_sizes[] = { + [CHAR_LEN] = sizeof ( char ), + [SHORT_LEN] = sizeof ( short ), + [INT_LEN] = sizeof ( int ), + [LONG_LEN] = sizeof ( long ), + [LONGLONG_LEN] = sizeof ( long long ), + [SIZE_T_LEN] = sizeof ( size_t ), +}; + +/** + * Use lower-case for hexadecimal digits + * + * Note that this value is set to 0x20 since that makes for very + * efficient calculations. (Bitwise-ORing with @c LCASE converts to a + * lower-case character, for example.) + */ +#define LCASE 0x20 + +/** + * Use "alternate form" + * + * For hexadecimal numbers, this means to add a "0x" or "0X" prefix to + * the number. + */ +#define ALT_FORM 0x02 + +/** + * Use zero padding + * + * Note that this value is set to 0x10 since that allows the pad + * character to be calculated as @c 0x20|(flags&ZPAD) + */ +#define ZPAD 0x10 + +/** + * Format a hexadecimal number + * + * @v end End of buffer to contain number + * @v num Number to format + * @v width Minimum field width + * @v flags Format flags + * @ret ptr End of buffer + * + * Fills a buffer in reverse order with a formatted hexadecimal + * number. The number will be zero-padded to the specified width. + * Lower-case and "alternate form" (i.e. "0x" prefix) flags may be + * set. + * + * There must be enough space in the buffer to contain the largest + * number that this function can format. + */ +static char * format_hex ( char *end, unsigned long long num, int width, + int flags ) { + char *ptr = end; + int case_mod = ( flags & LCASE ); + int pad = ( ( flags & ZPAD ) | ' ' ); + + /* Generate the number */ + do { + *(--ptr) = "0123456789ABCDEF"[ num & 0xf ] | case_mod; + num >>= 4; + } while ( num ); + + /* Pad to width */ + while ( ( end - ptr ) < width ) + *(--ptr) = pad; + + /* Add "0x" or "0X" if alternate form specified */ + if ( flags & ALT_FORM ) { + *(--ptr) = 'X' | case_mod; + *(--ptr) = '0'; + } + + return ptr; +} + +/** + * Format a decimal number + * + * @v end End of buffer to contain number + * @v num Number to format + * @v width Minimum field width + * @v flags Format flags + * @ret ptr End of buffer + * + * Fills a buffer in reverse order with a formatted decimal number. + * The number will be space-padded to the specified width. + * + * There must be enough space in the buffer to contain the largest + * number that this function can format. + */ +static char * format_decimal ( char *end, signed long num, int width, + int flags ) { + char *ptr = end; + int negative = 0; + int zpad = ( flags & ZPAD ); + int pad = ( zpad | ' ' ); + + /* Generate the number */ + if ( num < 0 ) { + negative = 1; + num = -num; + } + do { + *(--ptr) = '0' + ( num % 10 ); + num /= 10; + } while ( num ); + + /* Add "-" if necessary */ + if ( negative && ( ! zpad ) ) + *(--ptr) = '-'; + + /* Pad to width */ + while ( ( end - ptr ) < width ) + *(--ptr) = pad; + + /* Add "-" if necessary */ + if ( negative && zpad ) + *ptr = '-'; + + return ptr; +} + +#define ZPAD 0x10 +char *format_unsigned_decimal(char *end, unsigned long long num, int width, int flags) +{ + char *ptr = end; + int zpad = ( flags & ZPAD ); + int pad = ( zpad | ' ' ); + + do { + *(--ptr) = '0' + ( num % 10 ); + num /= 10; + } while ( num ); + + /* Pad to width */ + while ( ( end - ptr ) < width ) + *(--ptr) = pad; + + return ptr; +} + +/** + * Print character via a printf context + * + * @v ctx Context + * @v c Character + * + * Call's the printf_context::handler() method and increments + * printf_context::len. + */ +static inline void cputchar ( struct printf_context *ctx, unsigned char c ) { + ctx->handler ( ctx, c ); + ++ctx->len; +} + +/** + * Write a formatted string to a printf context + * + * @v ctx Context + * @v fmt Format string + * @v args Arguments corresponding to the format string + * @ret len Length of formatted string + */ +size_t vcprintf ( struct printf_context *ctx, const char *fmt, va_list args ) { + int flags; + int width; + uint8_t *length; + char *ptr; + char tmp_buf[32]; /* 32 is enough for all numerical formats. + * Insane width fields could overflow this buffer. */ + wchar_t *wptr; + + /* Initialise context */ + ctx->len = 0; + + for ( ; *fmt ; fmt++ ) { + /* Pass through ordinary characters */ + if ( *fmt != '%' ) { + cputchar ( ctx, *fmt ); + continue; + } + fmt++; + /* Process flag characters */ + flags = 0; + for ( ; ; fmt++ ) { + if ( *fmt == '#' ) { + flags |= ALT_FORM; + } else if ( *fmt == '0' ) { + flags |= ZPAD; + } else { + /* End of flag characters */ + break; + } + } + /* Process field width */ + width = 0; + for ( ; ; fmt++ ) { + if ( ( ( unsigned ) ( *fmt - '0' ) ) < 10 ) { + width = ( width * 10 ) + ( *fmt - '0' ); + } else { + break; + } + } + /* We don't do floating point */ + /* Process length modifier */ + length = &type_sizes[INT_LEN]; + for ( ; ; fmt++ ) { + if ( *fmt == 'h' ) { + length--; + } else if ( *fmt == 'l' ) { + length++; + } else if ( *fmt == 'z' ) { + length = &type_sizes[SIZE_T_LEN]; + } else { + break; + } + } + /* Process conversion specifier */ + ptr = tmp_buf + sizeof ( tmp_buf ) - 1; + *ptr = '\0'; + wptr = NULL; + if ( *fmt == 'c' ) { + if ( length < &type_sizes[LONG_LEN] ) { + cputchar ( ctx, va_arg ( args, unsigned int ) ); + } else { + wchar_t wc; + size_t len; + + wc = va_arg ( args, wint_t ); + len = wcrtomb ( tmp_buf, wc, NULL ); + tmp_buf[len] = '\0'; + ptr = tmp_buf; + } + } else if ( *fmt == 's' ) { + if ( length < &type_sizes[LONG_LEN] ) { + ptr = va_arg ( args, char * ); + if ( ! ptr ) + ptr = ""; + } else { + wptr = va_arg ( args, wchar_t * ); + if ( ! wptr ) + ptr = ""; + } + } else if ( *fmt == 'p' ) { + intptr_t ptrval; + + ptrval = ( intptr_t ) va_arg ( args, void * ); + ptr = format_hex ( ptr, ptrval, width, + ( ALT_FORM | LCASE ) ); + } else if ( ( *fmt & ~0x20 ) == 'X' ) { + unsigned long long hex; + + flags |= ( *fmt & 0x20 ); /* LCASE */ + if ( *length >= sizeof ( unsigned long long ) ) { + hex = va_arg ( args, unsigned long long ); + } else if ( *length >= sizeof ( unsigned long ) ) { + hex = va_arg ( args, unsigned long ); + } else { + hex = va_arg ( args, unsigned int ); + } + ptr = format_hex ( ptr, hex, width, flags ); + } else if ( ( *fmt == 'd' ) || ( *fmt == 'i' ) ){ + signed long decimal; + + if ( *length >= sizeof ( signed long ) ) { + decimal = va_arg ( args, signed long ); + } else { + decimal = va_arg ( args, signed int ); + } + ptr = format_decimal ( ptr, decimal, width, flags ); + } else if ( ( *fmt == 'u' ) || ( *fmt == 'U' )){ + unsigned long long decimal; + if ( *length >= sizeof ( unsigned long long ) ) { + decimal = va_arg ( args, unsigned long long ); + } else if ( *length >= sizeof ( unsigned long ) ) { + decimal = va_arg ( args, unsigned long ); + } else { + decimal = va_arg ( args, unsigned int ); + } + ptr = format_unsigned_decimal( ptr, decimal, width, flags ); + } else { + *(--ptr) = *fmt; + } + /* Write out conversion result */ + if ( wptr == NULL ) { + for ( ; *ptr ; ptr++ ) { + cputchar ( ctx, *ptr ); + } + } else { + for ( ; *wptr ; wptr++ ) { + size_t len = wcrtomb ( tmp_buf, *wptr, NULL ); + for ( ptr = tmp_buf ; len-- ; ptr++ ) { + cputchar ( ctx, *ptr ); + } + } + } + } + + return ctx->len; +} + +/** Context used by vsnprintf() and friends */ +struct sputc_context { + struct printf_context ctx; + /** Buffer for formatted string (used by printf_sputc()) */ + char *buf; + /** Buffer length (used by printf_sputc()) */ + size_t max_len; +}; + +/** + * Write character to buffer + * + * @v ctx Context + * @v c Character + */ +static void printf_sputc ( struct printf_context *ctx, unsigned int c ) { + struct sputc_context * sctx = + container_of ( ctx, struct sputc_context, ctx ); + + if ( ctx->len < sctx->max_len ) + sctx->buf[ctx->len] = c; +} + +/** + * Write a formatted string to a buffer + * + * @v buf Buffer into which to write the string + * @v size Size of buffer + * @v fmt Format string + * @v args Arguments corresponding to the format string + * @ret len Length of formatted string + * + * If the buffer is too small to contain the string, the returned + * length is the length that would have been written had enough space + * been available. + */ +int vsnprintf ( char *buf, size_t size, const char *fmt, va_list args ) { + struct sputc_context sctx; + size_t len; + size_t end; + + /* Hand off to vcprintf */ + sctx.ctx.handler = printf_sputc; + sctx.buf = buf; + sctx.max_len = size; + len = vcprintf ( &sctx.ctx, fmt, args ); + + /* Add trailing NUL */ + if ( size ) { + end = size - 1; + if ( len < end ) + end = len; + buf[end] = '\0'; + } + + return len; +} + +/** + * Write a formatted string to a buffer + * + * @v buf Buffer into which to write the string + * @v size Size of buffer + * @v fmt Format string + * @v ... Arguments corresponding to the format string + * @ret len Length of formatted string + */ +int snprintf ( char *buf, size_t size, const char *fmt, ... ) { + va_list args; + int i; + + va_start ( args, fmt ); + i = vsnprintf ( buf, size, fmt, args ); + va_end ( args ); + return i; +} + +/** + * Version of vsnprintf() that accepts a signed buffer size + * + * @v buf Buffer into which to write the string + * @v size Size of buffer + * @v fmt Format string + * @v args Arguments corresponding to the format string + * @ret len Length of formatted string + */ +int vssnprintf ( char *buf, ssize_t ssize, const char *fmt, va_list args ) { + + /* Treat negative buffer size as zero buffer size */ + if ( ssize < 0 ) + ssize = 0; + + /* Hand off to vsnprintf */ + return vsnprintf ( buf, ssize, fmt, args ); +} + +/** + * Version of vsnprintf() that accepts a signed buffer size + * + * @v buf Buffer into which to write the string + * @v size Size of buffer + * @v fmt Format string + * @v ... Arguments corresponding to the format string + * @ret len Length of formatted string + */ +int ssnprintf ( char *buf, ssize_t ssize, const char *fmt, ... ) { + va_list args; + int len; + + /* Hand off to vssnprintf */ + va_start ( args, fmt ); + len = vssnprintf ( buf, ssize, fmt, args ); + va_end ( args ); + return len; +} + +/** + * Write character to console + * + * @v ctx Context + * @v c Character + */ +static void printf_putchar ( struct printf_context *ctx __unused, + unsigned int c ) { + putchar ( c ); +} + +/** + * Write a formatted string to the console + * + * @v fmt Format string + * @v args Arguments corresponding to the format string + * @ret len Length of formatted string + */ +int vprintf ( const char *fmt, va_list args ) { + struct printf_context ctx; + + /* Hand off to vcprintf */ + ctx.handler = printf_putchar; + return vcprintf ( &ctx, fmt, args ); +} + +/** + * Write a formatted string to the console. + * + * @v fmt Format string + * @v ... Arguments corresponding to the format string + * @ret len Length of formatted string + */ +int printf ( const char *fmt, ... ) { + va_list args; + int i; + + va_start ( args, fmt ); + i = vprintf ( fmt, args ); + va_end ( args ); + return i; +} diff --git a/IPXE/ipxe-3fe683e/src/drivers/net/efi/snp.c b/IPXE/ipxe-3fe683e/src/drivers/net/efi/snp.c new file mode 100644 index 00000000..8d15b6f1 --- /dev/null +++ b/IPXE/ipxe-3fe683e/src/drivers/net/efi/snp.c @@ -0,0 +1,122 @@ +/* + * Copyright (C) 2014 Michael Brown . + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of the + * License, or any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + * + * You can also choose to distribute this program under the terms of + * the Unmodified Binary Distribution Licence (as given in the file + * COPYING.UBDL), provided that you have satisfied its requirements. + */ + +FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL ); + +#if 0 + +#include +#include +#include +#include +#include "snpnet.h" +#include "nii.h" + +/** @file + * + * SNP driver + * + */ + +/** + * Check to see if driver supports a device + * + * @v device EFI device handle + * @ret rc Return status code + */ +static int snp_supported ( EFI_HANDLE device ) { + EFI_BOOT_SERVICES *bs = efi_systab->BootServices; + EFI_STATUS efirc; + + /* Check that this is not a device we are providing ourselves */ + if ( find_snpdev ( device ) != NULL ) { + DBGCP ( device, "SNP %s is provided by this binary\n", + efi_handle_name ( device ) ); + return -ENOTTY; + } + + /* Test for presence of simple network protocol */ + if ( ( efirc = bs->OpenProtocol ( device, + &efi_simple_network_protocol_guid, + NULL, efi_image_handle, device, + EFI_OPEN_PROTOCOL_TEST_PROTOCOL))!=0){ + DBGCP ( device, "SNP %s is not an SNP device\n", + efi_handle_name ( device ) ); + return -EEFI ( efirc ); + } + DBGC ( device, "SNP %s is an SNP device\n", + efi_handle_name ( device ) ); + + return 0; +} + +/** + * Check to see if driver supports a device + * + * @v device EFI device handle + * @ret rc Return status code + */ +static int nii_supported ( EFI_HANDLE device ) { + EFI_BOOT_SERVICES *bs = efi_systab->BootServices; + EFI_STATUS efirc; + + /* Check that this is not a device we are providing ourselves */ + if ( find_snpdev ( device ) != NULL ) { + DBGCP ( device, "NII %s is provided by this binary\n", + efi_handle_name ( device ) ); + return -ENOTTY; + } + + /* Test for presence of NII protocol */ + if ( ( efirc = bs->OpenProtocol ( device, + &efi_nii31_protocol_guid, + NULL, efi_image_handle, device, + EFI_OPEN_PROTOCOL_TEST_PROTOCOL))!=0){ + DBGCP ( device, "NII %s is not an NII device\n", + efi_handle_name ( device ) ); + return -EEFI ( efirc ); + } + DBGC ( device, "NII %s is an NII device\n", + efi_handle_name ( device ) ); + + return 0; +} + +/** EFI SNP driver */ +struct efi_driver snp_driver __efi_driver ( EFI_DRIVER_NORMAL ) = { + .name = "SNP", + .supported = snp_supported, + .start = snpnet_start, + .stop = snpnet_stop, +}; + +/** EFI NII driver */ +struct efi_driver nii_driver __efi_driver ( EFI_DRIVER_NORMAL ) = { + .name = "NII", + .supported = nii_supported, + .start = nii_start, + .stop = nii_stop, +}; + +#endif + diff --git a/IPXE/ipxe-3fe683e/src/include/ipxe/sanboot.h b/IPXE/ipxe-3fe683e/src/include/ipxe/sanboot.h new file mode 100644 index 00000000..d9b9de49 --- /dev/null +++ b/IPXE/ipxe-3fe683e/src/include/ipxe/sanboot.h @@ -0,0 +1,255 @@ +#ifndef _IPXE_SANBOOT_H +#define _IPXE_SANBOOT_H + +/** @file + * + * iPXE sanboot API + * + * The sanboot API provides methods for hooking, unhooking, + * describing, and booting from SAN devices. + */ + +FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL ); + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/** A SAN path */ +struct san_path { + /** Containing SAN device */ + struct san_device *sandev; + /** Path index */ + unsigned int index; + /** SAN device URI */ + struct uri *uri; + /** List of open/closed paths */ + struct list_head list; + + /** Underlying block device interface */ + struct interface block; + /** Process */ + struct process process; + /** Path status */ + int path_rc; + + /** ACPI descriptor (if applicable) */ + struct acpi_descriptor *desc; +}; + +/** A SAN device */ +struct san_device { + /** Reference count */ + struct refcnt refcnt; + /** List of SAN devices */ + struct list_head list; + + /** Drive number */ + unsigned int drive; + /** Flags */ + unsigned int flags; + + /** Command interface */ + struct interface command; + /** Command timeout timer */ + struct retry_timer timer; + /** Command status */ + int command_rc; + + /** Raw block device capacity */ + struct block_device_capacity capacity; + /** Block size shift + * + * To allow for emulation of CD-ROM access, this represents + * the left-shift required to translate from exposed logical + * I/O blocks to underlying blocks. + */ + unsigned int blksize_shift; + /** Drive is a CD-ROM */ + int is_cdrom; + + /** Driver private data */ + void *priv; + + /** Number of paths */ + unsigned int paths; + /** Current active path */ + struct san_path *active; + /** List of opened SAN paths */ + struct list_head opened; + /** List of closed SAN paths */ + struct list_head closed; + /** SAN paths */ + struct san_path path[0]; + + unsigned int exdrive; + int int13_command; + void *x86_regptr; + uint8_t boot_catalog_sector[2048]; +}; + +/** SAN device flags */ +enum san_device_flags { + /** Device should not be included in description tables */ + SAN_NO_DESCRIBE = 0x0001, +}; + +/** + * Calculate static inline sanboot API function name + * + * @v _prefix Subsystem prefix + * @v _api_func API function + * @ret _subsys_func Subsystem API function + */ +#define SANBOOT_INLINE( _subsys, _api_func ) \ + SINGLE_API_INLINE ( SANBOOT_PREFIX_ ## _subsys, _api_func ) + +/** + * Provide a sanboot API implementation + * + * @v _prefix Subsystem prefix + * @v _api_func API function + * @v _func Implementing function + */ +#define PROVIDE_SANBOOT( _subsys, _api_func, _func ) \ + PROVIDE_SINGLE_API ( SANBOOT_PREFIX_ ## _subsys, _api_func, _func ) + +/** + * Provide a static inline sanboot API implementation + * + * @v _prefix Subsystem prefix + * @v _api_func API function + */ +#define PROVIDE_SANBOOT_INLINE( _subsys, _api_func ) \ + PROVIDE_SINGLE_API_INLINE ( SANBOOT_PREFIX_ ## _subsys, _api_func ) + +/* Include all architecture-independent sanboot API headers */ +#include +#include +#include + +/* Include all architecture-dependent sanboot API headers */ +#include + +/** + * Hook SAN device + * + * @v drive Drive number + * @v uris List of URIs + * @v count Number of URIs + * @v flags Flags + * @ret drive Drive number, or negative error + */ +int san_hook ( unsigned int drive, struct uri **uris, unsigned int count, + unsigned int flags ); + +/** + * Unhook SAN device + * + * @v drive Drive number + */ +void san_unhook ( unsigned int drive ); + +/** + * Attempt to boot from a SAN device + * + * @v drive Drive number + * @v filename Filename (or NULL to use default) + * @ret rc Return status code + */ +int san_boot ( unsigned int drive, const char *filename ); + +/** + * Describe SAN devices for SAN-booted operating system + * + * @ret rc Return status code + */ +int san_describe ( void ); + +extern struct list_head san_devices; + +/** Iterate over all SAN devices */ +#define for_each_sandev( sandev ) \ + list_for_each_entry ( (sandev), &san_devices, list ) + +/** There exist some SAN devices + * + * @ret existence Existence of SAN devices + */ +static inline int have_sandevs ( void ) { + return ( ! list_empty ( &san_devices ) ); +} + +/** + * Get reference to SAN device + * + * @v sandev SAN device + * @ret sandev SAN device + */ +static inline __attribute__ (( always_inline )) struct san_device * +sandev_get ( struct san_device *sandev ) { + ref_get ( &sandev->refcnt ); + return sandev; +} + +/** + * Drop reference to SAN device + * + * @v sandev SAN device + */ +static inline __attribute__ (( always_inline )) void +sandev_put ( struct san_device *sandev ) { + ref_put ( &sandev->refcnt ); +} + +/** + * Calculate SAN device block size + * + * @v sandev SAN device + * @ret blksize Sector size + */ +static inline size_t sandev_blksize ( struct san_device *sandev ) { + return ( sandev->capacity.blksize << sandev->blksize_shift ); +} + +/** + * Calculate SAN device capacity + * + * @v sandev SAN device + * @ret blocks Number of blocks + */ +static inline uint64_t sandev_capacity ( struct san_device *sandev ) { + return ( sandev->capacity.blocks >> sandev->blksize_shift ); +} + +/** + * Check if SAN device needs to be reopened + * + * @v sandev SAN device + * @ret needs_reopen SAN device needs to be reopened + */ +static inline int sandev_needs_reopen ( struct san_device *sandev ) { + return ( sandev->active == NULL ); +} + +extern struct san_device * sandev_find ( unsigned int drive ); +extern int sandev_reopen ( struct san_device *sandev ); +extern int sandev_reset ( struct san_device *sandev ); +extern int sandev_read ( struct san_device *sandev, uint64_t lba, + unsigned int count, userptr_t buffer ); +extern int sandev_write ( struct san_device *sandev, uint64_t lba, + unsigned int count, userptr_t buffer ); +extern struct san_device * alloc_sandev ( struct uri **uris, unsigned int count, + size_t priv_size ); +extern int register_sandev ( struct san_device *sandev, unsigned int drive, + unsigned int flags ); +extern void unregister_sandev ( struct san_device *sandev ); +extern unsigned int san_default_drive ( void ); + +#endif /* _IPXE_SANBOOT_H */ diff --git a/IPXE/ipxe-3fe683e/src/include/ventoy.h b/IPXE/ipxe-3fe683e/src/include/ventoy.h new file mode 100644 index 00000000..07b8d3c7 --- /dev/null +++ b/IPXE/ipxe-3fe683e/src/include/ventoy.h @@ -0,0 +1,215 @@ + +#ifndef __VENTOY_VDISK_H__ +#define __VENTOY_VDISK_H__ + +FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL ); + +#define grub_uint64_t uint64_t +#define grub_uint32_t uint32_t +#define grub_uint16_t uint16_t +#define grub_uint8_t uint8_t + +#define COMPILE_ASSERT(expr) extern char __compile_assert[(expr) ? 1 : -1] + +#define VENTOY_GUID { 0x77772020, 0x2e77, 0x6576, { 0x6e, 0x74, 0x6f, 0x79, 0x2e, 0x6e, 0x65, 0x74 }} + +#pragma pack(1) + +typedef struct ventoy_guid +{ + grub_uint32_t data1; + grub_uint16_t data2; + grub_uint16_t data3; + grub_uint8_t data4[8]; +}ventoy_guid; + +typedef struct ventoy_image_disk_region +{ + grub_uint32_t image_sector_count; /* image sectors contained in this region */ + grub_uint32_t image_start_sector; /* image sector start */ + grub_uint64_t disk_start_sector; /* disk sector start */ +}ventoy_image_disk_region; + +typedef struct ventoy_image_location +{ + ventoy_guid guid; + + /* image sector size, currently this value is always 2048 */ + grub_uint32_t image_sector_size; + + /* disk sector size, normally the value is 512 */ + grub_uint32_t disk_sector_size; + + grub_uint32_t region_count; + + /* + * disk region data + * If the image file has more than one fragments in disk, + * there will be more than one region data here. + * + */ + ventoy_image_disk_region regions[1]; + + /* ventoy_image_disk_region regions[2~region_count-1] */ +}ventoy_image_location; + +typedef struct ventoy_os_param +{ + ventoy_guid guid; // VENTOY_GUID + grub_uint8_t chksum; // checksum + + grub_uint8_t vtoy_disk_guid[16]; + grub_uint64_t vtoy_disk_size; // disk size in bytes + grub_uint16_t vtoy_disk_part_id; // begin with 1 + grub_uint16_t vtoy_disk_part_type; // 0:exfat 1:ntfs other: reserved + char vtoy_img_path[384]; // It seems to be enough, utf-8 format + grub_uint64_t vtoy_img_size; // image file size in bytes + + /* + * Ventoy will write a copy of ventoy_image_location data into runtime memory + * this is the physically address and length of that memory. + * Address 0 means no such data exist. + * Address will be aligned by 4KB. + * + */ + grub_uint64_t vtoy_img_location_addr; + grub_uint32_t vtoy_img_location_len; + + grub_uint64_t vtoy_reserved[4]; // Internal use by ventoy + + grub_uint8_t reserved[31]; +}ventoy_os_param; + +#pragma pack() + +// compile assert to check that size of ventoy_os_param must be 512 +COMPILE_ASSERT(sizeof(ventoy_os_param) == 512); + + + + + + + +#pragma pack(4) + +typedef struct ventoy_chain_head +{ + ventoy_os_param os_param; + + grub_uint32_t disk_drive; + grub_uint32_t drive_map; + grub_uint32_t disk_sector_size; + + grub_uint64_t real_img_size_in_bytes; + grub_uint64_t virt_img_size_in_bytes; + grub_uint32_t boot_catalog; + grub_uint8_t boot_catalog_sector[2048]; + + grub_uint32_t img_chunk_offset; + grub_uint32_t img_chunk_num; + + grub_uint32_t override_chunk_offset; + grub_uint32_t override_chunk_num; + + grub_uint32_t virt_chunk_offset; + grub_uint32_t virt_chunk_num; +}ventoy_chain_head; + + +typedef struct ventoy_img_chunk +{ + grub_uint32_t img_start_sector; //2KB + grub_uint32_t img_end_sector; + + grub_uint64_t disk_start_sector; // in disk_sector_size + grub_uint64_t disk_end_sector; +}ventoy_img_chunk; + + +typedef struct ventoy_override_chunk +{ + grub_uint64_t img_offset; + grub_uint32_t override_size; + grub_uint8_t override_data[512]; +}ventoy_override_chunk; + +typedef struct ventoy_virt_chunk +{ + grub_uint32_t mem_sector_start; + grub_uint32_t mem_sector_end; + grub_uint32_t mem_sector_offset; + grub_uint32_t remap_sector_start; + grub_uint32_t remap_sector_end; + grub_uint32_t org_sector_start; +}ventoy_virt_chunk; + + +#pragma pack() + + +#define ventoy_debug_pause() \ +{\ + printf("\nPress Ctrl+C to continue......");\ + sleep(3600);\ + printf("\n");\ +} + +typedef struct ventoy_sector_flag +{ + uint8_t flag; // 0:init 1:mem 2:remap + uint64_t remap_lba; +}ventoy_sector_flag; + +#define VENTOY_BIOS_FAKE_DRIVE 0xFE + +extern char *g_cmdline_copy; +extern void *g_initrd_addr; +extern size_t g_initrd_len; +extern uint32_t g_disk_sector_size; +unsigned int ventoy_int13_hook (ventoy_chain_head *chain); +int ventoy_int13_boot ( unsigned int drive, void *imginfo, const char *cmdline); +void * ventoy_get_runtime_addr(void); +int ventoy_boot_vdisk(void *data); + + +uint32_t CalculateCrc32 +( + const void *Buffer, + uint32_t Length, + uint32_t InitValue +); + +struct smbios3_entry { + + uint8_t signature[5]; + + /** Checksum */ + uint8_t checksum; + + /** Length */ + uint8_t len; + + /** Major version */ + uint8_t major; + + /** Minor version */ + uint8_t minor; + + uint8_t docrev; + + uint8_t revision; + + uint8_t reserved; + + uint32_t maxsize; + + uint64_t address; +} __attribute__ (( packed )); + + +//#undef DBGLVL +//#define DBGLVL 7 + +#endif /* __VENTOY_VDISK_H__ */ + diff --git a/IPXE/ipxe-3fe683e/src/interface/efi/efi_pci.c b/IPXE/ipxe-3fe683e/src/interface/efi/efi_pci.c new file mode 100644 index 00000000..6726ef3f --- /dev/null +++ b/IPXE/ipxe-3fe683e/src/interface/efi/efi_pci.c @@ -0,0 +1,467 @@ +/* + * Copyright (C) 2008 Michael Brown . + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of the + * License, or any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + * + * You can also choose to distribute this program under the terms of + * the Unmodified Binary Distribution Licence (as given in the file + * COPYING.UBDL), provided that you have satisfied its requirements. + */ + +FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL ); + +#if 0 + +#include +#include +#include +#include +#include +#include +#include +#include + +/** @file + * + * iPXE PCI I/O API for EFI + * + */ + +/* Disambiguate the various error causes */ +#define EINFO_EEFI_PCI \ + __einfo_uniqify ( EINFO_EPLATFORM, 0x01, \ + "Could not open PCI I/O protocol" ) +#define EINFO_EEFI_PCI_NOT_PCI \ + __einfo_platformify ( EINFO_EEFI_PCI, EFI_UNSUPPORTED, \ + "Not a PCI device" ) +#define EEFI_PCI_NOT_PCI __einfo_error ( EINFO_EEFI_PCI_NOT_PCI ) +#define EINFO_EEFI_PCI_IN_USE \ + __einfo_platformify ( EINFO_EEFI_PCI, EFI_ACCESS_DENIED, \ + "PCI device already has a driver" ) +#define EEFI_PCI_IN_USE __einfo_error ( EINFO_EEFI_PCI_IN_USE ) +#define EEFI_PCI( efirc ) \ + EPLATFORM ( EINFO_EEFI_PCI, efirc, \ + EEFI_PCI_NOT_PCI, EEFI_PCI_IN_USE ) + +/****************************************************************************** + * + * iPXE PCI API + * + ****************************************************************************** + */ + +/** + * Locate EFI PCI root bridge I/O protocol + * + * @v pci PCI device + * @ret handle EFI PCI root bridge handle + * @ret root EFI PCI root bridge I/O protocol, or NULL if not found + * @ret rc Return status code + */ +static int efipci_root ( struct pci_device *pci, EFI_HANDLE *handle, + EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL **root ) { + EFI_BOOT_SERVICES *bs = efi_systab->BootServices; + EFI_HANDLE *handles; + UINTN num_handles; + union { + void *interface; + EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *root; + } u; + EFI_STATUS efirc; + UINTN i; + int rc; + + /* Enumerate all handles */ + if ( ( efirc = bs->LocateHandleBuffer ( ByProtocol, + &efi_pci_root_bridge_io_protocol_guid, + NULL, &num_handles, &handles ) ) != 0 ) { + rc = -EEFI ( efirc ); + DBGC ( pci, "EFIPCI " PCI_FMT " cannot locate root bridges: " + "%s\n", PCI_ARGS ( pci ), strerror ( rc ) ); + goto err_locate; + } + + /* Look for matching root bridge I/O protocol */ + for ( i = 0 ; i < num_handles ; i++ ) { + *handle = handles[i]; + if ( ( efirc = bs->OpenProtocol ( *handle, + &efi_pci_root_bridge_io_protocol_guid, + &u.interface, efi_image_handle, *handle, + EFI_OPEN_PROTOCOL_GET_PROTOCOL ) ) != 0 ) { + rc = -EEFI ( efirc ); + DBGC ( pci, "EFIPCI " PCI_FMT " cannot open %s: %s\n", + PCI_ARGS ( pci ), efi_handle_name ( *handle ), + strerror ( rc ) ); + continue; + } + if ( u.root->SegmentNumber == PCI_SEG ( pci->busdevfn ) ) { + *root = u.root; + bs->FreePool ( handles ); + return 0; + } + bs->CloseProtocol ( *handle, + &efi_pci_root_bridge_io_protocol_guid, + efi_image_handle, *handle ); + } + DBGC ( pci, "EFIPCI " PCI_FMT " found no root bridge\n", + PCI_ARGS ( pci ) ); + rc = -ENOENT; + + bs->FreePool ( handles ); + err_locate: + return rc; +} + +/** + * Calculate EFI PCI configuration space address + * + * @v pci PCI device + * @v location Encoded offset and width + * @ret address EFI PCI address + */ +static unsigned long efipci_address ( struct pci_device *pci, + unsigned long location ) { + + return EFI_PCI_ADDRESS ( PCI_BUS ( pci->busdevfn ), + PCI_SLOT ( pci->busdevfn ), + PCI_FUNC ( pci->busdevfn ), + EFIPCI_OFFSET ( location ) ); +} + +/** + * Read from PCI configuration space + * + * @v pci PCI device + * @v location Encoded offset and width + * @ret value Value + * @ret rc Return status code + */ +int efipci_read ( struct pci_device *pci, unsigned long location, + void *value ) { + EFI_BOOT_SERVICES *bs = efi_systab->BootServices; + EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *root; + EFI_HANDLE handle; + EFI_STATUS efirc; + int rc; + + /* Identify root bridge */ + if ( ( rc = efipci_root ( pci, &handle, &root ) ) != 0 ) + goto err_root; + + /* Read from configuration space */ + if ( ( efirc = root->Pci.Read ( root, EFIPCI_WIDTH ( location ), + efipci_address ( pci, location ), 1, + value ) ) != 0 ) { + rc = -EEFI ( efirc ); + DBGC ( pci, "EFIPCI " PCI_FMT " config read from offset %02lx " + "failed: %s\n", PCI_ARGS ( pci ), + EFIPCI_OFFSET ( location ), strerror ( rc ) ); + goto err_read; + } + + err_read: + bs->CloseProtocol ( handle, &efi_pci_root_bridge_io_protocol_guid, + efi_image_handle, handle ); + err_root: + return rc; +} + +/** + * Write to PCI configuration space + * + * @v pci PCI device + * @v location Encoded offset and width + * @v value Value + * @ret rc Return status code + */ +int efipci_write ( struct pci_device *pci, unsigned long location, + unsigned long value ) { + EFI_BOOT_SERVICES *bs = efi_systab->BootServices; + EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *root; + EFI_HANDLE handle; + EFI_STATUS efirc; + int rc; + + /* Identify root bridge */ + if ( ( rc = efipci_root ( pci, &handle, &root ) ) != 0 ) + goto err_root; + + /* Read from configuration space */ + if ( ( efirc = root->Pci.Write ( root, EFIPCI_WIDTH ( location ), + efipci_address ( pci, location ), 1, + &value ) ) != 0 ) { + rc = -EEFI ( efirc ); + DBGC ( pci, "EFIPCI " PCI_FMT " config write to offset %02lx " + "failed: %s\n", PCI_ARGS ( pci ), + EFIPCI_OFFSET ( location ), strerror ( rc ) ); + goto err_write; + } + + err_write: + bs->CloseProtocol ( handle, &efi_pci_root_bridge_io_protocol_guid, + efi_image_handle, handle ); + err_root: + return rc; +} + +PROVIDE_PCIAPI_INLINE ( efi, pci_num_bus ); +PROVIDE_PCIAPI_INLINE ( efi, pci_read_config_byte ); +PROVIDE_PCIAPI_INLINE ( efi, pci_read_config_word ); +PROVIDE_PCIAPI_INLINE ( efi, pci_read_config_dword ); +PROVIDE_PCIAPI_INLINE ( efi, pci_write_config_byte ); +PROVIDE_PCIAPI_INLINE ( efi, pci_write_config_word ); +PROVIDE_PCIAPI_INLINE ( efi, pci_write_config_dword ); + +/****************************************************************************** + * + * EFI PCI device instantiation + * + ****************************************************************************** + */ + +/** + * Open EFI PCI device + * + * @v device EFI device handle + * @v attributes Protocol opening attributes + * @v pci PCI device to fill in + * @ret rc Return status code + */ +int efipci_open ( EFI_HANDLE device, UINT32 attributes, + struct pci_device *pci ) { + EFI_BOOT_SERVICES *bs = efi_systab->BootServices; + union { + EFI_PCI_IO_PROTOCOL *pci_io; + void *interface; + } pci_io; + UINTN pci_segment, pci_bus, pci_dev, pci_fn; + unsigned int busdevfn; + EFI_STATUS efirc; + int rc; + + /* See if device is a PCI device */ + if ( ( efirc = bs->OpenProtocol ( device, &efi_pci_io_protocol_guid, + &pci_io.interface, efi_image_handle, + device, attributes ) ) != 0 ) { + rc = -EEFI_PCI ( efirc ); + DBGCP ( device, "EFIPCI %s cannot open PCI protocols: %s\n", + efi_handle_name ( device ), strerror ( rc ) ); + goto err_open_protocol; + } + + /* Get PCI bus:dev.fn address */ + if ( ( efirc = pci_io.pci_io->GetLocation ( pci_io.pci_io, &pci_segment, + &pci_bus, &pci_dev, + &pci_fn ) ) != 0 ) { + rc = -EEFI ( efirc ); + DBGC ( device, "EFIPCI %s could not get PCI location: %s\n", + efi_handle_name ( device ), strerror ( rc ) ); + goto err_get_location; + } + busdevfn = PCI_BUSDEVFN ( pci_segment, pci_bus, pci_dev, pci_fn ); + pci_init ( pci, busdevfn ); + DBGCP ( device, "EFIPCI " PCI_FMT " is %s\n", + PCI_ARGS ( pci ), efi_handle_name ( device ) ); + + /* Try to enable I/O cycles, memory cycles, and bus mastering. + * Some platforms will 'helpfully' report errors if these bits + * can't be enabled (for example, if the card doesn't actually + * support I/O cycles). Work around any such platforms by + * enabling bits individually and simply ignoring any errors. + */ + pci_io.pci_io->Attributes ( pci_io.pci_io, + EfiPciIoAttributeOperationEnable, + EFI_PCI_IO_ATTRIBUTE_IO, NULL ); + pci_io.pci_io->Attributes ( pci_io.pci_io, + EfiPciIoAttributeOperationEnable, + EFI_PCI_IO_ATTRIBUTE_MEMORY, NULL ); + pci_io.pci_io->Attributes ( pci_io.pci_io, + EfiPciIoAttributeOperationEnable, + EFI_PCI_IO_ATTRIBUTE_BUS_MASTER, NULL ); + + /* Populate PCI device */ + if ( ( rc = pci_read_config ( pci ) ) != 0 ) { + DBGC ( device, "EFIPCI " PCI_FMT " cannot read PCI " + "configuration: %s\n", + PCI_ARGS ( pci ), strerror ( rc ) ); + goto err_pci_read_config; + } + + return 0; + + err_pci_read_config: + err_get_location: + bs->CloseProtocol ( device, &efi_pci_io_protocol_guid, + efi_image_handle, device ); + err_open_protocol: + return rc; +} + +/** + * Close EFI PCI device + * + * @v device EFI device handle + */ +void efipci_close ( EFI_HANDLE device ) { + EFI_BOOT_SERVICES *bs = efi_systab->BootServices; + + bs->CloseProtocol ( device, &efi_pci_io_protocol_guid, + efi_image_handle, device ); +} + +/** + * Get EFI PCI device information + * + * @v device EFI device handle + * @v pci PCI device to fill in + * @ret rc Return status code + */ +int efipci_info ( EFI_HANDLE device, struct pci_device *pci ) { + int rc; + + /* Open PCI device, if possible */ + if ( ( rc = efipci_open ( device, EFI_OPEN_PROTOCOL_GET_PROTOCOL, + pci ) ) != 0 ) + return rc; + + /* Close PCI device */ + efipci_close ( device ); + + return 0; +} + +/****************************************************************************** + * + * EFI PCI driver + * + ****************************************************************************** + */ + +/** + * Check to see if driver supports a device + * + * @v device EFI device handle + * @ret rc Return status code + */ +static int efipci_supported ( EFI_HANDLE device ) { + struct pci_device pci; + int rc; + + /* Get PCI device information */ + if ( ( rc = efipci_info ( device, &pci ) ) != 0 ) + return rc; + + /* Look for a driver */ + if ( ( rc = pci_find_driver ( &pci ) ) != 0 ) { + DBGC ( device, "EFIPCI " PCI_FMT " (%04x:%04x class %06x) " + "has no driver\n", PCI_ARGS ( &pci ), pci.vendor, + pci.device, pci.class ); + return rc; + } + DBGC ( device, "EFIPCI " PCI_FMT " (%04x:%04x class %06x) has driver " + "\"%s\"\n", PCI_ARGS ( &pci ), pci.vendor, pci.device, + pci.class, pci.id->name ); + + return 0; +} + +/** + * Attach driver to device + * + * @v efidev EFI device + * @ret rc Return status code + */ +static int efipci_start ( struct efi_device *efidev ) { + EFI_HANDLE device = efidev->device; + struct pci_device *pci; + int rc; + + /* Allocate PCI device */ + pci = zalloc ( sizeof ( *pci ) ); + if ( ! pci ) { + rc = -ENOMEM; + goto err_alloc; + } + + /* Open PCI device */ + if ( ( rc = efipci_open ( device, ( EFI_OPEN_PROTOCOL_BY_DRIVER | + EFI_OPEN_PROTOCOL_EXCLUSIVE ), + pci ) ) != 0 ) { + DBGC ( device, "EFIPCI %s could not open PCI device: %s\n", + efi_handle_name ( device ), strerror ( rc ) ); + DBGC_EFI_OPENERS ( device, device, &efi_pci_io_protocol_guid ); + goto err_open; + } + + /* Find driver */ + if ( ( rc = pci_find_driver ( pci ) ) != 0 ) { + DBGC ( device, "EFIPCI " PCI_FMT " has no driver\n", + PCI_ARGS ( pci ) ); + goto err_find_driver; + } + + /* Mark PCI device as a child of the EFI device */ + pci->dev.parent = &efidev->dev; + list_add ( &pci->dev.siblings, &efidev->dev.children ); + + /* Probe driver */ + if ( ( rc = pci_probe ( pci ) ) != 0 ) { + DBGC ( device, "EFIPCI " PCI_FMT " could not probe driver " + "\"%s\": %s\n", PCI_ARGS ( pci ), pci->id->name, + strerror ( rc ) ); + goto err_probe; + } + DBGC ( device, "EFIPCI " PCI_FMT " using driver \"%s\"\n", + PCI_ARGS ( pci ), pci->id->name ); + + efidev_set_drvdata ( efidev, pci ); + return 0; + + pci_remove ( pci ); + err_probe: + list_del ( &pci->dev.siblings ); + err_find_driver: + efipci_close ( device ); + err_open: + free ( pci ); + err_alloc: + return rc; +} + +/** + * Detach driver from device + * + * @v efidev EFI device + */ +static void efipci_stop ( struct efi_device *efidev ) { + struct pci_device *pci = efidev_get_drvdata ( efidev ); + EFI_HANDLE device = efidev->device; + + pci_remove ( pci ); + list_del ( &pci->dev.siblings ); + efipci_close ( device ); + free ( pci ); +} + +/** EFI PCI driver */ +struct efi_driver efipci_driver __efi_driver ( EFI_DRIVER_NORMAL ) = { + .name = "PCI", + .supported = efipci_supported, + .start = efipci_start, + .stop = efipci_stop, +}; + +#endif diff --git a/IPXE/ipxe-3fe683e/src/net/tcp/iscsi.c b/IPXE/ipxe-3fe683e/src/net/tcp/iscsi.c new file mode 100644 index 00000000..babf286c --- /dev/null +++ b/IPXE/ipxe-3fe683e/src/net/tcp/iscsi.c @@ -0,0 +1,2152 @@ +/* + * Copyright (C) 2006 Michael Brown . + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of the + * License, or any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + * + * You can also choose to distribute this program under the terms of + * the Unmodified Binary Distribution Licence (as given in the file + * COPYING.UBDL), provided that you have satisfied its requirements. + */ + +FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL ); + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/** @file + * + * iSCSI protocol + * + */ + +FEATURE ( FEATURE_PROTOCOL, "iSCSI", DHCP_EB_FEATURE_ISCSI, 1 ); + +/* Disambiguate the various error causes */ +#define EACCES_INCORRECT_TARGET_USERNAME \ + __einfo_error ( EINFO_EACCES_INCORRECT_TARGET_USERNAME ) +#define EINFO_EACCES_INCORRECT_TARGET_USERNAME \ + __einfo_uniqify ( EINFO_EACCES, 0x01, "Incorrect target username" ) +#define EACCES_INCORRECT_TARGET_PASSWORD \ + __einfo_error ( EINFO_EACCES_INCORRECT_TARGET_PASSWORD ) +#define EINFO_EACCES_INCORRECT_TARGET_PASSWORD \ + __einfo_uniqify ( EINFO_EACCES, 0x02, "Incorrect target password" ) +#define EINVAL_ROOT_PATH_TOO_SHORT \ + __einfo_error ( EINFO_EINVAL_ROOT_PATH_TOO_SHORT ) +#define EINFO_EINVAL_ROOT_PATH_TOO_SHORT \ + __einfo_uniqify ( EINFO_EINVAL, 0x01, "Root path too short" ) +#define EINVAL_BAD_CREDENTIAL_MIX \ + __einfo_error ( EINFO_EINVAL_BAD_CREDENTIAL_MIX ) +#define EINFO_EINVAL_BAD_CREDENTIAL_MIX \ + __einfo_uniqify ( EINFO_EINVAL, 0x02, "Bad credential mix" ) +#define EINVAL_NO_ROOT_PATH \ + __einfo_error ( EINFO_EINVAL_NO_ROOT_PATH ) +#define EINFO_EINVAL_NO_ROOT_PATH \ + __einfo_uniqify ( EINFO_EINVAL, 0x03, "No root path" ) +#define EINVAL_NO_TARGET_IQN \ + __einfo_error ( EINFO_EINVAL_NO_TARGET_IQN ) +#define EINFO_EINVAL_NO_TARGET_IQN \ + __einfo_uniqify ( EINFO_EINVAL, 0x04, "No target IQN" ) +#define EINVAL_NO_INITIATOR_IQN \ + __einfo_error ( EINFO_EINVAL_NO_INITIATOR_IQN ) +#define EINFO_EINVAL_NO_INITIATOR_IQN \ + __einfo_uniqify ( EINFO_EINVAL, 0x05, "No initiator IQN" ) +#define EIO_TARGET_UNAVAILABLE \ + __einfo_error ( EINFO_EIO_TARGET_UNAVAILABLE ) +#define EINFO_EIO_TARGET_UNAVAILABLE \ + __einfo_uniqify ( EINFO_EIO, 0x01, "Target not currently operational" ) +#define EIO_TARGET_NO_RESOURCES \ + __einfo_error ( EINFO_EIO_TARGET_NO_RESOURCES ) +#define EINFO_EIO_TARGET_NO_RESOURCES \ + __einfo_uniqify ( EINFO_EIO, 0x02, "Target out of resources" ) +#define ENOTSUP_INITIATOR_STATUS \ + __einfo_error ( EINFO_ENOTSUP_INITIATOR_STATUS ) +#define EINFO_ENOTSUP_INITIATOR_STATUS \ + __einfo_uniqify ( EINFO_ENOTSUP, 0x01, "Unsupported initiator status" ) +#define ENOTSUP_OPCODE \ + __einfo_error ( EINFO_ENOTSUP_OPCODE ) +#define EINFO_ENOTSUP_OPCODE \ + __einfo_uniqify ( EINFO_ENOTSUP, 0x02, "Unsupported opcode" ) +#define ENOTSUP_DISCOVERY \ + __einfo_error ( EINFO_ENOTSUP_DISCOVERY ) +#define EINFO_ENOTSUP_DISCOVERY \ + __einfo_uniqify ( EINFO_ENOTSUP, 0x03, "Discovery not supported" ) +#define ENOTSUP_TARGET_STATUS \ + __einfo_error ( EINFO_ENOTSUP_TARGET_STATUS ) +#define EINFO_ENOTSUP_TARGET_STATUS \ + __einfo_uniqify ( EINFO_ENOTSUP, 0x04, "Unsupported target status" ) +#define EPERM_INITIATOR_AUTHENTICATION \ + __einfo_error ( EINFO_EPERM_INITIATOR_AUTHENTICATION ) +#define EINFO_EPERM_INITIATOR_AUTHENTICATION \ + __einfo_uniqify ( EINFO_EPERM, 0x01, "Initiator authentication failed" ) +#define EPERM_INITIATOR_AUTHORISATION \ + __einfo_error ( EINFO_EPERM_INITIATOR_AUTHORISATION ) +#define EINFO_EPERM_INITIATOR_AUTHORISATION \ + __einfo_uniqify ( EINFO_EPERM, 0x02, "Initiator not authorised" ) +#define EPROTO_INVALID_CHAP_ALGORITHM \ + __einfo_error ( EINFO_EPROTO_INVALID_CHAP_ALGORITHM ) +#define EINFO_EPROTO_INVALID_CHAP_ALGORITHM \ + __einfo_uniqify ( EINFO_EPROTO, 0x01, "Invalid CHAP algorithm" ) +#define EPROTO_INVALID_CHAP_IDENTIFIER \ + __einfo_error ( EINFO_EPROTO_INVALID_CHAP_IDENTIFIER ) +#define EINFO_EPROTO_INVALID_CHAP_IDENTIFIER \ + __einfo_uniqify ( EINFO_EPROTO, 0x02, "Invalid CHAP identifier" ) +#define EPROTO_INVALID_LARGE_BINARY \ + __einfo_error ( EINFO_EPROTO_INVALID_LARGE_BINARY ) +#define EINFO_EPROTO_INVALID_LARGE_BINARY \ + __einfo_uniqify ( EINFO_EPROTO, 0x03, "Invalid large binary value" ) +#define EPROTO_INVALID_CHAP_RESPONSE \ + __einfo_error ( EINFO_EPROTO_INVALID_CHAP_RESPONSE ) +#define EINFO_EPROTO_INVALID_CHAP_RESPONSE \ + __einfo_uniqify ( EINFO_EPROTO, 0x04, "Invalid CHAP response" ) +#define EPROTO_INVALID_KEY_VALUE_PAIR \ + __einfo_error ( EINFO_EPROTO_INVALID_KEY_VALUE_PAIR ) +#define EINFO_EPROTO_INVALID_KEY_VALUE_PAIR \ + __einfo_uniqify ( EINFO_EPROTO, 0x05, "Invalid key/value pair" ) +#define EPROTO_VALUE_REJECTED \ + __einfo_error ( EINFO_EPROTO_VALUE_REJECTED ) +#define EINFO_EPROTO_VALUE_REJECTED \ + __einfo_uniqify ( EINFO_EPROTO, 0x06, "Parameter rejected" ) + +static void iscsi_start_tx ( struct iscsi_session *iscsi ); +static void iscsi_start_login ( struct iscsi_session *iscsi ); +static void iscsi_start_data_out ( struct iscsi_session *iscsi, + unsigned int datasn ); + +/** + * Finish receiving PDU data into buffer + * + * @v iscsi iSCSI session + */ +static void iscsi_rx_buffered_data_done ( struct iscsi_session *iscsi ) { + free ( iscsi->rx_buffer ); + iscsi->rx_buffer = NULL; +} + +/** + * Receive PDU data into buffer + * + * @v iscsi iSCSI session + * @v data Data to receive + * @v len Length of data + * @ret rc Return status code + * + * This can be used when the RX PDU type handler wishes to buffer up + * all received data and process the PDU as a single unit. The caller + * is repsonsible for calling iscsi_rx_buffered_data_done() after + * processing the data. + */ +static int iscsi_rx_buffered_data ( struct iscsi_session *iscsi, + const void *data, size_t len ) { + + /* Allocate buffer on first call */ + if ( ! iscsi->rx_buffer ) { + iscsi->rx_buffer = malloc ( iscsi->rx_len ); + if ( ! iscsi->rx_buffer ) + return -ENOMEM; + } + + /* Copy data to buffer */ + assert ( ( iscsi->rx_offset + len ) <= iscsi->rx_len ); + memcpy ( ( iscsi->rx_buffer + iscsi->rx_offset ), data, len ); + + return 0; +} + +/** + * Free iSCSI session + * + * @v refcnt Reference counter + */ +static void iscsi_free ( struct refcnt *refcnt ) { + struct iscsi_session *iscsi = + container_of ( refcnt, struct iscsi_session, refcnt ); + + free ( iscsi->initiator_iqn ); + free ( iscsi->target_address ); + free ( iscsi->target_iqn ); + free ( iscsi->initiator_username ); + free ( iscsi->initiator_password ); + free ( iscsi->target_username ); + free ( iscsi->target_password ); + chap_finish ( &iscsi->chap ); + iscsi_rx_buffered_data_done ( iscsi ); + free ( iscsi->command ); + free ( iscsi ); +} + +/** + * Shut down iSCSI interface + * + * @v iscsi iSCSI session + * @v rc Reason for close + */ +static void iscsi_close ( struct iscsi_session *iscsi, int rc ) { + + /* A TCP graceful close is still an error from our point of view */ + if ( rc == 0 ) + rc = -ECONNRESET; + + DBGC ( iscsi, "iSCSI %p closed: %s\n", iscsi, strerror ( rc ) ); + + /* Stop transmission process */ + process_del ( &iscsi->process ); + + /* Shut down interfaces */ + intfs_shutdown ( rc, &iscsi->socket, &iscsi->control, &iscsi->data, + NULL ); +} + +/** + * Assign new iSCSI initiator task tag + * + * @v iscsi iSCSI session + */ +static void iscsi_new_itt ( struct iscsi_session *iscsi ) { + static uint16_t itt_idx; + + iscsi->itt = ( ISCSI_TAG_MAGIC | (++itt_idx) ); +} + +/** + * Open iSCSI transport-layer connection + * + * @v iscsi iSCSI session + * @ret rc Return status code + */ +static int iscsi_open_connection ( struct iscsi_session *iscsi ) { + struct sockaddr_tcpip target; + int rc; + + assert ( iscsi->tx_state == ISCSI_TX_IDLE ); + assert ( iscsi->rx_state == ISCSI_RX_BHS ); + assert ( iscsi->rx_offset == 0 ); + + /* Open socket */ + memset ( &target, 0, sizeof ( target ) ); + target.st_port = htons ( iscsi->target_port ); + if ( ( rc = xfer_open_named_socket ( &iscsi->socket, SOCK_STREAM, + ( struct sockaddr * ) &target, + iscsi->target_address, + NULL ) ) != 0 ) { + DBGC ( iscsi, "iSCSI %p could not open socket: %s\n", + iscsi, strerror ( rc ) ); + return rc; + } + + /* Enter security negotiation phase */ + iscsi->status = ( ISCSI_STATUS_SECURITY_NEGOTIATION_PHASE | + ISCSI_STATUS_STRINGS_SECURITY ); + if ( iscsi->target_username ) + iscsi->status |= ISCSI_STATUS_AUTH_REVERSE_REQUIRED; + + /* Assign new ISID */ + iscsi->isid_iana_qual = ( random() & 0xffff ); + + /* Assign fresh initiator task tag */ + iscsi_new_itt ( iscsi ); + + /* Initiate login */ + iscsi_start_login ( iscsi ); + + return 0; +} + +/** + * Close iSCSI transport-layer connection + * + * @v iscsi iSCSI session + * @v rc Reason for close + * + * Closes the transport-layer connection and resets the session state + * ready to attempt a fresh login. + */ +static void iscsi_close_connection ( struct iscsi_session *iscsi, int rc ) { + + /* Close all data transfer interfaces */ + intf_restart ( &iscsi->socket, rc ); + + /* Clear connection status */ + iscsi->status = 0; + + /* Reset TX and RX state machines */ + iscsi->tx_state = ISCSI_TX_IDLE; + iscsi->rx_state = ISCSI_RX_BHS; + iscsi->rx_offset = 0; + + /* Free any temporary dynamically allocated memory */ + chap_finish ( &iscsi->chap ); + iscsi_rx_buffered_data_done ( iscsi ); +} + +/** + * Mark iSCSI SCSI operation as complete + * + * @v iscsi iSCSI session + * @v rc Return status code + * @v rsp SCSI response, if any + * + * Note that iscsi_scsi_done() will not close the connection, and must + * therefore be called only when the internal state machines are in an + * appropriate state, otherwise bad things may happen on the next call + * to iscsi_scsi_command(). The general rule is to call + * iscsi_scsi_done() only at the end of receiving a PDU; at this point + * the TX and RX engines should both be idle. + */ +static void iscsi_scsi_done ( struct iscsi_session *iscsi, int rc, + struct scsi_rsp *rsp ) { + uint32_t itt = iscsi->itt; + + assert ( iscsi->tx_state == ISCSI_TX_IDLE ); + + /* Clear command */ + free ( iscsi->command ); + iscsi->command = NULL; + + /* Send SCSI response, if any */ + if ( rsp ) + scsi_response ( &iscsi->data, rsp ); + + /* Close SCSI command, if this is still the same command. (It + * is possible that the command interface has already been + * closed as a result of the SCSI response we sent.) + */ + if ( iscsi->itt == itt ) + intf_restart ( &iscsi->data, rc ); +} + +/**************************************************************************** + * + * iSCSI SCSI command issuing + * + */ + +/** + * Build iSCSI SCSI command BHS + * + * @v iscsi iSCSI session + * + * We don't currently support bidirectional commands (i.e. with both + * Data-In and Data-Out segments); these would require providing code + * to generate an AHS, and there doesn't seem to be any need for it at + * the moment. + */ +static void iscsi_start_command ( struct iscsi_session *iscsi ) { + struct iscsi_bhs_scsi_command *command = &iscsi->tx_bhs.scsi_command; + + assert ( ! ( iscsi->command->data_in && iscsi->command->data_out ) ); + + /* Construct BHS and initiate transmission */ + iscsi_start_tx ( iscsi ); + command->opcode = ISCSI_OPCODE_SCSI_COMMAND; + command->flags = ( ISCSI_FLAG_FINAL | + ISCSI_COMMAND_ATTR_SIMPLE ); + if ( iscsi->command->data_in ) + command->flags |= ISCSI_COMMAND_FLAG_READ; + if ( iscsi->command->data_out ) + command->flags |= ISCSI_COMMAND_FLAG_WRITE; + /* lengths left as zero */ + memcpy ( &command->lun, &iscsi->command->lun, + sizeof ( command->lun ) ); + command->itt = htonl ( iscsi->itt ); + command->exp_len = htonl ( iscsi->command->data_in_len | + iscsi->command->data_out_len ); + command->cmdsn = htonl ( iscsi->cmdsn ); + command->expstatsn = htonl ( iscsi->statsn + 1 ); + memcpy ( &command->cdb, &iscsi->command->cdb, sizeof ( command->cdb )); + DBGC2 ( iscsi, "iSCSI %p start " SCSI_CDB_FORMAT " %s %#zx\n", + iscsi, SCSI_CDB_DATA ( command->cdb ), + ( iscsi->command->data_in ? "in" : "out" ), + ( iscsi->command->data_in ? + iscsi->command->data_in_len : + iscsi->command->data_out_len ) ); +} + +/** + * Receive data segment of an iSCSI SCSI response PDU + * + * @v iscsi iSCSI session + * @v data Received data + * @v len Length of received data + * @v remaining Data remaining after this data + * @ret rc Return status code + */ +static int iscsi_rx_scsi_response ( struct iscsi_session *iscsi, + const void *data, size_t len, + size_t remaining ) { + struct iscsi_bhs_scsi_response *response + = &iscsi->rx_bhs.scsi_response; + struct scsi_rsp rsp; + uint32_t residual_count; + size_t data_len; + int rc; + + /* Buffer up the PDU data */ + if ( ( rc = iscsi_rx_buffered_data ( iscsi, data, len ) ) != 0 ) { + DBGC ( iscsi, "iSCSI %p could not buffer SCSI response: %s\n", + iscsi, strerror ( rc ) ); + return rc; + } + if ( remaining ) + return 0; + + /* Parse SCSI response and discard buffer */ + memset ( &rsp, 0, sizeof ( rsp ) ); + rsp.status = response->status; + residual_count = ntohl ( response->residual_count ); + if ( response->flags & ISCSI_DATA_FLAG_OVERFLOW ) { + rsp.overrun = residual_count; + } else if ( response->flags & ISCSI_DATA_FLAG_UNDERFLOW ) { + rsp.overrun = -(residual_count); + } + data_len = ISCSI_DATA_LEN ( response->lengths ); + if ( data_len ) { + scsi_parse_sense ( ( iscsi->rx_buffer + 2 ), ( data_len - 2 ), + &rsp.sense ); + } + iscsi_rx_buffered_data_done ( iscsi ); + + /* Check for errors */ + if ( response->response != ISCSI_RESPONSE_COMMAND_COMPLETE ) + return -EIO; + + /* Mark as completed */ + iscsi_scsi_done ( iscsi, 0, &rsp ); + return 0; +} + +/** + * Receive data segment of an iSCSI data-in PDU + * + * @v iscsi iSCSI session + * @v data Received data + * @v len Length of received data + * @v remaining Data remaining after this data + * @ret rc Return status code + */ +static int iscsi_rx_data_in ( struct iscsi_session *iscsi, + const void *data, size_t len, + size_t remaining ) { + struct iscsi_bhs_data_in *data_in = &iscsi->rx_bhs.data_in; + unsigned long offset; + + /* Copy data to data-in buffer */ + offset = ntohl ( data_in->offset ) + iscsi->rx_offset; + assert ( iscsi->command != NULL ); + assert ( iscsi->command->data_in ); + assert ( ( offset + len ) <= iscsi->command->data_in_len ); + copy_to_user ( iscsi->command->data_in, offset, data, len ); + + /* Wait for whole SCSI response to arrive */ + if ( remaining ) + return 0; + + /* Mark as completed if status is present */ + if ( data_in->flags & ISCSI_DATA_FLAG_STATUS ) { + assert ( ( offset + len ) == iscsi->command->data_in_len ); + assert ( data_in->flags & ISCSI_FLAG_FINAL ); + /* iSCSI cannot return an error status via a data-in */ + iscsi_scsi_done ( iscsi, 0, NULL ); + } + + return 0; +} + +/** + * Receive data segment of an iSCSI R2T PDU + * + * @v iscsi iSCSI session + * @v data Received data + * @v len Length of received data + * @v remaining Data remaining after this data + * @ret rc Return status code + */ +static int iscsi_rx_r2t ( struct iscsi_session *iscsi, + const void *data __unused, size_t len __unused, + size_t remaining __unused ) { + struct iscsi_bhs_r2t *r2t = &iscsi->rx_bhs.r2t; + + /* Record transfer parameters and trigger first data-out */ + iscsi->ttt = ntohl ( r2t->ttt ); + iscsi->transfer_offset = ntohl ( r2t->offset ); + iscsi->transfer_len = ntohl ( r2t->len ); + iscsi_start_data_out ( iscsi, 0 ); + + return 0; +} + +/** + * Build iSCSI data-out BHS + * + * @v iscsi iSCSI session + * @v datasn Data sequence number within the transfer + * + */ +static void iscsi_start_data_out ( struct iscsi_session *iscsi, + unsigned int datasn ) { + struct iscsi_bhs_data_out *data_out = &iscsi->tx_bhs.data_out; + unsigned long offset; + unsigned long remaining; + unsigned long len; + + /* We always send 512-byte Data-Out PDUs; this removes the + * need to worry about the target's MaxRecvDataSegmentLength. + */ + offset = datasn * 512; + remaining = iscsi->transfer_len - offset; + len = remaining; + if ( len > 512 ) + len = 512; + + /* Construct BHS and initiate transmission */ + iscsi_start_tx ( iscsi ); + data_out->opcode = ISCSI_OPCODE_DATA_OUT; + if ( len == remaining ) + data_out->flags = ( ISCSI_FLAG_FINAL ); + ISCSI_SET_LENGTHS ( data_out->lengths, 0, len ); + data_out->lun = iscsi->command->lun; + data_out->itt = htonl ( iscsi->itt ); + data_out->ttt = htonl ( iscsi->ttt ); + data_out->expstatsn = htonl ( iscsi->statsn + 1 ); + data_out->datasn = htonl ( datasn ); + data_out->offset = htonl ( iscsi->transfer_offset + offset ); + DBGC ( iscsi, "iSCSI %p start data out DataSN %#x len %#lx\n", + iscsi, datasn, len ); +} + +/** + * Complete iSCSI data-out PDU transmission + * + * @v iscsi iSCSI session + * + */ +static void iscsi_data_out_done ( struct iscsi_session *iscsi ) { + struct iscsi_bhs_data_out *data_out = &iscsi->tx_bhs.data_out; + + /* If we haven't reached the end of the sequence, start + * sending the next data-out PDU. + */ + if ( ! ( data_out->flags & ISCSI_FLAG_FINAL ) ) + iscsi_start_data_out ( iscsi, ntohl ( data_out->datasn ) + 1 ); +} + +/** + * Send iSCSI data-out data segment + * + * @v iscsi iSCSI session + * @ret rc Return status code + */ +static int iscsi_tx_data_out ( struct iscsi_session *iscsi ) { + struct iscsi_bhs_data_out *data_out = &iscsi->tx_bhs.data_out; + struct io_buffer *iobuf; + unsigned long offset; + size_t len; + size_t pad_len; + + offset = ntohl ( data_out->offset ); + len = ISCSI_DATA_LEN ( data_out->lengths ); + pad_len = ISCSI_DATA_PAD_LEN ( data_out->lengths ); + + assert ( iscsi->command != NULL ); + assert ( iscsi->command->data_out ); + assert ( ( offset + len ) <= iscsi->command->data_out_len ); + + iobuf = xfer_alloc_iob ( &iscsi->socket, ( len + pad_len ) ); + if ( ! iobuf ) + return -ENOMEM; + + copy_from_user ( iob_put ( iobuf, len ), + iscsi->command->data_out, offset, len ); + memset ( iob_put ( iobuf, pad_len ), 0, pad_len ); + + return xfer_deliver_iob ( &iscsi->socket, iobuf ); +} + +/** + * Receive data segment of an iSCSI NOP-In + * + * @v iscsi iSCSI session + * @v data Received data + * @v len Length of received data + * @v remaining Data remaining after this data + * @ret rc Return status code + */ +static int iscsi_rx_nop_in ( struct iscsi_session *iscsi, + const void *data __unused, size_t len __unused, + size_t remaining __unused ) { + struct iscsi_nop_in *nop_in = &iscsi->rx_bhs.nop_in; + + DBGC2 ( iscsi, "iSCSI %p received NOP-In\n", iscsi ); + + /* We don't currently have the ability to respond to NOP-Ins + * sent as ping requests, but we can happily accept NOP-Ins + * sent merely to update CmdSN. + */ + if ( nop_in->ttt == htonl ( ISCSI_TAG_RESERVED ) ) + return 0; + + /* Ignore any other NOP-Ins. The target may eventually + * disconnect us for failing to respond, but this minimises + * unnecessary connection closures. + */ + DBGC ( iscsi, "iSCSI %p received unsupported NOP-In with TTT %08x\n", + iscsi, ntohl ( nop_in->ttt ) ); + return 0; +} + +/**************************************************************************** + * + * iSCSI login + * + */ + +/** + * Build iSCSI login request strings + * + * @v iscsi iSCSI session + * + * These are the initial set of strings sent in the first login + * request PDU. We want the following settings: + * + * HeaderDigest=None + * DataDigest=None + * MaxConnections=1 (irrelevant; we make only one connection anyway) [4] + * InitialR2T=Yes [1] + * ImmediateData=No (irrelevant; we never send immediate data) [4] + * MaxRecvDataSegmentLength=8192 (default; we don't care) [3] + * MaxBurstLength=262144 (default; we don't care) [3] + * FirstBurstLength=65536 (irrelevant due to other settings) [5] + * DefaultTime2Wait=0 [2] + * DefaultTime2Retain=0 [2] + * MaxOutstandingR2T=1 + * DataPDUInOrder=Yes + * DataSequenceInOrder=Yes + * ErrorRecoveryLevel=0 + * + * [1] InitialR2T has an OR resolution function, so the target may + * force us to use it. We therefore simplify our logic by always + * using it. + * + * [2] These ensure that we can safely start a new task once we have + * reconnected after a failure, without having to manually tidy up + * after the old one. + * + * [3] We are quite happy to use the RFC-defined default values for + * these parameters, but some targets (notably OpenSolaris) + * incorrectly assume a default value of zero, so we explicitly + * specify the default values. + * + * [4] We are quite happy to use the RFC-defined default values for + * these parameters, but some targets (notably a QNAP TS-639Pro) fail + * unless they are supplied, so we explicitly specify the default + * values. + * + * [5] FirstBurstLength is defined to be irrelevant since we already + * force InitialR2T=Yes and ImmediateData=No, but some targets + * (notably LIO as of kernel 4.11) fail unless it is specified, so we + * explicitly specify the default value. + */ +static int iscsi_build_login_request_strings ( struct iscsi_session *iscsi, + void *data, size_t len ) { + unsigned int used = 0; + const char *auth_method; + + if ( iscsi->status & ISCSI_STATUS_STRINGS_SECURITY ) { + /* Default to allowing no authentication */ + auth_method = "None"; + /* If we have a credential to supply, permit CHAP */ + if ( iscsi->initiator_username ) + auth_method = "CHAP,None"; + /* If we have a credential to check, force CHAP */ + if ( iscsi->target_username ) + auth_method = "CHAP"; + used += ssnprintf ( data + used, len - used, + "InitiatorName=%s%c" + "TargetName=%s%c" + "SessionType=Normal%c" + "AuthMethod=%s%c", + iscsi->initiator_iqn, 0, + iscsi->target_iqn, 0, 0, + auth_method, 0 ); + } + + if ( iscsi->status & ISCSI_STATUS_STRINGS_CHAP_ALGORITHM ) { + used += ssnprintf ( data + used, len - used, "CHAP_A=5%c", 0 ); + } + + if ( ( iscsi->status & ISCSI_STATUS_STRINGS_CHAP_RESPONSE ) ) { + char buf[ base16_encoded_len ( iscsi->chap.response_len ) + 1 ]; + assert ( iscsi->initiator_username != NULL ); + base16_encode ( iscsi->chap.response, iscsi->chap.response_len, + buf, sizeof ( buf ) ); + used += ssnprintf ( data + used, len - used, + "CHAP_N=%s%cCHAP_R=0x%s%c", + iscsi->initiator_username, 0, buf, 0 ); + } + + if ( ( iscsi->status & ISCSI_STATUS_STRINGS_CHAP_CHALLENGE ) ) { + size_t challenge_len = ( sizeof ( iscsi->chap_challenge ) - 1 ); + char buf[ base16_encoded_len ( challenge_len ) + 1 ]; + base16_encode ( ( iscsi->chap_challenge + 1 ), challenge_len, + buf, sizeof ( buf ) ); + used += ssnprintf ( data + used, len - used, + "CHAP_I=%d%cCHAP_C=0x%s%c", + iscsi->chap_challenge[0], 0, buf, 0 ); + } + + if ( iscsi->status & ISCSI_STATUS_STRINGS_OPERATIONAL ) { + used += ssnprintf ( data + used, len - used, + "HeaderDigest=None%c" + "DataDigest=None%c" + "MaxConnections=1%c" + "InitialR2T=Yes%c" + "ImmediateData=No%c" + "MaxRecvDataSegmentLength=8192%c" + "MaxBurstLength=262144%c" + "FirstBurstLength=65536%c" + "DefaultTime2Wait=0%c" + "DefaultTime2Retain=0%c" + "MaxOutstandingR2T=1%c" + "DataPDUInOrder=Yes%c" + "DataSequenceInOrder=Yes%c" + "ErrorRecoveryLevel=0%c", + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ); + } + + return used; +} + +/** + * Build iSCSI login request BHS + * + * @v iscsi iSCSI session + */ +static void iscsi_start_login ( struct iscsi_session *iscsi ) { + struct iscsi_bhs_login_request *request = &iscsi->tx_bhs.login_request; + int len; + + switch ( iscsi->status & ISCSI_LOGIN_CSG_MASK ) { + case ISCSI_LOGIN_CSG_SECURITY_NEGOTIATION: + DBGC ( iscsi, "iSCSI %p entering security negotiation\n", + iscsi ); + break; + case ISCSI_LOGIN_CSG_OPERATIONAL_NEGOTIATION: + DBGC ( iscsi, "iSCSI %p entering operational negotiation\n", + iscsi ); + break; + default: + assert ( 0 ); + } + + /* Construct BHS and initiate transmission */ + iscsi_start_tx ( iscsi ); + request->opcode = ( ISCSI_OPCODE_LOGIN_REQUEST | + ISCSI_FLAG_IMMEDIATE ); + request->flags = ( ( iscsi->status & ISCSI_STATUS_PHASE_MASK ) | + ISCSI_LOGIN_FLAG_TRANSITION ); + /* version_max and version_min left as zero */ + len = iscsi_build_login_request_strings ( iscsi, NULL, 0 ); + ISCSI_SET_LENGTHS ( request->lengths, 0, len ); + request->isid_iana_en = htonl ( ISCSI_ISID_IANA | + IANA_EN_FEN_SYSTEMS ); + request->isid_iana_qual = htons ( iscsi->isid_iana_qual ); + /* tsih left as zero */ + request->itt = htonl ( iscsi->itt ); + /* cid left as zero */ + request->cmdsn = htonl ( iscsi->cmdsn ); + request->expstatsn = htonl ( iscsi->statsn + 1 ); +} + +/** + * Complete iSCSI login request PDU transmission + * + * @v iscsi iSCSI session + * + */ +static void iscsi_login_request_done ( struct iscsi_session *iscsi ) { + + /* Clear any "strings to send" flags */ + iscsi->status &= ~ISCSI_STATUS_STRINGS_MASK; + + /* Free any dynamically allocated storage used for login */ + chap_finish ( &iscsi->chap ); +} + +/** + * Transmit data segment of an iSCSI login request PDU + * + * @v iscsi iSCSI session + * @ret rc Return status code + * + * For login requests, the data segment consists of the login strings. + */ +static int iscsi_tx_login_request ( struct iscsi_session *iscsi ) { + struct iscsi_bhs_login_request *request = &iscsi->tx_bhs.login_request; + struct io_buffer *iobuf; + size_t len; + size_t pad_len; + + len = ISCSI_DATA_LEN ( request->lengths ); + pad_len = ISCSI_DATA_PAD_LEN ( request->lengths ); + iobuf = xfer_alloc_iob ( &iscsi->socket, ( len + pad_len ) ); + if ( ! iobuf ) + return -ENOMEM; + iob_put ( iobuf, len ); + iscsi_build_login_request_strings ( iscsi, iobuf->data, len ); + memset ( iob_put ( iobuf, pad_len ), 0, pad_len ); + + return xfer_deliver_iob ( &iscsi->socket, iobuf ); +} + +/** + * Decode large binary value + * + * @v encoded Encoded large binary value + * @v raw Raw data + * @v len Length of data buffer + * @ret len Length of raw data, or negative error + */ +static int iscsi_large_binary_decode ( const char *encoded, uint8_t *raw, + size_t len ) { + + /* Check for initial '0x' or '0b' and decode as appropriate */ + if ( *(encoded++) == '0' ) { + switch ( tolower ( *(encoded++) ) ) { + case 'x' : + return base16_decode ( encoded, raw, len ); + case 'b' : + return base64_decode ( encoded, raw, len ); + } + } + + return -EPROTO_INVALID_LARGE_BINARY; +} + +/** + * Handle iSCSI TargetAddress text value + * + * @v iscsi iSCSI session + * @v value TargetAddress value + * @ret rc Return status code + */ +static int iscsi_handle_targetaddress_value ( struct iscsi_session *iscsi, + const char *value ) { + char *separator; + + DBGC ( iscsi, "iSCSI %p will redirect to %s\n", iscsi, value ); + + /* Replace target address */ + free ( iscsi->target_address ); + iscsi->target_address = strdup ( value ); + if ( ! iscsi->target_address ) + return -ENOMEM; + + /* Replace target port */ + iscsi->target_port = htons ( ISCSI_PORT ); + separator = strchr ( iscsi->target_address, ':' ); + if ( separator ) { + *separator = '\0'; + iscsi->target_port = strtoul ( ( separator + 1 ), NULL, 0 ); + } + + return 0; +} + +/** + * Handle iSCSI AuthMethod text value + * + * @v iscsi iSCSI session + * @v value AuthMethod value + * @ret rc Return status code + */ +static int iscsi_handle_authmethod_value ( struct iscsi_session *iscsi, + const char *value ) { + + /* If server requests CHAP, send the CHAP_A string */ + if ( strcmp ( value, "CHAP" ) == 0 ) { + DBGC ( iscsi, "iSCSI %p initiating CHAP authentication\n", + iscsi ); + iscsi->status |= ( ISCSI_STATUS_STRINGS_CHAP_ALGORITHM | + ISCSI_STATUS_AUTH_FORWARD_REQUIRED ); + } + + return 0; +} + +/** + * Handle iSCSI CHAP_A text value + * + * @v iscsi iSCSI session + * @v value CHAP_A value + * @ret rc Return status code + */ +static int iscsi_handle_chap_a_value ( struct iscsi_session *iscsi, + const char *value ) { + + /* We only ever offer "5" (i.e. MD5) as an algorithm, so if + * the server responds with anything else it is a protocol + * violation. + */ + if ( strcmp ( value, "5" ) != 0 ) { + DBGC ( iscsi, "iSCSI %p got invalid CHAP algorithm \"%s\"\n", + iscsi, value ); + return -EPROTO_INVALID_CHAP_ALGORITHM; + } + + return 0; +} + +/** + * Handle iSCSI CHAP_I text value + * + * @v iscsi iSCSI session + * @v value CHAP_I value + * @ret rc Return status code + */ +static int iscsi_handle_chap_i_value ( struct iscsi_session *iscsi, + const char *value ) { + unsigned int identifier; + char *endp; + int rc; + + /* The CHAP identifier is an integer value */ + identifier = strtoul ( value, &endp, 0 ); + if ( *endp != '\0' ) { + DBGC ( iscsi, "iSCSI %p saw invalid CHAP identifier \"%s\"\n", + iscsi, value ); + return -EPROTO_INVALID_CHAP_IDENTIFIER; + } + + /* Prepare for CHAP with MD5 */ + chap_finish ( &iscsi->chap ); + if ( ( rc = chap_init ( &iscsi->chap, &md5_algorithm ) ) != 0 ) { + DBGC ( iscsi, "iSCSI %p could not initialise CHAP: %s\n", + iscsi, strerror ( rc ) ); + return rc; + } + + /* Identifier and secret are the first two components of the + * challenge. + */ + chap_set_identifier ( &iscsi->chap, identifier ); + if ( iscsi->initiator_password ) { + chap_update ( &iscsi->chap, iscsi->initiator_password, + strlen ( iscsi->initiator_password ) ); + } + + return 0; +} + +/** + * Handle iSCSI CHAP_C text value + * + * @v iscsi iSCSI session + * @v value CHAP_C value + * @ret rc Return status code + */ +static int iscsi_handle_chap_c_value ( struct iscsi_session *iscsi, + const char *value ) { + uint8_t buf[ strlen ( value ) ]; /* Decoding never expands data */ + unsigned int i; + int len; + int rc; + + /* Process challenge */ + len = iscsi_large_binary_decode ( value, buf, sizeof ( buf ) ); + if ( len < 0 ) { + rc = len; + DBGC ( iscsi, "iSCSI %p invalid CHAP challenge \"%s\": %s\n", + iscsi, value, strerror ( rc ) ); + return rc; + } + chap_update ( &iscsi->chap, buf, len ); + + /* Build CHAP response */ + DBGC ( iscsi, "iSCSI %p sending CHAP response\n", iscsi ); + chap_respond ( &iscsi->chap ); + iscsi->status |= ISCSI_STATUS_STRINGS_CHAP_RESPONSE; + + /* Send CHAP challenge, if applicable */ + if ( iscsi->target_username ) { + iscsi->status |= ISCSI_STATUS_STRINGS_CHAP_CHALLENGE; + /* Generate CHAP challenge data */ + for ( i = 0 ; i < sizeof ( iscsi->chap_challenge ) ; i++ ) { + iscsi->chap_challenge[i] = random(); + } + } + + return 0; +} + +/** + * Handle iSCSI CHAP_N text value + * + * @v iscsi iSCSI session + * @v value CHAP_N value + * @ret rc Return status code + */ +static int iscsi_handle_chap_n_value ( struct iscsi_session *iscsi, + const char *value ) { + + /* The target username isn't actually involved at any point in + * the authentication process; it merely serves to identify + * which password the target is using to generate the CHAP + * response. We unnecessarily verify that the username is as + * expected, in order to provide mildly helpful diagnostics if + * the target is supplying the wrong username/password + * combination. + */ + if ( iscsi->target_username && + ( strcmp ( iscsi->target_username, value ) != 0 ) ) { + DBGC ( iscsi, "iSCSI %p target username \"%s\" incorrect " + "(wanted \"%s\")\n", + iscsi, value, iscsi->target_username ); + return -EACCES_INCORRECT_TARGET_USERNAME; + } + + return 0; +} + +/** + * Handle iSCSI CHAP_R text value + * + * @v iscsi iSCSI session + * @v value CHAP_R value + * @ret rc Return status code + */ +static int iscsi_handle_chap_r_value ( struct iscsi_session *iscsi, + const char *value ) { + uint8_t buf[ strlen ( value ) ]; /* Decoding never expands data */ + int len; + int rc; + + /* Generate CHAP response for verification */ + chap_finish ( &iscsi->chap ); + if ( ( rc = chap_init ( &iscsi->chap, &md5_algorithm ) ) != 0 ) { + DBGC ( iscsi, "iSCSI %p could not initialise CHAP: %s\n", + iscsi, strerror ( rc ) ); + return rc; + } + chap_set_identifier ( &iscsi->chap, iscsi->chap_challenge[0] ); + if ( iscsi->target_password ) { + chap_update ( &iscsi->chap, iscsi->target_password, + strlen ( iscsi->target_password ) ); + } + chap_update ( &iscsi->chap, &iscsi->chap_challenge[1], + ( sizeof ( iscsi->chap_challenge ) - 1 ) ); + chap_respond ( &iscsi->chap ); + + /* Process response */ + len = iscsi_large_binary_decode ( value, buf, sizeof ( buf ) ); + if ( len < 0 ) { + rc = len; + DBGC ( iscsi, "iSCSI %p invalid CHAP response \"%s\": %s\n", + iscsi, value, strerror ( rc ) ); + return rc; + } + + /* Check CHAP response */ + if ( len != ( int ) iscsi->chap.response_len ) { + DBGC ( iscsi, "iSCSI %p invalid CHAP response length\n", + iscsi ); + return -EPROTO_INVALID_CHAP_RESPONSE; + } + if ( memcmp ( buf, iscsi->chap.response, len ) != 0 ) { + DBGC ( iscsi, "iSCSI %p incorrect CHAP response \"%s\"\n", + iscsi, value ); + return -EACCES_INCORRECT_TARGET_PASSWORD; + } + + /* Mark session as authenticated */ + iscsi->status |= ISCSI_STATUS_AUTH_REVERSE_OK; + + return 0; +} + +/** An iSCSI text string that we want to handle */ +struct iscsi_string_type { + /** String key + * + * This is the portion preceding the "=" sign, + * e.g. "InitiatorName", "CHAP_A", etc. + */ + const char *key; + /** Handle iSCSI string value + * + * @v iscsi iSCSI session + * @v value iSCSI string value + * @ret rc Return status code + */ + int ( * handle ) ( struct iscsi_session *iscsi, const char *value ); +}; + +/** iSCSI text strings that we want to handle */ +static struct iscsi_string_type iscsi_string_types[] = { + { "TargetAddress", iscsi_handle_targetaddress_value }, + { "AuthMethod", iscsi_handle_authmethod_value }, + { "CHAP_A", iscsi_handle_chap_a_value }, + { "CHAP_I", iscsi_handle_chap_i_value }, + { "CHAP_C", iscsi_handle_chap_c_value }, + { "CHAP_N", iscsi_handle_chap_n_value }, + { "CHAP_R", iscsi_handle_chap_r_value }, + { NULL, NULL } +}; + +/** + * Handle iSCSI string + * + * @v iscsi iSCSI session + * @v string iSCSI string (in "key=value" format) + * @ret rc Return status code + */ +static int iscsi_handle_string ( struct iscsi_session *iscsi, + const char *string ) { + struct iscsi_string_type *type; + const char *separator; + const char *value; + size_t key_len; + int rc; + + /* Find separator */ + separator = strchr ( string, '=' ); + if ( ! separator ) { + DBGC ( iscsi, "iSCSI %p malformed string %s\n", + iscsi, string ); + return -EPROTO_INVALID_KEY_VALUE_PAIR; + } + key_len = ( separator - string ); + value = ( separator + 1 ); + + /* Check for rejections. Since we send only non-rejectable + * values, any rejection is a fatal protocol error. + */ + if ( strcmp ( value, "Reject" ) == 0 ) { + DBGC ( iscsi, "iSCSI %p rejection: %s\n", iscsi, string ); + return -EPROTO_VALUE_REJECTED; + } + + /* Handle key/value pair */ + for ( type = iscsi_string_types ; type->key ; type++ ) { + if ( strncmp ( string, type->key, key_len ) != 0 ) + continue; + DBGC ( iscsi, "iSCSI %p handling %s\n", iscsi, string ); + if ( ( rc = type->handle ( iscsi, value ) ) != 0 ) { + DBGC ( iscsi, "iSCSI %p could not handle %s: %s\n", + iscsi, string, strerror ( rc ) ); + return rc; + } + return 0; + } + DBGC ( iscsi, "iSCSI %p ignoring %s\n", iscsi, string ); + return 0; +} + +/** + * Handle iSCSI strings + * + * @v iscsi iSCSI session + * @v string iSCSI string buffer + * @v len Length of string buffer + * @ret rc Return status code + */ +static int iscsi_handle_strings ( struct iscsi_session *iscsi, + const char *strings, size_t len ) { + size_t string_len; + int rc; + + /* Handle each string in turn, taking care not to overrun the + * data buffer in case of badly-terminated data. + */ + while ( 1 ) { + string_len = ( strnlen ( strings, len ) + 1 ); + if ( string_len > len ) + break; + if ( ( rc = iscsi_handle_string ( iscsi, strings ) ) != 0 ) + return rc; + strings += string_len; + len -= string_len; + } + return 0; +} + +/** + * Convert iSCSI response status to return status code + * + * @v status_class iSCSI status class + * @v status_detail iSCSI status detail + * @ret rc Return status code + */ +static int iscsi_status_to_rc ( unsigned int status_class, + unsigned int status_detail ) { + switch ( status_class ) { + case ISCSI_STATUS_INITIATOR_ERROR : + switch ( status_detail ) { + case ISCSI_STATUS_INITIATOR_ERROR_AUTHENTICATION : + return -EPERM_INITIATOR_AUTHENTICATION; + case ISCSI_STATUS_INITIATOR_ERROR_AUTHORISATION : + return -EPERM_INITIATOR_AUTHORISATION; + case ISCSI_STATUS_INITIATOR_ERROR_NOT_FOUND : + case ISCSI_STATUS_INITIATOR_ERROR_REMOVED : + return -ENODEV; + default : + return -ENOTSUP_INITIATOR_STATUS; + } + case ISCSI_STATUS_TARGET_ERROR : + switch ( status_detail ) { + case ISCSI_STATUS_TARGET_ERROR_UNAVAILABLE: + return -EIO_TARGET_UNAVAILABLE; + case ISCSI_STATUS_TARGET_ERROR_NO_RESOURCES: + return -EIO_TARGET_NO_RESOURCES; + default: + return -ENOTSUP_TARGET_STATUS; + } + default : + return -EINVAL; + } +} + +/** + * Receive data segment of an iSCSI login response PDU + * + * @v iscsi iSCSI session + * @v data Received data + * @v len Length of received data + * @v remaining Data remaining after this data + * @ret rc Return status code + */ +static int iscsi_rx_login_response ( struct iscsi_session *iscsi, + const void *data, size_t len, + size_t remaining ) { + struct iscsi_bhs_login_response *response + = &iscsi->rx_bhs.login_response; + int rc; + + /* Buffer up the PDU data */ + if ( ( rc = iscsi_rx_buffered_data ( iscsi, data, len ) ) != 0 ) { + DBGC ( iscsi, "iSCSI %p could not buffer login response: %s\n", + iscsi, strerror ( rc ) ); + return rc; + } + if ( remaining ) + return 0; + + /* Process string data and discard string buffer */ + if ( ( rc = iscsi_handle_strings ( iscsi, iscsi->rx_buffer, + iscsi->rx_len ) ) != 0 ) + return rc; + iscsi_rx_buffered_data_done ( iscsi ); + + /* Check for login redirection */ + if ( response->status_class == ISCSI_STATUS_REDIRECT ) { + DBGC ( iscsi, "iSCSI %p redirecting to new server\n", iscsi ); + iscsi_close_connection ( iscsi, 0 ); + if ( ( rc = iscsi_open_connection ( iscsi ) ) != 0 ) { + DBGC ( iscsi, "iSCSI %p could not redirect: %s\n ", + iscsi, strerror ( rc ) ); + return rc; + } + return 0; + } + + /* Check for fatal errors */ + if ( response->status_class != 0 ) { + DBGC ( iscsi, "iSCSI login failure: class %02x detail %02x\n", + response->status_class, response->status_detail ); + rc = iscsi_status_to_rc ( response->status_class, + response->status_detail ); + return rc; + } + + /* Handle login transitions */ + if ( response->flags & ISCSI_LOGIN_FLAG_TRANSITION ) { + iscsi->status &= ~( ISCSI_STATUS_PHASE_MASK | + ISCSI_STATUS_STRINGS_MASK ); + switch ( response->flags & ISCSI_LOGIN_NSG_MASK ) { + case ISCSI_LOGIN_NSG_OPERATIONAL_NEGOTIATION: + iscsi->status |= + ( ISCSI_STATUS_OPERATIONAL_NEGOTIATION_PHASE | + ISCSI_STATUS_STRINGS_OPERATIONAL ); + break; + case ISCSI_LOGIN_NSG_FULL_FEATURE_PHASE: + iscsi->status |= ISCSI_STATUS_FULL_FEATURE_PHASE; + break; + default: + DBGC ( iscsi, "iSCSI %p got invalid response flags " + "%02x\n", iscsi, response->flags ); + return -EIO; + } + } + + /* Send next login request PDU if we haven't reached the full + * feature phase yet. + */ + if ( ( iscsi->status & ISCSI_STATUS_PHASE_MASK ) != + ISCSI_STATUS_FULL_FEATURE_PHASE ) { + iscsi_start_login ( iscsi ); + return 0; + } + + /* Check that target authentication was successful (if required) */ + if ( ( iscsi->status & ISCSI_STATUS_AUTH_REVERSE_REQUIRED ) && + ! ( iscsi->status & ISCSI_STATUS_AUTH_REVERSE_OK ) ) { + DBGC ( iscsi, "iSCSI %p nefarious target tried to bypass " + "authentication\n", iscsi ); + return -EPROTO; + } + + /* Notify SCSI layer of window change */ + DBGC ( iscsi, "iSCSI %p entering full feature phase\n", iscsi ); + xfer_window_changed ( &iscsi->control ); + + return 0; +} + +/**************************************************************************** + * + * iSCSI to socket interface + * + */ + +/** + * Pause TX engine + * + * @v iscsi iSCSI session + */ +static void iscsi_tx_pause ( struct iscsi_session *iscsi ) { + process_del ( &iscsi->process ); +} + +/** + * Resume TX engine + * + * @v iscsi iSCSI session + */ +static void iscsi_tx_resume ( struct iscsi_session *iscsi ) { + process_add ( &iscsi->process ); +} + +/** + * Start up a new TX PDU + * + * @v iscsi iSCSI session + * + * This initiates the process of sending a new PDU. Only one PDU may + * be in transit at any one time. + */ +static void iscsi_start_tx ( struct iscsi_session *iscsi ) { + + assert ( iscsi->tx_state == ISCSI_TX_IDLE ); + + /* Initialise TX BHS */ + memset ( &iscsi->tx_bhs, 0, sizeof ( iscsi->tx_bhs ) ); + + /* Flag TX engine to start transmitting */ + iscsi->tx_state = ISCSI_TX_BHS; + + /* Start transmission process */ + iscsi_tx_resume ( iscsi ); +} + +/** + * Transmit nothing + * + * @v iscsi iSCSI session + * @ret rc Return status code + */ +static int iscsi_tx_nothing ( struct iscsi_session *iscsi __unused ) { + return 0; +} + +/** + * Transmit basic header segment of an iSCSI PDU + * + * @v iscsi iSCSI session + * @ret rc Return status code + */ +static int iscsi_tx_bhs ( struct iscsi_session *iscsi ) { + return xfer_deliver_raw ( &iscsi->socket, &iscsi->tx_bhs, + sizeof ( iscsi->tx_bhs ) ); +} + +/** + * Transmit data segment of an iSCSI PDU + * + * @v iscsi iSCSI session + * @ret rc Return status code + * + * Handle transmission of part of a PDU data segment. iscsi::tx_bhs + * will be valid when this is called. + */ +static int iscsi_tx_data ( struct iscsi_session *iscsi ) { + struct iscsi_bhs_common *common = &iscsi->tx_bhs.common; + + switch ( common->opcode & ISCSI_OPCODE_MASK ) { + case ISCSI_OPCODE_DATA_OUT: + return iscsi_tx_data_out ( iscsi ); + case ISCSI_OPCODE_LOGIN_REQUEST: + return iscsi_tx_login_request ( iscsi ); + default: + /* Nothing to send in other states */ + return 0; + } +} + +/** + * Complete iSCSI PDU transmission + * + * @v iscsi iSCSI session + * + * Called when a PDU has been completely transmitted and the TX state + * machine is about to enter the idle state. iscsi::tx_bhs will be + * valid for the just-completed PDU when this is called. + */ +static void iscsi_tx_done ( struct iscsi_session *iscsi ) { + struct iscsi_bhs_common *common = &iscsi->tx_bhs.common; + + /* Stop transmission process */ + iscsi_tx_pause ( iscsi ); + + switch ( common->opcode & ISCSI_OPCODE_MASK ) { + case ISCSI_OPCODE_DATA_OUT: + iscsi_data_out_done ( iscsi ); + break; + case ISCSI_OPCODE_LOGIN_REQUEST: + iscsi_login_request_done ( iscsi ); + break; + default: + /* No action */ + break; + } +} + +/** + * Transmit iSCSI PDU + * + * @v iscsi iSCSI session + * @v buf Temporary data buffer + * @v len Length of temporary data buffer + * + * Constructs data to be sent for the current TX state + */ +static void iscsi_tx_step ( struct iscsi_session *iscsi ) { + struct iscsi_bhs_common *common = &iscsi->tx_bhs.common; + int ( * tx ) ( struct iscsi_session *iscsi ); + enum iscsi_tx_state next_state; + size_t tx_len; + int rc; + + /* Select fragment to transmit */ + while ( 1 ) { + switch ( iscsi->tx_state ) { + case ISCSI_TX_BHS: + tx = iscsi_tx_bhs; + tx_len = sizeof ( iscsi->tx_bhs ); + next_state = ISCSI_TX_AHS; + break; + case ISCSI_TX_AHS: + tx = iscsi_tx_nothing; + tx_len = 0; + next_state = ISCSI_TX_DATA; + break; + case ISCSI_TX_DATA: + tx = iscsi_tx_data; + tx_len = ISCSI_DATA_LEN ( common->lengths ); + next_state = ISCSI_TX_IDLE; + break; + case ISCSI_TX_IDLE: + /* Nothing to do; pause processing */ + iscsi_tx_pause ( iscsi ); + return; + default: + assert ( 0 ); + return; + } + + /* Check for window availability, if needed */ + if ( tx_len && ( xfer_window ( &iscsi->socket ) == 0 ) ) { + /* Cannot transmit at this point; pause + * processing and wait for window to reopen + */ + iscsi_tx_pause ( iscsi ); + return; + } + + /* Transmit data */ + if ( ( rc = tx ( iscsi ) ) != 0 ) { + DBGC ( iscsi, "iSCSI %p could not transmit: %s\n", + iscsi, strerror ( rc ) ); + /* Transmission errors are fatal */ + iscsi_close ( iscsi, rc ); + return; + } + + /* Move to next state */ + iscsi->tx_state = next_state; + + /* If we have moved to the idle state, mark + * transmission as complete + */ + if ( iscsi->tx_state == ISCSI_TX_IDLE ) + iscsi_tx_done ( iscsi ); + } +} + +/** iSCSI TX process descriptor */ +static struct process_descriptor iscsi_process_desc = + PROC_DESC ( struct iscsi_session, process, iscsi_tx_step ); + +/** + * Receive basic header segment of an iSCSI PDU + * + * @v iscsi iSCSI session + * @v data Received data + * @v len Length of received data + * @v remaining Data remaining after this data + * @ret rc Return status code + * + * This fills in iscsi::rx_bhs with the data from the BHS portion of + * the received PDU. + */ +static int iscsi_rx_bhs ( struct iscsi_session *iscsi, const void *data, + size_t len, size_t remaining __unused ) { + memcpy ( &iscsi->rx_bhs.bytes[iscsi->rx_offset], data, len ); + if ( ( iscsi->rx_offset + len ) >= sizeof ( iscsi->rx_bhs ) ) { + DBGC2 ( iscsi, "iSCSI %p received PDU opcode %#x len %#x\n", + iscsi, iscsi->rx_bhs.common.opcode, + ISCSI_DATA_LEN ( iscsi->rx_bhs.common.lengths ) ); + } + return 0; +} + +/** + * Discard portion of an iSCSI PDU. + * + * @v iscsi iSCSI session + * @v data Received data + * @v len Length of received data + * @v remaining Data remaining after this data + * @ret rc Return status code + * + * This discards data from a portion of a received PDU. + */ +static int iscsi_rx_discard ( struct iscsi_session *iscsi __unused, + const void *data __unused, size_t len __unused, + size_t remaining __unused ) { + /* Do nothing */ + return 0; +} + +/** + * Receive data segment of an iSCSI PDU + * + * @v iscsi iSCSI session + * @v data Received data + * @v len Length of received data + * @v remaining Data remaining after this data + * @ret rc Return status code + * + * Handle processing of part of a PDU data segment. iscsi::rx_bhs + * will be valid when this is called. + */ +static int iscsi_rx_data ( struct iscsi_session *iscsi, const void *data, + size_t len, size_t remaining ) { + struct iscsi_bhs_common_response *response + = &iscsi->rx_bhs.common_response; + + /* Update cmdsn and statsn */ + iscsi->cmdsn = ntohl ( response->expcmdsn ); + iscsi->statsn = ntohl ( response->statsn ); + + switch ( response->opcode & ISCSI_OPCODE_MASK ) { + case ISCSI_OPCODE_LOGIN_RESPONSE: + return iscsi_rx_login_response ( iscsi, data, len, remaining ); + case ISCSI_OPCODE_SCSI_RESPONSE: + return iscsi_rx_scsi_response ( iscsi, data, len, remaining ); + case ISCSI_OPCODE_DATA_IN: + return iscsi_rx_data_in ( iscsi, data, len, remaining ); + case ISCSI_OPCODE_R2T: + return iscsi_rx_r2t ( iscsi, data, len, remaining ); + case ISCSI_OPCODE_NOP_IN: + return iscsi_rx_nop_in ( iscsi, data, len, remaining ); + default: + if ( remaining ) + return 0; + DBGC ( iscsi, "iSCSI %p unknown opcode %02x\n", iscsi, + response->opcode ); + return -ENOTSUP_OPCODE; + } +} + +/** + * Receive new data + * + * @v iscsi iSCSI session + * @v iobuf I/O buffer + * @v meta Data transfer metadata + * @ret rc Return status code + * + * This handles received PDUs. The receive strategy is to fill in + * iscsi::rx_bhs with the contents of the BHS portion of the PDU, + * throw away any AHS portion, and then process each part of the data + * portion as it arrives. The data processing routine therefore + * always has a full copy of the BHS available, even for portions of + * the data in different packets to the BHS. + */ +static int iscsi_socket_deliver ( struct iscsi_session *iscsi, + struct io_buffer *iobuf, + struct xfer_metadata *meta __unused ) { + struct iscsi_bhs_common *common = &iscsi->rx_bhs.common; + int ( * rx ) ( struct iscsi_session *iscsi, const void *data, + size_t len, size_t remaining ); + enum iscsi_rx_state next_state; + size_t frag_len; + size_t remaining; + int rc; + + while ( 1 ) { + switch ( iscsi->rx_state ) { + case ISCSI_RX_BHS: + rx = iscsi_rx_bhs; + iscsi->rx_len = sizeof ( iscsi->rx_bhs ); + next_state = ISCSI_RX_AHS; + break; + case ISCSI_RX_AHS: + rx = iscsi_rx_discard; + iscsi->rx_len = 4 * ISCSI_AHS_LEN ( common->lengths ); + next_state = ISCSI_RX_DATA; + break; + case ISCSI_RX_DATA: + rx = iscsi_rx_data; + iscsi->rx_len = ISCSI_DATA_LEN ( common->lengths ); + next_state = ISCSI_RX_DATA_PADDING; + break; + case ISCSI_RX_DATA_PADDING: + rx = iscsi_rx_discard; + iscsi->rx_len = ISCSI_DATA_PAD_LEN ( common->lengths ); + next_state = ISCSI_RX_BHS; + break; + default: + assert ( 0 ); + rc = -EINVAL; + goto done; + } + + frag_len = iscsi->rx_len - iscsi->rx_offset; + if ( frag_len > iob_len ( iobuf ) ) + frag_len = iob_len ( iobuf ); + remaining = iscsi->rx_len - iscsi->rx_offset - frag_len; + if ( ( rc = rx ( iscsi, iobuf->data, frag_len, + remaining ) ) != 0 ) { + DBGC ( iscsi, "iSCSI %p could not process received " + "data: %s\n", iscsi, strerror ( rc ) ); + goto done; + } + + iscsi->rx_offset += frag_len; + iob_pull ( iobuf, frag_len ); + + /* If all the data for this state has not yet been + * received, stay in this state for now. + */ + if ( iscsi->rx_offset != iscsi->rx_len ) { + rc = 0; + goto done; + } + + iscsi->rx_state = next_state; + iscsi->rx_offset = 0; + } + + done: + /* Free I/O buffer */ + free_iob ( iobuf ); + + /* Destroy session on error */ + if ( rc != 0 ) + iscsi_close ( iscsi, rc ); + + return rc; +} + +/** + * Handle redirection event + * + * @v iscsi iSCSI session + * @v type Location type + * @v args Remaining arguments depend upon location type + * @ret rc Return status code + */ +static int iscsi_vredirect ( struct iscsi_session *iscsi, int type, + va_list args ) { + va_list tmp; + struct sockaddr *peer; + int rc; + + /* Intercept redirects to a LOCATION_SOCKET and record the IP + * address for the iBFT. This is a bit of a hack, but avoids + * inventing an ioctl()-style call to retrieve the socket + * address from a data-xfer interface. + */ + if ( type == LOCATION_SOCKET ) { + va_copy ( tmp, args ); + ( void ) va_arg ( tmp, int ); /* Discard "semantics" */ + peer = va_arg ( tmp, struct sockaddr * ); + memcpy ( &iscsi->target_sockaddr, peer, + sizeof ( iscsi->target_sockaddr ) ); + va_end ( tmp ); + } + + /* Redirect to new location */ + if ( ( rc = xfer_vreopen ( &iscsi->socket, type, args ) ) != 0 ) + goto err; + + return 0; + + err: + iscsi_close ( iscsi, rc ); + return rc; +} + +/** iSCSI socket interface operations */ +static struct interface_operation iscsi_socket_operations[] = { + INTF_OP ( xfer_deliver, struct iscsi_session *, iscsi_socket_deliver ), + INTF_OP ( xfer_window_changed, struct iscsi_session *, + iscsi_tx_resume ), + INTF_OP ( xfer_vredirect, struct iscsi_session *, iscsi_vredirect ), + INTF_OP ( intf_close, struct iscsi_session *, iscsi_close ), +}; + +/** iSCSI socket interface descriptor */ +static struct interface_descriptor iscsi_socket_desc = + INTF_DESC ( struct iscsi_session, socket, iscsi_socket_operations ); + +/**************************************************************************** + * + * iSCSI command issuing + * + */ + +/** + * Check iSCSI flow-control window + * + * @v iscsi iSCSI session + * @ret len Length of window + */ +static size_t iscsi_scsi_window ( struct iscsi_session *iscsi ) { + + if ( ( ( iscsi->status & ISCSI_STATUS_PHASE_MASK ) == + ISCSI_STATUS_FULL_FEATURE_PHASE ) && + ( iscsi->command == NULL ) ) { + /* We cannot handle concurrent commands */ + return 1; + } else { + return 0; + } +} + +/** + * Issue iSCSI SCSI command + * + * @v iscsi iSCSI session + * @v parent Parent interface + * @v command SCSI command + * @ret tag Command tag, or negative error + */ +static int iscsi_scsi_command ( struct iscsi_session *iscsi, + struct interface *parent, + struct scsi_cmd *command ) { + + /* This iSCSI implementation cannot handle multiple concurrent + * commands or commands arriving before login is complete. + */ + if ( iscsi_scsi_window ( iscsi ) == 0 ) { + DBGC ( iscsi, "iSCSI %p cannot handle concurrent commands\n", + iscsi ); + return -EOPNOTSUPP; + } + + /* Store command */ + iscsi->command = malloc ( sizeof ( *command ) ); + if ( ! iscsi->command ) + return -ENOMEM; + memcpy ( iscsi->command, command, sizeof ( *command ) ); + + /* Assign new ITT */ + iscsi_new_itt ( iscsi ); + + /* Start sending command */ + iscsi_start_command ( iscsi ); + + /* Attach to parent interface and return */ + intf_plug_plug ( &iscsi->data, parent ); + return iscsi->itt; +} + +/** + * Get iSCSI ACPI descriptor + * + * @v iscsi iSCSI session + * @ret desc ACPI descriptor + */ +static struct acpi_descriptor * iscsi_describe ( struct iscsi_session *iscsi ) { + + return &iscsi->desc; +} + +/** iSCSI SCSI command-issuing interface operations */ +static struct interface_operation iscsi_control_op[] = { + INTF_OP ( scsi_command, struct iscsi_session *, iscsi_scsi_command ), + INTF_OP ( xfer_window, struct iscsi_session *, iscsi_scsi_window ), + INTF_OP ( intf_close, struct iscsi_session *, iscsi_close ), + INTF_OP ( acpi_describe, struct iscsi_session *, iscsi_describe ), +}; + +/** iSCSI SCSI command-issuing interface descriptor */ +static struct interface_descriptor iscsi_control_desc = + INTF_DESC ( struct iscsi_session, control, iscsi_control_op ); + +/** + * Close iSCSI command + * + * @v iscsi iSCSI session + * @v rc Reason for close + */ +static void iscsi_command_close ( struct iscsi_session *iscsi, int rc ) { + + /* Restart interface */ + intf_restart ( &iscsi->data, rc ); + + /* Treat unsolicited command closures mid-command as fatal, + * because we have no code to handle partially-completed PDUs. + */ + if ( iscsi->command != NULL ) + iscsi_close ( iscsi, ( ( rc == 0 ) ? -ECANCELED : rc ) ); +} + +/** iSCSI SCSI command interface operations */ +static struct interface_operation iscsi_data_op[] = { + INTF_OP ( intf_close, struct iscsi_session *, iscsi_command_close ), +}; + +/** iSCSI SCSI command interface descriptor */ +static struct interface_descriptor iscsi_data_desc = + INTF_DESC ( struct iscsi_session, data, iscsi_data_op ); + +/**************************************************************************** + * + * Instantiator + * + */ + +/** iSCSI root path components (as per RFC4173) */ +enum iscsi_root_path_component { + RP_SERVERNAME = 0, + RP_PROTOCOL, + RP_PORT, + RP_LUN, + RP_TARGETNAME, + NUM_RP_COMPONENTS +}; + +/** iSCSI initiator IQN setting */ +const struct setting initiator_iqn_setting __setting ( SETTING_SANBOOT_EXTRA, + initiator-iqn ) = { + .name = "initiator-iqn", + .description = "iSCSI initiator name", + .tag = DHCP_ISCSI_INITIATOR_IQN, + .type = &setting_type_string, +}; + +/** iSCSI reverse username setting */ +const struct setting reverse_username_setting __setting ( SETTING_AUTH_EXTRA, + reverse-username ) = { + .name = "reverse-username", + .description = "Reverse user name", + .tag = DHCP_EB_REVERSE_USERNAME, + .type = &setting_type_string, +}; + +/** iSCSI reverse password setting */ +const struct setting reverse_password_setting __setting ( SETTING_AUTH_EXTRA, + reverse-password ) = { + .name = "reverse-password", + .description = "Reverse password", + .tag = DHCP_EB_REVERSE_PASSWORD, + .type = &setting_type_string, +}; + +/** + * Parse iSCSI root path + * + * @v iscsi iSCSI session + * @v root_path iSCSI root path (as per RFC4173) + * @ret rc Return status code + */ +static int iscsi_parse_root_path ( struct iscsi_session *iscsi, + const char *root_path ) { + char rp_copy[ strlen ( root_path ) + 1 ]; + char *rp_comp[NUM_RP_COMPONENTS]; + char *rp = rp_copy; + int skip = 0; + int i = 0; + int rc; + + /* Split root path into component parts */ + strcpy ( rp_copy, root_path ); + while ( 1 ) { + rp_comp[i++] = rp; + if ( i == NUM_RP_COMPONENTS ) + break; + for ( ; ( ( *rp != ':' ) || skip ) ; rp++ ) { + if ( ! *rp ) { + DBGC ( iscsi, "iSCSI %p root path \"%s\" " + "too short\n", iscsi, root_path ); + return -EINVAL_ROOT_PATH_TOO_SHORT; + } else if ( *rp == '[' ) { + skip = 1; + } else if ( *rp == ']' ) { + skip = 0; + } + } + *(rp++) = '\0'; + } + + /* Use root path components to configure iSCSI session */ + iscsi->target_address = strdup ( rp_comp[RP_SERVERNAME] ); + if ( ! iscsi->target_address ) + return -ENOMEM; + iscsi->target_port = strtoul ( rp_comp[RP_PORT], NULL, 10 ); + if ( ! iscsi->target_port ) + iscsi->target_port = ISCSI_PORT; + if ( ( rc = scsi_parse_lun ( rp_comp[RP_LUN], &iscsi->lun ) ) != 0 ) { + DBGC ( iscsi, "iSCSI %p invalid LUN \"%s\"\n", + iscsi, rp_comp[RP_LUN] ); + return rc; + } + iscsi->target_iqn = strdup ( rp_comp[RP_TARGETNAME] ); + if ( ! iscsi->target_iqn ) + return -ENOMEM; + + return 0; +} + +/** + * Fetch iSCSI settings + * + * @v iscsi iSCSI session + * @ret rc Return status code + */ +static int iscsi_fetch_settings ( struct iscsi_session *iscsi ) { + char *hostname; + union uuid uuid; + int len; + + /* Fetch relevant settings. Don't worry about freeing on + * error, since iscsi_free() will take care of that anyway. + */ + fetch_string_setting_copy ( NULL, &username_setting, + &iscsi->initiator_username ); + fetch_string_setting_copy ( NULL, &password_setting, + &iscsi->initiator_password ); + fetch_string_setting_copy ( NULL, &reverse_username_setting, + &iscsi->target_username ); + fetch_string_setting_copy ( NULL, &reverse_password_setting, + &iscsi->target_password ); + + /* Use explicit initiator IQN if provided */ + fetch_string_setting_copy ( NULL, &initiator_iqn_setting, + &iscsi->initiator_iqn ); + if ( iscsi->initiator_iqn ) + return 0; + + /* Otherwise, try to construct an initiator IQN from the hostname */ + fetch_string_setting_copy ( NULL, &hostname_setting, &hostname ); + if ( hostname ) { + len = asprintf ( &iscsi->initiator_iqn, + ISCSI_DEFAULT_IQN_PREFIX ":%s", hostname ); + free ( hostname ); + if ( len < 0 ) { + DBGC ( iscsi, "iSCSI %p could not allocate initiator " + "IQN\n", iscsi ); + return -ENOMEM; + } + assert ( iscsi->initiator_iqn ); + return 0; + } + + /* Otherwise, try to construct an initiator IQN from the UUID */ + if ( ( len = fetch_uuid_setting ( NULL, &uuid_setting, &uuid ) ) < 0 ) { + DBGC ( iscsi, "iSCSI %p has no suitable initiator IQN\n", + iscsi ); + return -EINVAL_NO_INITIATOR_IQN; + } + if ( ( len = asprintf ( &iscsi->initiator_iqn, + ISCSI_DEFAULT_IQN_PREFIX ":%s", + uuid_ntoa ( &uuid ) ) ) < 0 ) { + DBGC ( iscsi, "iSCSI %p could not allocate initiator IQN\n", + iscsi ); + return -ENOMEM; + } + assert ( iscsi->initiator_iqn ); + + return 0; +} + + +/** + * Check iSCSI authentication details + * + * @v iscsi iSCSI session + * @ret rc Return status code + */ +static int iscsi_check_auth ( struct iscsi_session *iscsi ) { + + /* Check for invalid authentication combinations */ + if ( ( /* Initiator username without password (or vice-versa) */ + ( !! iscsi->initiator_username ) ^ + ( !! iscsi->initiator_password ) ) || + ( /* Target username without password (or vice-versa) */ + ( !! iscsi->target_username ) ^ + ( !! iscsi->target_password ) ) || + ( /* Target (reverse) without initiator (forward) */ + ( iscsi->target_username && + ( ! iscsi->initiator_username ) ) ) ) { + DBGC ( iscsi, "iSCSI %p invalid credentials: initiator " + "%sname,%spw, target %sname,%spw\n", iscsi, + ( iscsi->initiator_username ? "" : "no " ), + ( iscsi->initiator_password ? "" : "no " ), + ( iscsi->target_username ? "" : "no " ), + ( iscsi->target_password ? "" : "no " ) ); + return -EINVAL_BAD_CREDENTIAL_MIX; + } + + return 0; +} + +/** + * Open iSCSI URI + * + * @v parent Parent interface + * @v uri URI + * @ret rc Return status code + */ +static int iscsi_open ( struct interface *parent, struct uri *uri ) { + struct iscsi_session *iscsi; + int rc; + + /* Sanity check */ + if ( ! uri->opaque ) { + rc = -EINVAL_NO_ROOT_PATH; + goto err_sanity_uri; + } + + /* Allocate and initialise structure */ + iscsi = zalloc ( sizeof ( *iscsi ) ); + if ( ! iscsi ) { + rc = -ENOMEM; + goto err_zalloc; + } + ref_init ( &iscsi->refcnt, iscsi_free ); + intf_init ( &iscsi->control, &iscsi_control_desc, &iscsi->refcnt ); + intf_init ( &iscsi->data, &iscsi_data_desc, &iscsi->refcnt ); + intf_init ( &iscsi->socket, &iscsi_socket_desc, &iscsi->refcnt ); + process_init_stopped ( &iscsi->process, &iscsi_process_desc, + &iscsi->refcnt ); +// acpi_init ( &iscsi->desc, &ibft_model, &iscsi->refcnt ); + + /* Parse root path */ + if ( ( rc = iscsi_parse_root_path ( iscsi, uri->opaque ) ) != 0 ) + goto err_parse_root_path; + /* Set fields not specified by root path */ + if ( ( rc = iscsi_fetch_settings ( iscsi ) ) != 0 ) + goto err_fetch_settings; + /* Validate authentication */ + if ( ( rc = iscsi_check_auth ( iscsi ) ) != 0 ) + goto err_check_auth; + + /* Sanity checks */ + if ( ! iscsi->target_address ) { + DBGC ( iscsi, "iSCSI %p does not yet support discovery\n", + iscsi ); + rc = -ENOTSUP_DISCOVERY; + goto err_sanity_address; + } + if ( ! iscsi->target_iqn ) { + DBGC ( iscsi, "iSCSI %p no target address supplied in %s\n", + iscsi, uri->opaque ); + rc = -EINVAL_NO_TARGET_IQN; + goto err_sanity_iqn; + } + DBGC ( iscsi, "iSCSI %p initiator %s\n",iscsi, iscsi->initiator_iqn ); + DBGC ( iscsi, "iSCSI %p target %s %s\n", + iscsi, iscsi->target_address, iscsi->target_iqn ); + + /* Open socket */ + if ( ( rc = iscsi_open_connection ( iscsi ) ) != 0 ) + goto err_open_connection; + + /* Attach SCSI device to parent interface */ + if ( ( rc = scsi_open ( parent, &iscsi->control, + &iscsi->lun ) ) != 0 ) { + DBGC ( iscsi, "iSCSI %p could not create SCSI device: %s\n", + iscsi, strerror ( rc ) ); + goto err_scsi_open; + } + + /* Mortalise self, and return */ + ref_put ( &iscsi->refcnt ); + return 0; + + err_scsi_open: + err_open_connection: + err_sanity_iqn: + err_sanity_address: + err_check_auth: + err_fetch_settings: + err_parse_root_path: + iscsi_close ( iscsi, rc ); + ref_put ( &iscsi->refcnt ); + err_zalloc: + err_sanity_uri: + return rc; +} + +/** iSCSI URI opener */ +struct uri_opener iscsi_uri_opener __uri_opener = { + .scheme = "iscsi", + .open = iscsi_open, +}; diff --git a/IPXE/ipxe_org_code/ipxe-3fe683e.tar.bz2 b/IPXE/ipxe_org_code/ipxe-3fe683e.tar.bz2 new file mode 100644 index 00000000..0f60c1e0 Binary files /dev/null and b/IPXE/ipxe_org_code/ipxe-3fe683e.tar.bz2 differ diff --git a/License/BSD-2-Clause-Patent.txt b/License/BSD-2-Clause-Patent.txt new file mode 100644 index 00000000..3795cafc --- /dev/null +++ b/License/BSD-2-Clause-Patent.txt @@ -0,0 +1,51 @@ +Copyright (c) 2019, TianoCore and contributors. All rights reserved. + +SPDX-License-Identifier: BSD-2-Clause-Patent + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +Subject to the terms and conditions of this license, each copyright holder +and contributor hereby grants to those receiving rights under this license +a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable +(except for failure to satisfy the conditions of this license) patent +license to make, have made, use, offer to sell, sell, import, and otherwise +transfer this software, where such license applies only to those patent +claims, already acquired or hereafter acquired, licensable by such copyright +holder or contributor that are necessarily infringed by: + +(a) their Contribution(s) (the licensed copyrights of copyright holders and + non-copyrightable additions of contributors, in source or binary form) + alone; or + +(b) combination of their Contribution(s) with the work of authorship to + which such Contribution(s) was added by such copyright holder or + contributor, if, at the time the Contribution is added, such addition + causes such combination to be necessarily infringed. The patent license + shall not apply to any other combinations which include the + Contribution. + +Except as expressly stated above, no rights or licenses from any copyright +holder or contributor is granted under this license, whether expressly, by +implication, estoppel or otherwise. + +DISCLAIMER + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/License/BSD.txt b/License/BSD.txt new file mode 100644 index 00000000..dbdb05ed --- /dev/null +++ b/License/BSD.txt @@ -0,0 +1,30 @@ +BSD License + +For Zstandard software + +Copyright (c) 2016-present, Facebook, Inc. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + * Neither the name Facebook nor the names of its contributors may be used to + endorse or promote products derived from this software without specific + prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/License/MIT.txt b/License/MIT.txt new file mode 100644 index 00000000..f47dc843 --- /dev/null +++ b/License/MIT.txt @@ -0,0 +1,8 @@ +The MIT License (MIT) +Copyright © 2020 + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/License/gpl-2.0.txt b/License/gpl-2.0.txt new file mode 100644 index 00000000..d159169d --- /dev/null +++ b/License/gpl-2.0.txt @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/License/gpl-3.0.txt b/License/gpl-3.0.txt new file mode 100644 index 00000000..f288702d --- /dev/null +++ b/License/gpl-3.0.txt @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/License/license-busybox.txt b/License/license-busybox.txt new file mode 100644 index 00000000..65dfcb4d --- /dev/null +++ b/License/license-busybox.txt @@ -0,0 +1,3 @@ +BusyBox follows GPLv2 license (see gpl-2.0.txt) + +Ventoy does not modify its source code, only its binary is used. diff --git a/License/license-device-mapper.txt b/License/license-device-mapper.txt new file mode 100644 index 00000000..e8ffffab --- /dev/null +++ b/License/license-device-mapper.txt @@ -0,0 +1,4 @@ + +Device Mapper follows GPLv2 License (see gpl-2.0.txt) + +Ventoy modify its source code, these code modified by Ventoy follows the same license as Device Mapper. diff --git a/License/license-edk2.txt b/License/license-edk2.txt new file mode 100644 index 00000000..849aa701 --- /dev/null +++ b/License/license-edk2.txt @@ -0,0 +1,2 @@ +EDK2 follows BSD-2-Clause Plus Patent License (see BSD-2-Clause-Patent.txt) +Ventoy add an uefi application module in MdeModulePkg, the code is developed by ventoy and is under GPLv3+ License (see gpl-3.0.txt). diff --git a/License/license-efifs.txt b/License/license-efifs.txt new file mode 100644 index 00000000..3fd3627c --- /dev/null +++ b/License/license-efifs.txt @@ -0,0 +1,2 @@ +efifs follows GPLv3 (see gpl-3.0.txt) License. +Ventoy modify its source code, these code modified by Ventoy follows the same license as efifs. diff --git a/License/license-exfat.txt b/License/license-exfat.txt new file mode 100644 index 00000000..a4c7a171 --- /dev/null +++ b/License/license-exfat.txt @@ -0,0 +1,2 @@ +exfat follows GPLv2 (see gpl-2.0.txt) License. +Ventoy modify its source code, these code modified by Ventoy follows the same license as exfat. diff --git a/License/license-fat-filelib.txt b/License/license-fat-filelib.txt new file mode 100644 index 00000000..73b8c28a --- /dev/null +++ b/License/license-fat-filelib.txt @@ -0,0 +1,3 @@ +fat-filelib follows GPL license (see gpl-3.0.txt) + +Ventoy does not modify its source code, only its library is used. diff --git a/License/license-fatfs.txt b/License/license-fatfs.txt new file mode 100644 index 00000000..83abcac3 --- /dev/null +++ b/License/license-fatfs.txt @@ -0,0 +1,4 @@ +Therefore FatFs license is one of the BSD-style licenses but there is a significant feature. FatFs is mainly intended for embedded systems. In order to extend the usability for commercial products, the redistributions of FatFs in binary form, such as embedded code, binary library and any forms without source code, does not need to include about FatFs in the documentations. This is equivalent to the 1-clause BSD license. Of course FatFs is compatible with the most of open source software licenses including GNU GPL. When you redistribute the FatFs source code with any changes or create a fork, the license can also be changed to GNU GPL, BSD-style license or any open source software license that not conflict with FatFs license. + +Ventoy modify its source code, these code modified by Ventoy follow the same license as FatFs. + diff --git a/License/license-grub2.txt b/License/license-grub2.txt new file mode 100644 index 00000000..7d4dfd73 --- /dev/null +++ b/License/license-grub2.txt @@ -0,0 +1,3 @@ +GRUB2 follows GPLv3+ license (see gpl-3.0.txt) +Ventoy modify its source code, these code modified by Ventoy follow the same license as grub2. + diff --git a/License/license-imdisk.txt b/License/license-imdisk.txt new file mode 100644 index 00000000..72122f66 --- /dev/null +++ b/License/license-imdisk.txt @@ -0,0 +1,4 @@ +imdisk follows GPL license (see gpl-3.0.txt) + +Ventoy does not modify its source code, only its binary is used. + diff --git a/License/license-ipxe.txt b/License/license-ipxe.txt new file mode 100644 index 00000000..7045ba91 --- /dev/null +++ b/License/license-ipxe.txt @@ -0,0 +1,2 @@ +iPXE follows GPLv2 (see gpl-2.0.txt) or Unmodified Binary Distribution Licence (see ubdl.txt) +Ventoy modify its source code, these code modified by Ventoy follow the same license as iPXE. diff --git a/License/license-libfuse.txt b/License/license-libfuse.txt new file mode 100644 index 00000000..5b3759cc --- /dev/null +++ b/License/license-libfuse.txt @@ -0,0 +1,3 @@ +libfuse follows LGPL license (see lgpl.txt) + +Ventoy does not modify its source code, only its library is used. diff --git a/License/license-liblzma.txt b/License/license-liblzma.txt new file mode 100644 index 00000000..7a7b7b26 --- /dev/null +++ b/License/license-liblzma.txt @@ -0,0 +1,3 @@ +liblzma follows LGPL license (see lgpl.txt) + +Ventoy does not modify its source code, only its library is used. diff --git a/License/license-lz4.txt b/License/license-lz4.txt new file mode 100644 index 00000000..dc4fd586 --- /dev/null +++ b/License/license-lz4.txt @@ -0,0 +1,5 @@ + +Ventoy does not modify its source code, only its library is used. + +The library source of lz4 follows the BSD 2-Clause License. + diff --git a/License/license-lzo.txt b/License/license-lzo.txt new file mode 100644 index 00000000..28f3456e --- /dev/null +++ b/License/license-lzo.txt @@ -0,0 +1,3 @@ +lzo follows GPLv2+ license (see gpl-2.0.txt) + +Ventoy does not modify its source code, only its library is used. diff --git a/License/license-rufus.txt b/License/license-rufus.txt new file mode 100644 index 00000000..fb2244d8 --- /dev/null +++ b/License/license-rufus.txt @@ -0,0 +1,3 @@ +Rufus follows GPLv3+ license (see gpl-3.0.txt) +Ventoy uses some function from Rufus, and all the Ventoy's code also follow GPLv3+ license. + diff --git a/License/license-smallz4.txt b/License/license-smallz4.txt new file mode 100644 index 00000000..956869fc --- /dev/null +++ b/License/license-smallz4.txt @@ -0,0 +1,4 @@ +smalLz4 follows MIT license (see MIT.txt) + +Ventoy does not modify its source code, only its binary is used. + diff --git a/License/license-squashfs-tools.txt b/License/license-squashfs-tools.txt new file mode 100644 index 00000000..bf9785ed --- /dev/null +++ b/License/license-squashfs-tools.txt @@ -0,0 +1,4 @@ + +squashfs-tools follows the GPLv2 License (see gpl-2.0.txt). +Ventoy modify its source code, these code modified by Ventoy follow the same license as squashfs-tools. + diff --git a/License/license-vblade.txt b/License/license-vblade.txt new file mode 100644 index 00000000..a0b45cba --- /dev/null +++ b/License/license-vblade.txt @@ -0,0 +1,3 @@ +vblade follows GPLv2 license (see gpl-2.0.txt) +Ventoy modify its source code, these code modified by Ventoy follow the same license as vblade. + diff --git a/License/license-ventoy.txt b/License/license-ventoy.txt new file mode 100644 index 00000000..f6c5012f --- /dev/null +++ b/License/license-ventoy.txt @@ -0,0 +1 @@ +All the modules and tools developed by Ventoy are under GPLv3+ (see gpl-3.0.txt) License. diff --git a/License/license-wimboot.txt b/License/license-wimboot.txt new file mode 100644 index 00000000..9179d035 --- /dev/null +++ b/License/license-wimboot.txt @@ -0,0 +1,5 @@ +wimboot follows GPLv2+ license (see gpl-2.0.txt) + +Ventoy use the lzx decompress file from wimboot. These code follow the same license as wimboot. + + diff --git a/License/license-xzembedded.txt b/License/license-xzembedded.txt new file mode 100644 index 00000000..4641c7f5 --- /dev/null +++ b/License/license-xzembedded.txt @@ -0,0 +1 @@ +XZ Embedded has been put into the public domain, thus you can do whatever you want with it. diff --git a/License/license-zlib.txt b/License/license-zlib.txt new file mode 100644 index 00000000..cad708d0 --- /dev/null +++ b/License/license-zlib.txt @@ -0,0 +1,27 @@ +/* zlib.h -- interface of the 'zlib' general purpose compression library + version 1.2.11, January 15th, 2017 + + Copyright (C) 1995-2017 Jean-loup Gailly and Mark Adler + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + +*/ + +Ventoy does not modify its source code, only its library is used. diff --git a/License/license-zstd.txt b/License/license-zstd.txt new file mode 100644 index 00000000..f2cad9f4 --- /dev/null +++ b/License/license-zstd.txt @@ -0,0 +1,3 @@ +zstd follows the BSD License (see BSD.txt) + +Ventoy does not modify its source code, only its binrary is used. diff --git a/License/ubdl.txt b/License/ubdl.txt new file mode 100644 index 00000000..780ddcd7 --- /dev/null +++ b/License/ubdl.txt @@ -0,0 +1,59 @@ +UNMODIFIED BINARY DISTRIBUTION LICENCE + + +PREAMBLE + +The GNU General Public License provides a legal guarantee that +software covered by it remains free (in the sense of freedom, not +price). It achieves this guarantee by imposing obligations on anyone +who chooses to distribute the software. + +Some of these obligations may be seen as unnecessarily burdensome. In +particular, when the source code for the software is already publicly +and freely available, there is minimal value in imposing upon each +distributor the obligation to provide the complete source code (or an +equivalent written offer to provide the complete source code). + +This Licence allows for the distribution of unmodified binaries built +from publicly available source code, without imposing the obligations +of the GNU General Public License upon anyone who chooses to +distribute only the unmodified binaries built from that source code. + +The extra permissions granted by this Licence apply only to unmodified +binaries built from source code which has already been made available +to the public in accordance with the terms of the GNU General Public +Licence. Nothing in this Licence allows for the creation of +closed-source modified versions of the Program. Any modified versions +of the Program are subject to the usual terms and conditions of the +GNU General Public License. + + +TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + +This Licence applies to any Program or other work which contains a +notice placed by the copyright holder saying it may be distributed +under the terms of this Unmodified Binary Distribution Licence. All +terms used in the text of this Licence are to be interpreted as they +are used in version 2 of the GNU General Public License as published +by the Free Software Foundation. + +If you have made this Program available to the public in both source +code and executable form in accordance with the terms of the GNU +General Public License as published by the Free Software Foundation; +either version 2 of the License, or (at your option) any later +version, then you are hereby granted an additional permission to use, +copy, and distribute the unmodified executable form of this Program +(the "Unmodified Binary") without restriction, including the right to +permit persons to whom the Unmodified Binary is furnished to do +likewise, subject to the following conditions: + +- when started running, the Program must display an announcement which + includes the details of your existing publication of the Program + made in accordance with the terms of the GNU General Public License. + For example, the Program could display the URL of the publicly + available source code from which the Unmodified Binary was built. + +- when exercising your right to grant permissions under this Licence, + you do not need to refer directly to the text of this Licence, but + you may not grant permissions beyond those granted to you by this + Licence. diff --git a/SQUASHFS/SRC/build_lz4.sh b/SQUASHFS/SRC/build_lz4.sh new file mode 100644 index 00000000..883e26e0 --- /dev/null +++ b/SQUASHFS/SRC/build_lz4.sh @@ -0,0 +1,22 @@ +#!/bin/bash + +LIBDIR=$PWD/../LIB/LZ4 + +rm -rf $LIBDIR +rm -rf lz4-1.8.1.2 +tar -xf lz4-1.8.1.2.tar.gz + + +cd lz4-1.8.1.2 +make && PREFIX=$LIBDIR make install + +cd .. +rm -rf lz4-1.8.1.2 + +if [ -d $LIBDIR ]; then + echo -e "\n========== SUCCESS ============\n" +else + echo -e "\n========== FAILED ============\n" +fi + + diff --git a/SQUASHFS/SRC/build_lzma.sh b/SQUASHFS/SRC/build_lzma.sh new file mode 100644 index 00000000..54f93e06 --- /dev/null +++ b/SQUASHFS/SRC/build_lzma.sh @@ -0,0 +1,22 @@ +#!/bin/bash + +LIBDIR=$PWD/../LIB/LZMA + +rm -rf $LIBDIR +rm -rf liblzma-master +unzip liblzma-master.zip + +cd liblzma-master +./configure --prefix=$LIBDIR --disable-xz --disable-xzdec --disable-lzmadec --disable-lzmainfo --enable-small +make -j 8 && make install + +cd .. +rm -rf liblzma-master + +if [ -d $LIBDIR ]; then + echo -e "\n========== SUCCESS ============\n" +else + echo -e "\n========== FAILED ============\n" +fi + + diff --git a/SQUASHFS/SRC/build_lzo.sh b/SQUASHFS/SRC/build_lzo.sh new file mode 100644 index 00000000..30c12089 --- /dev/null +++ b/SQUASHFS/SRC/build_lzo.sh @@ -0,0 +1,24 @@ +#!/bin/bash + +LIBDIR=$PWD/../LIB/LZO +LZODIR=lzo-2.08 + +rm -rf $LIBDIR +rm -rf $LZODIR +tar -xf ${LZODIR}.tar.gz + + +cd $LZODIR +./configure --prefix=$LIBDIR --disable-shared + +make && make install + +cd .. +rm -rf $LZODIR + +if [ -d $LIBDIR ]; then + echo -e "\n========== SUCCESS ============\n" +else + echo -e "\n========== FAILED ============\n" +fi + diff --git a/SQUASHFS/SRC/build_zstd.sh b/SQUASHFS/SRC/build_zstd.sh new file mode 100644 index 00000000..aea55bbe --- /dev/null +++ b/SQUASHFS/SRC/build_zstd.sh @@ -0,0 +1,23 @@ +#!/bin/bash + +LIBDIR=$PWD/../LIB/ZSTD +ZSTDDIR=zstd-1.4.4 + +rm -rf $LIBDIR +rm -rf $ZSTDDIR +tar -xf ${ZSTDDIR}.tar.gz + + +cd $ZSTDDIR +PREFIX=$LIBDIR ZSTD_LIB_COMPRESSION=0 make +PREFIX=$LIBDIR ZSTD_LIB_COMPRESSION=0 make install + +cd .. +rm -rf $ZSTDDIR + +if [ -d $LIBDIR ]; then + echo -e "\n========== SUCCESS ============\n" +else + echo -e "\n========== FAILED ============\n" +fi + diff --git a/SQUASHFS/SRC/liblzma-master.zip b/SQUASHFS/SRC/liblzma-master.zip new file mode 100644 index 00000000..5528ab8f Binary files /dev/null and b/SQUASHFS/SRC/liblzma-master.zip differ diff --git a/SQUASHFS/SRC/lz4-1.8.1.2.tar.gz b/SQUASHFS/SRC/lz4-1.8.1.2.tar.gz new file mode 100644 index 00000000..6aac7add Binary files /dev/null and b/SQUASHFS/SRC/lz4-1.8.1.2.tar.gz differ diff --git a/SQUASHFS/SRC/lzo-2.08.tar.gz b/SQUASHFS/SRC/lzo-2.08.tar.gz new file mode 100644 index 00000000..18540708 Binary files /dev/null and b/SQUASHFS/SRC/lzo-2.08.tar.gz differ diff --git a/SQUASHFS/SRC/zstd-1.4.4.tar.gz b/SQUASHFS/SRC/zstd-1.4.4.tar.gz new file mode 100644 index 00000000..96e22adb Binary files /dev/null and b/SQUASHFS/SRC/zstd-1.4.4.tar.gz differ diff --git a/SQUASHFS/squashfs-tools-4.4/ACKNOWLEDGEMENTS b/SQUASHFS/squashfs-tools-4.4/ACKNOWLEDGEMENTS new file mode 100644 index 00000000..2097bb77 --- /dev/null +++ b/SQUASHFS/squashfs-tools-4.4/ACKNOWLEDGEMENTS @@ -0,0 +1,162 @@ + ACKNOWLEDGEMENTS + +Thanks to everyone who have downloaded Squashfs. I appreciate people +using it, and any feedback you have. + +The following have provided useful feedback, which has guided +some of the extra features in squashfs. This is a randomly ordered +(roughly in chronological order) list, which is updated when +I remember... + +Acknowledgements for Squashfs 4.3 +--------------------------------- + +Thanks to Bruno Wolff III and Andy Lutomirski for useful feedback +during the long development process of Squashfs 4.3. + +Acknowledgements for Squashfs 4.2 +--------------------------------- + +Thanks to Lasse Collin (http://tukaani.org/xz/) for mainlining XZ +decompression support. + +Acknowledgements for Squashfs 4.1 +--------------------------------- + +Thanks to Chan Jeong and LG for the patches to support LZO +compression. + +Acknowledgements for Squashfs 4.0 +--------------------------------- + +Thanks to Tim Bird and CELF (Consumer Electronics Linux Forum) for helping +fund mainstreaming of Squashfs into the 2.6.29 kernel and the +changes to the Squashfs tools to support the new 4.0 file system layout. + +Acknowledgements for Squashfs-3.3 +------------------------------------ + +Peter Korsgaard and others sent patches updating Squashfs to changes in the +VFS interface for 2.6.22/2.6.23/2.6.24-rc1. Peter also sent some small patches +for the Squashfs kernel code. + +Vito Di Leo sent a patch extending Mksquashfs to support regex filters. +While his patched worked, it unfortunately made it easy to make Mksquashfs +perform unpredictably with poorly choosen regex expressions. It, however, +encouraged myself to add support for wildcard pattern matching and regex +filters in a different way. + +Acknowledgements for Squashfs-3.2-r2 +------------------------------------ + +Junjiro Okajima discovered a couple of SMP issues, thanks. + +Junjiro Okajima and Tomas Matejicek have produced some good LZMA patches +for Squashfs. + +Acknowledgements for Squashfs-3.2 +--------------------------------- + +Peter Korsgaard sent a patch updating Squashfs to changes in the VFS interface +in Linux 2.6.20. + +Acknowledgements for Squashfs-3.1 +--------------------------------- + +Kenneth Duda and Ed Swierk of Arastra Inc. identified numerous bugs with +Squashfs, and provided patches which were the basis for some of the +fixes. In particular they identified the fragment rounding bug, the +NFS bug, the initrd bug, and helped identify the 4K stack overflow bug. + +Scott James Remnant (Ubuntu) also identified the fragment rounding bug, +and he also provided a patch. + +Ming Zhang identified the Lseek bug in Mksquashfs. His tests on the +performance of Mksquashfs on SMP systems encouraged the rewrite of +Mksquashfs. + +Peter Korsgaard, Daniel Olivera and Zilvinas Valinskas noticed +Squashfs 3.0 didn't compile on Linux-2.6.18-rc[1-4] due to changes +in the Linux VFS interfaces, and provided patches. + +Tomas Matejicek (SLAX) suggested the -force option on Unsquashfs, and noticed +Unsquashfs didn't return the correct exit status. + +Yann Le Doare reported a kernel oops and provided a Qemu image that led +to the identification of the simultaneously accessing multiply mounted Squashfs +filesystems bug. + + +Older acknowledgements +---------------------- + +Mark Robson - pointed out early on that initrds didn't work + +Adam Warner - pointed out that greater than 2GB filesystems didn't work. + +John Sutton - raised the problem when archiving the entire filesystem +(/) there was no way to prevent /proc being archived. This prompted +exclude files. + +Martin Mueller (LinuxTV) - noticed that the filesystem length in the +superblock doesn't match the output filesystem length. This is due to +padding to a 4K boundary. This prompted the addition of the -nopad option. +He also reported a problem where 32K block filesystems hung when used as +initrds. + +Arkadiusz Patyk (Polish Linux Distribution - PLD) reported a problem where 32K +block filesystems hung when used as a root filesystem mounted as a loopback +device. + +David Fox (Lindows) noticed that the exit codes returned by Mksquashfs were +wrong. He also noticed that a lot of time was spent in the duplicate scan +routine. + +Cameron Rich complained that Squashfs did not support FIFOs or sockets. + +Steve Chadsey and Thomas Weissmuller noticed that files larger than the +available memory could not be compressed by Mksquashfs. + +"Ptwahyu" and "Hoan" (I have no full names and I don't like giving people's +email addresses), noticed that Mksquashfs 1.3 SEGV'd occasionally. Even though +I had already noticed this bug, it is useful to be informed by other people. + +Don Elwell, Murray Jensen and Cameron Rich, have all sent in patches. Thanks, +I have not had time to do anything about them yet... + +Drew Scott Daniels has been a good advocate for Squashfs. + +Erik Andersen has made some nice suggestions, unfortunately, I have +not had time to implement anything. + +Artemiy I. Pavlov has written a useful LDP mini-howto for Squashfs +(http://linuxdoc.artemio.net/squashfs). + +Yves Combe reported the Apple G5 bug, when using Squashfs for +his PPC Knoppix-mib livecd project. + +Jaco Greeff (mklivecd project, and maintainer of the Mandrake +squashfs-tools package) suggested the new mksquashfs -ef option, and the +standalone build for mksquashfs. + +Mike Schaudies made a donation. + +Arkadiusz Patyk from the Polish Linux Distribution reported that Squashfs +didn't work on amd64 machines. He gave me an account on a PLD amd64 machine +which allowed myself to track down these bugs. + +Miles Roper, Peter Kjellerstedt and Willy Tarreau reported that release 2.1 did +not compile with gcc < 3.x. + +Marcel J.E. Mol reported lack of kernel memory issues when using Squashfs +on small memory embedded systems. This prompted the addition of the embedded +system kernel configuration options. + +Era Scarecrow noticed that Mksquashfs had not been updated to reflect that +smaller than 4K blocks are no longer supported. + +Kenichi Shima reported the Kconfig file had not been updated to 2.2. + +Aaron Ten Clay made a donation! + +Tomas Matejicek (SLAX) made a donation! diff --git a/SQUASHFS/squashfs-tools-4.4/CHANGES b/SQUASHFS/squashfs-tools-4.4/CHANGES new file mode 100644 index 00000000..c35107bd --- /dev/null +++ b/SQUASHFS/squashfs-tools-4.4/CHANGES @@ -0,0 +1,664 @@ + SQUASHFS CHANGE LOG + +4.4 29 AUG 2019 Reproducible builds, new compressors, + CVE fixes, security hardening and new options + for Mksquashfs/Unsquashfs. + + 1. Overall improvements: + + 1.1 Mksquashfs now generates reproducible images by default. + 1.2 Mkfs time and file timestamps can also be specified. + 1.3 Support for the Zstandard (ZSTD) compression algorithm. + 1.4 CVE-2015-4645 and CVE-2015-4646 have been fixed. + + 2. Mksquashfs improvements and major bug fixes: + + 2.1 Pseudo files now support symbolic links. + 2.2 New -mkfs-time option. + 2.3 New -all-time option. + 2.4 New -root-mode option. + 2.5 New -quiet option. + 2.6 New -noId option. + 2.7 New -offset option. + 2.8 Update lz4 wrapper to use new functions introduced + in 1.7.0. + 2.9 Bug fix, don't allow "/" pseudo filenames. + 2.10 Bug fix, allow quoting of pseudo files, to + better handle filenames with spaces. + 2.11 Fix compilation with glibc 2.25+. + + 3. Unsquashfs improvements and major bug fixes: + + 3.1 CVE-2015-4645 and CVE-2015-4646 have been fixed. + 3.2 Unsquashfs has been further hardened against corrupted + filestems. + 3.3 Unsquashfs is now more strict about error handling. + 3.4 New -ignore-errors option. + 3.5 New -strict-errors option. + 3.6 New -lln[umeric] option. + 3.7 New -lc option. + 3.8 New -llc option. + 3.9 New -mkfs-time option. + 3.10 New -UTC option. + 3.11 New -offset option. + 3.12 New -quiet option. + 3.13 Update lz4 wrapper to use new functions introduced + in 1.7.0. + 3.14 Bug fix, fatal and non-fatal errors now set the exit + code to 1. + 3.15 Bug fix, fix time setting for symlinks. + 3.16 Bug fix, try to set sticky-bit when running as a + user process. + 3.17 Fix compilation with glibc 2.25+. + +4.3 12 MAY 2014 New compressor options, new Mksquashfs/Unsquashfs + functionality, duplicate checking optimisations, + stability improvements (option/file parsing, + buffer/memory overflow checks, filesystem hardening + on corrupted filesystems), CVE fixes. + + Too many changes to do the traditional custom changelog. But, this + is now unnecessary, so instead list most significant 15% of commits + from git changelog in chronological order. + + - unsquashfs: add checks for corrupted data in opendir functions + - unsquashfs: completely empty filesystems incorrectly generate an error + - unsquashfs: fix open file limit + - mksquashfs: Use linked list to store directory entries rather + - mksquashfs: Remove qsort and add a bottom up linked list merge sort + - mksquashfs: optimise lookup_inode2() for dirs + - pseudo: fix handling of modify pseudo files + - pseudo: fix handling of directory pseudo files + - xattr: Fix ERROR() so that it is synchronised with the progress bar + - mksquashfs/sort: Fix INFO() so that it is synced with the progress bar + - mksquashfs: Add -progress to force progress bar when using -info + - error.h: consolidate the various error macros into one header file + - mksquashfs: fix stack overflow in write_fragment_table() + - mksquashfs: move list allocation from off the stack + - unsquashfs: fix oversight in directory permission setting + - mksquashfs: dynamically allocate recovery_file + - mksquashfs: dynamically allocate buffer in subpathname() + - mksquashfs: dynamically allocate buffer in pathname() + - unsquashfs: fix CVE-2012-4024 + - unsquashfs: fix CVE-2012-4025 + - mksquashfs: fix potential stack overflow in get_component() + - mksquashfs: add parse_number() helper for numeric command line options + - mksquasfs: check return value of fstat() in reader_read_file() + - mksquashfs: dynamically allocate filename in old_add_exclude() + - unsquashfs: dynamically allocate pathname in dir_scan() + - unsquashfs: dynamically allocate pathname in pre_scan() + - sort: dynamically allocate filename in add_sort_list() + - mksquashfs: fix dir_scan() exit if lstat of source directory fails + - pseudo: fix memory leak in read_pseudo_def() if exec_file() fails + - pseudo: dynamically allocate path in dump_pseudo() + - mksquashfs: dynamically allocate path in display_path2() + - mksquashfs: dynamically allocate b_buffer in getbase() + - pseudo: fix potential stack overflow in get_component() + - pseudo: avoid buffer overflow in read_pseudo_def() using sscanf() + - pseudo: dynamically allocate filename in exec_file() + - pseudo: avoid buffer overflow in read_sort_file() using fscanf() + - sort: tighten up sort file parsing + - unsquashfs: fix name under-allocation in process_extract_files() + - unsquashfs: avoid buffer overflow in print_filename() using sprintf() + - Fix some limits in the file parsing routines + - pseudo: Rewrite pseudo file processing + - read_fs: fix small memory leaks in read_filesystem() + - mksquashfs: fix fclose leak in reader_read_file() on I/O error + - mksquashfs: fix frag struct leak in write_file_{process|blocks|frag} + - unsquashfs_xattr: fix memory leak in write_xattr() + - read_xattrs: fix xattr free in get_xattr() in error path + - unsquashfs: add -user-xattrs option to only extract user.xxx xattrs + - unsquashfs: add code to only print "not superuser" error message once + - unsquashfs: check for integer overflow in user input + - mksquashfs: check for integer overflow in user input + - mksquashfs: fix "new" variable leak in dir_scan1() + - read_fs: prevent buffer {over|under}flow in read_block() with + corrupted filesystems + - read_fs: check metadata blocks are expected size in scan_inode_table() + - read_fs: check the root inode block is found in scan_inode_table() + - read_fs: Further harden scan_inode_table() against corrupted + filesystems + - unsquashfs: prevent buffer {over|under}flow in read_block() with + corrupted filesystems + - read_xattrs: harden xattr data reading against corrupted filesystems + - unsquash-[23]: harden frag table reading against corrupted filesystems + - unsquash-4.c: harden uid/gid & frag table reading against corruption + - unsquashfs: harden inode/directory table reading against corruption + - mksquashfs: improve out of space in output filesystem handling + - mksquashfs: flag lseek error in writer as probable out of space + - mksquashfs: flag lseek error in write_destination as probable out of + space + - mksquashfs: print file being squashed when ^\ (SIGQUIT) typed + - mksquashfs: make EXIT_MKSQUASHFS() etc restore via new restore thread + - mksquashfs: fix recursive restore failure check + - info: dump queue and cache status if ^\ hit twice within one second + - mksquashfs: fix rare race condition in "locked fragment" queueing + - lz4: add experimental support for lz4 compression + - lz4: add support for lz4 "high compression" + - lzo_wrapper: new implementation with compression options + - gzip_wrapper: add compression options + - mksquashfs: redo -comp parsing + - mksquashfs: display compressor options when -X option isn't recognised + - mksquashfs: add -Xhelp option + - mksquashfs/unsquashfs: fix mtime signedness + - Mksquashfs: optimise duplicate checking when appending + - Mksquashfs: introduce additional per CPU fragment process threads + - Mksquashfs: significantly optimise fragment duplicate checking + - read_fs: scan_inode_table(), fix memory leak on filesystem corruption + - pseudo: add_pseudo(), fix use of freed variable + - mksquashfs/unsquashfs: exclude/extract/pseudo files, fix handling of + leaf name + - mksquashfs: rewrite default queue size so it's based on physical mem + - mksquashfs: add a new -mem option + - mksquashfs: fix limit on the number of dynamic pseudo files + - mksquashfs: make -mem take a normal byte value, optionally with a + K, M or G + +4.2 28 FEB 2011 XZ compression, and compression options support + + 1. Filesystem improvements: + + 1.1 Added XZ compression + 1.2 Added compression options support + + 2. Miscellaneous improvements/bug fixes + + 1.1 Add missing NO_XATTR filesystem flag to indicate no-xattrs + option was specified and no xattrs should be stored when + appending. + 1.2 Add suppport in Unquashfs -stat option for displaying + NO_XATTR flag. + 1.3 Remove checkdata entry from Unsquashfs -stat option if a 4.0 + filesystem - checkdata is no longer supported. + 1.4 Fix appending bug when appending to an empty filesystem - this + would be incorrectly treated as an error. + 1.5 Use glibc sys/xattr.h include rather than using attr/xattr.h + which isn't present by default on some distributions. + 1.6 Unsquashfs, fix block calculation error with regular files when + file size is between 2^32-block_size+1 and 2^32-1. + 1.7 Unsquashfs, fix sparse file writing when holes are larger than + 2^31-1. + 1.8 Add external CFLAGS and LDFLAGS support to Makefile, and allow + build options to be specified on command line. Also don't + over-write passed in CFLAGS definition. + + +4.1 19 SEPT 2010 Major filesystem and tools improvements + + 1. Filesystem improvements: + + 1.1 Extended attribute support + 1.2 New compression framework + 1.3 Support for LZO compression + 1.4 Support for LZMA compression (not yet in mainline) + + 2. Mksquashfs improvements: + + 1.1 Enhanced pseudo file support + 1.2 New options for choosing compression algorithm used + 1.3 New options for controlling extended attributes + 1.4 Fix misalignment issues with memcpy etc. seen on ARM + 1.5 Fix floating point error in progress_bar when max == 0 + 1.6 Removed use of get_nproc() call unavailable in ulibc + 1.7 Reorganised help text + + 3. Unsquashfs improvements: + + 1.1 New options for controlling extended attributes + 1.2 Fix misalignment issues with memcpy etc. seen on ARM + 1.3 Fix floating point error in progress_bar when max == 0 + 1.4 Removed use of get_nproc() call unavailable in ulibc + + +4.0 5 APR 2009 Major filesystems improvements + + 1. Kernel code improvements: + + 1.1 Fixed little endian layout adopted. All swapping macros + removed, and in-line swapping added for big-endian + architectures. + 1.2 Kernel code substantially improved and restructured. + 1.3 Kernel code split into separate files along functional lines. + 1.4 Vmalloc usage removed, and code changed to use separately + allocated 4K buffers + + 2. Unsquashfs improvements: + + 2.1 Support for 4.0 filesystems added. + 2.2 Swapping macros rewritten. + 2.3 Unsquashfs code restructured and split into separate files. + + 3. Mksquashfs improvements: + + 3.1 Swapping macros rewritten. Fixed little-endian layout allows + code to be optimised and only added at compile time for + big endian systems. + 3.2 Support for pseudo files added. + +3.4 26 AUG 2008 Performance improvements to Unsquashfs, Mksquashfs + and the kernel code. Plus many small bug fixes. + + 1. Kernel code improvements: + + 1.1 Internal Squashfs kernel metadata and fragment cache + implementations have been merged and optimised. Spinlocks are + now used, locks are held for smaller periods and wakeups have + been minimised. Small race condition fixed where if two or + more processes tried to read the same cache block + simultaneously they would both read and decompress it. 10-20%+ + speed improvement has been seen on tests. + 1.2 NFS export code rewritten following VFS changes in + linux-2.6.24. + 1.3 New patches for linux-2.6.25, linux-2.6.26, and linux-2.6.27. + Fixed patch for linux-2.6.24. + 1.4 Fixed small buffer_head leak in squashfs_read_data when + handling badly corrupted filesystems. + 1.5 Fixed bug in get_dir_index_using_offset. + + 2. Unsquashfs improvements: + + 2.1 Unsquashfs has been parallelised. Filesystem reading, writing + and decompression is now multi-threaded. Up to 40% speed + improvement seen on tests. + 2.2 Unsquashfs now has a progress bar. Use -no-progress to + disable it. + 2.3 Fixed small bug where unistd.h wasn't being included on + some distributions, leading to lseek being used rather than + lseek64 - which meant on these distributions Unsquashfs + couldn't unsquash filesystems larger than 4GB. + + 3. Mksquashfs improvements: + + 3.1 Removed some small remaining parallelisation bottlenecks. + Depending on source filesystem, up to 10%+ speed improvement. + 3.2 Progress bar improved, and moved to separate thread. + 3.3 Sparse file handling bug in Mksquashfs 3.3 fixed. + 3.4 Two rare appending restore bugs fixed (when ^C hit twice). + + +3.3 1 NOV 2007 Increase in block size, sparse file support, + Mksquashfs and Unsquashfs extended to use + pattern matching in exclude/extract files, plus + many more improvements and bug fixes. + + 1. Filesystem improvements: + + 1.1. Maximum block size has been increased to 1Mbyte, and the + default block size has been increased to 128 Kbytes. + This improves compression. + + 1.2. Sparse files are now supported. Sparse files are files + which have large areas of unallocated data commonly called + holes. These files are now detected by Squashfs and stored + more efficiently. This improves compression and read + performance for sparse files. + + 2. Mksquashfs improvements: + + 2.1. Exclude files have been extended to use wildcard pattern + matching and regular expressions. Support has also been + added for non-anchored excludes, which means it is + now possible to specify excludes which match anywhere + in the filesystem (i.e. leaf files), rather than always + having to specify exclude files starting from the root + directory (anchored excludes). + + 2.2. Recovery files are now created when appending to existing + Squashfs filesystems. This allows the original filesystem + to be recovered if Mksquashfs aborts unexpectedly + (i.e. power failure). + + 3. Unsquashfs improvements: + + 3.1. Multiple extract files can now be specified on the + command line, and the files/directories to be extracted can + now also be given in a file. + + 3.2. Extract files have been extended to use wildcard pattern + matching and regular expressions. + + 3.3. Filename printing has been enhanced and Unquashfs can + now display filenames with file attributes + ('ls -l' style output). + + 3.4. A -stat option has been added which displays the filesystem + superblock information. + + 3.5. Unsquashfs now supports 1.x filesystems. + + 4. Miscellaneous improvements/bug fixes: + + 4.1. Squashfs kernel code improved to use SetPageError in + squashfs_readpage() if I/O error occurs. + + 4.2. Fixed Squashfs kernel code bug preventing file + seeking beyond 2GB. + + 4.3. Mksquashfs now detects file size changes between + first phase directory scan and second phase filesystem create. + It also deals better with file I/O errors. + + +3.2-r2 15 JAN 2007 Kernel patch update and progress bar bug fix + + 1. Kernel patches 2.6.19/2.6.20 have been updated to use + const structures and mutexes rather than older semaphores. + 2. Minor SMP bug fixes. + 3. Progress bar broken on x86-64. Fixed. + +3.2 2 JAN 2007 NFS support, improvements to the Squashfs-tools, major + bug fixes, lots of small improvements/bug fixes, and new + kernel patches. + + Improvements: + + 1. Squashfs filesystems can now be exported via NFS. + 2. Unsquashfs now supports 2.x filesystems. + 3. Mksquashfs now displays a progress bar. + 4. Squashfs kernel code has been hardened against accidently or + maliciously corrupted Squashfs filesystems. + + Bug fixes: + + 5. Race condition occurring on S390 in readpage() fixed. + 6. Odd behaviour of MIPS memcpy in read_data() routine worked-around. + 7. Missing cache_flush in Squashfs symlink_readpage() added. + + +3.1-r2 30 AUG 2006 Mksquashfs -sort bug fix + + A code optimisation after testing unfortunately + broke sorting in Mksquashfs. This has been fixed. + +3.1 19 AUG 2006 This release has some major improvements to + the squashfs-tools, a couple of major bug + fixes, lots of small improvements/bug fixes, + and new kernel patches. + + + 1. Mksquashfs has been rewritten to be multi-threaded. It + has the following improvements + + 1.1. Parallel compression. By default as many compression and + fragment compression threads are created as there are available + processors. This significantly speeds up performance on SMP + systems. + 1.2. File input and filesystem output is peformed in parallel on + separate threads to maximise I/O performance. Even on single + processor systems this speeds up performance by at least 10%. + 1.3. Appending has been significantly improved, and files within the + filesystem being appended to are no longer scanned and + checksummed. This significantly improves append time for large + filesystems. + 1.4. File duplicate checking has been optimised, and split into two + separate phases. Only files which are considered possible + duplicates after the first phase are checksummed and cached in + memory. + 1.5 The use of swap memory was found to significantly impact + performance. The amount of memory used to cache files is now a + command line option, by default this is 512 Mbytes. + + 2. Unsquashfs has the following improvements + + 2.1 Unsquashfs now allows you to specify the filename or the + directory within the Squashfs filesystem that is to be + extracted, rather than always extracting the entire filesystem. + 2.2 A new -force option has been added which forces Unsquashfs to + output to the destination directory even if files and directories + already exist in the destination directory. This allows you to + update an already existing directory tree, or to Unsquashfs to + a partially filled directory tree. Without the -force option + Unsquashfs will refuse to output. + + 3. The following major bug fixes have been made + + 3.1 A fragment table rounding bug has been fixed in Mksquashfs. + Previously if the number of fragments in the filesystem + were a multiple of 512, Mksquashfs would generate an + incorrect filesystem. + 3.2 A rare SMP bug which occurred when simultaneously acccessing + multiply mounted Squashfs filesystems has been fixed. + + 4. Miscellaneous improvements/bug fixes + + 4.1 Kernel code stack usage has been reduced. This is to ensure + Squashfs works with 4K stacks. + 4.2 Readdir (Squashfs kernel code) has been fixed to always + return 0, rather than the number of directories read. Squashfs + should now interact better with NFS. + 4.3 Lseek bug in Mksquashfs when appending to larger than 4GB + filesystems fixed. + 4.4 Squashfs 2.x initrds can now been mounted. + 4.5 Unsquashfs exit status fixed. + 4.6 New patches for linux-2.6.18 and linux-2.4.33. + + +3.0 15 MAR 2006 Major filesystem improvements + + 1. Filesystems are no longer limited to 4 GB. In + theory 2^64 or 4 exabytes is now supported. + 2. Files are no longer limited to 4 GB. In theory the maximum + file size is 4 exabytes. + 3. Metadata (inode table and directory tables) are no longer + restricted to 16 Mbytes. + 4. Hardlinks are now suppported. + 5. Nlink counts are now supported. + 6. Readdir now returns '.' and '..' entries. + 7. Special support for files larger than 256 MB has been added to + the Squashfs kernel code for faster read access. + 8. Inode numbers are now stored within the inode rather than being + computed from inode location on disk (this is not so much an + improvement, but a change forced by the previously listed + improvements). + +2.2-r2 8 SEPT 2005 Second release of 2.2, this release fixes a couple + of small bugs, a couple of small documentation + mistakes, and adds a patch for kernel 2.6.13. + + 1. Mksquashfs now deletes the output filesystem image file if an + error occurs whilst generating the filesystem. Previously on + error the image file was left empty or partially written. + 2. Updated mksquashfs so that it doesn't allow you to generate + filesystems with block sizes smaller than 4K. Squashfs hasn't + supported block sizes less than 4K since 2.0-alpha. + 3. Mksquashfs now ignores missing files/directories in sort files. + This was the original behaviour before 2.2. + 4. Fixed small mistake in fs/Kconfig where the version was still + listed as 2.0. + 5. Updated ACKNOWLEDGEMENTS file. + + +2.2 3 JUL 2005 This release has some small improvements, bug fixes + and patches for new kernels. + + 1. Sort routine re-worked and debugged from release 2.1. It now allows + you to give Mkisofs style sort files and checks for filenames that + don't match anything. Sort priority has also been changed to + conform to Mkisofs usage, highest priority files are now placed + at the start of the filesystem (this means they will be on the + inside of a CD or DVD). + 2. New Configure options for embedded systems (memory constrained + systems). See INSTALL file for further details. + 3. Directory index bug fixed where chars were treated as signed on + some architectures. A file would not be found in the rare case + that the filename started with a chracter greater than 127. + 4. Bug introduced into the read_data() routine when sped up to use data + block queueing fixed. If the second or later block resulted in an + I/O error this was not checked. + 5. Append bug introduced in 2.1 fixed. The code to compute the new + compressed and uncompressed directory parts after appending was + wrong. + 6. Metadata block length read routine altered to not perform a + misaligned short read. This was to fix reading on an ARM7 running + uCLinux without a misaligned read interrupt handler. + 7. Checkdata bug introduced in 2.1 fixed. + + +2.1-r2 15 DEC 2004 Code changed so it can be compiled with gcc 2.x + + 1. In some of the code added for release 2.1 I unknowingly used some + gcc extensions only supported by 3.x compilers. I have received + a couple of reports that the 2.1 release doesn't build on 2.x and so + people are clearly still using gcc 2.x. The code has been + rewritten to remove these extensions. + +2.1 10 DEC 2004 Significantly improved directory handling plus numerous + other smaller improvements + + 1. Fast indexed directories implemented. These speed up directory + operations (ls, file lookup etc.) significantly for directories + larger than 8 KB. + 2. All directories are now sorted in alphabetical order. This again + speeds up directory operations, and in some cases it also results in + a small compression improvement (greater data similarity between + files with alphabetically similar names). + 3. Maximum directory size increased from 512 KB to 128 MB. + 4. Duplicate fragment checking and appending optimised in mksquashfs, + depending on filesystem, this is now up to 25% faster. + 5. Mksquashfs help information reformatted and reorganised. + 6. The Squashfs version and release date is now printed at kernel + boot-time or module insertion. This addition will hopefully help + to reduce the growing problem where the Squashfs version supported + by a kernel is unknown and the kernel source is unavailable. + 7. New PERFORMANCE.README file. + 8. New -2.0 mksquashfs option. + 9. CHANGES file reorganised. + 10. README file reorganised, clarified and updated to include the 2.0 + mksquashfs options. + 11. New patch for Linux 2.6.9. + 12. New patch for Linux 2.4.28. + +2.0r2 29 AUG 2004 Workaround for kernel bug in kernels 2.6.8 and newer + added + + 1. New patch for kernel 2.6.8.1. This includes a workaround for a + kernel bug introduced in 2.6.7bk14, which is present in all later + versions of the kernel. + + If you're using a 2.6.8 kernel or later then you must use this + 2.6.8.1 patch. If you've experienced hangs or oopses using Squashfs + with a 2.6.8 or later kernel then you've hit this bug, and this + patch will fix it. + + It is worth mentioning that this kernel bug potentially affects + other filesystems. If you receive odd results with other + filesystems you may be experiencing this bug with that filesystem. + I submitted a patch but this has not yet gone into the + kernel, hopefully the bug will be fixed in later kernels. + +2.0 13 JULY 2004 A couple of new options, and some bug fixes + + 1. New mksquashfs -all-root, -root-owned, -force-uid, and -force-gid + options. These allow the uids/gids of files in the generated + filesystem to be specified, overriding the uids/gids in the + source filesystem. + 2. Initrds are now supported for kernels 2.6.x. + 3. amd64 bug fixes. If you use an amd64, please read the README-AMD64 + file. + 4. Check-data and gid bug fixes. With 2.0-alpha when mounting 1.x + filesystems in certain cases file gids were corrupted. + 5. New patch for Linux 2.6.7. + +2.0-ALPHA 21 MAY 2004 Filesystem changes and compression improvements + + 1. Squashfs 2.0 has added the concept of fragment blocks. + Files smaller than the file block size and optionally the + remainder of files that do not fit fully into a block (i.e. the + last 32K in a 96K file) are packed into shared fragments and + compressed together. This achieves on average 5 - 20% better + compression than Squashfs 1.x. + 2. The maximum block size has been increased to 64K (in the ALPHA + version of Squashfs 2.0). + 3. The maximum number of UIDs has been increased to 256 (from 48 in + 1.x). + 4. The maximum number of GIDs has been increased to 256 (from 15 in + 1.x). + 5. Removal of sleep_on() function call in 2.6.x patch, to allow Squashfs + to work on the Fedora rc2 kernel. + 6. Numerous small bug fixes have been made. + +1.3r3 18 JAN 2004 Third release of 1.3, this adds a new mksquashfs option, + some bug fixes, and extra patches for new kernels + + 1. New mksquashfs -ef exclude option. This option reads the exclude + dirs/files from an exclude file, one exclude dir/file per line. This + avoids the command line size limit when using the -e exclude option, + 2. When appending to existing filesystems, if mksquashfs experiences a + fatal error (e.g. out of space when adding to the destination), the + original filesystem is restored, + 3. Mksquashfs now builds standalone, without the kernel needing to be + patched. + 4. Bug fix in the kernel squashfs filesystem, where the pages being + filled were not kmapped. This seems to only have caused problems + on an Apple G5, + 5. New patch for Linux 2.4.24, + + 6. New patch for Linux 2.6.1, this replaces the patch for 2.6.0-test7. + +1.3r2 14 OCT 2003 Second release of 1.3, bug fixes and extra patches for + new kernels + + 1. Bug fix in routine that adds files to the filesystem being + generated in mksquashfs. This bug was introduced in 1.3 + (not enough testing...) when I rewrote it to handle files larger + than available memory. This bug caused a SEGV, so if you've ever + got that, it is now fixed, + 2. Long running bug where ls -s and du reported wrong block size + fixed. I'm pretty sure this used to work many kernel versions ago + (2.4.7) but it broke somewhere along the line since then, + 3. New patch for Linux 2.4.22, + 4. New patch for 2.6.0-test7, this replaces the patch for 2.6.0-test1. + +1.3 29 JUL 2003 FIFO/Socket support added plus optimisations and + improvements + + 1. FIFOs and Socket inodes are now supported, + 2. Mksquashfs can now compress files larger than available + memory, + 3. File duplicate check routine optimised, + 4. Exit codes fixed in Mksquashfs, + 5. Patch for Linux 2.4.21, + 6. Patch for Linux 2.6.0-test1. Hopefully, this will work for + the next few releases of 2.6.0-testx, otherwise, I'll be + releasing a lot of updates to the 2.6.0 patch... + +1.2 13 MAR 2003 Append feature and new mksquashfs options added + + Mksquashfs can now add to existing squashfs filesystems. Three extra + options "-noappend", "-keep-as-directory", and "root-becomes" + have been added. + + The append option with file duplicate detection, means squashfs can be + used as a simple versioning archiving filesystem. A squashfs + filesystem can be created with for example the linux-2.4.19 source. + Appending the linux-2.4.20 source will create a filesystem with the + two source trees, but only the changed files will take extra room, + the unchanged files will be detected as duplicates. + + See the README file for usage changes. + +1.1b 16 JAN 2003 Bug fix release + + Fixed readpage deadlock bug. This was a rare deadlock bug that + happened when pushing pages into the page cache when using greater + than 4K blocks. I never got this bug when I tested the filesystem, + but two people emailed me on the same day about the problem! + I fixed it by using a page cache function that wasn't there when + I originally did the work, which was nice :-) + +1.1 8 JAN 2003 Added features + + 1. Kernel squashfs can now mount different byte order filesystems. + 2. Additional features added to mksquashfs. Mksquashfs now supports + exclude files and multiple source files/directories can be + specified. A nopad option has also been added, which + informs mksquashfs not to pad filesystems to a multiple of 4K. + See README for mksquashfs usage changes. + 3. Greater than 2GB filesystems bug fix. Filesystems greater than 2GB + can now be created. + +1.0c 14 NOV 2002 Bug fix release + + Fixed bugs with initrds and device nodes + +1.0 23 OCT 2002 Initial release diff --git a/SQUASHFS/squashfs-tools-4.4/COPYING b/SQUASHFS/squashfs-tools-4.4/COPYING new file mode 100644 index 00000000..d159169d --- /dev/null +++ b/SQUASHFS/squashfs-tools-4.4/COPYING @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/SQUASHFS/squashfs-tools-4.4/INSTALL b/SQUASHFS/squashfs-tools-4.4/INSTALL new file mode 100644 index 00000000..5eed1463 --- /dev/null +++ b/SQUASHFS/squashfs-tools-4.4/INSTALL @@ -0,0 +1,44 @@ + INSTALLING SQUASHFS + +1. Kernel support +----------------- + +This release is for 2.6.29 and newer kernels. Kernel patching is not necessary. + +Extended attribute support requires 2.6.35 or newer kernels. But +file systems with extended attributes can be mounted on 2.6.29 and +newer kernels (the extended attributes will be ignored with a warning). + +LZO compression support requires 2.6.36 or newer kernels. + +XZ compression support requires 2.6.38 or newer kernels. + +LZ4 compression support requires 3.11 or newer kernels. + +ZSTD compression support requires 4.14 or newer kernels. + +2. Building squashfs tools +-------------------------- + +The squashfs-tools directory contains the source code for the Mksquashfs and +Unsquashfs programs. These can be compiled by typing make (or sudo make +install to install in /usr/local/bin) within that directory. + +2.1 Compressors supported + +By default the Makefile is configured to build Mksquashfs and Unsquashfs +with GZIP suppport. Read the Makefile in squashfs-tools for instructions on +building LZO, LZ4, XZ and ZSTD compression support. + +2.2 Extended attribute support + +By default the Makefile is configured to build Mksquashfs and Unsquashfs +with extended attribute support. Read the Makefile in squashfs-tools for +instructions on how to disable extended attribute support, if not supported +by your distribution/C library, or if it is not needed. + +2.3 Reproducible builds + +By default the Makefile is configured to build Mksquashfs with reproducible +output as default. Read the Makefile in squashfs-tools for instructions +on how to disable reproducible output as default if desired. diff --git a/SQUASHFS/squashfs-tools-4.4/README b/SQUASHFS/squashfs-tools-4.4/README new file mode 100644 index 00000000..478c2fa5 --- /dev/null +++ b/SQUASHFS/squashfs-tools-4.4/README @@ -0,0 +1,15 @@ +GitHub + +This is now the main development repository for Squashfs-Tools. + +There are older repositories on Sourceforge and kernel.org. These +are currently out of date, but should be updated in the near future. + +The kernel directories are obsolete, all kernel code is now in +mainline at www.kernel.org. + +kernel-2.4: If you still need Squashfs support in the 2.4 kernel +then use the squashfs 3.2-r2 release. This is the last release +that has a Mksquashfs which generates filesystems mountable with +Squashfs patched 2.4 kernels. This release has patches for 2.4 +kernels (but they have not been updated since the 3.1 release). diff --git a/SQUASHFS/squashfs-tools-4.4/README-4.4 b/SQUASHFS/squashfs-tools-4.4/README-4.4 new file mode 100644 index 00000000..404bf86e --- /dev/null +++ b/SQUASHFS/squashfs-tools-4.4/README-4.4 @@ -0,0 +1,316 @@ + SQUASHFS 4.4 - A squashed read-only filesystem for Linux + + Copyright 2002-2019 Phillip Lougher + + Released under the GPL licence (version 2 or later). + +Welcome to Squashfs 4.4. This is the first release in over 5 years, and +there are substantial improvements: reproducible builds, new compressors, +CVE fixes, security hardening and new options for Mksquashfs/Unsquashfs. + +Please see the INSTALL file for instructions on installing the tools, +and the USAGE file for documentation on how to use the tools. + +Summary of changes (and sections below) +--------------------------------------- + +1. Mksquashfs now generates reproducible images by default. Mkfs time and + file timestamps can also be specified. + +2. Support for the Zstandard (ZSTD) compression algorithm has been added. + +3. Pseudo files now support symbolic links. + +4. CVE-2015-4645 and CVE-2015-4646 have been fixed. + +5. Unsquashfs has been further hardened against corrupted filestems. + +6. Unsquashfs is now more strict about error handling. + +7. Miscellaneous new options and major bug fixes for Mksquashfs. + +8. Miscellaneous new options and major bug fixes for Unsquashfs. + +9. Squashfs-tools 4.4 is compatible with all earlier 4.x filesystems + and releases. + + +1. Introducing reproducible builds +---------------------------------- + +Ever since Mksquashfs was parallelised back in 2006, there +has been a certain randomness in how fragments and multi-block +files are ordered in the output filesystem even if the input +remains the same. + +This is because the multiple parallel threads can be scheduled +differently between Mksquashfs runs. For example, the thread +given fragment 10 to compress may finish before the thread +given fragment 9 to compress on one run (writing fragment 10 +to the output filesystem before fragment 9), but, on the next +run it could be vice-versa. There are many different scheduling +scenarios here, all of which can have a knock on effect causing +different scheduling and ordering later in the filesystem too. + +Mkquashfs doesn't care about the ordering of fragments and +multi-block files within the filesystem, as this does not +affect the correctness of the filesystem. + +In fact not caring about the ordering, as it doesn't matter, allows +Mksquashfs to run as fast as possible, maximising CPU and I/O +performance. + +But, in the last couple of years, Squashfs has become used in +scenarios (cloud etc) where this randomness is causing problems. +Specifically this appears to be where downloaders, installers etc. +try to work out the differences between Squashfs filesystem +updates to minimise the amount of data that needs to transferred +to update an image. + +Additionally, in the last couple of years has arisen the notion +of reproducible builds, that is the same source and build +environment etc should be able to (re-)generate identical +output. This is usually for verification and security, allowing +binaries/distributions to be checked for malicious activity. +See https://reproducible-builds.org/ for more information. + +Mksquashfs now generates reproducible images by default. +Images generated by Mksquashfs will be ordered identically to +previous runs if the same input has been supplied, and the +same options used. + +1.1.1 Dealing with timestamps + +Timestamps embedded in the filesystem will stiil cause differences. +Each new run of Mksquashfs will produce a different mkfs (make filesystem) +timestamp in the super-block. Moreover if any file timestamps have changed +(even if the content hasn't), this will produce a difference. + +To prevent timestamps from producing differences, the following +new Mksquashfs options have been added. + +1.1.2 -mkfs-time