@@ -309,19 +309,20 @@ namespace
309309 return nt_headers->FileHeader .Machine == IMAGE_FILE_MACHINE_AMD64;
310310 }
311311
312- void relocate_for_base (std::uint8_t * local_image, const std::uintptr_t target_base)
312+ [[nodiscard]]
313+ bool relocate_for_base (std::uint8_t * local_image, const std::uintptr_t target_base)
313314 {
314315 const auto * dos_headers = reinterpret_cast <IMAGE_DOS_HEADER*>(local_image);
315316 auto * nt_headers = reinterpret_cast <IMAGE_NT_HEADERS*>(local_image + dos_headers->e_lfanew );
316317
317318 const auto delta = static_cast <std::intptr_t >(target_base - nt_headers->OptionalHeader .ImageBase );
318319 if (delta == 0 )
319- return ;
320+ return true ;
320321
321322 // ReSharper disable once CppUseStructuredBinding
322323 const auto & relocation_directory = nt_headers->OptionalHeader .DataDirectory [IMAGE_DIRECTORY_ENTRY_BASERELOC];
323324 if (!relocation_directory.Size )
324- return ;
325+ return false ;
325326
326327 auto * block = reinterpret_cast <IMAGE_BASE_RELOCATION*>(local_image + relocation_directory.VirtualAddress );
327328 while (block->SizeOfBlock && block->VirtualAddress )
@@ -339,6 +340,7 @@ namespace
339340 }
340341
341342 nt_headers->OptionalHeader .ImageBase = target_base;
343+ return true ;
342344 }
343345 [[nodiscard]]
344346 std::optional<std::uintptr_t > get_process_id_by_name (const std::string_view& process_name)
@@ -415,7 +417,12 @@ namespace yail
415417 }
416418
417419 // Relocate for remote base address
418- relocate_for_base (local_image.data (), reinterpret_cast <std::uintptr_t >(remote_image));
420+ if (!relocate_for_base (local_image.data (), reinterpret_cast <std::uintptr_t >(remote_image)))
421+ {
422+ VirtualFreeEx (process_handle, remote_image, 0 , MEM_RELEASE);
423+ CloseHandle (process_handle);
424+ return std::unexpected (" Image requires relocation but has no relocation directory" );
425+ }
419426
420427 // Write image to target
421428 if (!WriteProcessMemory (process_handle, remote_image, local_image.data (), image_size, nullptr ))
0 commit comments