Compare commits

...

13 Commits

Author SHA1 Message Date
longpanda
039e68400d 1.0.15 release 2020-07-09 22:44:10 +08:00
longpanda
e384dad4d0 update languages.ini 2020-07-09 19:31:58 +08:00
longpanda
dcb3264519 prepare for new release 2020-07-09 19:26:23 +08:00
longpanda
4fda20d844 update 2020-07-07 23:38:57 +08:00
longpanda
b32cf97f1f update 2020-07-05 22:13:01 +08:00
longpanda
f7b35f371b update 2020-07-05 15:02:39 +08:00
longpanda
49ca1e05a4 add GPT support 2020-07-04 22:39:20 +08:00
longpanda
9ecbff9ce6 add GPT support 2020-07-04 22:30:04 +08:00
longpanda
1d034f0a24 update 2020-07-03 23:20:41 +08:00
longpanda
0ddc76a3aa update languages.ini 2020-07-03 00:00:59 +08:00
longpanda
a1ddade13c Update ventoy_pack.sh 2020-07-01 13:41:41 +08:00
longpanda
b925bbdeec update languages.ini 2020-06-27 22:24:02 +08:00
longpanda
e91b315f09 fix bug when update Ventoy in some Linux distros. 2020-06-26 09:48:52 +08:00
66 changed files with 6429 additions and 2495 deletions

View File

@@ -52,6 +52,8 @@ static grub_env_get_pf grub_env_get = NULL;
ventoy_grub_param_file_replace *g_file_replace_list = NULL;
ventoy_efi_file_replace g_efi_file_replace;
BOOLEAN g_fix_windows_1st_cdrom_issue = FALSE;
STATIC BOOLEAN g_hook_keyboard = FALSE;
CHAR16 gFirstTryBootFile[256] = {0};
@@ -493,6 +495,7 @@ STATIC EFI_STATUS EFIAPI ventoy_parse_cmdline(IN EFI_HANDLE ImageHandle)
EFI_STATUS Status = EFI_SUCCESS;
ventoy_grub_param *pGrubParam = NULL;
EFI_LOADED_IMAGE_PROTOCOL *pImageInfo = NULL;
ventoy_chain_head *chain = NULL;
Status = gBS->HandleProtocol(ImageHandle, &gEfiLoadedImageProtocolGuid, (VOID **)&pImageInfo);
if (EFI_ERROR(Status))
@@ -559,12 +562,15 @@ STATIC EFI_STATUS EFIAPI ventoy_parse_cmdline(IN EFI_HANDLE ImageHandle)
);
pPos = StrStr(pCmdLine, L"mem:");
g_chain = (ventoy_chain_head *)StrHexToUintn(pPos + 4);
chain = (ventoy_chain_head *)StrHexToUintn(pPos + 4);
pPos = StrStr(pPos, L"size:");
size = StrDecimalToUintn(pPos + 5);
debug("memory addr:%p size:%lu", g_chain, size);
debug("memory addr:%p size:%lu", chain, size);
g_chain = AllocatePool(size);
CopyMem(g_chain, chain, size);
if (StrStr(pCmdLine, L"memdisk"))
{
@@ -583,12 +589,12 @@ STATIC EFI_STATUS EFIAPI ventoy_parse_cmdline(IN EFI_HANDLE ImageHandle)
g_os_param_reserved = (UINT8 *)(g_chain->os_param.vtoy_reserved);
/* Workaround for Windows & ISO9660 */
if (g_os_param_reserved[2] == 1 && g_os_param_reserved[3] == 0)
if (g_os_param_reserved[2] == ventoy_chain_windows && g_os_param_reserved[3] == 0)
{
g_fixup_iso9660_secover_enable = TRUE;
}
if (g_os_param_reserved[2] == 1 && g_os_param_reserved[4] != 1)
if (g_os_param_reserved[2] == ventoy_chain_windows && g_os_param_reserved[4] != 1)
{
g_hook_keyboard = TRUE;
}
@@ -613,6 +619,17 @@ STATIC EFI_STATUS EFIAPI ventoy_parse_cmdline(IN EFI_HANDLE ImageHandle)
}
}
g_fix_windows_1st_cdrom_issue = FALSE;
if (ventoy_chain_windows == g_os_param_reserved[2] ||
ventoy_chain_wim == g_os_param_reserved[2])
{
if (ventoy_is_cdrom_dp_exist())
{
debug("fixup the 1st cdrom influences when boot windows ...");
g_fix_windows_1st_cdrom_issue = TRUE;
}
}
FreePool(pCmdLine);
return EFI_SUCCESS;
}
@@ -636,6 +653,44 @@ EFI_STATUS EFIAPI ventoy_clean_env(VOID)
FreePool((VOID *)(UINTN)g_chain->os_param.vtoy_img_location_addr);
}
FreePool(g_chain);
return EFI_SUCCESS;
}
STATIC EFI_STATUS ventoy_hook_start(VOID)
{
/* don't add debug print in this function */
if (g_fix_windows_1st_cdrom_issue)
{
ventoy_hook_1st_cdrom_start();
}
/* let this the last */
if (g_hook_keyboard)
{
ventoy_hook_keyboard_start();
}
return EFI_SUCCESS;
}
STATIC EFI_STATUS ventoy_hook_stop(VOID)
{
/* don't add debug print in this function */
if (g_fix_windows_1st_cdrom_issue)
{
ventoy_hook_1st_cdrom_stop();
}
/* let this the last */
if (g_hook_keyboard)
{
ventoy_hook_keyboard_stop();
}
return EFI_SUCCESS;
}
@@ -725,17 +780,11 @@ EFI_STATUS EFIAPI ventoy_boot(IN EFI_HANDLE ImageHandle)
pFile->OpenVolume = ventoy_wrapper_open_volume;
}
if (g_hook_keyboard)
{
ventoy_hook_keyboard_start();
}
ventoy_hook_start();
/* can't add debug print here */
//ventoy_wrapper_system();
Status = gBS->StartImage(Image, NULL, NULL);
if (g_hook_keyboard)
{
ventoy_hook_keyboard_stop();
}
ventoy_hook_stop();
if (EFI_ERROR(Status))
{

View File

@@ -25,6 +25,15 @@
#define VENTOY_GUID { 0x77772020, 0x2e77, 0x6576, { 0x6e, 0x74, 0x6f, 0x79, 0x2e, 0x6e, 0x65, 0x74 }}
typedef enum ventoy_chain_type
{
ventoy_chain_linux = 0, /* 0: linux */
ventoy_chain_windows, /* 1: windows */
ventoy_chain_wim, /* 2: wim */
ventoy_chain_max
}ventoy_chain_type;
#pragma pack(1)
typedef struct ventoy_guid
@@ -216,6 +225,7 @@ if (gDebugPrint) \
}
typedef const char * (*grub_env_get_pf)(const char *name);
typedef int (*grub_env_printf_pf)(const char *fmt, ...);
#pragma pack(1)
@@ -242,8 +252,8 @@ typedef struct ventoy_grub_param_file_replace
typedef struct ventoy_grub_param
{
grub_env_get_pf grub_env_get;
ventoy_grub_param_file_replace file_replace;
grub_env_printf_pf grub_env_printf;
}ventoy_grub_param;
typedef struct ventoy_ram_disk
@@ -279,6 +289,18 @@ typedef struct ventoy_system_wrapper
EFI_OPEN_PROTOCOL NewOpenProtocol;
EFI_OPEN_PROTOCOL OriOpenProtocol;
EFI_LOCATE_HANDLE_BUFFER NewLocateHandleBuffer;
EFI_LOCATE_HANDLE_BUFFER OriLocateHandleBuffer;
EFI_PROTOCOLS_PER_HANDLE NewProtocolsPerHandle;
EFI_PROTOCOLS_PER_HANDLE OriProtocolsPerHandle;
EFI_LOCATE_HANDLE NewLocateHandle;
EFI_LOCATE_HANDLE OriLocateHandle;
EFI_LOCATE_DEVICE_PATH NewLocateDevicePath;
EFI_LOCATE_DEVICE_PATH OriLocateDevicePath;
} ventoy_system_wrapper;
#define ventoy_wrapper(bs, wrapper, func, newfunc) \
@@ -317,6 +339,7 @@ extern UINTN g_iso_buf_size;
extern ventoy_grub_param_file_replace *g_file_replace_list;
extern BOOLEAN g_fixup_iso9660_secover_enable;
extern EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL *g_con_simple_input_ex;
extern BOOLEAN g_fix_windows_1st_cdrom_issue;
EFI_STATUS EFIAPI ventoy_wrapper_open_volume
(
@@ -327,6 +350,9 @@ EFI_STATUS EFIAPI ventoy_install_blockio(IN EFI_HANDLE ImageHandle, IN UINT64 Im
EFI_STATUS EFIAPI ventoy_wrapper_push_openvolume(IN EFI_SIMPLE_FILE_SYSTEM_PROTOCOL_OPEN_VOLUME OpenVolume);
EFI_STATUS ventoy_hook_keyboard_start(VOID);
EFI_STATUS ventoy_hook_keyboard_stop(VOID);
BOOLEAN ventoy_is_cdrom_dp_exist(VOID);
EFI_STATUS ventoy_hook_1st_cdrom_start(VOID);
EFI_STATUS ventoy_hook_1st_cdrom_stop(VOID);
#endif

View File

@@ -36,9 +36,9 @@
#include <Protocol/SimpleFileSystem.h>
#include <Ventoy.h>
#define PROCOTOL_SLEEP_SECONDS 0
#define PROCOTOL_SLEEP_MSECONDS 0
#define debug_sleep() if (PROCOTOL_SLEEP_SECONDS) sleep(PROCOTOL_SLEEP_SECONDS)
#define debug_sleep() if (PROCOTOL_SLEEP_MSECONDS) gBS->Stall(1000 * PROCOTOL_SLEEP_MSECONDS)
STATIC ventoy_system_wrapper g_system_wrapper;
@@ -126,7 +126,7 @@ STATIC EFI_STATUS EFIAPI ventoy_open_protocol
IN UINT32 Attributes
)
{
debug("ventoy_open_protocol:%a", ventoy_get_guid_name(Protocol)); debug_sleep();
debug("ventoy_open_protocol:<%p> %a", Handle, ventoy_get_guid_name(Protocol)); debug_sleep();
return g_system_wrapper.OriOpenProtocol(Handle, Protocol, Interface, AgentHandle, ControllerHandle, Attributes);
}
@@ -141,11 +141,87 @@ STATIC EFI_STATUS EFIAPI ventoy_locate_protocol
return g_system_wrapper.OriLocateProtocol(Protocol, Registration, Interface);
}
STATIC EFI_STATUS EFIAPI ventoy_locate_handle_buffer
(
IN EFI_LOCATE_SEARCH_TYPE SearchType,
IN EFI_GUID *Protocol, OPTIONAL
IN VOID *SearchKey, OPTIONAL
IN OUT UINTN *NoHandles,
OUT EFI_HANDLE **Buffer
)
{
debug("ventoy_locate_handle_buffer:%a", ventoy_get_guid_name(Protocol)); debug_sleep();
return g_system_wrapper.OriLocateHandleBuffer(SearchType, Protocol, SearchKey, NoHandles, Buffer);
}
STATIC EFI_STATUS EFIAPI ventoy_protocol_per_handle
(
IN EFI_HANDLE Handle,
OUT EFI_GUID ***ProtocolBuffer,
OUT UINTN *ProtocolBufferCount
)
{
debug("ventoy_protocol_per_handle:%p", Handle); debug_sleep();
return g_system_wrapper.OriProtocolsPerHandle(Handle, ProtocolBuffer, ProtocolBufferCount);
}
EFI_STATUS EFIAPI ventoy_locate_handle
(
IN EFI_LOCATE_SEARCH_TYPE SearchType,
IN EFI_GUID *Protocol, OPTIONAL
IN VOID *SearchKey, OPTIONAL
IN OUT UINTN *BufferSize,
OUT EFI_HANDLE *Buffer
)
{
UINTN i;
EFI_HANDLE Handle;
EFI_STATUS Status = EFI_SUCCESS;
debug("ventoy_locate_handle: %d %a %p", SearchType, ventoy_get_guid_name(Protocol), SearchKey);
Status = g_system_wrapper.OriLocateHandle(SearchType, Protocol, SearchKey, BufferSize, Buffer);
debug("ventoy_locate_handle: %r Handle Count:%u", Status, *BufferSize/sizeof(EFI_HANDLE));
if (EFI_SUCCESS == Status)
{
for (i = 0; i < *BufferSize / sizeof(EFI_HANDLE); i++)
{
if (Buffer[i] == gBlockData.Handle)
{
Handle = Buffer[0];
Buffer[0] = Buffer[i];
Buffer[i] = Handle;
debug("####### Handle at %u", i);
break;
}
}
}
debug_sleep();
return Status;
}
STATIC EFI_STATUS EFIAPI ventoy_locate_device_path
(
IN EFI_GUID *Protocol,
IN OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath,
OUT EFI_HANDLE *Device
)
{
debug("ventoy_locate_device_path:%a", ventoy_get_guid_name(Protocol)); debug_sleep();
return g_system_wrapper.OriLocateDevicePath(Protocol, DevicePath, Device);
}
EFI_STATUS EFIAPI ventoy_wrapper_system(VOID)
{
ventoy_wrapper(gBS, g_system_wrapper, LocateProtocol, ventoy_locate_protocol);
ventoy_wrapper(gBS, g_system_wrapper, HandleProtocol, ventoy_handle_protocol);
ventoy_wrapper(gBS, g_system_wrapper, OpenProtocol, ventoy_open_protocol);
ventoy_wrapper(gBS, g_system_wrapper, LocateProtocol, ventoy_locate_protocol);
ventoy_wrapper(gBS, g_system_wrapper, HandleProtocol, ventoy_handle_protocol);
ventoy_wrapper(gBS, g_system_wrapper, OpenProtocol, ventoy_open_protocol);
ventoy_wrapper(gBS, g_system_wrapper, LocateHandleBuffer, ventoy_locate_handle_buffer);
ventoy_wrapper(gBS, g_system_wrapper, ProtocolsPerHandle, ventoy_protocol_per_handle);
ventoy_wrapper(gBS, g_system_wrapper, LocateHandle, ventoy_locate_handle);
ventoy_wrapper(gBS, g_system_wrapper, LocateDevicePath, ventoy_locate_device_path);
return EFI_SUCCESS;
}

View File

@@ -65,6 +65,47 @@ EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL *g_con_simple_input_ex = NULL;
STATIC EFI_INPUT_READ_KEY_EX g_org_read_key_ex = NULL;
STATIC EFI_INPUT_READ_KEY g_org_read_key = NULL;
STATIC EFI_LOCATE_HANDLE g_org_locate_handle = NULL;
BOOLEAN ventoy_is_cdrom_dp_exist(VOID)
{
UINTN i = 0;
UINTN Count = 0;
EFI_HANDLE *Handles = NULL;
EFI_STATUS Status = EFI_SUCCESS;
EFI_DEVICE_PATH_PROTOCOL *DevicePath = NULL;
Status = gBS->LocateHandleBuffer(ByProtocol, &gEfiDevicePathProtocolGuid,
NULL, &Count, &Handles);
if (EFI_ERROR(Status))
{
return FALSE;
}
for (i = 0; i < Count; i++)
{
Status = gBS->HandleProtocol(Handles[i], &gEfiDevicePathProtocolGuid, (VOID **)&DevicePath);
if (EFI_ERROR(Status))
{
continue;
}
while (!IsDevicePathEnd(DevicePath))
{
if (MEDIA_DEVICE_PATH == DevicePath->Type && MEDIA_CDROM_DP == DevicePath->SubType)
{
FreePool(Handles);
return TRUE;
}
DevicePath = NextDevicePathNode(DevicePath);
}
}
FreePool(Handles);
return FALSE;
}
#if 0
/* Block IO procotol */
#endif
@@ -126,7 +167,7 @@ STATIC EFI_STATUS EFIAPI ventoy_read_iso_sector
MapLba, secRead * 2048, pCurBuf);
if (EFI_ERROR(Status))
{
debug("Raw disk read block failed %r", Status);
debug("Raw disk read block failed %r LBA:%lu Count:%u", Status, MapLba, secRead);
return Status;
}
@@ -475,7 +516,7 @@ EFI_STATUS EFIAPI ventoy_connect_driver(IN EFI_HANDLE ControllerHandle, IN CONST
if (i < Count)
{
Status = gBS->ConnectController(ControllerHandle, DrvHandles, NULL, TRUE);
debug("Connect partition driver:<%r>", Status);
debug("ventoy_connect_driver:<%s> <%r>", DrvName, Status);
goto end;
}
@@ -517,7 +558,7 @@ EFI_STATUS EFIAPI ventoy_connect_driver(IN EFI_HANDLE ControllerHandle, IN CONST
if (i < Count)
{
Status = gBS->ConnectController(ControllerHandle, DrvHandles, NULL, TRUE);
debug("Connect partition driver:<%r>", Status);
debug("ventoy_connect_driver:<%s> <%r>", DrvName, Status);
goto end;
}
@@ -535,6 +576,9 @@ EFI_STATUS EFIAPI ventoy_install_blockio(IN EFI_HANDLE ImageHandle, IN UINT64 Im
EFI_BLOCK_IO_PROTOCOL *pBlockIo = &(gBlockData.BlockIo);
ventoy_fill_device_path();
debug("install block io protocol %p", ImageHandle);
ventoy_debug_pause();
gBlockData.Media.BlockSize = 2048;
gBlockData.Media.LastBlock = ImgSize / 2048 - 1;
@@ -561,7 +605,6 @@ EFI_STATUS EFIAPI ventoy_install_blockio(IN EFI_HANDLE ImageHandle, IN UINT64 Im
Status = ventoy_connect_driver(gBlockData.Handle, L"Disk I/O Driver");
debug("Connect disk IO driver %r", Status);
ventoy_debug_pause();
Status = ventoy_connect_driver(gBlockData.Handle, L"Partition Driver");
debug("Connect partition driver %r", Status);
@@ -916,3 +959,55 @@ EFI_STATUS ventoy_hook_keyboard_stop(VOID)
return EFI_SUCCESS;
}
#if 0
/* Fixup the 1st cdrom influnce for Windows boot */
#endif
STATIC EFI_STATUS EFIAPI ventoy_wrapper_locate_handle
(
IN EFI_LOCATE_SEARCH_TYPE SearchType,
IN EFI_GUID *Protocol, OPTIONAL
IN VOID *SearchKey, OPTIONAL
IN OUT UINTN *BufferSize,
OUT EFI_HANDLE *Buffer
)
{
UINTN i;
EFI_HANDLE Handle = NULL;
EFI_STATUS Status = EFI_SUCCESS;
Status = g_org_locate_handle(SearchType, Protocol, SearchKey, BufferSize, Buffer);
if (EFI_SUCCESS == Status && Protocol && CompareGuid(&gEfiBlockIoProtocolGuid, Protocol))
{
for (i = 0; i < (*BufferSize) / sizeof(EFI_HANDLE); i++)
{
if (Buffer[i] == gBlockData.Handle)
{
Handle = Buffer[0];
Buffer[0] = Buffer[i];
Buffer[i] = Handle;
break;
}
}
}
return Status;
}
EFI_STATUS ventoy_hook_1st_cdrom_start(VOID)
{
g_org_locate_handle = gBS->LocateHandle;
gBS->LocateHandle = ventoy_wrapper_locate_handle;
return EFI_SUCCESS;
}
EFI_STATUS ventoy_hook_1st_cdrom_stop(VOID)
{
gBS->LocateHandle = g_org_locate_handle;
g_org_locate_handle = NULL;
return EFI_SUCCESS;
}

View File

@@ -0,0 +1,179 @@
/******************************************************************************
* Memhole.c
*
* Copyright (c) 2020, longpanda <admin@ventoy.net>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
#include <Uefi.h>
#include <Library/DebugLib.h>
#include <Library/PrintLib.h>
#include <Library/UefiLib.h>
#include <Library/BaseMemoryLib.h>
#include <Library/DevicePathLib.h>
#include <Library/MemoryAllocationLib.h>
#include <Library/UefiBootServicesTableLib.h>
#include <Library/UefiRuntimeServicesTableLib.h>
#include <Library/UefiApplicationEntryPoint.h>
#include <Protocol/LoadedImage.h>
#include <Guid/FileInfo.h>
#include <Guid/FileSystemInfo.h>
#include <Protocol/BlockIo.h>
#include <Protocol/RamDisk.h>
#include <Protocol/SimpleFileSystem.h>
#include <VtoyUtil.h>
STATIC BOOLEAN IsMemContiguous
(
IN CONST EFI_MEMORY_DESCRIPTOR *Prev,
IN CONST EFI_MEMORY_DESCRIPTOR *Curr,
IN CONST EFI_MEMORY_DESCRIPTOR *Next
)
{
UINTN Addr1 = 0;
UINTN Addr2 = 0;
if (Prev == NULL || Curr == NULL || Next == NULL)
{
return FALSE;
}
if (Prev->Type == EfiBootServicesData &&
Curr->Type == EfiConventionalMemory &&
Next->Type == EfiBootServicesData)
{
Addr1 = Prev->PhysicalStart + MultU64x64(SIZE_4KB, Prev->NumberOfPages);
Addr2 = Curr->PhysicalStart + MultU64x64(SIZE_4KB, Curr->NumberOfPages);
if (Addr1 == Curr->PhysicalStart && Addr2 == Next->PhysicalStart)
{
return TRUE;
}
}
return FALSE;
}
STATIC EFI_MEMORY_DESCRIPTOR* GetMemDesc
(
OUT UINTN *pSize,
OUT UINTN *pItemSize,
OUT UINTN *pDescCount
)
{
UINTN Size = 0;
UINTN MapKey = 0;
UINTN ItemSize = 0;
UINTN DescCount = 0;
UINT32 Version = 0;
EFI_STATUS Status = EFI_SUCCESS;
EFI_MEMORY_DESCRIPTOR *pDesc = NULL;
EFI_MEMORY_DESCRIPTOR *Curr = NULL;
Status = gBS->GetMemoryMap(&Size, pDesc, &MapKey, &ItemSize, &Version);
if (EFI_BUFFER_TOO_SMALL != Status)
{
debug("GetMemoryMap: %r", Status);
return NULL;
}
Size += SIZE_1KB;
pDesc = AllocatePool(Size);
if (!pDesc)
{
debug("AllocatePool: %lu failed", Size);
return NULL;
}
ZeroMem(pDesc, Size);
Status = gBS->GetMemoryMap(&Size, pDesc, &MapKey, &ItemSize, &Version);
if (EFI_ERROR(Status))
{
debug("GetMemoryMap: %r", Status);
FreePool(pDesc);
return NULL;
}
Curr = pDesc;
while (Curr && Curr < (EFI_MEMORY_DESCRIPTOR *)((UINT8 *)pDesc + Size))
{
DescCount++;
Curr = (EFI_MEMORY_DESCRIPTOR *)((UINT8 *)Curr + ItemSize);
}
*pSize = Size;
*pItemSize = ItemSize;
*pDescCount = DescCount;
debug("GetMemoryMap: ItemSize:%lu Count:%lu", ItemSize, DescCount);
return pDesc;
}
EFI_STATUS FixWindowsMemhole(IN EFI_HANDLE ImageHandle, IN CONST CHAR16 *CmdLine)
{
UINTN Size = 0;
UINTN ItemSize = 0;
UINTN DescCount = 0;
UINTN TotalMem = 0;
EFI_STATUS Status = EFI_SUCCESS;
EFI_PHYSICAL_ADDRESS AllocAddr = 0;
EFI_MEMORY_DESCRIPTOR *pDescs = NULL;
EFI_MEMORY_DESCRIPTOR *Prev = NULL;
EFI_MEMORY_DESCRIPTOR *Next = NULL;
EFI_MEMORY_DESCRIPTOR *Curr = NULL;
(VOID)ImageHandle;
(VOID)CmdLine;
pDescs = GetMemDesc(&Size, &ItemSize, &DescCount);
if (!pDescs)
{
return EFI_NOT_FOUND;
}
if (DescCount < 500)
{
FreePool(pDescs);
Printf("There is no need to fixup (%lu)\n", DescCount);
return EFI_SUCCESS;
}
Curr = pDescs;
while ((UINT8 *)Curr < (UINT8 *)pDescs + Size)
{
Next = (EFI_MEMORY_DESCRIPTOR *)((UINT8 *)Curr + ItemSize);
if (IsMemContiguous(Prev, Curr, Next))
{
AllocAddr = Curr->PhysicalStart;
Status = gBS->AllocatePages(AllocateAddress, EfiBootServicesData, Curr->NumberOfPages, &AllocAddr);
if (EFI_SUCCESS == Status)
{
TotalMem += MultU64x64(SIZE_4KB, Curr->NumberOfPages);
}
}
Prev = Curr;
Curr = Next;
}
Printf("Fixup Windows mmap issue OK (%lu)\n", TotalMem);
return EFI_SUCCESS;
}

View File

@@ -0,0 +1,135 @@
/******************************************************************************
* VtoyUtil.c
*
* Copyright (c) 2020, longpanda <admin@ventoy.net>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
#include <Uefi.h>
#include <Library/DebugLib.h>
#include <Library/PrintLib.h>
#include <Library/UefiLib.h>
#include <Library/BaseMemoryLib.h>
#include <Library/DevicePathLib.h>
#include <Library/MemoryAllocationLib.h>
#include <Library/UefiBootServicesTableLib.h>
#include <Library/UefiRuntimeServicesTableLib.h>
#include <Library/UefiApplicationEntryPoint.h>
#include <Protocol/LoadedImage.h>
#include <Guid/FileInfo.h>
#include <Guid/FileSystemInfo.h>
#include <Protocol/BlockIo.h>
#include <Protocol/RamDisk.h>
#include <Protocol/SimpleFileSystem.h>
#include <VtoyUtil.h>
BOOLEAN gVtoyDebugPrint = FALSE;
STATIC CONST CHAR16 *gCurFeature= NULL;
STATIC CHAR16 *gCmdLine = NULL;
STATIC grub_env_printf_pf g_env_printf = NULL;
STATIC VtoyUtilFeature gFeatureList[] =
{
{ L"fix_windows_mmap", FixWindowsMemhole },
};
VOID EFIAPI VtoyUtilDebug(IN CONST CHAR8 *Format, ...)
{
VA_LIST Marker;
CHAR8 Buffer[512];
VA_START (Marker, Format);
AsciiVSPrint(Buffer, sizeof(Buffer), Format, Marker);
VA_END (Marker);
if (g_env_printf)
{
g_env_printf("%s", Buffer);
}
}
STATIC EFI_STATUS ParseCmdline(IN EFI_HANDLE ImageHandle)
{
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))
{
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"))
{
gVtoyDebugPrint = TRUE;
}
pPos = StrStr(pCmdLine, L"env_param=");
if (!pPos)
{
return EFI_INVALID_PARAMETER;
}
pGrubParam = (ventoy_grub_param *)StrHexToUintn(pPos + StrLen(L"env_param="));
g_env_printf = pGrubParam->grub_env_printf;
pPos = StrStr(pCmdLine, L"feature=");
if (!pPos)
{
return EFI_INVALID_PARAMETER;
}
gCurFeature = pPos + StrLen(L"feature=");
gCmdLine = pCmdLine;
return EFI_SUCCESS;
}
EFI_STATUS EFIAPI VtoyUtilEfiMain
(
IN EFI_HANDLE ImageHandle,
IN EFI_SYSTEM_TABLE *SystemTable
)
{
UINTN i;
UINTN Len;
ParseCmdline(ImageHandle);
for (i = 0; i < ARRAY_SIZE(gFeatureList); i++)
{
Len = StrLen(gFeatureList[i].Cmd);
if (StrnCmp(gFeatureList[i].Cmd, gCurFeature, Len) == 0)
{
debug("Find main proc <%s>", gFeatureList[i].Cmd);
gFeatureList[i].MainProc(ImageHandle, gCurFeature + Len);
break;
}
}
FreePool(gCmdLine);
gCmdLine = NULL;
return EFI_SUCCESS;
}

View File

@@ -0,0 +1,61 @@
/******************************************************************************
* VtoyUtil.h
*
* Copyright (c) 2020, longpanda <admin@ventoy.net>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
#ifndef __VTOYUTIL_H__
#define __VTOYUTIL_H__
#pragma pack(1)
typedef EFI_STATUS (*VTOY_UTIL_PROC_PF)(IN EFI_HANDLE ImageHandle, IN CONST CHAR16 *CmdLine);
typedef const char * (*grub_env_get_pf)(const char *name);
typedef int (*grub_env_printf_pf)(const char *fmt, ...);
typedef struct ventoy_grub_param_file_replace
{
UINT32 magic;
char old_file_name[4][256];
UINT32 old_file_cnt;
UINT32 new_file_virtual_id;
}ventoy_grub_param_file_replace;
typedef struct ventoy_grub_param
{
grub_env_get_pf grub_env_get;
ventoy_grub_param_file_replace file_replace;
grub_env_printf_pf grub_env_printf;
}ventoy_grub_param;
#pragma pack()
typedef struct VtoyUtilFeature
{
CONST CHAR16 *Cmd;
VTOY_UTIL_PROC_PF MainProc;
}VtoyUtilFeature;
extern BOOLEAN gVtoyDebugPrint;
VOID EFIAPI VtoyUtilDebug(IN CONST CHAR8 *Format, ...);
#define debug(expr, ...) if (gVtoyDebugPrint) VtoyUtilDebug("[VTOY] "expr"\n", ##__VA_ARGS__)
#define Printf VtoyUtilDebug
EFI_STATUS FixWindowsMemhole(IN EFI_HANDLE ImageHandle, IN CONST CHAR16 *CmdLine);
#endif

View File

@@ -0,0 +1,80 @@
#************************************************************************************
# Copyright (c) 2020, longpanda <admin@ventoy.net>
#
# 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 <http://www.gnu.org/licenses/>.
#
#************************************************************************************
[Defines]
INF_VERSION = 0x00010005
BASE_NAME = VtoyUtil
FILE_GUID = a43466a0-68c6-469d-ba4b-678bbe90bc47
MODULE_TYPE = UEFI_APPLICATION
VERSION_STRING = 1.0
ENTRY_POINT = VtoyUtilEfiMain
[Sources]
VtoyUtil.h
VtoyUtil.c
Memhole.c
[Packages]
MdePkg/MdePkg.dec
MdeModulePkg/MdeModulePkg.dec
ShellPkg/ShellPkg.dec
[LibraryClasses]
UefiApplicationEntryPoint
UefiLib
DebugLib
[Guids]
gShellVariableGuid
gEfiVirtualCdGuid
gEfiFileInfoGuid
[Protocols]
gEfiLoadedImageProtocolGuid
gEfiBlockIoProtocolGuid
gEfiDevicePathProtocolGuid
gEfiSimpleFileSystemProtocolGuid
gEfiRamDiskProtocolGuid
gEfiAbsolutePointerProtocolGuid
gEfiAcpiTableProtocolGuid
gEfiBlockIo2ProtocolGuid
gEfiBusSpecificDriverOverrideProtocolGuid
gEfiComponentNameProtocolGuid
gEfiComponentName2ProtocolGuid
gEfiDriverBindingProtocolGuid
gEfiDiskIoProtocolGuid
gEfiDiskIo2ProtocolGuid
gEfiGraphicsOutputProtocolGuid
gEfiHiiConfigAccessProtocolGuid
gEfiHiiFontProtocolGuid
gEfiLoadFileProtocolGuid
gEfiLoadFile2ProtocolGuid
gEfiLoadedImageProtocolGuid
gEfiLoadedImageDevicePathProtocolGuid
gEfiPciIoProtocolGuid
gEfiSerialIoProtocolGuid
gEfiSimpleTextInProtocolGuid
gEfiSimpleTextInputExProtocolGuid
gEfiSimpleTextOutProtocolGuid

View File

@@ -204,6 +204,7 @@
[Components]
MdeModulePkg/Application/Ventoy/Ventoy.inf
MdeModulePkg/Application/VtoyUtil/VtoyUtil.inf
MdeModulePkg/Application/HelloWorld/HelloWorld.inf
MdeModulePkg/Application/DumpDynPcd/DumpDynPcd.inf
MdeModulePkg/Application/MemoryProfileInfo/MemoryProfileInfo.inf

View File

@@ -891,8 +891,8 @@ static int ventoy_colect_img_files(const char *filename, const struct grub_dirho
*((img_info **)(node->tail)) = img;
g_ventoy_img_count++;
img->alias = ventoy_plugin_get_menu_alias(img->path);
img->class = ventoy_plugin_get_menu_class(img->name);
img->alias = ventoy_plugin_get_menu_alias(vtoy_alias_image_file, img->path);
img->class = ventoy_plugin_get_menu_class(vtoy_class_image_file, img->name);
if (!img->class)
{
img->class = g_menu_class[type];
@@ -1029,7 +1029,9 @@ static img_iterator_node * ventoy_get_min_child(img_iterator_node *node)
static int ventoy_dynamic_tree_menu(img_iterator_node *node)
{
int offset = 1;
img_info *img;
img_info *img = NULL;
const char *dir_class = NULL;
const char *dir_alias = NULL;
img_iterator_node *child = NULL;
if (node->isocnt == 0 || node->done == 1)
@@ -1055,9 +1057,25 @@ static int ventoy_dynamic_tree_menu(img_iterator_node *node)
else
{
node->dir[node->dirlen - 1] = 0;
vtoy_ssprintf(g_tree_script_buf, g_tree_script_pos,
"submenu \"%-10s [%s]\" --class=\"vtoydir\" {\n",
"DIR", node->dir + offset);
dir_class = ventoy_plugin_get_menu_class(vtoy_class_directory, node->dir);
if (!dir_class)
{
dir_class = "vtoydir";
}
dir_alias = ventoy_plugin_get_menu_alias(vtoy_alias_directory, node->dir);
if (dir_alias)
{
vtoy_ssprintf(g_tree_script_buf, g_tree_script_pos,
"submenu \"%-10s %s\" --class=\"%s\" {\n",
"DIR", dir_alias, dir_class);
}
else
{
vtoy_ssprintf(g_tree_script_buf, g_tree_script_pos,
"submenu \"%-10s [%s]\" --class=\"%s\" {\n",
"DIR", node->dir + offset, dir_class);
}
vtoy_ssprintf(g_tree_script_buf, g_tree_script_pos,
"menuentry \"%-10s [../]\" --class=\"vtoyret\" VTOY_RET {\n "
@@ -1662,7 +1680,7 @@ static grub_err_t ventoy_cmd_sel_auto_install(grub_extcmd_context_t ctxt, int ar
(void)argc;
(void)args;
debug("select auto installation %d\n", argc);
debug("select auto installation argc:%d\n", argc);
if (argc < 1)
{
@@ -1672,7 +1690,14 @@ static grub_err_t ventoy_cmd_sel_auto_install(grub_extcmd_context_t ctxt, int ar
node = ventoy_plugin_find_install_template(args[0]);
if (!node)
{
debug("Install template not found for %s\n", args[0]);
debug("Auto install template not found for %s\n", args[0]);
return 0;
}
if (node->autosel >= 0 && node->autosel <= node->templatenum)
{
node->cursel = node->autosel - 1;
debug("Auto install template auto select %d\n", node->autosel);
return 0;
}
@@ -1720,7 +1745,7 @@ static grub_err_t ventoy_cmd_sel_persistence(grub_extcmd_context_t ctxt, int arg
(void)argc;
(void)args;
debug("select persistece %d\n", argc);
debug("select persistence argc:%d\n", argc);
if (argc < 1)
{
@@ -1734,6 +1759,13 @@ static grub_err_t ventoy_cmd_sel_persistence(grub_extcmd_context_t ctxt, int arg
return 0;
}
if (node->autosel >= 0 && node->autosel <= node->backendnum)
{
node->cursel = node->autosel - 1;
debug("Persistence image auto select %d\n", node->autosel);
return 0;
}
buf = (char *)grub_malloc(VTOY_MAX_SCRIPT_BUF);
if (!buf)
{
@@ -1979,27 +2011,6 @@ static grub_err_t ventoy_cmd_dump_auto_install(grub_extcmd_context_t ctxt, int a
(void)argc;
(void)args;
{
grub_file_t file;
char *buf;
char name[128];
file = grub_file_open("(hd0,1)/ventoy/ventoy.disk.img.xz", GRUB_FILE_TYPE_NONE);
if (file)
{
grub_printf("Open File OK (size:%llu)\n", (ulonglong)file->size);
buf = grub_malloc(file->size);
grub_file_read(file, buf, file->size);
grub_file_close(file);
grub_snprintf(name, sizeof(name), "mem:0x%llx:size:%llu", (ulonglong)(ulong)buf, (ulonglong)file->size);
grub_printf("<%s>\n", name);
}
}
ventoy_plugin_dump_auto_install();
return 0;
@@ -2267,6 +2278,32 @@ int ventoy_is_file_exist(const char *fmt, ...)
return 0;
}
int ventoy_is_dir_exist(const char *fmt, ...)
{
va_list ap;
int len;
char *pos = NULL;
char buf[256] = {0};
grub_snprintf(buf, sizeof(buf), "%s", "[ -d ");
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];
@@ -2285,6 +2322,7 @@ static int ventoy_env_init(void)
if (g_grub_param)
{
g_grub_param->grub_env_get = grub_env_get;
g_grub_param->grub_env_printf = (grub_env_printf_pf)grub_printf;
grub_snprintf(buf, sizeof(buf), "%p", g_grub_param);
grub_env_set("env_param", buf);
}

View File

@@ -225,6 +225,7 @@ void ventoy_debug(const char *fmt, ...);
#define FLAG_HEADER_COMPRESS_RESERVED 0x00010000
#define FLAG_HEADER_COMPRESS_XPRESS 0x00020000
#define FLAG_HEADER_COMPRESS_LZX 0x00040000
#define FLAG_HEADER_COMPRESS_LZMS 0x00080000
#define RESHDR_FLAG_FREE 0x01
#define RESHDR_FLAG_METADATA 0x02
@@ -460,6 +461,7 @@ int ventoy_cpio_newc_fill_head(void *buf, int filesize, const void *filedata, co
grub_file_t ventoy_grub_file_open(enum grub_file_type type, const char *fmt, ...);
grub_uint64_t ventoy_grub_get_file_size(const char *fmt, ...);
int ventoy_is_file_exist(const char *fmt, ...);
int ventoy_is_dir_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);
@@ -600,6 +602,7 @@ typedef struct install_template
int pathlen;
char isopath[256];
int autosel;
int cursel;
int templatenum;
file_fullpath *templatepath;
@@ -612,6 +615,7 @@ typedef struct persistence_config
int pathlen;
char isopath[256];
int autosel;
int cursel;
int backendnum;
file_fullpath *backendpath;
@@ -619,8 +623,12 @@ typedef struct persistence_config
struct persistence_config *next;
}persistence_config;
#define vtoy_alias_image_file 0
#define vtoy_alias_directory 1
typedef struct menu_alias
{
int type;
int pathlen;
char isopath[256];
char alias[256];
@@ -628,8 +636,12 @@ typedef struct menu_alias
struct menu_alias *next;
}menu_alias;
#define vtoy_class_image_file 0
#define vtoy_class_directory 1
typedef struct menu_class
{
int type;
int patlen;
char pattern[256];
char class[64];
@@ -654,8 +666,8 @@ persistence_config * ventoy_plugin_find_persistent(const char *isopath);
void ventoy_plugin_dump_auto_install(void);
int ventoy_fill_windows_rtdata(void *buf, char *isopath);
int ventoy_plugin_get_persistent_chunklist(const char *isopath, int index, ventoy_img_chunk_list *chunk_list);
const char * ventoy_plugin_get_menu_alias(const char *isopath);
const char * ventoy_plugin_get_menu_class(const char *isoname);
const char * ventoy_plugin_get_menu_alias(int type, const char *isopath);
const char * ventoy_plugin_get_menu_class(int type, const char *name);
int ventoy_get_block_list(grub_file_t file, ventoy_img_chunk_list *chunklist, grub_disk_addr_t start);
int ventoy_check_block_list(grub_file_t file, ventoy_img_chunk_list *chunklist, grub_disk_addr_t start);
void ventoy_plugin_dump_persistence(void);

View File

@@ -1144,7 +1144,7 @@ grub_err_t ventoy_cmd_linux_chain_data(grub_extcmd_context_t ctxt, int argc, cha
grub_memset(chain, 0, sizeof(ventoy_chain_head));
/* part 1: os parameter */
g_ventoy_chain_type = 0;
g_ventoy_chain_type = ventoy_chain_linux;
ventoy_fill_os_param(file, &(chain->os_param));
/* part 2: chain head */

View File

@@ -310,11 +310,13 @@ static int ventoy_plugin_check_fullpath
(
VTOY_JSON *json,
const char *isodisk,
const char *key
const char *key,
int *pathnum
)
{
int rc = 0;
int ret = 0;
int cnt = 0;
VTOY_JSON *node = json;
VTOY_JSON *child = NULL;
@@ -334,6 +336,7 @@ static int ventoy_plugin_check_fullpath
if (JSON_TYPE_STRING == node->enDataType)
{
cnt = 1;
ret = ventoy_plugin_check_path(isodisk, node->unData.pcStrVal);
grub_printf("%s: %s [%s]\n", key, node->unData.pcStrVal, ret ? "FAIL" : "OK");
}
@@ -350,10 +353,12 @@ static int ventoy_plugin_check_fullpath
rc = ventoy_plugin_check_path(isodisk, child->unData.pcStrVal);
grub_printf("%s: %s [%s]\n", key, child->unData.pcStrVal, rc ? "FAIL" : "OK");
ret += rc;
cnt++;
}
}
}
*pathnum = cnt;
return ret;
}
@@ -443,6 +448,8 @@ static int ventoy_plugin_parse_fullpath
static int ventoy_plugin_auto_install_check(VTOY_JSON *json, const char *isodisk)
{
int pathnum = 0;
int autosel = 0;
const char *iso = NULL;
VTOY_JSON *pNode = NULL;
@@ -465,7 +472,19 @@ static int ventoy_plugin_auto_install_check(VTOY_JSON *json, const char *isodisk
if (0 == ventoy_plugin_check_path(isodisk, iso))
{
grub_printf("image: %s [OK]\n", iso);
ventoy_plugin_check_fullpath(pNode->pstChild, isodisk, "template");
ventoy_plugin_check_fullpath(pNode->pstChild, isodisk, "template", &pathnum);
if (JSON_SUCCESS == vtoy_json_get_int(pNode->pstChild, "autosel", &autosel))
{
if (autosel >= 0 && autosel <= pathnum)
{
grub_printf("autosel: %d [OK]\n", autosel);
}
else
{
grub_printf("autosel: %d [FAIL]\n", autosel);
}
}
}
else
{
@@ -484,6 +503,7 @@ static int ventoy_plugin_auto_install_check(VTOY_JSON *json, const char *isodisk
static int ventoy_plugin_auto_install_entry(VTOY_JSON *json, const char *isodisk)
{
int pathnum = 0;
int autosel = 0;
const char *iso = NULL;
VTOY_JSON *pNode = NULL;
install_template *node = NULL;
@@ -522,6 +542,15 @@ static int ventoy_plugin_auto_install_entry(VTOY_JSON *json, const char *isodisk
node->templatepath = templatepath;
node->templatenum = pathnum;
node->autosel = -1;
if (JSON_SUCCESS == vtoy_json_get_int(pNode->pstChild, "autosel", &autosel))
{
if (autosel >= 0 && autosel <= pathnum)
{
node->autosel = autosel;
}
}
if (g_install_template_head)
{
node->next = g_install_template_head;
@@ -538,6 +567,8 @@ static int ventoy_plugin_auto_install_entry(VTOY_JSON *json, const char *isodisk
static int ventoy_plugin_persistence_check(VTOY_JSON *json, const char *isodisk)
{
int autosel = 0;
int pathnum = 0;
const char *iso = NULL;
VTOY_JSON *pNode = NULL;
@@ -560,7 +591,19 @@ static int ventoy_plugin_persistence_check(VTOY_JSON *json, const char *isodisk)
if (0 == ventoy_plugin_check_path(isodisk, iso))
{
grub_printf("image: %s [OK]\n", iso);
ventoy_plugin_check_fullpath(pNode->pstChild, isodisk, "backend");
ventoy_plugin_check_fullpath(pNode->pstChild, isodisk, "backend", &pathnum);
if (JSON_SUCCESS == vtoy_json_get_int(pNode->pstChild, "autosel", &autosel))
{
if (autosel >= 0 && autosel <= pathnum)
{
grub_printf("autosel: %d [OK]\n", autosel);
}
else
{
grub_printf("autosel: %d [FAIL]\n", autosel);
}
}
}
else
{
@@ -578,6 +621,7 @@ static int ventoy_plugin_persistence_check(VTOY_JSON *json, const char *isodisk)
static int ventoy_plugin_persistence_entry(VTOY_JSON *json, const char *isodisk)
{
int autosel = 0;
int pathnum = 0;
const char *iso = NULL;
VTOY_JSON *pNode = NULL;
@@ -619,6 +663,15 @@ static int ventoy_plugin_persistence_entry(VTOY_JSON *json, const char *isodisk)
node->backendpath = backendpath;
node->backendnum = pathnum;
node->autosel = -1;
if (JSON_SUCCESS == vtoy_json_get_int(pNode->pstChild, "autosel", &autosel))
{
if (autosel >= 0 && autosel <= pathnum)
{
node->autosel = autosel;
}
}
if (g_persistence_head)
{
node->next = g_persistence_head;
@@ -635,7 +688,8 @@ static int ventoy_plugin_persistence_entry(VTOY_JSON *json, const char *isodisk)
static int ventoy_plugin_menualias_check(VTOY_JSON *json, const char *isodisk)
{
const char *iso = NULL;
int type;
const char *path = NULL;
const char *alias = NULL;
VTOY_JSON *pNode = NULL;
@@ -649,17 +703,38 @@ static int ventoy_plugin_menualias_check(VTOY_JSON *json, const char *isodisk)
for (pNode = json->pstChild; pNode; pNode = pNode->pstNext)
{
iso = vtoy_json_get_string_ex(pNode->pstChild, "image");
alias = vtoy_json_get_string_ex(pNode->pstChild, "alias");
if (iso && iso[0] == '/' && alias)
type = vtoy_alias_image_file;
path = vtoy_json_get_string_ex(pNode->pstChild, "image");
if (!path)
{
if (ventoy_is_file_exist("%s%s", isodisk, iso))
{
grub_printf("image: <%s> [ OK ]\n", iso);
path = vtoy_json_get_string_ex(pNode->pstChild, "dir");
type = vtoy_alias_directory;
}
alias = vtoy_json_get_string_ex(pNode->pstChild, "alias");
if (path && path[0] == '/' && alias)
{
if (vtoy_alias_image_file == type)
{
if (ventoy_is_file_exist("%s%s", isodisk, path))
{
grub_printf("image: <%s> [ OK ]\n", path);
}
else
{
grub_printf("image: <%s> [ NOT EXIST ]\n", path);
}
}
else
{
grub_printf("image: <%s> [ NOT EXIST ]\n", iso);
if (ventoy_is_dir_exist("%s%s", isodisk, path))
{
grub_printf("dir: <%s> [ OK ]\n", path);
}
else
{
grub_printf("dir: <%s> [ NOT EXIST ]\n", path);
}
}
grub_printf("alias: <%s>\n\n", alias);
@@ -671,7 +746,8 @@ static int ventoy_plugin_menualias_check(VTOY_JSON *json, const char *isodisk)
static int ventoy_plugin_menualias_entry(VTOY_JSON *json, const char *isodisk)
{
const char *iso = NULL;
int type;
const char *path = NULL;
const char *alias = NULL;
VTOY_JSON *pNode = NULL;
menu_alias *node = NULL;
@@ -698,14 +774,22 @@ static int ventoy_plugin_menualias_entry(VTOY_JSON *json, const char *isodisk)
for (pNode = json->pstChild; pNode; pNode = pNode->pstNext)
{
iso = vtoy_json_get_string_ex(pNode->pstChild, "image");
type = vtoy_alias_image_file;
path = vtoy_json_get_string_ex(pNode->pstChild, "image");
if (!path)
{
path = vtoy_json_get_string_ex(pNode->pstChild, "dir");
type = vtoy_alias_directory;
}
alias = vtoy_json_get_string_ex(pNode->pstChild, "alias");
if (iso && iso[0] == '/' && alias)
if (path && path[0] == '/' && alias)
{
node = grub_zalloc(sizeof(menu_alias));
if (node)
{
node->pathlen = grub_snprintf(node->isopath, sizeof(node->isopath), "%s", iso);
node->type = type;
node->pathlen = grub_snprintf(node->isopath, sizeof(node->isopath), "%s", path);
grub_snprintf(node->alias, sizeof(node->alias), "%s", alias);
if (g_menu_alias_head)
@@ -723,6 +807,7 @@ static int ventoy_plugin_menualias_entry(VTOY_JSON *json, const char *isodisk)
static int ventoy_plugin_menuclass_entry(VTOY_JSON *json, const char *isodisk)
{
int type;
const char *key = NULL;
const char *class = NULL;
VTOY_JSON *pNode = NULL;
@@ -751,13 +836,21 @@ static int ventoy_plugin_menuclass_entry(VTOY_JSON *json, const char *isodisk)
for (pNode = json->pstChild; pNode; pNode = pNode->pstNext)
{
type = vtoy_class_image_file;
key = vtoy_json_get_string_ex(pNode->pstChild, "key");
if (!key)
{
key = vtoy_json_get_string_ex(pNode->pstChild, "dir");
type = vtoy_class_directory;
}
class = vtoy_json_get_string_ex(pNode->pstChild, "class");
if (key && class)
{
node = grub_zalloc(sizeof(menu_class));
if (node)
{
node->type = type;
node->patlen = grub_snprintf(node->pattern, sizeof(node->pattern), "%s", key);
grub_snprintf(node->class, sizeof(node->class), "%s", class);
@@ -779,6 +872,7 @@ static int ventoy_plugin_menuclass_entry(VTOY_JSON *json, const char *isodisk)
static int ventoy_plugin_menuclass_check(VTOY_JSON *json, const char *isodisk)
{
int type;
const char *key = NULL;
const char *class = NULL;
VTOY_JSON *pNode = NULL;
@@ -793,11 +887,18 @@ static int ventoy_plugin_menuclass_check(VTOY_JSON *json, const char *isodisk)
for (pNode = json->pstChild; pNode; pNode = pNode->pstNext)
{
type = vtoy_class_image_file;
key = vtoy_json_get_string_ex(pNode->pstChild, "key");
if (!key)
{
key = vtoy_json_get_string_ex(pNode->pstChild, "dir");
type = vtoy_class_directory;
}
class = vtoy_json_get_string_ex(pNode->pstChild, "class");
if (key && class)
{
grub_printf("key: <%s>\n", key);
grub_printf("%s: <%s>\n", (type == vtoy_class_directory) ? "dir" : "key", key);
grub_printf("class: <%s>\n\n", class);
}
}
@@ -901,7 +1002,7 @@ void ventoy_plugin_dump_auto_install(void)
for (node = g_install_template_head; node; node = node->next)
{
grub_printf("\nIMAGE:<%s>\n", node->isopath);
grub_printf("\nIMAGE:<%s> <%d>\n", node->isopath, node->templatenum);
for (i = 0; i < node->templatenum; i++)
{
grub_printf("SCRIPT %d:<%s>\n", i, node->templatepath[i].path);
@@ -920,7 +1021,7 @@ void ventoy_plugin_dump_persistence(void)
for (node = g_persistence_head; node; node = node->next)
{
grub_printf("\nIMAGE:<%s>\n", node->isopath);
grub_printf("\nIMAGE:<%s> <%d>\n", node->isopath, node->backendnum);
for (i = 0; i < node->backendnum; i++)
{
@@ -1050,14 +1151,15 @@ end:
return rc;
}
const char * ventoy_plugin_get_menu_alias(const char *isopath)
const char * ventoy_plugin_get_menu_alias(int type, const char *isopath)
{
menu_alias *node = NULL;
int len = (int)grub_strlen(isopath);
for (node = g_menu_alias_head; node; node = node->next)
{
if (node->pathlen == len && grub_strcmp(node->isopath, isopath) == 0)
if (node->type == type && node->pathlen &&
node->pathlen == len && grub_strcmp(node->isopath, isopath) == 0)
{
return node->alias;
}
@@ -1066,23 +1168,35 @@ const char * ventoy_plugin_get_menu_alias(const char *isopath)
return NULL;
}
const char * ventoy_plugin_get_menu_class(const char *isoname)
const char * ventoy_plugin_get_menu_class(int type, const char *name)
{
menu_class *node = NULL;
int len = (int)grub_strlen(isoname);
for (node = g_menu_class_head; node; node = node->next)
int len = (int)grub_strlen(name);
if (vtoy_class_image_file == type)
{
if (node->patlen <= len && grub_strstr(isoname, node->pattern))
for (node = g_menu_class_head; node; node = node->next)
{
return node->class;
if (node->type == type && node->patlen <= len && grub_strstr(name, node->pattern))
{
return node->class;
}
}
}
else
{
for (node = g_menu_class_head; node; node = node->next)
{
if (node->type == type && node->patlen == len && grub_strncmp(name, node->pattern, len) == 0)
{
return node->class;
}
}
}
return NULL;
}
grub_err_t ventoy_cmd_plugin_check_json(grub_extcmd_context_t ctxt, int argc, char **args)
{
int i = 0;

View File

@@ -332,7 +332,7 @@ grub_err_t ventoy_cmd_wimdows_reset(grub_extcmd_context_t ctxt, int argc, char *
g_wim_patch_head = NULL;
g_wim_total_patch_count = 0;
g_wim_valid_patch_count = 0;
return 0;
}
@@ -549,13 +549,9 @@ static wim_directory_entry * search_full_wim_dirent
{
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;
}
@@ -563,16 +559,18 @@ static wim_directory_entry * search_replace_wim_dirent(void *meta_data, wim_dire
{
wim_directory_entry *wim_dirent = NULL;
const char *winpeshl_path[] = { "Windows", "System32", "winpeshl.exe", NULL };
//const char *pecmd_path[] = { "Windows", "System32", "PECMD.exe", NULL };
//const char *native_path[] = { "Windows", "System32", "native.exe", NULL };
wim_dirent = search_full_wim_dirent(meta_data, dir, winpeshl_path);
debug("search winpeshl.exe %p\n", wim_dirent);
if (wim_dirent)
{
return wim_dirent;
}
#if 0
wim_dirent = search_full_wim_dirent(meta_data, dir, pecmd_path);
wim_dirent = search_full_wim_dirent(meta_data, dir, native_path);
debug("search native.exe %p\n", wim_dirent);
if (wim_dirent)
{
return wim_dirent;
@@ -813,9 +811,9 @@ static int ventoy_wimdows_locate_wim(const char *disk, wim_patch *patch)
return 1;
}
if (head->flags & FLAG_HEADER_COMPRESS_XPRESS)
if ((head->flags & FLAG_HEADER_COMPRESS_XPRESS) || (head->flags & FLAG_HEADER_COMPRESS_LZMS))
{
debug("Xpress compress is not supported 0x%x\n", head->flags);
debug("Xpress or LZMS compress is not supported 0x%x\n", head->flags);
grub_file_close(file);
return 1;
}
@@ -1385,7 +1383,7 @@ grub_err_t ventoy_cmd_windows_chain_data(grub_extcmd_context_t ctxt, int argc, c
grub_memset(chain, 0, sizeof(ventoy_chain_head));
/* part 1: os parameter */
g_ventoy_chain_type = 1;
g_ventoy_chain_type = ventoy_chain_windows;
ventoy_fill_os_param(file, &(chain->os_param));
if (0 == unknown_image)
@@ -1597,7 +1595,7 @@ grub_err_t ventoy_cmd_wim_chain_data(grub_extcmd_context_t ctxt, int argc, char
grub_memset(chain, 0, sizeof(ventoy_chain_head));
/* part 1: os parameter */
g_ventoy_chain_type = 0;
g_ventoy_chain_type = ventoy_chain_wim;
ventoy_fill_os_param(file, &(chain->os_param));
/* part 2: chain head */

View File

@@ -40,6 +40,15 @@ typedef enum ventoy_fs_type
ventoy_fs_max
}ventoy_fs_type;
typedef enum ventoy_chain_type
{
ventoy_chain_linux = 0, /* 0: linux */
ventoy_chain_windows, /* 1: windows */
ventoy_chain_wim, /* 2: wim */
ventoy_chain_max
}ventoy_chain_type;
#pragma pack(1)
typedef struct ventoy_guid
@@ -109,7 +118,7 @@ typedef struct ventoy_os_param
*
* vtoy_reserved[0]: vtoy_break_level
* vtoy_reserved[1]: vtoy_debug_level
* vtoy_reserved[2]: vtoy_chain_type 0:Linux 1:Windows
* vtoy_reserved[2]: vtoy_chain_type 0:Linux 1:Windows 2:wimfile
* vtoy_reserved[3]: vtoy_iso_format 0:iso9660 1:udf
* vtoy_reserved[4]: vtoy_windows_cd_prompt
*
@@ -204,12 +213,13 @@ typedef struct ventoy_img_chunk_list
#define ventoy_filt_register grub_file_filter_register
typedef const char * (*grub_env_get_pf)(const char *name);
#pragma pack(1)
#define GRUB_FILE_REPLACE_MAGIC 0x1258BEEF
typedef const char * (*grub_env_get_pf)(const char *name);
typedef int (*grub_env_printf_pf)(const char *fmt, ...);
typedef struct ventoy_grub_param_file_replace
{
grub_uint32_t magic;
@@ -221,8 +231,8 @@ typedef struct ventoy_grub_param_file_replace
typedef struct ventoy_grub_param
{
grub_env_get_pf grub_env_get;
ventoy_grub_param_file_replace file_replace;
grub_env_printf_pf grub_env_printf;
}ventoy_grub_param;
#pragma pack()

View File

@@ -12,7 +12,7 @@ make install
PATH=$PATH:$VT_DIR/GRUB2/INSTALL/bin/:$VT_DIR/GRUB2/INSTALL/sbin/
net_modules_legacy="net tftp http"
all_modules_legacy="date drivemap blocklist ntldr search at_keyboard usb_keyboard gcry_md5 hashsum gzio xzio lzopio lspci pci ext2 xfs ventoy chain read halt iso9660 linux16 test true sleep reboot echo videotest videoinfo videotest_checksum video_colors video_cirrus video_bochs vga vbe video_fb font video gettext extcmd terminal linux minicmd help configfile tr trig boot biosdisk disk ls tar squash4 password_pbkdf2 all_video png jpeg part_gpt part_msdos fat exfat ntfs loopback gzio normal udf gfxmenu gfxterm gfxterm_background gfxterm_menu"
all_modules_legacy="date drivemap blocklist vga_text ntldr search at_keyboard usb_keyboard gcry_md5 hashsum gzio xzio lzopio lspci pci ext2 xfs ventoy chain read halt iso9660 linux16 test true sleep reboot echo videotest videoinfo videotest_checksum video_colors video_cirrus video_bochs vga vbe video_fb font video gettext extcmd terminal linux minicmd help configfile tr trig boot biosdisk disk ls tar squash4 password_pbkdf2 all_video png jpeg part_gpt part_msdos fat exfat ntfs loopback gzio normal udf gfxmenu gfxterm gfxterm_background gfxterm_menu"
net_modules_uefi="efinet net tftp http"
all_modules_uefi="blocklist ventoy test search at_keyboard usb_keyboard gcry_md5 hashsum gzio xzio lzopio ext2 xfs read halt sleep serial terminfo png password_pbkdf2 gcry_sha512 pbkdf2 part_gpt part_msdos ls tar squash4 loopback part_apple minicmd diskfilter linux relocator jpeg iso9660 udf hfsplus halt acpi mmap gfxmenu video_colors trig bitmap_scale gfxterm bitmap font fat exfat ntfs fshelp efifwsetup reboot echo configfile normal terminal gettext chain priority_queue bufio datetime cat extcmd crypto gzio boot all_video efi_gop efi_uga video_bochs video_cirrus video video_fb gfxterm_background gfxterm_menu"
@@ -21,10 +21,10 @@ all_extra_modules="elf macho offsetio regexp file"
if [ "$1" = "uefi" ]; then
all_modules="$net_modules_uefi $all_modules_uefi $all_extra_modules"
grub-mkimage -v --directory "$VT_DIR/GRUB2/INSTALL/lib/grub/x86_64-efi" --prefix '(,msdos2)/grub' --output "$VT_DIR/INSTALL/EFI/BOOT/grubx64_real.efi" --format 'x86_64-efi' --compression 'auto' $all_modules_uefi 'fat' 'part_msdos'
grub-mkimage -v --directory "$VT_DIR/GRUB2/INSTALL/lib/grub/x86_64-efi" --prefix '(,2)/grub' --output "$VT_DIR/INSTALL/EFI/BOOT/grubx64_real.efi" --format 'x86_64-efi' --compression 'auto' $all_modules_uefi 'fat' 'part_msdos'
else
all_modules="$net_modules_legacy $all_modules_legacy"
grub-mkimage -v --directory "$VT_DIR/GRUB2/INSTALL/lib/grub/i386-pc" --prefix '(,msdos2)/grub' --output "$VT_DIR/INSTALL/grub/i386-pc/core.img" --format 'i386-pc' --compression 'auto' $all_modules_legacy 'fat' 'part_msdos' 'biosdisk'
grub-mkimage -v --directory "$VT_DIR/GRUB2/INSTALL/lib/grub/i386-pc" --prefix '(,2)/grub' --output "$VT_DIR/INSTALL/grub/i386-pc/core.img" --format 'i386-pc' --compression 'auto' $all_modules_legacy 'fat' 'part_msdos' 'biosdisk'
fi
grub-mknetdir --modules="$all_modules" --net-directory=$VT_DIR/GRUB2/PXE --subdir=grub2 --locales=en@quot || exit 1

View File

@@ -0,0 +1,47 @@
#!/ventoy/busybox/sh
#************************************************************************************
# Copyright (c) 2020, longpanda <admin@ventoy.net>
#
# 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 <http://www.gnu.org/licenses/>.
#
#************************************************************************************
. /ventoy/hook/ventoy-hook-lib.sh
if is_ventoy_hook_finished; then
exit 0
fi
vtlog "####### $0 $* ########"
VTPATH_OLD=$PATH; PATH=$BUSYBOX_PATH:$VTOY_PATH/tool:$PATH
wait_for_usb_disk_ready
vtdiskname=$(get_ventoy_disk_name)
if [ "$vtdiskname" = "unknown" ]; then
vtlog "ventoy disk not found"
PATH=$VTPATH_OLD
exit 0
fi
ventoy_udev_disk_common_hook "${vtdiskname#/dev/}2" "noreplace"
blkdev_num=$($VTOY_PATH/tool/dmsetup ls | grep ventoy | sed 's/.*(\([0-9][0-9]*\),.*\([0-9][0-9]*\).*/\1 \2/')
mknod -m 0666 /dev/ventoy b $blkdev_num
PATH=$VTPATH_OLD
set_ventoy_hook_finish

View File

@@ -0,0 +1,43 @@
#!/ventoy/busybox/sh
#************************************************************************************
# Copyright (c) 2020, longpanda <admin@ventoy.net>
#
# 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 <http://www.gnu.org/licenses/>.
#
#************************************************************************************
. $VTOY_PATH/hook/ventoy-os-lib.sh
echo "CDlinux process..." >> $VTLOG
$BUSYBOX_PATH/mknod -m 0660 /ventoy/ram0 b 1 0
$BUSYBOX_PATH/mkdir /vtmnt /ventoy_rdroot
$BUSYBOX_PATH/mount -t squashfs /ventoy/ram0 /vtmnt
$BUSYBOX_PATH/mount -nt tmpfs -o mode=755 tmpfs /ventoy_rdroot
$BUSYBOX_PATH/cp -a /vtmnt/* /ventoy_rdroot
$BUSYBOX_PATH/ls -1a /vtmnt/ | $GREP '^\.[^.]' | while read vtLine; do
$BUSYBOX_PATH/cp -a /vtmnt/$vtLine /ventoy_rdroot
done
$BUSYBOX_PATH/umount /vtmnt && $BUSYBOX_PATH/rm -rf /vtmnt
$BUSYBOX_PATH/cp -a /ventoy /ventoy_rdroot
echo "CDL_DEV=/dev/mapper/ventoy" >> /ventoy_rdroot/etc/default/cdlinux
ventoy_set_rule_dir_prefix /ventoy_rdroot
ventoy_systemd_udevd_work_around
ventoy_add_udev_rule "$VTOY_PATH/hook/default/udev_disk_hook.sh %k"

View File

@@ -17,6 +17,8 @@
#
#************************************************************************************
CD_DETECT="/var/lib/dpkg/info/cdrom-detect.postinst"
if [ -e /init ] && $GREP -q '^mountroot$' /init; then
echo "Here before mountroot ..." >> $VTLOG
@@ -29,7 +31,15 @@ if [ -e /init ] && $GREP -q '^mountroot$' /init; then
$SED "s#^ *LIVEMEDIA=.*#LIVEMEDIA=/dev/mapper/ventoy#" -i /scripts/casper
fi
fi
elif [ -e "$CD_DETECT" ]; then
echo "$CD_DETECT exist, now add hook in it..." >> $VTLOG
$SED "1 a $BUSYBOX_PATH/sh $VTOY_PATH/hook/debian/disk_mount_hook.sh" -i "$CD_DETECT"
TITLE_LINE=$($GREP -m1 '^hw-detect.*detect_progress_title' "$CD_DETECT")
if [ $? -eq 0 ]; then
echo "add $TITLE_LINE for hook" >> $VTLOG
$SED "1 a$TITLE_LINE" -i "$CD_DETECT"
fi
elif [ -e /init ] && $GREP -q '/start-udev$' /init; then
echo "Here use notify ..." >> $VTLOG

View File

@@ -99,7 +99,18 @@ ventoy_udev_disk_common_hook $*
# 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
VT_BUS_USB=""
if [ -n "$ID_BUS" ]; then
if echo $ID_BUS | $GREP -q -i usb; then
VT_BUS_USB="YES"
fi
else
if $BUSYBOX_PATH/ls -l /sys/class/block/${1:0:-1} | $GREP -q -i usb; then
VT_BUS_USB="YES"
fi
fi
if [ -n "$VT_BUS_USB" ]; then
vtlog "$1 is USB device"
else
vtlog "$1 is NOT USB device (bus $ID_BUS)"

View File

@@ -23,13 +23,15 @@ if is_ventoy_hook_finished; then
exit 0
fi
vtlog "##### INOTIFYD: $2/$3 is created ..."
VTPATH_OLD=$PATH; PATH=$BUSYBOX_PATH:$VTOY_PATH/tool:$PATH
if is_inotify_ventoy_part $3; then
vtlog "##### INOTIFYD: $2/$3 is created (YES) ..."
vtlog "find ventoy partition $3 ..."
$BUSYBOX_PATH/sh $VTOY_PATH/hook/debian/udev_disk_hook.sh "$3"
else
vtlog "##### INOTIFYD: $2/$3 is created (NO)..."
fi
PATH=$VTPATH_OLD

View File

@@ -23,11 +23,11 @@ if is_ventoy_hook_finished; then
exit 0
fi
vtlog "##### INOTIFYD: $2/$3 is created ..."
VTPATH_OLD=$PATH; PATH=$BUSYBOX_PATH:$VTOY_PATH/tool:$PATH
if is_inotify_ventoy_part $3; then
vtlog "##### INOTIFYD: $2/$3 is created (YES)..."
vtlog "find ventoy partition $3 ..."
$BUSYBOX_PATH/sh $VTOY_PATH/hook/default/udev_disk_hook.sh $3 noreplace
@@ -42,6 +42,8 @@ if is_inotify_ventoy_part $3; then
# fi
set_ventoy_hook_finish
else
vtlog "##### INOTIFYD: $2/$3 is created (NO)..."
fi
PATH=$VTPATH_OLD

View File

@@ -23,12 +23,11 @@ if is_ventoy_hook_finished; then
exit 0
fi
vtlog "##### INOTIFYD: $2/$3 is created ..."
VTPATH_OLD=$PATH; PATH=$BUSYBOX_PATH:$VTOY_PATH/tool:$PATH
if is_inotify_ventoy_part $3; then
vtlog "##### INOTIFYD: $2/$3 is created (YES) ..."
vtlog "find ventoy partition ..."
$BUSYBOX_PATH/sh $VTOY_PATH/hook/default/udev_disk_hook.sh $3 noreplace
@@ -64,6 +63,8 @@ if is_inotify_ventoy_part $3; then
fi
set_ventoy_hook_finish
else
vtlog "##### INOTIFYD: $2/$3 is created (NO) ..."
fi
PATH=$VTPATH_OLD

View File

@@ -23,11 +23,10 @@ if is_ventoy_hook_finished; then
exit 0
fi
vtlog "##### INOTIFYD: $2/$3 is created ..."
VTPATH_OLD=$PATH; PATH=$BUSYBOX_PATH:$VTOY_PATH/tool:$PATH
if is_inotify_ventoy_part $3; then
vtlog "##### INOTIFYD: $2/$3 is created (YES) ..."
vtlog "find ventoy partition $3 ..."
$BUSYBOX_PATH/sh $VTOY_PATH/hook/default/udev_disk_hook.sh "$3"
@@ -41,6 +40,8 @@ if is_inotify_ventoy_part $3; then
mkdir -p /dev/disk/by-label
fi
$BUSYBOX_PATH/cp -a /dev/$vtDM /dev/disk/by-label/$vtLABEL
else
vtlog "##### INOTIFYD: $2/$3 is created (NO) ..."
fi
PATH=$VTPATH_OLD

View File

@@ -0,0 +1,47 @@
#!/ventoy/busybox/sh
#************************************************************************************
# Copyright (c) 2020, longpanda <admin@ventoy.net>
#
# 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 <http://www.gnu.org/licenses/>.
#
#************************************************************************************
. /ventoy/hook/ventoy-hook-lib.sh
if is_ventoy_hook_finished; then
exit 0
fi
vtlog "####### $0 $* ########"
VTPATH_OLD=$PATH; PATH=$BUSYBOX_PATH:$VTOY_PATH/tool:$PATH
wait_for_usb_disk_ready
vtdiskname=$(get_ventoy_disk_name)
if [ "$vtdiskname" = "unknown" ]; then
vtlog "ventoy disk not found"
PATH=$VTPATH_OLD
exit 0
fi
ventoy_udev_disk_common_hook "${vtdiskname#/dev/}2" "noreplace"
blkdev_num=$($VTOY_PATH/tool/dmsetup ls | grep ventoy | sed 's/.*(\([0-9][0-9]*\),.*\([0-9][0-9]*\).*/\1 \2/')
mknod -m 0666 /dev/ventoy b $blkdev_num
PATH=$VTPATH_OLD
set_ventoy_hook_finish

View File

@@ -0,0 +1,32 @@
#!/ventoy/busybox/sh
#************************************************************************************
# Copyright (c) 2020, longpanda <admin@ventoy.net>
#
# 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 <http://www.gnu.org/licenses/>.
#
#************************************************************************************
. /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 $* "noreplace"
blkdev_num=$($VTOY_PATH/tool/dmsetup ls | grep ventoy | sed 's/.*(\([0-9][0-9]*\),.*\([0-9][0-9]*\).*/\1 \2/')
mknod -m 0666 /dev/ventoy b $blkdev_num
# OK finish
set_ventoy_hook_finish

View File

@@ -0,0 +1,31 @@
#!/ventoy/busybox/sh
#************************************************************************************
# Copyright (c) 2020, longpanda <admin@ventoy.net>
#
# 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 <http://www.gnu.org/licenses/>.
#
#************************************************************************************
. $VTOY_PATH/hook/ventoy-os-lib.sh
if $GREP -q 'Searching *for *PMAGIC' /init; then
echo "Find Searching PMAGIC" >> $VTLOG
$SED "/Searching *for *PMAGIC/a\ root=/dev/ventoy" -i /init
$SED "/Searching *for *PMAGIC/a\ $BUSYBOX_PATH/sh $VTOY_PATH/hook/pmagic/disk-hook.sh" -i /init
else
echo "Use default..." >> $VTLOG
$SED "s#^root=.*cmdline.*#root=/dev/ventoy#g'" -i /init
ventoy_systemd_udevd_work_around
ventoy_add_udev_rule "$VTOY_PATH/hook/pmagic/udev_disk_hook.sh %k"
fi

View File

@@ -23,12 +23,12 @@ if is_ventoy_hook_finished; then
exit 0
fi
vtlog "##### INOTIFYD: $2/$3 is created ..."
VTPATH_OLD=$PATH; PATH=$BUSYBOX_PATH:$VTOY_PATH/tool:$PATH
if is_inotify_ventoy_part $3; then
vtlog "##### INOTIFYD: $2/$3 is created (YES) ..."
vtGenRulFile='/etc/udev/rules.d/99-live-squash.rules'
if [ -e $vtGenRulFile ] && $GREP -q dmsquash $vtGenRulFile; then
vtScript=$($GREP -m1 'RUN.=' $vtGenRulFile | $AWK -F'RUN.=' '{print $2}' | $SED 's/"\(.*\)".*/\1/')
@@ -57,6 +57,8 @@ if is_inotify_ventoy_part $3; then
fi
set_ventoy_hook_finish
else
vtlog "##### INOTIFYD: $2/$3 is created (NO) ..."
fi
PATH=$VTPATH_OLD

View File

@@ -72,6 +72,13 @@ ventoy_is_initrd_ramdisk() {
fi
}
ventoy_mount_squashfs() {
mkdir /dev
mount -t devtmpfs devtmpfs /dev
dd if=$1 of=/dev/ram0 status=none
umount /dev && rm -rf /dev
}
# param: file skip magic tmp
ventoy_unpack_initramfs() {
vtfile=$1; vtskip=$2; vtmagic=$3; vttmp=$4
@@ -83,6 +90,11 @@ ventoy_unpack_initramfs() {
# vtmagic='1F8B'
#fi
if [ "${vtmagic:0:4}" = '6873' ]; then
ventoy_mount_squashfs $vtfile
return
fi
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

View File

@@ -196,6 +196,14 @@ ventoy_get_os_type() {
echo 'adelie'; return
fi
if $GREP -q 'pmagic' /proc/version; then
echo 'pmagic'; return
fi
if $GREP -q 'CDlinux' /proc/cmdline; then
echo 'cdlinux'; return
fi
echo "default"
}

Binary file not shown.

Binary file not shown.

View File

@@ -23,6 +23,8 @@ sh buildlib.sh
cd $VTOY_PATH/vtoyfat
sh build.sh || exit 1
cd $VTOY_PATH/vtoygpt
sh build.sh || exit 1
cd $VTOY_PATH/ExFAT
sh buidlibfuse.sh || exit 1

View File

@@ -1,5 +1,5 @@
submenu 'Check plugin json configuration (ventoy.json)' --class=debug_json {
menuentry 'Check global control plugin configuration' {
menuentry 'Check global control plugin configuration' --class=debug_control {
set pager=1
vt_check_plugin_json $vt_plugin_path control $iso_path
@@ -61,6 +61,22 @@ submenu 'Check plugin json configuration (ventoy.json)' --class=debug_json {
}
}
if [ "$grub_platform" != "pc" ]; then
submenu 'Ventoy UEFI Utilities' --class=debug_util {
menuentry 'Fixup Windows BlinitializeLibrary Failure' {
chainloader ${vtoy_path}/vtoyutil_x64.efi env_param=${env_param} ${vtdebug_flag} feature=fix_windows_mmap
boot
echo -e "\npress ENTER to exit ..."
read vtInputKey
}
menuentry 'Return to previous menu [Esc]' --class=vtoyret VTOY_RET {
echo 'Return ...'
}
}
fi
menuentry 'Return to previous menu [Esc]' --class=vtoyret VTOY_RET {
echo 'Return ...'
}

View File

@@ -30,6 +30,30 @@ function ventoy_debug_pause {
fi
}
function ventoy_cli_console {
if [ "$grub_platform" = "pc" ]; then
#terminal_output vga_text
terminal_output console
else
if [ "$vtoy_display_mode" != "CLI" ]; then
terminal_output console
fi
fi
}
function ventoy_gui_console {
if [ "$grub_platform" = "pc" ]; then
if [ "$vtoy_display_mode" = "CLI" ]; then
terminal_output console
else
terminal_output gfxterm
fi
else
if [ "$vtoy_display_mode" != "CLI" ]; then
terminal_output gfxterm
fi
fi
}
function ventoy_power {
configfile $prefix/power.cfg
@@ -154,6 +178,8 @@ function distro_specify_initrd_file_phase2 {
vt_linux_specify_initrd_file /initrd.img
elif [ -f (loop)/sysresccd/boot/x86_64/sysresccd.img ]; then
vt_linux_specify_initrd_file /sysresccd/boot/x86_64/sysresccd.img
elif [ -f (loop)/CDlinux/initrd ]; then
vt_linux_specify_initrd_file /CDlinux/initrd
fi
}
@@ -186,7 +212,7 @@ function uefi_windows_menu_func {
ventoy_debug_pause
if [ -n "$vtoy_chain_mem_addr" ]; then
terminal_output console
ventoy_cli_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
@@ -262,7 +288,7 @@ function uefi_linux_menu_func {
vt_linux_chain_data ${1}${chosen_path}
if [ -n "$vtoy_chain_mem_addr" ]; then
terminal_output console
ventoy_cli_console
chainloader ${vtoy_path}/ventoy_x64.efi env_param=${env_param} isoefi=${LoadIsoEfiDriver} FirstTry=${FirstTryBootFile} ${vtdebug_flag} mem:${vtoy_chain_mem_addr}:size:${vtoy_chain_mem_size}
boot
else
@@ -327,7 +353,7 @@ function uefi_iso_menu_func {
uefi_linux_menu_func $1 ${chosen_path}
fi
terminal_output gfxterm
ventoy_gui_console
}
function uefi_iso_memdisk {
@@ -336,11 +362,11 @@ function uefi_iso_memdisk {
echo 'Loading ISO file to memory ...'
vt_load_iso_to_mem ${1}${chosen_path} vtoy_iso_buf
terminal_output console
ventoy_cli_console
chainloader ${vtoy_path}/ventoy_x64.efi memdisk env_param=${env_param} isoefi=${LoadIsoEfiDriver} ${vtdebug_flag} mem:${vtoy_iso_buf_addr}:size:${vtoy_iso_buf_size}
boot
terminal_output gfxterm
ventoy_gui_console
}
@@ -527,9 +553,9 @@ function wim_common_menuentry {
if [ "$grub_platform" = "pc" ]; then
linux16 $vtoy_path/ipxe.krn ${vtdebug_flag} mem:${vtoy_chain_mem_addr}:size:${vtoy_chain_mem_size}
else
terminal_output console
ventoy_cli_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}
terminal_output gfxterm
ventoy_gui_console
fi
boot
else
@@ -545,16 +571,18 @@ function wim_unsupport_menuentry {
function efi_common_menuentry {
vt_chosen_img_path chosen_path
terminal_output console
ventoy_cli_console
chainloader ${iso_path}${chosen_path}
boot
terminal_output gfxterm
ventoy_gui_console
}
function efi_unsupport_menuentry {
common_unsupport_menuentry
}
#############################################################
#############################################################
#############################################################
@@ -563,7 +591,7 @@ function efi_unsupport_menuentry {
#############################################################
#############################################################
set VENTOY_VERSION="1.0.14"
set VENTOY_VERSION="1.0.15"
# Default menu display mode, you can change it as you want.
# 0: List mode
@@ -650,15 +678,14 @@ else
set gfxmode=1920x1080,1366x768,1024x768
fi
if [ -n "$vtoy_theme" ]; then
set theme=$vtoy_theme
else
set theme=$prefix/themes/ventoy/theme.txt
fi
if [ "$vtoy_display_mode" = "CLI" ]; then
terminal_output console
else
else
if [ -n "$vtoy_theme" ]; then
set theme=$vtoy_theme
else
set theme=$prefix/themes/ventoy/theme.txt
fi
terminal_output gfxterm
fi

Binary file not shown.

View File

@@ -6,14 +6,14 @@ print_usage() {
echo 'Usage: Ventoy2Disk.sh CMD [ OPTION ] /dev/sdX'
echo ' CMD:'
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 ' -u update ventoy in sdX'
echo ''
echo ' OPTION: (optional)'
echo ' -r SIZE_MB preserve some space at the bottom of the disk (only for install)'
echo ' -s enable secure boot support (default is disabled)'
echo ' -g use GPT partition style, default is MBR (only for install)'
echo ''
}
RESERVE_SIZE_MB=0
@@ -27,6 +27,8 @@ while [ -n "$1" ]; do
MODE="update"
elif [ "$1" = "-s" ]; then
SECUREBOOT="YES"
elif [ "$1" = "-g" ]; then
VTGPT="YES"
elif [ "$1" = "-r" ]; then
RESERVE_SPACE="YES"
shift
@@ -110,13 +112,22 @@ fi
if [ "$MODE" = "install" ]; then
vtdebug "install ventoy ..."
if parted -v > /dev/null 2>&1; then
PARTTOOL='parted'
elif fdisk -v >/dev/null 2>&1; then
PARTTOOL='fdisk'
if [ -n "$VTGPT" ]; then
if parted -v > /dev/null 2>&1; then
PARTTOOL='parted'
else
vterr "parted is not found in the sysstem, Ventoy can't create new partition."
exit 1
fi
else
vterr "Both parted and fdisk are not found in the sysstem, Ventoy can't create new partition."
exit 1
if parted -v > /dev/null 2>&1; then
PARTTOOL='parted'
elif fdisk -v >/dev/null 2>&1; then
PARTTOOL='fdisk'
else
vterr "Both parted and fdisk are not found in the sysstem, Ventoy can't create new partition."
exit 1
fi
fi
version=$(get_disk_ventoy_version $DISK)
@@ -148,11 +159,15 @@ if [ "$MODE" = "install" ]; then
fi
fi
#Print disk info
echo "Disk : $DISK"
parted -s $DISK p 2>&1 | grep Model
echo "Size : $disk_size_gb GB"
echo "Size : $disk_size_gb GB"
if [ -n "$VTGPT" ]; then
echo "Style: GPT"
else
echo "Style: MBR"
fi
echo ''
if [ -n "$RESERVE_SPACE" ]; then
@@ -192,7 +207,13 @@ if [ "$MODE" = "install" ]; then
exit 1
fi
format_ventoy_disk $RESERVE_SIZE_MB $DISK $PARTTOOL
if [ -n "$VTGPT" ]; then
vtdebug "format_ventoy_disk_gpt $RESERVE_SIZE_MB $DISK $PARTTOOL ..."
format_ventoy_disk_gpt $RESERVE_SIZE_MB $DISK $PARTTOOL
else
vtdebug "format_ventoy_disk_mbr $RESERVE_SIZE_MB $DISK $PARTTOOL ..."
format_ventoy_disk_mbr $RESERVE_SIZE_MB $DISK $PARTTOOL
fi
# format part1
if ventoy_is_linux64; then
@@ -216,8 +237,17 @@ if [ "$MODE" = "install" ]; then
chmod +x ./tool/vtoy_gen_uuid
vtinfo "writing data to disk ..."
dd status=none conv=fsync if=./boot/boot.img of=$DISK bs=1 count=446
./tool/xzcat ./boot/core.img.xz | dd status=none conv=fsync of=$DISK bs=512 count=2047 seek=1
if [ -n "$VTGPT" ]; then
echo -en '\x22' | dd status=none of=$DISK conv=fsync bs=1 count=1 seek=92
./tool/xzcat ./boot/core.img.xz | dd status=none conv=fsync of=$DISK bs=512 count=2014 seek=34
echo -en '\x23' | dd of=$DISK conv=fsync bs=1 count=1 seek=17908 status=none
else
./tool/xzcat ./boot/core.img.xz | dd status=none conv=fsync of=$DISK bs=512 count=2047 seek=1
fi
./tool/xzcat ./ventoy/ventoy.disk.img.xz | dd status=none conv=fsync of=$DISK bs=512 count=$VENTOY_SECTOR_NUM seek=$part2_start_sector
#disk uuid
@@ -293,22 +323,31 @@ else
fi
PART2=$(get_disk_part_name $DISK 2)
SHORT_PART2=${PART2#/dev/}
part2_start=$(cat /sys/class/block/$SHORT_PART2/start)
dd status=none conv=fsync if=./boot/boot.img of=$DISK bs=1 count=440
PART1_TYPE=$(dd if=$DISK bs=1 count=1 skip=450 status=none | ./tool/hexdump -n1 -e '1/1 "%02X"')
PART1_ACTIVE=$(dd if=$DISK bs=1 count=1 skip=446 status=none | ./tool/hexdump -n1 -e '1/1 "%02X"')
PART2_ACTIVE=$(dd if=$DISK bs=1 count=1 skip=462 status=none | ./tool/hexdump -n1 -e '1/1 "%02X"')
if [ "$PART1_TYPE" = "EE" ]; then
vtdebug "This is GPT partition style ..."
./tool/xzcat ./boot/core.img.xz | dd status=none conv=fsync of=$DISK bs=512 count=2014 seek=34
echo -en '\x23' | dd of=$DISK conv=fsync bs=1 count=1 seek=17908 status=none
else
vtdebug "This is MBR partition style ..."
dd status=none conv=fsync if=./boot/boot.img of=$DISK bs=1 count=440
vtdebug "PART1_ACTIVE=$PART1_ACTIVE PART2_ACTIVE=$PART2_ACTIVE"
if [ "$PART1_ACTIVE" = "00" ] && [ "$PART2_ACTIVE" = "80" ]; then
vtdebug "change 1st partition active, 2nd partition inactive ..."
echo -en '\x80' | dd of=$DISK conv=fsync bs=1 count=1 seek=446 status=none
echo -en '\x00' | dd of=$DISK conv=fsync bs=1 count=1 seek=462 status=none
PART1_ACTIVE=$(dd if=$DISK bs=1 count=1 skip=446 status=none | ./tool/hexdump -n1 -e '1/1 "%02X"')
PART2_ACTIVE=$(dd if=$DISK bs=1 count=1 skip=462 status=none | ./tool/hexdump -n1 -e '1/1 "%02X"')
vtdebug "PART1_ACTIVE=$PART1_ACTIVE PART2_ACTIVE=$PART2_ACTIVE"
if [ "$PART1_ACTIVE" = "00" ] && [ "$PART2_ACTIVE" = "80" ]; then
vtdebug "change 1st partition active, 2nd partition inactive ..."
echo -en '\x80' | dd of=$DISK conv=fsync bs=1 count=1 seek=446 status=none
echo -en '\x00' | dd of=$DISK conv=fsync bs=1 count=1 seek=462 status=none
fi
./tool/xzcat ./boot/core.img.xz | dd status=none conv=fsync of=$DISK bs=512 count=2047 seek=1
fi
./tool/xzcat ./boot/core.img.xz | dd status=none conv=fsync of=$DISK bs=512 count=2047 seek=1
part2_start=$(cat /sys/class/block/${PART2#/dev/}/start)
./tool/xzcat ./ventoy/ventoy.disk.img.xz | dd status=none conv=fsync of=$DISK bs=512 count=$VENTOY_SECTOR_NUM seek=$part2_start
sync

View File

@@ -103,7 +103,7 @@ get_ventoy_version_from_cfg() {
}
is_disk_contains_ventoy() {
DISK=$1
DISK=$1
PART1=$(get_disk_part_name $1 1)
PART2=$(get_disk_part_name $1 2)
@@ -126,11 +126,15 @@ is_disk_contains_ventoy() {
return
fi
PART1_TYPE=$(dd if=$DISK bs=1 count=1 skip=450 status=none | ./tool/hexdump -n1 -e '1/1 "%02X"')
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
if [ "$PART1_TYPE" != "EE" ]; then
if [ "$PART2_TYPE" != "EF" ]; then
vtdebug "part2 type is $PART2_TYPE not EF"
ventoy_false
return
fi
fi
# PART1_TYPE=$(dd if=$DISK bs=1 count=1 skip=450 status=none | ./tool/hexdump -n1 -e '1/1 "%02X"')
@@ -185,7 +189,7 @@ get_disk_ventoy_version() {
ventoy_false
}
format_ventoy_disk() {
format_ventoy_disk_mbr() {
reserve_mb=$1
DISK=$2
PARTTOOL=$3
@@ -218,7 +222,7 @@ format_ventoy_disk() {
fi
echo ""
echo "Create partitions on $DISK by $PARTTOOL ..."
echo "Create partitions on $DISK by $PARTTOOL in MBR style ..."
if [ "$PARTTOOL" = "parted" ]; then
vtdebug "format disk by parted ..."
@@ -300,5 +304,103 @@ EOF
}
format_ventoy_disk_gpt() {
reserve_mb=$1
DISK=$2
PARTTOOL=$3
PART1=$(get_disk_part_name $DISK 1)
PART2=$(get_disk_part_name $DISK 2)
sector_num=$(cat /sys/block/${DISK#/dev/}/size)
part1_start_sector=2048
if [ $reserve_mb -gt 0 ]; then
reserve_sector_num=$(expr $reserve_mb \* 2048 + 33)
part1_end_sector=$(expr $sector_num - $reserve_sector_num - $VENTOY_SECTOR_NUM - 1)
else
part1_end_sector=$(expr $sector_num - $VENTOY_SECTOR_NUM - 34)
fi
part2_start_sector=$(expr $part1_end_sector + 1)
part2_end_sector=$(expr $part2_start_sector + $VENTOY_SECTOR_NUM - 1)
export part2_start_sector
vtdebug "part1_start_sector=$part1_start_sector part1_end_sector=$part1_end_sector"
vtdebug "part2_start_sector=$part2_start_sector part2_end_sector=$part2_end_sector"
if [ -e $PART2 ]; then
echo "delete $PART2"
rm -f $PART2
fi
echo ""
echo "Create partitions on $DISK by $PARTTOOL in GPT style ..."
vtdebug "format disk by parted ..."
parted -a none --script $DISK \
mklabel gpt \
unit s \
mkpart Ventoy ntfs $part1_start_sector $part1_end_sector \
mkpart VTOYEFI fat16 $part2_start_sector $part2_end_sector \
set 2 msftdata on \
set 2 hidden on \
quit
sync
if ventoy_is_linux64; then
vtoygpt=./tool/vtoygpt_64
else
vtoygpt=./tool/vtoygpt_32
fi
$vtoygpt -f $DISK
sync
udevadm trigger >/dev/null 2>&1
partprobe >/dev/null 2>&1
sleep 3
echo "Done"
echo 'mkfs on disk partitions ...'
for i in 1 2 3 4 5 6 7; do
if [ -b $PART2 ]; then
break
else
echo "wait $PART2 ..."
sleep 1
fi
done
if ! [ -b $PART2 ]; then
MajorMinor=$(sed "s/:/ /" /sys/class/block/${PART2#/dev/}/dev)
echo "mknod -m 0660 $PART2 b $MajorMinor ..."
mknod -m 0660 $PART2 b $MajorMinor
if ! [ -b $PART1 ]; then
MajorMinor=$(sed "s/:/ /" /sys/class/block/${PART1#/dev/}/dev)
echo "mknod -m 0660 $PART1 b $MajorMinor ..."
mknod -m 0660 $PART1 b $MajorMinor
fi
fi
echo "create efi fat fs $PART2 ..."
for i in 0 1 2 3 4 5 6 7 8 9; do
if mkfs.vfat -F 16 -n VTOYEFI $PART2; then
echo 'success'
break
else
echo "$? retry ..."
sleep 2
fi
done
}

BIN
INSTALL/tool/vtoygpt_32 Normal file

Binary file not shown.

BIN
INSTALL/tool/vtoygpt_64 Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -31,7 +31,7 @@ while ! grep -q 524288 /sys/block/${LOOP#/dev/}/size 2>/dev/null; do
sleep 1
done
format_ventoy_disk $LOOP fdisk
format_ventoy_disk_mbr 0 $LOOP fdisk
$GRUB_DIR/sbin/grub-bios-setup --skip-fs-probe --directory="./grub/i386-pc" $LOOP
@@ -104,7 +104,7 @@ cd $CurDir
tar -czvf ventoy-${curver}-linux.tar.gz $tmpdir
rm -f ventoy-${curver}-windows.zip
cp -a Ventoy2Disk.exe $tmpdir/
cp -a Ventoy2Disk*.exe $tmpdir/
cp -a $LANG_DIR/languages.ini $tmpdir/ventoy/
rm -rf $tmpdir/tool
rm -f $tmpdir/*.sh

View File

@@ -574,7 +574,7 @@ int ventoy_boot_vdisk(void *data)
g_os_param_reserved = (uint8_t *)(g_chain->os_param.vtoy_reserved);
/* Workaround for Windows & ISO9660 */
if (g_os_param_reserved[2] == 1 && g_os_param_reserved[3] == 0)
if (g_os_param_reserved[2] == ventoy_chain_windows && g_os_param_reserved[3] == 0)
{
g_fixup_iso9660_secover_enable = 1;
}

View File

@@ -13,6 +13,15 @@ FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL );
#define VENTOY_GUID { 0x77772020, 0x2e77, 0x6576, { 0x6e, 0x74, 0x6f, 0x79, 0x2e, 0x6e, 0x65, 0x74 }}
typedef enum ventoy_chain_type
{
ventoy_chain_linux = 0, /* 0: linux */
ventoy_chain_windows, /* 1: windows */
ventoy_chain_wim, /* 2: wim */
ventoy_chain_max
}ventoy_chain_type;
#pragma pack(1)
typedef struct ventoy_guid

Binary file not shown.

View File

@@ -57,6 +57,13 @@ typedef enum STR_ID
STR_PRESERVE_SPACE,//24
STR_SPACE_VAL_INVALID,//25
STR_MENU_CLEAR, //26
STR_CLEAR_SUCCESS, //27
STR_CLEAR_FAILED, //28
STR_MENU_PART_STYLE, //29
STR_DISK_2TB_MBR_ERROR,//30
STR_ID_MAX
}STR_ID;
@@ -64,6 +71,23 @@ extern BOOL g_SecureBoot;
#define VTOY_MENU_SECURE_BOOT 0xA000
#define VTOY_MENU_PART_CFG 0xA001
#define VTOY_MENU_CLEAN 0xA002
#define VTOY_MENU_PART_STYLE 0xA003
#define VTOY_MENU_PART_MBR 0xA004
#define VTOY_MENU_PART_GPT 0xA005
typedef enum OPT_SUBMENU
{
OPT_SUBMENU_SECURE_BOOT = 0,
OPT_SUBMENU_PART_STYLE,
OPT_SUBMENU_PART_CFG,
OPT_SUBMENU_CLEAR,
OPT_SUBMENU_MAX
}OPT_SUBMENU;
#define VTOY_MENU_LANGUAGE_BEGIN 0xB000

Binary file not shown.

File diff suppressed because it is too large Load Diff

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

File diff suppressed because it is too large Load Diff

View File

@@ -70,7 +70,7 @@ int ParseCmdLineOption(LPSTR lpCmdLine)
return 0;
}
static BOOL IsVentoyPhyDrive(int PhyDrive, UINT64 SizeBytes, MBR_HEAD *pMBR)
static BOOL IsVentoyPhyDrive(int PhyDrive, UINT64 SizeBytes, MBR_HEAD *pMBR, UINT64 *Part2StartSector)
{
int i;
BOOL bRet;
@@ -80,6 +80,7 @@ static BOOL IsVentoyPhyDrive(int PhyDrive, UINT64 SizeBytes, MBR_HEAD *pMBR)
UINT32 PartStartSector;
UINT32 PartSectorCount;
CHAR PhyDrivePath[128];
VTOY_GPT_INFO *pGpt = NULL;
safe_sprintf(PhyDrivePath, "\\\\.\\PhysicalDrive%d", PhyDrive);
hDrive = CreateFileA(PhyDrivePath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
@@ -90,63 +91,101 @@ static BOOL IsVentoyPhyDrive(int PhyDrive, UINT64 SizeBytes, MBR_HEAD *pMBR)
return FALSE;
}
bRet = ReadFile(hDrive, &MBR, sizeof(MBR), &dwSize, NULL);
CHECK_CLOSE_HANDLE(hDrive);
Log("Read MBR Ret:%u Size:%u code:%u", bRet, dwSize, LASTERR);
bRet = ReadFile(hDrive, &MBR, sizeof(MBR), &dwSize, NULL);
Log("Read MBR Ret:%u Size:%u code:%u", bRet, dwSize, LASTERR);
if ((!bRet) || (dwSize != sizeof(MBR)))
{
CHECK_CLOSE_HANDLE(hDrive);
return FALSE;
}
if (MBR.Byte55 != 0x55 || MBR.ByteAA != 0xAA)
{
Log("Byte55 ByteAA not match 0x%x 0x%x", MBR.Byte55, MBR.ByteAA);
CHECK_CLOSE_HANDLE(hDrive);
return FALSE;
}
for (i = 0; i < 4; i++)
{
Log("=========== Partition Table %d ============", i + 1);
Log("PartTbl.Active = 0x%x", MBR.PartTbl[i].Active);
Log("PartTbl.FsFlag = 0x%x", MBR.PartTbl[i].FsFlag);
Log("PartTbl.StartSectorId = %u", MBR.PartTbl[i].StartSectorId);
Log("PartTbl.SectorCount = %u", MBR.PartTbl[i].SectorCount);
Log("PartTbl.StartHead = %u", MBR.PartTbl[i].StartHead);
Log("PartTbl.StartSector = %u", MBR.PartTbl[i].StartSector);
Log("PartTbl.StartCylinder = %u", MBR.PartTbl[i].StartCylinder);
Log("PartTbl.EndHead = %u", MBR.PartTbl[i].EndHead);
Log("PartTbl.EndSector = %u", MBR.PartTbl[i].EndSector);
Log("PartTbl.EndCylinder = %u", MBR.PartTbl[i].EndCylinder);
}
for (i = 0; i < 4; i++)
{
Log("=========== Partition Table %d ============", i + 1);
Log("PartTbl.Active = 0x%x", MBR.PartTbl[i].Active);
Log("PartTbl.FsFlag = 0x%x", MBR.PartTbl[i].FsFlag);
Log("PartTbl.StartSectorId = %u", MBR.PartTbl[i].StartSectorId);
Log("PartTbl.SectorCount = %u", MBR.PartTbl[i].SectorCount);
Log("PartTbl.StartHead = %u", MBR.PartTbl[i].StartHead);
Log("PartTbl.StartSector = %u", MBR.PartTbl[i].StartSector);
Log("PartTbl.StartCylinder = %u", MBR.PartTbl[i].StartCylinder);
Log("PartTbl.EndHead = %u", MBR.PartTbl[i].EndHead);
Log("PartTbl.EndSector = %u", MBR.PartTbl[i].EndSector);
Log("PartTbl.EndCylinder = %u", MBR.PartTbl[i].EndCylinder);
}
if (MBR.PartTbl[0].FsFlag == 0xEE)
{
pGpt = malloc(sizeof(VTOY_GPT_INFO));
if (!pGpt)
{
CHECK_CLOSE_HANDLE(hDrive);
return FALSE;
}
if (MBR.PartTbl[0].StartSectorId != 2048)
{
Log("Part1 not match %u", MBR.PartTbl[0].StartSectorId);
return FALSE;
}
SetFilePointer(hDrive, 0, NULL, FILE_BEGIN);
bRet = ReadFile(hDrive, pGpt, sizeof(VTOY_GPT_INFO), &dwSize, NULL);
CHECK_CLOSE_HANDLE(hDrive);
if ((!bRet) || (dwSize != sizeof(VTOY_GPT_INFO)))
{
Log("Failed to read gpt info %d %u %d", bRet, dwSize, LASTERR);
return FALSE;
}
PartStartSector = MBR.PartTbl[0].StartSectorId + MBR.PartTbl[0].SectorCount;
PartSectorCount = VENTOY_EFI_PART_SIZE / 512;
if (memcmp(pGpt->Head.Signature, "EFI PART", 8))
{
Log("Invalid GPT signature");
return FALSE;
}
if (MBR.PartTbl[1].FsFlag != 0xEF ||
MBR.PartTbl[1].StartSectorId != PartStartSector ||
MBR.PartTbl[1].SectorCount != PartSectorCount)
{
Log("Part2 not match [0x%x 0x%x] [%u %u] [%u %u]",
MBR.PartTbl[1].FsFlag, 0xEF,
MBR.PartTbl[1].StartSectorId, PartStartSector,
MBR.PartTbl[1].SectorCount, PartSectorCount);
return FALSE;
}
if (memcmp(pGpt->PartTbl[1].Name, L"VTOYEFI", 7 * 2))
{
Log("Invalid ventoy efi part name");
return FALSE;
}
if (MBR.PartTbl[0].Active != 0x80 && MBR.PartTbl[1].Active != 0x80)
{
Log("Part1 and Part2 are both NOT active 0x%x 0x%x", MBR.PartTbl[0].Active, MBR.PartTbl[1].Active);
return FALSE;
}
*Part2StartSector = pGpt->PartTbl[1].StartLBA;
}
else
{
CHECK_CLOSE_HANDLE(hDrive);
if (MBR.PartTbl[0].StartSectorId != 2048)
{
Log("Part1 not match %u", MBR.PartTbl[0].StartSectorId);
return FALSE;
}
PartStartSector = MBR.PartTbl[0].StartSectorId + MBR.PartTbl[0].SectorCount;
PartSectorCount = VENTOY_EFI_PART_SIZE / 512;
if (MBR.PartTbl[1].FsFlag != 0xEF ||
MBR.PartTbl[1].StartSectorId != PartStartSector ||
MBR.PartTbl[1].SectorCount != PartSectorCount)
{
Log("Part2 not match [0x%x 0x%x] [%u %u] [%u %u]",
MBR.PartTbl[1].FsFlag, 0xEF,
MBR.PartTbl[1].StartSectorId, PartStartSector,
MBR.PartTbl[1].SectorCount, PartSectorCount);
return FALSE;
}
if (MBR.PartTbl[0].Active != 0x80 && MBR.PartTbl[1].Active != 0x80)
{
Log("Part1 and Part2 are both NOT active 0x%x 0x%x", MBR.PartTbl[0].Active, MBR.PartTbl[1].Active);
return FALSE;
}
*Part2StartSector = MBR.PartTbl[1].StartSectorId;
}
memcpy(pMBR, &MBR, sizeof(MBR_HEAD));
Log("PhysicalDrive%d is ventoy disk", PhyDrive);
@@ -161,6 +200,7 @@ static int FilterPhysicalDrive(PHY_DRIVE_INFO *pDriveList, DWORD DriveCount)
int Letter = 'A';
int Id = 0;
int LetterCount = 0;
UINT64 Part2StartSector = 0;
PHY_DRIVE_INFO *CurDrive;
MBR_HEAD MBR;
int LogLetter[VENTOY_MAX_PHY_DRIVE];
@@ -217,9 +257,10 @@ static int FilterPhysicalDrive(PHY_DRIVE_INFO *pDriveList, DWORD DriveCount)
}
}
if (IsVentoyPhyDrive(CurDrive->PhyDrive, CurDrive->SizeInBytes, &MBR))
if (IsVentoyPhyDrive(CurDrive->PhyDrive, CurDrive->SizeInBytes, &MBR, &Part2StartSector))
{
GetVentoyVerInPhyDrive(CurDrive, &MBR, CurDrive->VentoyVersion, sizeof(CurDrive->VentoyVersion));
CurDrive->PartStyle = (MBR.PartTbl[0].FsFlag == 0xEE) ? 1 : 0;
GetVentoyVerInPhyDrive(CurDrive, Part2StartSector, CurDrive->VentoyVersion, sizeof(CurDrive->VentoyVersion));
}
}
@@ -276,6 +317,7 @@ int SortPhysicalDrive(PHY_DRIVE_INFO *pDriveList, DWORD DriveCount)
int Ventoy2DiskInit(void)
{
Log("\n===================== Enum All PhyDrives =====================");
g_PhyDriveList = (PHY_DRIVE_INFO *)malloc(sizeof(PHY_DRIVE_INFO)* VENTOY_MAX_PHY_DRIVE);
if (NULL == g_PhyDriveList)
{

View File

@@ -79,6 +79,43 @@ typedef struct MBR_HEAD
UINT8 Byte55;
UINT8 ByteAA;
}MBR_HEAD;
typedef struct VTOY_GPT_HDR
{
CHAR Signature[8]; /* EFI PART */
UINT8 Version[4];
UINT32 Length;
UINT32 Crc;
UINT8 Reserved1[4];
UINT64 EfiStartLBA;
UINT64 EfiBackupLBA;
UINT64 PartAreaStartLBA;
UINT64 PartAreaEndLBA;
GUID DiskGuid;
UINT64 PartTblStartLBA;
UINT32 PartTblTotNum;
UINT32 PartTblEntryLen;
UINT32 PartTblCrc;
UINT8 Reserved2[420];
}VTOY_GPT_HDR;
typedef struct VTOY_GPT_PART_TBL
{
GUID PartType;
GUID PartGuid;
UINT64 StartLBA;
UINT64 LastLBA;
UINT64 Attr;
UINT16 Name[36];
}VTOY_GPT_PART_TBL;
typedef struct VTOY_GPT_INFO
{
MBR_HEAD MBR;
VTOY_GPT_HDR Head;
VTOY_GPT_PART_TBL PartTbl[128];
}VTOY_GPT_INFO;
#pragma pack()
#define VENTOY_MAX_PHY_DRIVE 128
@@ -87,6 +124,7 @@ typedef struct PHY_DRIVE_INFO
{
int Id;
int PhyDrive;
int PartStyle;//0:MBR 1:GPT
UINT64 SizeInBytes;
BYTE DeviceType;
BOOL RemovableMedia;
@@ -138,19 +176,21 @@ const CHAR * GetBusTypeString(STORAGE_BUS_TYPE Type);
int VentoyGetLocalBootImg(MBR_HEAD *pMBR);
int GetHumanReadableGBSize(UINT64 SizeBytes);
void TrimString(CHAR *String);
int VentoyFillMBR(UINT64 DiskSizeBytes, MBR_HEAD *pMBR);
int VentoyFillMBR(UINT64 DiskSizeBytes, MBR_HEAD *pMBR, int PartStyle);
int VentoyFillGpt(UINT64 DiskSizeBytes, VTOY_GPT_INFO *pInfo);
BOOL IsVentoyLogicalDrive(CHAR DriveLetter);
int GetRegDwordValue(HKEY Key, LPCSTR SubKey, LPCSTR ValueName, DWORD *pValue);
int GetPhysicalDriveCount(void);
int GetAllPhysicalDriveInfo(PHY_DRIVE_INFO *pDriveList, DWORD *pDriveCount);
int GetPhyDriveByLogicalDrive(int DriveLetter);
int GetVentoyVerInPhyDrive(const PHY_DRIVE_INFO *pDriveInfo, MBR_HEAD *pMBR, CHAR *VerBuf, size_t BufLen);
int GetVentoyVerInPhyDrive(const PHY_DRIVE_INFO *pDriveInfo, UINT64 Part2StartSector, CHAR *VerBuf, size_t BufLen);
int Ventoy2DiskInit(void);
int Ventoy2DiskDestroy(void);
PHY_DRIVE_INFO * GetPhyDriveInfoById(int Id);
int ParseCmdLineOption(LPSTR lpCmdLine);
int InstallVentoy2PhyDrive(PHY_DRIVE_INFO *pPhyDrive);
int InstallVentoy2PhyDrive(PHY_DRIVE_INFO *pPhyDrive, int PartStyle);
int UpdateVentoy2PhyDrive(PHY_DRIVE_INFO *pPhyDrive);
int VentoyFillBackupGptHead(VTOY_GPT_INFO *pInfo, VTOY_GPT_HDR *pHead);
void SetProgressBarPos(int Pos);
int ReadWholeFileToBuf(const CHAR *FileName, int ExtLen, void **Bufer, int *BufLen);
int INIT unxz(unsigned char *in, int in_size,
@@ -161,5 +201,14 @@ int INIT unxz(unsigned char *in, int in_size,
void disk_io_set_param(HANDLE Handle, UINT64 SectorCount);
INT_PTR CALLBACK PartDialogProc(HWND hWnd, UINT Message, WPARAM wParam, LPARAM lParam);
int GetReservedSpaceInMB(void);
int FindProcessOccupyDisk(HANDLE hDrive, PHY_DRIVE_INFO *pPhyDrive);
int VentoyFillLocation(UINT64 DiskSizeInBytes, UINT32 StartSectorId, UINT32 SectorCount, PART_TABLE *Table);
int ClearVentoyFromPhyDrive(HWND hWnd, PHY_DRIVE_INFO *pPhyDrive, char *pDrvLetter);
UINT32 VentoyCrc32(void *Buffer, UINT32 Length);
#define SET_FILE_POS(pos) \
liCurrentPosition.QuadPart = pos; \
SetFilePointerEx(hDrive, liCurrentPosition, &liCurrentPosition, FILE_BEGIN)\
#endif

View File

@@ -91,6 +91,7 @@
</Manifest>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="crc32.c" />
<ClCompile Include="fat_io_lib\fat_access.c" />
<ClCompile Include="fat_io_lib\fat_cache.c" />
<ClCompile Include="fat_io_lib\fat_filelib.c" />
@@ -106,6 +107,7 @@
<ClCompile Include="Language.c" />
<ClCompile Include="PartDialog.c" />
<ClCompile Include="PhyDrive.c" />
<ClCompile Include="process.c" />
<ClCompile Include="Utility.c" />
<ClCompile Include="Ventoy2Disk.c" />
<ClCompile Include="WinDialog.c" />
@@ -128,6 +130,7 @@
<ClInclude Include="ff14\source\ff.h" />
<ClInclude Include="ff14\source\ffconf.h" />
<ClInclude Include="Language.h" />
<ClInclude Include="process.h" />
<ClInclude Include="resource.h" />
<ClInclude Include="Ventoy2Disk.h" />
</ItemGroup>
@@ -135,6 +138,8 @@
<ResourceCompile Include="Ventoy2Disk.rc" />
</ItemGroup>
<ItemGroup>
<Image Include="res\icon2.ico" />
<Image Include="Res\refresh.ico" />
<Image Include="Res\ventoy.ico" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />

View File

@@ -72,6 +72,12 @@
<ClCompile Include="PartDialog.c">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="process.c">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="crc32.c">
<Filter>源文件</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="Ventoy2Disk.h">
@@ -128,6 +134,9 @@
<ClInclude Include="ff14\source\ffconf.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="process.h">
<Filter>头文件</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="Ventoy2Disk.rc">
@@ -138,5 +147,11 @@
<Image Include="Res\ventoy.ico">
<Filter>资源文件</Filter>
</Image>
<Image Include="res\icon2.ico">
<Filter>资源文件</Filter>
</Image>
<Image Include="Res\refresh.ico">
<Filter>资源文件</Filter>
</Image>
</ItemGroup>
</Project>

Binary file not shown.

View File

@@ -0,0 +1,275 @@
#include <Windows.h>
static UINT32 g_CrcTable[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 VentoyCrc32(void *Buffer, UINT32 Length)
{
UINT32 Index;
UINT32 Crc;
UINT8 *Byte = Buffer;
Crc = 0xffffffff;
for (Index = 0; Index < Length; Index++, Byte++)
{
Crc = (Crc >> 8) ^ g_CrcTable[(UINT8)Crc ^ *Byte];
}
return Crc ^ 0xffffffff;
}

View File

@@ -0,0 +1,672 @@
/*
* Rufus: The Reliable USB Formatting Utility
* Process search functionality
*
* Modified from Process Hacker:
* https://github.com/processhacker2/processhacker2/
* Copyright © 2017-2019 Pete Batard <pete@akeo.ie>
* Copyright © 2017 dmex
* Copyright © 2009-2016 wj32
* Copyright (c) 2020, longpanda <admin@ventoy.net>
*
* 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 <http://www.gnu.org/licenses/>.
*/
#include <Windows.h>
#include <winternl.h>
#include <commctrl.h>
#include <initguid.h>
#include <vds.h>
#include "resource.h"
#include "Language.h"
#include "Ventoy2Disk.h"
#include "fat_filelib.h"
#include "ff.h"
#include "process.h"
#include <Psapi.h>
OPENED_LIBRARIES_VARS;
STATIC WCHAR *_wHandleName = NULL;
static PVOID PhHeapHandle = NULL;
/*
* Convert an NT Status to an error message
*
* \param Status An operattonal status.
*
* \return An error message string.
*
*/
char* NtStatusError(NTSTATUS Status) {
static char unknown[32];
switch (Status) {
case STATUS_SUCCESS:
return "Operation Successful";
case STATUS_UNSUCCESSFUL:
return "Operation Failed";
case STATUS_BUFFER_OVERFLOW:
return "Buffer Overflow";
case STATUS_NOT_IMPLEMENTED:
return "Not Implemented";
case STATUS_INFO_LENGTH_MISMATCH:
return "Info Length Mismatch";
case STATUS_INVALID_HANDLE:
return "Invalid Handle.";
case STATUS_INVALID_PARAMETER:
return "Invalid Parameter";
case STATUS_NO_MEMORY:
return "Not Enough Quota";
case STATUS_ACCESS_DENIED:
return "Access Denied";
case STATUS_BUFFER_TOO_SMALL:
return "Buffer Too Small";
case STATUS_OBJECT_TYPE_MISMATCH:
return "Wrong Type";
case STATUS_OBJECT_NAME_INVALID:
return "Object Name Invalid";
case STATUS_OBJECT_NAME_NOT_FOUND:
return "Object Name not found";
case STATUS_OBJECT_PATH_INVALID:
return "Object Path Invalid";
case STATUS_SHARING_VIOLATION:
return "Sharing Violation";
case STATUS_INSUFFICIENT_RESOURCES:
return "Insufficient resources";
case STATUS_NOT_SUPPORTED:
return "Operation is not supported";
default:
safe_sprintf(unknown, "Unknown error 0x%08lx", Status);
return unknown;
}
}
static NTSTATUS PhCreateHeap(VOID)
{
NTSTATUS status = STATUS_SUCCESS;
if (PhHeapHandle != NULL)
return STATUS_ALREADY_COMPLETE;
PF_INIT_OR_SET_STATUS(RtlCreateHeap, Ntdll);
if (NT_SUCCESS(status)) {
PhHeapHandle = pfRtlCreateHeap(HEAP_NO_SERIALIZE | HEAP_GROWABLE, NULL, 2 * MB, 1 * MB, NULL, NULL);
if (PhHeapHandle == NULL)
status = STATUS_UNSUCCESSFUL;
}
return status;
}
static NTSTATUS PhDestroyHeap(VOID)
{
NTSTATUS status = STATUS_SUCCESS;
if (PhHeapHandle == NULL)
return STATUS_ALREADY_COMPLETE;
PF_INIT_OR_SET_STATUS(RtlDestroyHeap, Ntdll);
if (NT_SUCCESS(status)) {
if (pfRtlDestroyHeap(PhHeapHandle) == NULL) {
PhHeapHandle = NULL;
}
else {
status = STATUS_UNSUCCESSFUL;
}
}
return status;
}
/**
* Allocates a block of memory.
*
* \param Size The number of bytes to allocate.
*
* \return A pointer to the allocated block of memory.
*
*/
static PVOID PhAllocate(SIZE_T Size)
{
PF_INIT(RtlAllocateHeap, Ntdll);
if (pfRtlAllocateHeap == NULL)
return NULL;
return pfRtlAllocateHeap(PhHeapHandle, 0, Size);
}
/**
* Frees a block of memory allocated with PhAllocate().
*
* \param Memory A pointer to a block of memory.
*
*/
static VOID PhFree(PVOID Memory)
{
PF_INIT(RtlFreeHeap, Ntdll);
if (pfRtlFreeHeap != NULL)
pfRtlFreeHeap(PhHeapHandle, 0, Memory);
}
/**
* Enumerates all open handles.
*
* \param Handles A variable which receives a pointer to a structure containing information about
* all opened handles. You must free the structure using PhFree() when you no longer need it.
*
* \return An NTStatus indicating success or the error code.
*/
NTSTATUS PhEnumHandlesEx(PSYSTEM_HANDLE_INFORMATION_EX *Handles)
{
static ULONG initialBufferSize = 0x10000;
NTSTATUS status = STATUS_SUCCESS;
PVOID buffer;
ULONG bufferSize;
PF_INIT_OR_SET_STATUS(NtQuerySystemInformation, Ntdll);
if (!NT_SUCCESS(status))
return status;
bufferSize = initialBufferSize;
buffer = PhAllocate(bufferSize);
if (buffer == NULL)
return STATUS_NO_MEMORY;
while ((status = pfNtQuerySystemInformation(SystemExtendedHandleInformation,
buffer, bufferSize, NULL)) == STATUS_INFO_LENGTH_MISMATCH) {
PhFree(buffer);
bufferSize *= 2;
// Fail if we're resizing the buffer to something very large.
if (bufferSize > PH_LARGE_BUFFER_SIZE)
return STATUS_INSUFFICIENT_RESOURCES;
buffer = PhAllocate(bufferSize);
if (buffer == NULL)
return STATUS_NO_MEMORY;
}
if (!NT_SUCCESS(status)) {
PhFree(buffer);
return status;
}
if (bufferSize <= 0x200000)
initialBufferSize = bufferSize;
*Handles = (PSYSTEM_HANDLE_INFORMATION_EX)buffer;
return status;
}
/**
* Opens a process.
*
* \param ProcessHandle A variable which receives a handle to the process.
* \param DesiredAccess The desired access to the process.
* \param ProcessId The ID of the process.
*
* \return An NTStatus indicating success or the error code.
*/
NTSTATUS PhOpenProcess(PHANDLE ProcessHandle, ACCESS_MASK DesiredAccess, HANDLE ProcessId)
{
NTSTATUS status = STATUS_SUCCESS;
OBJECT_ATTRIBUTES objectAttributes;
CLIENT_ID clientId;
if ((LONG_PTR)ProcessId == (LONG_PTR)GetCurrentProcessId()) {
*ProcessHandle = NtCurrentProcess();
return 0;
}
PF_INIT_OR_SET_STATUS(NtOpenProcess, Ntdll);
if (!NT_SUCCESS(status))
return status;
clientId.UniqueProcess = ProcessId;
clientId.UniqueThread = NULL;
InitializeObjectAttributes(&objectAttributes, NULL, 0, NULL, NULL);
status = pfNtOpenProcess(ProcessHandle, DesiredAccess, &objectAttributes, &clientId);
return status;
}
/**
* Query processes with open handles to a file, volume or disk.
*
* \param VolumeOrFileHandle The handle to the target.
* \param Information The returned list of processes.
*
* \return An NTStatus indicating success or the error code.
*/
NTSTATUS PhQueryProcessesUsingVolumeOrFile(HANDLE VolumeOrFileHandle,
PFILE_PROCESS_IDS_USING_FILE_INFORMATION *Information)
{
static ULONG initialBufferSize = 16 * KB;
NTSTATUS status = STATUS_SUCCESS;
PVOID buffer;
ULONG bufferSize;
IO_STATUS_BLOCK isb;
PF_INIT_OR_SET_STATUS(NtQueryInformationFile, NtDll);
if (!NT_SUCCESS(status))
return status;
bufferSize = initialBufferSize;
buffer = PhAllocate(bufferSize);
if (buffer == NULL)
return STATUS_INSUFFICIENT_RESOURCES;
while ((status = pfNtQueryInformationFile(VolumeOrFileHandle, &isb, buffer, bufferSize,
FileProcessIdsUsingFileInformation)) == STATUS_INFO_LENGTH_MISMATCH) {
PhFree(buffer);
bufferSize *= 2;
// Fail if we're resizing the buffer to something very large.
if (bufferSize > 64 * MB)
return STATUS_INSUFFICIENT_RESOURCES;
buffer = PhAllocate(bufferSize);
}
if (!NT_SUCCESS(status)) {
PhFree(buffer);
return status;
}
if (bufferSize <= 64 * MB)
initialBufferSize = bufferSize;
*Information = (PFILE_PROCESS_IDS_USING_FILE_INFORMATION)buffer;
return status;
}
/**
* Query the full commandline that was used to create a process.
* This can be helpful to differentiate between service instances (svchost.exe).
* Taken from: https://stackoverflow.com/a/14012919/1069307
*
* \param hProcess A handle to a process.
*
* \return A Unicode commandline string, or NULL on error.
* The returned string must be freed by the caller.
*/
static PWSTR GetProcessCommandLine(HANDLE hProcess)
{
PWSTR wcmdline = NULL;
BOOL wow;
DWORD pp_offset, cmd_offset;
NTSTATUS status = STATUS_SUCCESS;
SYSTEM_INFO si;
PBYTE peb = NULL, pp = NULL;
// Determine if 64 or 32-bit processor
GetNativeSystemInfo(&si);
if ((si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) || (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_ARM64)) {
pp_offset = 0x20;
cmd_offset = 0x70;
}
else {
pp_offset = 0x10;
cmd_offset = 0x40;
}
// PEB and Process Parameters (we only need the beginning of these structs)
peb = (PBYTE)calloc(pp_offset + 8, 1);
if (peb == NULL)
goto out;
pp = (PBYTE)calloc(cmd_offset + 16, 1);
if (pp == NULL)
goto out;
IsWow64Process(GetCurrentProcess(), &wow);
if (wow) {
// 32-bit process running on a 64-bit OS
PROCESS_BASIC_INFORMATION_WOW64 pbi = { 0 };
ULONGLONG params;
UNICODE_STRING_WOW64* ucmdline;
PF_INIT_OR_OUT(NtWow64QueryInformationProcess64, NtDll);
PF_INIT_OR_OUT(NtWow64ReadVirtualMemory64, NtDll);
status = pfNtWow64QueryInformationProcess64(hProcess, 0, &pbi, sizeof(pbi), NULL);
if (!NT_SUCCESS(status))
goto out;
status = pfNtWow64ReadVirtualMemory64(hProcess, pbi.PebBaseAddress, peb, pp_offset + 8, NULL);
if (!NT_SUCCESS(status))
goto out;
// Read Process Parameters from the 64-bit address space
params = (ULONGLONG)*((ULONGLONG*)(peb + pp_offset));
status = pfNtWow64ReadVirtualMemory64(hProcess, params, pp, cmd_offset + 16, NULL);
if (!NT_SUCCESS(status))
goto out;
ucmdline = (UNICODE_STRING_WOW64*)(pp + cmd_offset);
wcmdline = (PWSTR)calloc(ucmdline->Length + 1, sizeof(WCHAR));
if (wcmdline == NULL)
goto out;
status = pfNtWow64ReadVirtualMemory64(hProcess, ucmdline->Buffer, wcmdline, ucmdline->Length, NULL);
if (!NT_SUCCESS(status)) {
safe_free(wcmdline);
goto out;
}
}
else {
// 32-bit process on a 32-bit OS, or 64-bit process on a 64-bit OS
PROCESS_BASIC_INFORMATION pbi = { 0 };
PBYTE* params;
UNICODE_STRING* ucmdline;
PF_INIT_OR_OUT(NtQueryInformationProcess, NtDll);
status = pfNtQueryInformationProcess(hProcess, 0, &pbi, sizeof(pbi), NULL);
if (!NT_SUCCESS(status))
goto out;
// Read PEB
if (!ReadProcessMemory(hProcess, pbi.PebBaseAddress, peb, pp_offset + 8, NULL))
goto out;
// Read Process Parameters
params = (PBYTE*)*(LPVOID*)(peb + pp_offset);
if (!ReadProcessMemory(hProcess, params, pp, cmd_offset + 16, NULL))
goto out;
ucmdline = (UNICODE_STRING*)(pp + cmd_offset);
// In the absolute, someone could craft a process with dodgy attributes to try to cause an overflow
ucmdline->Length = min(ucmdline->Length, 512);
wcmdline = (PWSTR)calloc(ucmdline->Length + 1, sizeof(WCHAR));
if (!ReadProcessMemory(hProcess, ucmdline->Buffer, wcmdline, ucmdline->Length, NULL)) {
safe_free(wcmdline);
goto out;
}
}
out:
free(peb);
free(pp);
return wcmdline;
}
static int GetDevicePathName(PHY_DRIVE_INFO *pPhyDrive, WCHAR *wDevPath)
{
int i;
CHAR PhyDrive[128];
CHAR DevPath[MAX_PATH] = { 0 };
safe_sprintf(PhyDrive, "\\\\.\\PhysicalDrive%d", pPhyDrive->PhyDrive);
if (0 == QueryDosDeviceA(PhyDrive + 4, DevPath, sizeof(DevPath)))
{
Log("QueryDosDeviceA failed error:%u", GetLastError());
strcpy_s(DevPath, sizeof(DevPath), "???");
}
else
{
Log("QueryDosDeviceA success %s", DevPath);
}
for (i = 0; DevPath[i] && i < MAX_PATH; i++)
{
wDevPath[i] = DevPath[i];
}
return 0;
}
static __inline DWORD GetModuleFileNameExU(HANDLE hProcess, HMODULE hModule, char* lpFilename, DWORD nSize)
{
DWORD ret = 0, err = ERROR_INVALID_DATA;
// coverity[returned_null]
walloc(lpFilename, nSize);
ret = GetModuleFileNameExW(hProcess, hModule, wlpFilename, nSize);
err = GetLastError();
if ((ret != 0)
&& ((ret = wchar_to_utf8_no_alloc(wlpFilename, lpFilename, nSize)) == 0)) {
err = GetLastError();
}
wfree(lpFilename);
SetLastError(err);
return ret;
}
int FindProcessOccupyDisk(HANDLE hDrive, PHY_DRIVE_INFO *pPhyDrive)
{
WCHAR wDevPath[MAX_PATH] = { 0 };
const char *access_rights_str[8] = { "n", "r", "w", "rw", "x", "rx", "wx", "rwx" };
NTSTATUS status = STATUS_SUCCESS;
PSYSTEM_HANDLE_INFORMATION_EX handles = NULL;
POBJECT_NAME_INFORMATION buffer = NULL;
ULONG_PTR i;
ULONG_PTR pid[2];
ULONG_PTR last_access_denied_pid = 0;
ULONG bufferSize;
USHORT wHandleNameLen;
HANDLE dupHandle = NULL;
HANDLE processHandle = NULL;
BOOLEAN bFound = FALSE, bGotCmdLine, verbose = TRUE;
ULONG access_rights = 0;
DWORD size;
char cmdline[MAX_PATH] = { 0 };
wchar_t wexe_path[MAX_PATH], *wcmdline;
int cur_pid;
Log("FindProcessOccupyDisk for PhyDrive %d", pPhyDrive->PhyDrive);
GetDevicePathName(pPhyDrive, wDevPath);
_wHandleName = wDevPath;
PF_INIT_OR_SET_STATUS(NtQueryObject, Ntdll);
PF_INIT_OR_SET_STATUS(NtDuplicateObject, NtDll);
PF_INIT_OR_SET_STATUS(NtClose, NtDll);
if (NT_SUCCESS(status))
status = PhCreateHeap();
if (NT_SUCCESS(status))
status = PhEnumHandlesEx(&handles);
if (!NT_SUCCESS(status)) {
Log("Warning: Could not enumerate process handles: %s", NtStatusError(status));
goto out;
}
pid[0] = (ULONG_PTR)0;
cur_pid = 1;
wHandleNameLen = (USHORT)wcslen(_wHandleName);
bufferSize = 0x200;
buffer = PhAllocate(bufferSize);
if (buffer == NULL)
goto out;
for (i = 0;; i++) {
ULONG attempts = 8;
PSYSTEM_HANDLE_TABLE_ENTRY_INFO_EX handleInfo =
(i < handles->NumberOfHandles) ? &handles->Handles[i] : NULL;
if ((dupHandle != NULL) && (processHandle != NtCurrentProcess())) {
pfNtClose(dupHandle);
dupHandle = NULL;
}
// Update the current handle's process PID and compare against last
// Note: Be careful about not trying to overflow our list!
pid[cur_pid] = (handleInfo != NULL) ? handleInfo->UniqueProcessId : -1;
if (pid[0] != pid[1]) {
cur_pid = (cur_pid + 1) % 2;
// If we're switching process and found a match, print it
if (bFound) {
Log("* [%06u] %s (%s)", (UINT32)pid[cur_pid], cmdline, access_rights_str[access_rights & 0x7]);
bFound = FALSE;
access_rights = 0;
}
// Close the previous handle
if (processHandle != NULL) {
if (processHandle != NtCurrentProcess())
pfNtClose(processHandle);
processHandle = NULL;
}
}
// Exit loop condition
if (i >= handles->NumberOfHandles)
break;
// Don't bother with processes we can't access
if (handleInfo->UniqueProcessId == last_access_denied_pid)
continue;
// Filter out handles that aren't opened with Read (bit 0), Write (bit 1) or Execute (bit 5) access
if ((handleInfo->GrantedAccess & 0x23) == 0)
continue;
// Open the process to which the handle we are after belongs, if not already opened
if (pid[0] != pid[1]) {
status = PhOpenProcess(&processHandle, PROCESS_DUP_HANDLE | PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
(HANDLE)handleInfo->UniqueProcessId);
// There exists some processes we can't access
if (!NT_SUCCESS(status)) {
//Log("SearchProcess: Could not open process %ld: %s",
// handleInfo->UniqueProcessId, NtStatusError(status));
processHandle = NULL;
if (status == STATUS_ACCESS_DENIED) {
last_access_denied_pid = handleInfo->UniqueProcessId;
}
continue;
}
}
// Now duplicate this handle onto our own process, so that we can access its properties
if (processHandle == NtCurrentProcess()) {
continue;
}
else {
status = pfNtDuplicateObject(processHandle, (HANDLE)handleInfo->HandleValue,
NtCurrentProcess(), &dupHandle, 0, 0, 0);
if (!NT_SUCCESS(status))
continue;
}
// Filter non-storage handles. We're not interested in them and they make NtQueryObject() freeze
if (GetFileType(dupHandle) != FILE_TYPE_DISK)
continue;
// A loop is needed because the I/O subsystem likes to give us the wrong return lengths...
do {
ULONG returnSize;
// TODO: We might potentially still need a timeout on ObjectName queries, as PH does...
status = pfNtQueryObject(dupHandle, ObjectNameInformation, buffer, bufferSize, &returnSize);
if (status == STATUS_BUFFER_OVERFLOW || status == STATUS_INFO_LENGTH_MISMATCH ||
status == STATUS_BUFFER_TOO_SMALL) {
Log("SearchProcess: Realloc from %d to %d", bufferSize, returnSize);
bufferSize = returnSize;
PhFree(buffer);
buffer = PhAllocate(bufferSize);
}
else {
break;
}
} while (--attempts);
if (!NT_SUCCESS(status)) {
Log("SearchProcess: NtQueryObject failed for handle %X of process %ld: %s",
handleInfo->HandleValue, handleInfo->UniqueProcessId, NtStatusError(status));
continue;
}
// we are looking for a partial match and the current length is smaller
if (wHandleNameLen > buffer->Name.Length)
continue;
// Match against our target string
if (wcsncmp(_wHandleName, buffer->Name.Buffer, wHandleNameLen) != 0)
continue;
// If we are here, we have a process accessing our target!
bFound = TRUE;
// Keep a mask of all the access rights being used
access_rights |= handleInfo->GrantedAccess;
// The Executable bit is in a place we don't like => reposition it
if (access_rights & 0x20)
access_rights = (access_rights & 0x03) | 0x04;
// If this is the very first process we find, print a header
if (cmdline[0] == 0)
Log("WARNING: The following process(es) or service(s) are accessing %S:", _wHandleName);
// Where possible, try to get the full command line
bGotCmdLine = FALSE;
size = MAX_PATH;
wcmdline = GetProcessCommandLine(processHandle);
if (wcmdline != NULL) {
bGotCmdLine = TRUE;
wchar_to_utf8_no_alloc(wcmdline, cmdline, sizeof(cmdline));
free(wcmdline);
}
// If we couldn't get the full commandline, try to get the executable path
if (!bGotCmdLine)
bGotCmdLine = (GetModuleFileNameExU(processHandle, 0, cmdline, MAX_PATH - 1) != 0);
// The above may not work on Windows 7, so try QueryFullProcessImageName (Vista or later)
if (!bGotCmdLine) {
bGotCmdLine = QueryFullProcessImageNameW(processHandle, 0, wexe_path, &size);
if (bGotCmdLine)
wchar_to_utf8_no_alloc(wexe_path, cmdline, sizeof(cmdline));
}
// Still nothing? Try GetProcessImageFileName. Note that GetProcessImageFileName uses
// '\Device\Harddisk#\Partition#\' instead drive letters
if (!bGotCmdLine) {
bGotCmdLine = (GetProcessImageFileNameW(processHandle, wexe_path, MAX_PATH) != 0);
if (bGotCmdLine)
wchar_to_utf8_no_alloc(wexe_path, cmdline, sizeof(cmdline));
}
// Complete failure => Just craft a default process name that includes the PID
if (!bGotCmdLine) {
safe_sprintf(cmdline, "Unknown_Process_0x%llx", (ULONGLONG)handleInfo->UniqueProcessId);
}
}
out:
if (cmdline[0] != 0)
Log("You should close these applications before attempting to reformat the drive.");
else
Log("NOTE: Could not identify the process(es) or service(s) accessing %S", _wHandleName);
PhFree(buffer);
PhFree(handles);
PhDestroyHeap();
return 0;
}

View File

@@ -0,0 +1,405 @@
/*
* Rufus: The Reliable USB Formatting Utility
* Process search functionality
*
* Modified from Process Hacker:
* https://github.com/processhacker2/processhacker2/
* Copyright © 2017-2019 Pete Batard <pete@akeo.ie>
* Copyright © 2017 dmex
* Copyright © 2009-2016 wj32
* Copyright (c) 2020, longpanda <admin@ventoy.net>
*
* 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 <http://www.gnu.org/licenses/>.
*/
#include <windows.h>
#include <winnt.h>
#include <winternl.h>
#pragma once
#define PH_LARGE_BUFFER_SIZE (256 * 1024 * 1024)
#define STATUS_SUCCESS ((NTSTATUS)0x00000000L)
#define STATUS_ALREADY_COMPLETE ((NTSTATUS)0x000000FFL)
#define STATUS_UNSUCCESSFUL ((NTSTATUS)0x80000001L)
#define STATUS_BUFFER_OVERFLOW ((NTSTATUS)0x80000005L)
#define STATUS_NOT_IMPLEMENTED ((NTSTATUS)0xC0000002L)
#define STATUS_INFO_LENGTH_MISMATCH ((NTSTATUS)0xC0000004L)
//#define STATUS_INVALID_HANDLE ((NTSTATUS)0xC0000008L)
#define STATUS_ACCESS_DENIED ((NTSTATUS)0xC0000022L)
#define STATUS_BUFFER_TOO_SMALL ((NTSTATUS)0xC0000023L)
#define STATUS_OBJECT_TYPE_MISMATCH ((NTSTATUS)0xC0000024L)
#define STATUS_OBJECT_NAME_INVALID ((NTSTATUS)0xC0000033L)
#define STATUS_OBJECT_NAME_NOT_FOUND ((NTSTATUS)0xC0000034L)
#define STATUS_OBJECT_PATH_INVALID ((NTSTATUS)0xC0000039L)
#define STATUS_SHARING_VIOLATION ((NTSTATUS)0xC0000043L)
#define STATUS_INSUFFICIENT_RESOURCES ((NTSTATUS)0xC000009AL)
#define STATUS_NOT_SUPPORTED ((NTSTATUS)0xC00000BBL)
#define SystemExtendedHandleInformation 64
#define FileProcessIdsUsingFileInformation 47
// MinGW doesn't know this one yet
#if !defined(PROCESSOR_ARCHITECTURE_ARM64)
#define PROCESSOR_ARCHITECTURE_ARM64 12
#endif
#define NtCurrentProcess() ((HANDLE)(LONG_PTR)-1)
typedef struct _SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX
{
PVOID Object;
ULONG_PTR UniqueProcessId;
ULONG_PTR HandleValue;
ULONG GrantedAccess;
USHORT CreatorBackTraceIndex;
USHORT ObjectTypeIndex;
ULONG HandleAttributes;
ULONG Reserved;
} SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX, *PSYSTEM_HANDLE_TABLE_ENTRY_INFO_EX;
typedef struct _SYSTEM_HANDLE_INFORMATION_EX
{
ULONG_PTR NumberOfHandles;
ULONG_PTR Reserved;
SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX Handles[1];
} SYSTEM_HANDLE_INFORMATION_EX, *PSYSTEM_HANDLE_INFORMATION_EX;
#if defined(_MSC_VER)
typedef struct _OBJECT_NAME_INFORMATION
{
UNICODE_STRING Name;
} OBJECT_NAME_INFORMATION, *POBJECT_NAME_INFORMATION;
typedef struct _OBJECT_TYPE_INFORMATION
{
UNICODE_STRING TypeName;
ULONG TotalNumberOfObjects;
ULONG TotalNumberOfHandles;
ULONG TotalPagedPoolUsage;
ULONG TotalNonPagedPoolUsage;
ULONG TotalNamePoolUsage;
ULONG TotalHandleTableUsage;
ULONG HighWaterNumberOfObjects;
ULONG HighWaterNumberOfHandles;
ULONG HighWaterPagedPoolUsage;
ULONG HighWaterNonPagedPoolUsage;
ULONG HighWaterNamePoolUsage;
ULONG HighWaterHandleTableUsage;
ULONG InvalidAttributes;
GENERIC_MAPPING GenericMapping;
ULONG ValidAccessMask;
BOOLEAN SecurityRequired;
BOOLEAN MaintainHandleCount;
UCHAR TypeIndex; // since WINBLUE
CHAR ReservedByte;
ULONG PoolType;
ULONG DefaultPagedPoolCharge;
ULONG DefaultNonPagedPoolCharge;
} OBJECT_TYPE_INFORMATION, *POBJECT_TYPE_INFORMATION;
#define ObjectNameInformation 1
#endif
#define ObjectTypesInformation 3
typedef struct _OBJECT_TYPES_INFORMATION
{
ULONG NumberOfTypes;
} OBJECT_TYPES_INFORMATION, *POBJECT_TYPES_INFORMATION;
typedef struct _PROCESS_BASIC_INFORMATION_WOW64
{
PVOID Reserved1[2];
// MinGW32 screws us with a sizeof(PVOID64) of 4 instead of 8 => Use ULONGLONG instead
ULONGLONG PebBaseAddress;
PVOID Reserved2[4];
ULONG_PTR UniqueProcessId[2];
PVOID Reserved3[2];
} PROCESS_BASIC_INFORMATION_WOW64;
typedef struct _UNICODE_STRING_WOW64
{
USHORT Length;
USHORT MaximumLength;
ULONGLONG Buffer;
} UNICODE_STRING_WOW64;
typedef struct _FILE_PROCESS_IDS_USING_FILE_INFORMATION
{
ULONG NumberOfProcessIdsInList;
ULONG_PTR ProcessIdList[1];
} FILE_PROCESS_IDS_USING_FILE_INFORMATION, *PFILE_PROCESS_IDS_USING_FILE_INFORMATION;
#define ALIGN_UP_BY(Address, Align) (((ULONG_PTR)(Address) + (Align) - 1) & ~((Align) - 1))
#define ALIGN_UP(Address, Type) ALIGN_UP_BY(Address, sizeof(Type))
#define PH_FIRST_OBJECT_TYPE(ObjectTypes) \
(POBJECT_TYPE_INFORMATION)((PCHAR)(ObjectTypes)+ALIGN_UP(sizeof(OBJECT_TYPES_INFORMATION), ULONG_PTR))
#define PH_NEXT_OBJECT_TYPE(ObjectType) \
(POBJECT_TYPE_INFORMATION)((PCHAR)(ObjectType)+sizeof(OBJECT_TYPE_INFORMATION)+\
ALIGN_UP(ObjectType->TypeName.MaximumLength, ULONG_PTR))
// Heaps
typedef struct _RTL_HEAP_ENTRY
{
SIZE_T Size;
USHORT Flags;
USHORT AllocatorBackTraceIndex;
union
{
struct
{
SIZE_T Settable;
ULONG Tag;
} s1;
struct
{
SIZE_T CommittedSize;
PVOID FirstBlock;
} s2;
} u;
} RTL_HEAP_ENTRY, *PRTL_HEAP_ENTRY;
#define RTL_HEAP_BUSY (USHORT)0x0001
#define RTL_HEAP_SEGMENT (USHORT)0x0002
#define RTL_HEAP_SETTABLE_VALUE (USHORT)0x0010
#define RTL_HEAP_SETTABLE_FLAG1 (USHORT)0x0020
#define RTL_HEAP_SETTABLE_FLAG2 (USHORT)0x0040
#define RTL_HEAP_SETTABLE_FLAG3 (USHORT)0x0080
#define RTL_HEAP_SETTABLE_FLAGS (USHORT)0x00e0
#define RTL_HEAP_UNCOMMITTED_RANGE (USHORT)0x0100
#define RTL_HEAP_PROTECTED_ENTRY (USHORT)0x0200
typedef struct _RTL_HEAP_TAG
{
ULONG NumberOfAllocations;
ULONG NumberOfFrees;
SIZE_T BytesAllocated;
USHORT TagIndex;
USHORT CreatorBackTraceIndex;
WCHAR TagName[24];
} RTL_HEAP_TAG, *PRTL_HEAP_TAG;
typedef struct _RTL_HEAP_INFORMATION
{
PVOID BaseAddress;
ULONG Flags;
USHORT EntryOverhead;
USHORT CreatorBackTraceIndex;
SIZE_T BytesAllocated;
SIZE_T BytesCommitted;
ULONG NumberOfTags;
ULONG NumberOfEntries;
ULONG NumberOfPseudoTags;
ULONG PseudoTagGranularity;
ULONG Reserved[5];
PRTL_HEAP_TAG Tags;
PRTL_HEAP_ENTRY Entries;
} RTL_HEAP_INFORMATION, *PRTL_HEAP_INFORMATION;
typedef struct _RTL_PROCESS_HEAPS
{
ULONG NumberOfHeaps;
RTL_HEAP_INFORMATION Heaps[1];
} RTL_PROCESS_HEAPS, *PRTL_PROCESS_HEAPS;
typedef NTSTATUS(NTAPI *PRTL_HEAP_COMMIT_ROUTINE)(
_In_ PVOID Base,
_Inout_ PVOID *CommitAddress,
_Inout_ PSIZE_T CommitSize
);
#if defined(_MSC_VER)
typedef struct _RTL_HEAP_PARAMETERS
{
ULONG Length;
SIZE_T SegmentReserve;
SIZE_T SegmentCommit;
SIZE_T DeCommitFreeBlockThreshold;
SIZE_T DeCommitTotalFreeThreshold;
SIZE_T MaximumAllocationSize;
SIZE_T VirtualMemoryThreshold;
SIZE_T InitialCommit;
SIZE_T InitialReserve;
PRTL_HEAP_COMMIT_ROUTINE CommitRoutine;
SIZE_T Reserved[2];
} RTL_HEAP_PARAMETERS, *PRTL_HEAP_PARAMETERS;
#endif
#define HEAP_SETTABLE_USER_VALUE 0x00000100
#define HEAP_SETTABLE_USER_FLAG1 0x00000200
#define HEAP_SETTABLE_USER_FLAG2 0x00000400
#define HEAP_SETTABLE_USER_FLAG3 0x00000800
#define HEAP_SETTABLE_USER_FLAGS 0x00000e00
#define HEAP_CLASS_0 0x00000000 // Process heap
#define HEAP_CLASS_1 0x00001000 // Private heap
#define HEAP_CLASS_2 0x00002000 // Kernel heap
#define HEAP_CLASS_3 0x00003000 // GDI heap
#define HEAP_CLASS_4 0x00004000 // User heap
#define HEAP_CLASS_5 0x00005000 // Console heap
#define HEAP_CLASS_6 0x00006000 // User desktop heap
#define HEAP_CLASS_7 0x00007000 // CSR shared heap
#define HEAP_CLASS_8 0x00008000 // CSR port heap
#define HEAP_CLASS_MASK 0x0000f000
// Privileges
#define SE_MIN_WELL_KNOWN_PRIVILEGE (2L)
#define SE_CREATE_TOKEN_PRIVILEGE (2L)
#define SE_ASSIGNPRIMARYTOKEN_PRIVILEGE (3L)
#define SE_LOCK_MEMORY_PRIVILEGE (4L)
#define SE_INCREASE_QUOTA_PRIVILEGE (5L)
#define SE_MACHINE_ACCOUNT_PRIVILEGE (6L)
#define SE_TCB_PRIVILEGE (7L)
#define SE_SECURITY_PRIVILEGE (8L)
#define SE_TAKE_OWNERSHIP_PRIVILEGE (9L)
#define SE_LOAD_DRIVER_PRIVILEGE (10L)
#define SE_SYSTEM_PROFILE_PRIVILEGE (11L)
#define SE_SYSTEMTIME_PRIVILEGE (12L)
#define SE_PROF_SINGLE_PROCESS_PRIVILEGE (13L)
#define SE_INC_BASE_PRIORITY_PRIVILEGE (14L)
#define SE_CREATE_PAGEFILE_PRIVILEGE (15L)
#define SE_CREATE_PERMANENT_PRIVILEGE (16L)
#define SE_BACKUP_PRIVILEGE (17L)
#define SE_RESTORE_PRIVILEGE (18L)
#define SE_SHUTDOWN_PRIVILEGE (19L)
#define SE_DEBUG_PRIVILEGE (20L)
#define SE_AUDIT_PRIVILEGE (21L)
#define SE_SYSTEM_ENVIRONMENT_PRIVILEGE (22L)
#define SE_CHANGE_NOTIFY_PRIVILEGE (23L)
#define SE_REMOTE_SHUTDOWN_PRIVILEGE (24L)
#define SE_UNDOCK_PRIVILEGE (25L)
#define SE_SYNC_AGENT_PRIVILEGE (26L)
#define SE_ENABLE_DELEGATION_PRIVILEGE (27L)
#define SE_MANAGE_VOLUME_PRIVILEGE (28L)
#define SE_IMPERSONATE_PRIVILEGE (29L)
#define SE_CREATE_GLOBAL_PRIVILEGE (30L)
#define SE_TRUSTED_CREDMAN_ACCESS_PRIVILEGE (31L)
#define SE_RELABEL_PRIVILEGE (32L)
#define SE_INC_WORKING_SET_PRIVILEGE (33L)
#define SE_TIME_ZONE_PRIVILEGE (34L)
#define SE_CREATE_SYMBOLIC_LINK_PRIVILEGE (35L)
#define SE_MAX_WELL_KNOWN_PRIVILEGE SE_CREATE_SYMBOLIC_LINK_PRIVILEGE
/*
* typedefs for the function prototypes. Use the something like:
* PF_DECL(FormatEx);
* which translates to:
* FormatEx_t pfFormatEx = NULL;
* in your code, to declare the entrypoint and then use:
* PF_INIT(FormatEx, Fmifs);
* which translates to:
* pfFormatEx = (FormatEx_t) GetProcAddress(GetDLLHandle("fmifs"), "FormatEx");
* to make it accessible.
*/
#define MAX_LIBRARY_HANDLES 32
extern HMODULE OpenedLibrariesHandle[MAX_LIBRARY_HANDLES];
extern UINT16 OpenedLibrariesHandleSize;
#define OPENED_LIBRARIES_VARS HMODULE OpenedLibrariesHandle[MAX_LIBRARY_HANDLES]; UINT16 OpenedLibrariesHandleSize = 0
#define CLOSE_OPENED_LIBRARIES while(OpenedLibrariesHandleSize > 0) FreeLibrary(OpenedLibrariesHandle[--OpenedLibrariesHandleSize])
static __inline HMODULE GetLibraryHandle(char* szLibraryName) {
HMODULE h = NULL;
if ((h = GetModuleHandleA(szLibraryName)) == NULL) {
if (OpenedLibrariesHandleSize >= MAX_LIBRARY_HANDLES) {
Log("Error: MAX_LIBRARY_HANDLES is too small\n");
}
else {
h = LoadLibraryA(szLibraryName);
if (h != NULL)
OpenedLibrariesHandle[OpenedLibrariesHandleSize++] = h;
}
}
return h;
}
#define PF_TYPE(api, ret, proc, args) typedef ret (api *proc##_t)args
#define PF_DECL(proc) static proc##_t pf##proc = NULL
#define PF_TYPE_DECL(api, ret, proc, args) PF_TYPE(api, ret, proc, args); PF_DECL(proc)
#define PF_INIT(proc, name) if (pf##proc == NULL) pf##proc = \
(proc##_t) GetProcAddress(GetLibraryHandle(#name), #proc)
#define PF_INIT_OR_OUT(proc, name) do {PF_INIT(proc, name); \
if (pf##proc == NULL) { Log("Unable to locate %s() in %s.dll: %d\n", \
#proc, #name, GetLastError()); goto out;} } while (0)
#define PF_INIT_OR_SET_STATUS(proc, name) do {PF_INIT(proc, name); \
if ((pf##proc == NULL) && (NT_SUCCESS(status))) status = STATUS_NOT_IMPLEMENTED; \
} while (0)
/* Custom application errors */
#define FAC(f) ((f)<<16)
#define APPERR(err) (APPLICATION_ERROR_MASK|(err))
#define ERROR_INCOMPATIBLE_FS 0x1201
#define ERROR_CANT_QUICK_FORMAT 0x1202
#define ERROR_INVALID_CLUSTER_SIZE 0x1203
#define ERROR_INVALID_VOLUME_SIZE 0x1204
#define ERROR_CANT_START_THREAD 0x1205
#define ERROR_BADBLOCKS_FAILURE 0x1206
#define ERROR_ISO_SCAN 0x1207
#define ERROR_ISO_EXTRACT 0x1208
#define ERROR_CANT_REMOUNT_VOLUME 0x1209
#define ERROR_CANT_PATCH 0x120A
#define ERROR_CANT_ASSIGN_LETTER 0x120B
#define ERROR_CANT_MOUNT_VOLUME 0x120C
#define ERROR_BAD_SIGNATURE 0x120D
#define ERROR_CANT_DOWNLOAD 0x120E
#define KB 1024LL
#define MB 1048576LL
#define GB 1073741824LL
#define TB 1099511627776LL
typedef struct _CLIENT_ID {
HANDLE UniqueProcess;
HANDLE UniqueThread;
} CLIENT_ID;
PF_TYPE_DECL(NTAPI, PVOID, RtlCreateHeap, (ULONG, PVOID, SIZE_T, SIZE_T, PVOID, PRTL_HEAP_PARAMETERS));
PF_TYPE_DECL(NTAPI, PVOID, RtlDestroyHeap, (PVOID));
PF_TYPE_DECL(NTAPI, PVOID, RtlAllocateHeap, (PVOID, ULONG, SIZE_T));
PF_TYPE_DECL(NTAPI, BOOLEAN, RtlFreeHeap, (PVOID, ULONG, PVOID));
PF_TYPE_DECL(NTAPI, NTSTATUS, NtQuerySystemInformation, (SYSTEM_INFORMATION_CLASS, PVOID, ULONG, PULONG));
PF_TYPE_DECL(NTAPI, NTSTATUS, NtQueryInformationFile, (HANDLE, PIO_STATUS_BLOCK, PVOID, ULONG, FILE_INFORMATION_CLASS));
PF_TYPE_DECL(NTAPI, NTSTATUS, NtQueryInformationProcess, (HANDLE, PROCESSINFOCLASS, PVOID, ULONG, PULONG));
PF_TYPE_DECL(NTAPI, NTSTATUS, NtWow64QueryInformationProcess64, (HANDLE, ULONG, PVOID, ULONG, PULONG));
PF_TYPE_DECL(NTAPI, NTSTATUS, NtWow64ReadVirtualMemory64, (HANDLE, ULONGLONG, PVOID, ULONG64, PULONG64));
PF_TYPE_DECL(NTAPI, NTSTATUS, NtQueryObject, (HANDLE, OBJECT_INFORMATION_CLASS, PVOID, ULONG, PULONG));
PF_TYPE_DECL(NTAPI, NTSTATUS, NtDuplicateObject, (HANDLE, HANDLE, HANDLE, PHANDLE, ACCESS_MASK, ULONG, ULONG));
PF_TYPE_DECL(NTAPI, NTSTATUS, NtOpenProcess, (PHANDLE, ACCESS_MASK, POBJECT_ATTRIBUTES, CLIENT_ID*));
PF_TYPE_DECL(NTAPI, NTSTATUS, NtOpenProcessToken, (HANDLE, ACCESS_MASK, PHANDLE));
PF_TYPE_DECL(NTAPI, NTSTATUS, NtAdjustPrivilegesToken, (HANDLE, BOOLEAN, PTOKEN_PRIVILEGES, ULONG, PTOKEN_PRIVILEGES, PULONG));
PF_TYPE_DECL(NTAPI, NTSTATUS, NtClose, (HANDLE));
#define safe_free(p) do {free((void*)p); p = NULL;} while(0)
#define wchar_to_utf8_no_alloc(wsrc, dest, dest_size) \
WideCharToMultiByte(CP_UTF8, 0, wsrc, -1, dest, dest_size, NULL, NULL)
#define utf8_to_wchar_no_alloc(src, wdest, wdest_size) \
MultiByteToWideChar(CP_UTF8, 0, src, -1, wdest, wdest_size)
#define sfree(p) do {if (p != NULL) {free((void*)(p)); p = NULL;}} while(0)
#define wconvert(p) wchar_t* w ## p = utf8_to_wchar(p)
#define walloc(p, size) wchar_t* w ## p = (p == NULL)?NULL:(wchar_t*)calloc(size, sizeof(wchar_t))
#define wfree(p) sfree(w ## p)

Binary file not shown.

19
vtoygpt/build.sh Normal file
View File

@@ -0,0 +1,19 @@
#!/bin/bash
rm -f vtoytool/00/*
/opt/diet64/bin/diet -Os gcc -D_FILE_OFFSET_BITS=64 vtoygpt.c crc32.c -o vtoygpt_64
/opt/diet32/bin/diet -Os gcc -D_FILE_OFFSET_BITS=64 -m32 vtoygpt.c crc32.c -o vtoygpt_32
#gcc -D_FILE_OFFSET_BITS=64 -static -Wall vtoygpt.c -o vtoytool_64
#gcc -D_FILE_OFFSET_BITS=64 -Wall -m32 vtoygpt.c -o vtoytool_32
if [ -e vtoygpt_64 ] && [ -e vtoygpt_32 ]; then
echo -e '\n############### SUCCESS ###############\n'
mv vtoygpt_64 ../INSTALL/tool/
mv vtoygpt_32 ../INSTALL/tool/
else
echo -e '\n############### FAILED ################\n'
exit 1
fi

315
vtoygpt/crc32.c Normal file
View File

@@ -0,0 +1,315 @@
/******************************************************************************
* vtoygpt.c ---- ventoy gpt util
*
* Copyright (c) 2020, longpanda <admin@ventoy.net>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <linux/fs.h>
#include <dirent.h>
#define VOID void
#define CHAR char
#define UINT64 unsigned long long
#define UINT32 unsigned int
#define UINT16 unsigned short
#define CHAR16 unsigned short
#define UINT8 unsigned char
UINT32 g_crc_table[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 VtoyCrc32(VOID *Buffer, UINT32 Length)
{
UINT32 i;
UINT8 *Ptr = Buffer;
UINT32 Crc = 0xFFFFFFFF;
for (i = 0; i < Length; i++, Ptr++)
{
Crc = (Crc >> 8) ^ g_crc_table[(UINT8) Crc ^ *Ptr];
}
return Crc ^ 0xffffffff;
}

320
vtoygpt/vtoygpt.c Normal file
View File

@@ -0,0 +1,320 @@
/******************************************************************************
* vtoygpt.c ---- ventoy gpt util
*
* Copyright (c) 2020, longpanda <admin@ventoy.net>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <linux/fs.h>
#include <dirent.h>
#define VOID void
#define CHAR char
#define UINT64 unsigned long long
#define UINT32 unsigned int
#define UINT16 unsigned short
#define CHAR16 unsigned short
#define UINT8 unsigned char
UINT32 VtoyCrc32(VOID *Buffer, UINT32 Length);
#define COMPILE_ASSERT(expr) extern char __compile_assert[(expr) ? 1 : -1]
#pragma pack(1)
typedef struct PART_TABLE
{
UINT8 Active;
UINT8 StartHead;
UINT16 StartSector : 6;
UINT16 StartCylinder : 10;
UINT8 FsFlag;
UINT8 EndHead;
UINT16 EndSector : 6;
UINT16 EndCylinder : 10;
UINT32 StartSectorId;
UINT32 SectorCount;
}PART_TABLE;
typedef struct MBR_HEAD
{
UINT8 BootCode[446];
PART_TABLE PartTbl[4];
UINT8 Byte55;
UINT8 ByteAA;
}MBR_HEAD;
typedef struct GUID
{
UINT32 data1;
UINT16 data2;
UINT16 data3;
UINT8 data4[8];
}GUID;
typedef struct VTOY_GPT_HDR
{
CHAR Signature[8]; /* EFI PART */
UINT8 Version[4];
UINT32 Length;
UINT32 Crc;
UINT8 Reserved1[4];
UINT64 EfiStartLBA;
UINT64 EfiBackupLBA;
UINT64 PartAreaStartLBA;
UINT64 PartAreaEndLBA;
GUID DiskGuid;
UINT64 PartTblStartLBA;
UINT32 PartTblTotNum;
UINT32 PartTblEntryLen;
UINT32 PartTblCrc;
UINT8 Reserved2[420];
}VTOY_GPT_HDR;
COMPILE_ASSERT(sizeof(VTOY_GPT_HDR) == 512);
typedef struct VTOY_GPT_PART_TBL
{
GUID PartType;
GUID PartGuid;
UINT64 StartLBA;
UINT64 LastLBA;
UINT64 Attr;
CHAR16 Name[36];
}VTOY_GPT_PART_TBL;
COMPILE_ASSERT(sizeof(VTOY_GPT_PART_TBL) == 128);
typedef struct VTOY_GPT_INFO
{
MBR_HEAD MBR;
VTOY_GPT_HDR Head;
VTOY_GPT_PART_TBL PartTbl[128];
}VTOY_GPT_INFO;
typedef struct VTOY_BK_GPT_INFO
{
VTOY_GPT_PART_TBL PartTbl[128];
VTOY_GPT_HDR Head;
}VTOY_BK_GPT_INFO;
COMPILE_ASSERT(sizeof(VTOY_GPT_INFO) == 512 * 34);
COMPILE_ASSERT(sizeof(VTOY_BK_GPT_INFO) == 512 * 33);
#pragma pack()
void DumpGuid(const char *prefix, GUID *guid)
{
printf("%s: %08x-%04x-%04x-%02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x\n",
prefix,
guid->data1, guid->data2, guid->data3,
guid->data4[0], guid->data4[1], guid->data4[2], guid->data4[3],
guid->data4[4], guid->data4[5], guid->data4[6], guid->data4[7]
);
}
void DumpHead(VTOY_GPT_HDR *pHead)
{
UINT32 CrcRead;
UINT32 CrcCalc;
printf("Signature:<%s>\n", pHead->Signature);
printf("Version:<%02x %02x %02x %02x>\n", pHead->Version[0], pHead->Version[1], pHead->Version[2], pHead->Version[3]);
printf("Length:%u\n", pHead->Length);
printf("Crc:0x%08x\n", pHead->Crc);
printf("EfiStartLBA:%lu\n", pHead->EfiStartLBA);
printf("EfiBackupLBA:%lu\n", pHead->EfiBackupLBA);
printf("PartAreaStartLBA:%lu\n", pHead->PartAreaStartLBA);
printf("PartAreaEndLBA:%lu\n", pHead->PartAreaEndLBA);
DumpGuid("DiskGuid", &pHead->DiskGuid);
printf("PartTblStartLBA:%lu\n", pHead->PartTblStartLBA);
printf("PartTblTotNum:%u\n", pHead->PartTblTotNum);
printf("PartTblEntryLen:%u\n", pHead->PartTblEntryLen);
printf("PartTblCrc:0x%08x\n", pHead->PartTblCrc);
CrcRead = pHead->Crc;
pHead->Crc = 0;
CrcCalc = VtoyCrc32(pHead, pHead->Length);
if (CrcCalc != CrcRead)
{
printf("Head CRC Check Failed\n");
}
else
{
printf("Head CRC Check SUCCESS [%x] [%x]\n", CrcCalc, CrcRead);
}
CrcRead = pHead->PartTblCrc;
CrcCalc = VtoyCrc32(pHead + 1, pHead->PartTblEntryLen * pHead->PartTblTotNum);
if (CrcCalc != CrcRead)
{
printf("Part Table CRC Check Failed\n");
}
else
{
printf("Part Table CRC Check SUCCESS [%x] [%x]\n", CrcCalc, CrcRead);
}
}
void DumpPartTable(VTOY_GPT_PART_TBL *Tbl)
{
int i;
DumpGuid("PartType", &Tbl->PartType);
DumpGuid("PartGuid", &Tbl->PartGuid);
printf("StartLBA:%lu\n", Tbl->StartLBA);
printf("LastLBA:%lu\n", Tbl->LastLBA);
printf("Attr:0x%lx\n", Tbl->Attr);
printf("Name:");
for (i = 0; i < 36 && Tbl->Name[i]; i++)
{
printf("%c", (CHAR)(Tbl->Name[i]));
}
printf("\n");
}
void DumpMBR(MBR_HEAD *pMBR)
{
int i;
for (i = 0; i < 4; i++)
{
printf("=========== Partition Table %d ============\n", i + 1);
printf("PartTbl.Active = 0x%x\n", pMBR->PartTbl[i].Active);
printf("PartTbl.FsFlag = 0x%x\n", pMBR->PartTbl[i].FsFlag);
printf("PartTbl.StartSectorId = %u\n", pMBR->PartTbl[i].StartSectorId);
printf("PartTbl.SectorCount = %u\n", pMBR->PartTbl[i].SectorCount);
printf("PartTbl.StartHead = %u\n", pMBR->PartTbl[i].StartHead);
printf("PartTbl.StartSector = %u\n", pMBR->PartTbl[i].StartSector);
printf("PartTbl.StartCylinder = %u\n", pMBR->PartTbl[i].StartCylinder);
printf("PartTbl.EndHead = %u\n", pMBR->PartTbl[i].EndHead);
printf("PartTbl.EndSector = %u\n", pMBR->PartTbl[i].EndSector);
printf("PartTbl.EndCylinder = %u\n", pMBR->PartTbl[i].EndCylinder);
}
}
int DumpGptInfo(VTOY_GPT_INFO *pGptInfo)
{
int i;
DumpMBR(&pGptInfo->MBR);
DumpHead(&pGptInfo->Head);
for (i = 0; i < 128; i++)
{
if (pGptInfo->PartTbl[i].StartLBA == 0)
{
break;
}
printf("=====Part %d=====\n", i);
DumpPartTable(pGptInfo->PartTbl + i);
}
return 0;
}
#define VENTOY_EFI_PART_ATTR 0xC000000000000001ULL
int main(int argc, const char **argv)
{
int i;
int fd;
UINT64 DiskSize;
CHAR16 *Name = NULL;
VTOY_GPT_INFO *pMainGptInfo = NULL;
VTOY_BK_GPT_INFO *pBackGptInfo = NULL;
if (argc != 3)
{
printf("usage: vtoygpt -f /dev/sdb\n");
return 1;
}
fd = open(argv[2], O_RDWR);
if (fd < 0)
{
printf("Failed to open %s\n", argv[2]);
return 1;
}
pMainGptInfo = malloc(sizeof(VTOY_GPT_INFO));
pBackGptInfo = malloc(sizeof(VTOY_BK_GPT_INFO));
if (NULL == pMainGptInfo || NULL == pBackGptInfo)
{
close(fd);
return 1;
}
read(fd, pMainGptInfo, sizeof(VTOY_GPT_INFO));
if (argv[1][0] == '-' && argv[1][1] == 'd')
{
DumpGptInfo(pMainGptInfo);
}
else
{
DiskSize = lseek(fd, 0, SEEK_END);
lseek(fd, DiskSize - 33 * 512, SEEK_SET);
read(fd, pBackGptInfo, sizeof(VTOY_BK_GPT_INFO));
Name = pMainGptInfo->PartTbl[1].Name;
if (Name[0] == 'V' && Name[1] == 'T' && Name[2] == 'O' && Name[3] == 'Y')
{
pMainGptInfo->PartTbl[1].Attr = VENTOY_EFI_PART_ATTR;
pMainGptInfo->Head.PartTblCrc = VtoyCrc32(pMainGptInfo->PartTbl, sizeof(pMainGptInfo->PartTbl));
pMainGptInfo->Head.Crc = 0;
pMainGptInfo->Head.Crc = VtoyCrc32(&pMainGptInfo->Head, pMainGptInfo->Head.Length);
pBackGptInfo->PartTbl[1].Attr = VENTOY_EFI_PART_ATTR;
pBackGptInfo->Head.PartTblCrc = VtoyCrc32(pBackGptInfo->PartTbl, sizeof(pBackGptInfo->PartTbl));
pBackGptInfo->Head.Crc = 0;
pBackGptInfo->Head.Crc = VtoyCrc32(&pBackGptInfo->Head, pBackGptInfo->Head.Length);
lseek(fd, 512, SEEK_SET);
write(fd, (UINT8 *)pMainGptInfo + 512, sizeof(VTOY_GPT_INFO) - 512);
lseek(fd, DiskSize - 33 * 512, SEEK_SET);
write(fd, pBackGptInfo, sizeof(VTOY_BK_GPT_INFO));
fsync(fd);
}
}
free(pMainGptInfo);
free(pBackGptInfo);
close(fd);
return 0;
}