Host.c 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278
  1. /*++ @file
  2. Copyright (c) 2006 - 2022, Intel Corporation. All rights reserved.<BR>
  3. Portions copyright (c) 2008 - 2011, Apple Inc. All rights reserved.<BR>
  4. SPDX-License-Identifier: BSD-2-Clause-Patent
  5. **/
  6. #include "Host.h"
  7. #ifdef __APPLE__
  8. #define MAP_ANONYMOUS MAP_ANON
  9. #endif
  10. //
  11. // Globals
  12. //
  13. EMU_THUNK_PPI mSecEmuThunkPpi = {
  14. GasketSecUnixPeiAutoScan,
  15. GasketSecUnixFdAddress,
  16. GasketSecEmuThunkAddress
  17. };
  18. char *gGdbWorkingFileName = NULL;
  19. unsigned int mScriptSymbolChangesCount = 0;
  20. //
  21. // Default information about where the FD is located.
  22. // This array gets filled in with information from EFI_FIRMWARE_VOLUMES
  23. // EFI_FIRMWARE_VOLUMES is a host environment variable set by system.cmd.
  24. // The number of array elements is allocated base on parsing
  25. // EFI_FIRMWARE_VOLUMES and the memory is never freed.
  26. //
  27. UINTN gFdInfoCount = 0;
  28. EMU_FD_INFO *gFdInfo;
  29. //
  30. // Array that supports separate memory ranges.
  31. // The memory ranges are set in system.cmd via the EFI_MEMORY_SIZE variable.
  32. // The number of array elements is allocated base on parsing
  33. // EFI_MEMORY_SIZE and the memory is never freed.
  34. //
  35. UINTN gSystemMemoryCount = 0;
  36. EMU_SYSTEM_MEMORY *gSystemMemory;
  37. UINTN mImageContextModHandleArraySize = 0;
  38. IMAGE_CONTEXT_TO_MOD_HANDLE *mImageContextModHandleArray = NULL;
  39. EFI_PEI_PPI_DESCRIPTOR *gPpiList;
  40. int gInXcode = 0;
  41. /*++
  42. Breakpoint target for Xcode project. Set in the Xcode XML
  43. Xcode breakpoint will 'source Host.gdb'
  44. gGdbWorkingFileName is set to Host.gdb
  45. **/
  46. VOID
  47. SecGdbConfigBreak (
  48. VOID
  49. )
  50. {
  51. }
  52. /*++
  53. Routine Description:
  54. Main entry point to SEC for Unix. This is a unix program
  55. Arguments:
  56. Argc - Number of command line arguments
  57. Argv - Array of command line argument strings
  58. Envp - Array of environment variable strings
  59. Returns:
  60. 0 - Normal exit
  61. 1 - Abnormal exit
  62. **/
  63. int
  64. main (
  65. IN int Argc,
  66. IN char **Argv,
  67. IN char **Envp
  68. )
  69. {
  70. EFI_STATUS Status;
  71. EFI_PHYSICAL_ADDRESS InitialStackMemory;
  72. UINT64 InitialStackMemorySize;
  73. UINTN Index;
  74. UINTN Index1;
  75. UINTN Index2;
  76. UINTN PeiIndex;
  77. CHAR8 *FileName;
  78. BOOLEAN Done;
  79. EFI_PEI_FILE_HANDLE FileHandle;
  80. VOID *SecFile;
  81. CHAR16 *MemorySizeStr;
  82. CHAR16 *FirmwareVolumesStr;
  83. UINTN *StackPointer;
  84. FILE *GdbTempFile;
  85. EMU_THUNK_PPI *SecEmuThunkPpi;
  86. //
  87. // Xcode does not support sourcing gdb scripts directly, so the Xcode XML
  88. // has a break point script to source the GdbRun.sh script.
  89. //
  90. SecGdbConfigBreak ();
  91. //
  92. // If dlopen doesn't work, then we build a gdb script to allow the
  93. // symbols to be loaded.
  94. //
  95. Index = strlen (*Argv);
  96. gGdbWorkingFileName = AllocatePool (Index + strlen (".gdb") + 1);
  97. strcpy (gGdbWorkingFileName, *Argv);
  98. strcat (gGdbWorkingFileName, ".gdb");
  99. //
  100. // Empty out the gdb symbols script file.
  101. //
  102. GdbTempFile = fopen (gGdbWorkingFileName, "w");
  103. if (GdbTempFile != NULL) {
  104. fclose (GdbTempFile);
  105. }
  106. printf ("\nEDK II UNIX Host Emulation Environment from http://www.tianocore.org/edk2/\n");
  107. setbuf (stdout, 0);
  108. setbuf (stderr, 0);
  109. MemorySizeStr = (CHAR16 *)PcdGetPtr (PcdEmuMemorySize);
  110. FirmwareVolumesStr = (CHAR16 *)PcdGetPtr (PcdEmuFirmwareVolume);
  111. //
  112. // PPIs pased into PEI_CORE
  113. //
  114. SecEmuThunkPpi = AllocateZeroPool (sizeof (EMU_THUNK_PPI) + FixedPcdGet32 (PcdPersistentMemorySize));
  115. if (SecEmuThunkPpi == NULL) {
  116. printf ("ERROR : Can not allocate memory for SecEmuThunkPpi. Exiting.\n");
  117. exit (1);
  118. }
  119. CopyMem (SecEmuThunkPpi, &mSecEmuThunkPpi, sizeof (EMU_THUNK_PPI));
  120. SecEmuThunkPpi->PersistentMemorySize = FixedPcdGet32 (PcdPersistentMemorySize);
  121. AddThunkPpi (EFI_PEI_PPI_DESCRIPTOR_PPI, &gEmuThunkPpiGuid, SecEmuThunkPpi);
  122. SecInitThunkProtocol ();
  123. //
  124. // Emulator Bus Driver Thunks
  125. //
  126. AddThunkProtocol (&gX11ThunkIo, (CHAR16 *)PcdGetPtr (PcdEmuGop), TRUE);
  127. AddThunkProtocol (&gPosixFileSystemThunkIo, (CHAR16 *)PcdGetPtr (PcdEmuFileSystem), TRUE);
  128. AddThunkProtocol (&gBlockIoThunkIo, (CHAR16 *)PcdGetPtr (PcdEmuVirtualDisk), TRUE);
  129. AddThunkProtocol (&gSnpThunkIo, (CHAR16 *)PcdGetPtr (PcdEmuNetworkInterface), TRUE);
  130. //
  131. // Emulator other Thunks
  132. //
  133. AddThunkProtocol (&gPthreadThunkIo, (CHAR16 *)PcdGetPtr (PcdEmuApCount), FALSE);
  134. // EmuSecLibConstructor ();
  135. gPpiList = GetThunkPpiList ();
  136. //
  137. // Allocate space for gSystemMemory Array
  138. //
  139. gSystemMemoryCount = CountSeparatorsInString (MemorySizeStr, '!') + 1;
  140. gSystemMemory = AllocateZeroPool (gSystemMemoryCount * sizeof (EMU_SYSTEM_MEMORY));
  141. if (gSystemMemory == NULL) {
  142. printf ("ERROR : Can not allocate memory for system. Exiting.\n");
  143. exit (1);
  144. }
  145. //
  146. // Allocate space for gSystemMemory Array
  147. //
  148. gFdInfoCount = CountSeparatorsInString (FirmwareVolumesStr, '!') + 1;
  149. gFdInfo = AllocateZeroPool (gFdInfoCount * sizeof (EMU_FD_INFO));
  150. if (gFdInfo == NULL) {
  151. printf ("ERROR : Can not allocate memory for fd info. Exiting.\n");
  152. exit (1);
  153. }
  154. printf (" BootMode 0x%02x\n", (unsigned int)PcdGet32 (PcdEmuBootMode));
  155. //
  156. // Open up a 128K file to emulate temp memory for SEC.
  157. // on a real platform this would be SRAM, or using the cache as RAM.
  158. // Set InitialStackMemory to zero so UnixOpenFile will allocate a new mapping
  159. //
  160. InitialStackMemorySize = STACK_SIZE;
  161. InitialStackMemory = (UINTN)MapMemory (
  162. 0,
  163. (UINT32)InitialStackMemorySize,
  164. PROT_READ | PROT_WRITE | PROT_EXEC,
  165. MAP_ANONYMOUS | MAP_PRIVATE
  166. );
  167. if (InitialStackMemory == 0) {
  168. printf ("ERROR : Can not open SecStack Exiting\n");
  169. exit (1);
  170. }
  171. printf (
  172. " OS Emulator passing in %u KB of temp RAM at 0x%08lx to SEC\n",
  173. (unsigned int)(InitialStackMemorySize / 1024),
  174. (unsigned long)InitialStackMemory
  175. );
  176. for (StackPointer = (UINTN *)(UINTN)InitialStackMemory;
  177. StackPointer < (UINTN *)(UINTN)((UINTN)InitialStackMemory + (UINT64)InitialStackMemorySize);
  178. StackPointer++)
  179. {
  180. *StackPointer = 0x5AA55AA5;
  181. }
  182. //
  183. // Open All the firmware volumes and remember the info in the gFdInfo global
  184. //
  185. FileName = (CHAR8 *)AllocatePool (StrLen (FirmwareVolumesStr) + 1);
  186. if (FileName == NULL) {
  187. printf ("ERROR : Can not allocate memory for firmware volume string\n");
  188. exit (1);
  189. }
  190. Index2 = 0;
  191. for (Done = FALSE, Index = 0, PeiIndex = 0, SecFile = NULL;
  192. FirmwareVolumesStr[Index2] != 0;
  193. Index++)
  194. {
  195. for (Index1 = 0; (FirmwareVolumesStr[Index2] != '!') && (FirmwareVolumesStr[Index2] != 0); Index2++) {
  196. FileName[Index1++] = FirmwareVolumesStr[Index2];
  197. }
  198. if (FirmwareVolumesStr[Index2] == '!') {
  199. Index2++;
  200. }
  201. FileName[Index1] = '\0';
  202. if (Index == 0) {
  203. // Map FV Recovery Read Only and other areas Read/Write
  204. Status = MapFd0 (
  205. FileName,
  206. &gFdInfo[0].Address,
  207. &gFdInfo[0].Size
  208. );
  209. } else {
  210. //
  211. // Open the FD and remember where it got mapped into our processes address space
  212. // Maps Read Only
  213. //
  214. Status = MapFile (
  215. FileName,
  216. &gFdInfo[Index].Address,
  217. &gFdInfo[Index].Size
  218. );
  219. }
  220. if (EFI_ERROR (Status)) {
  221. printf ("ERROR : Can not open Firmware Device File %s (%x). Exiting.\n", FileName, (unsigned int)Status);
  222. exit (1);
  223. }
  224. printf (" FD loaded from %s at 0x%08lx", FileName, (unsigned long)gFdInfo[Index].Address);
  225. if (SecFile == NULL) {
  226. //
  227. // Assume the beginning of the FD is an FV and look for the SEC Core.
  228. // Load the first one we find.
  229. //
  230. FileHandle = NULL;
  231. Status = PeiServicesFfsFindNextFile (
  232. EFI_FV_FILETYPE_SECURITY_CORE,
  233. (EFI_PEI_FV_HANDLE)(UINTN)gFdInfo[Index].Address,
  234. &FileHandle
  235. );
  236. if (!EFI_ERROR (Status)) {
  237. Status = PeiServicesFfsFindSectionData (EFI_SECTION_PE32, FileHandle, &SecFile);
  238. if (!EFI_ERROR (Status)) {
  239. PeiIndex = Index;
  240. printf (" contains SEC Core");
  241. }
  242. }
  243. }
  244. printf ("\n");
  245. }
  246. if (SecFile == NULL) {
  247. printf ("ERROR : SEC not found!\n");
  248. exit (1);
  249. }
  250. //
  251. // Calculate memory regions and store the information in the gSystemMemory
  252. // global for later use. The autosizing code will use this data to
  253. // map this memory into the SEC process memory space.
  254. //
  255. Index1 = 0;
  256. Index = 0;
  257. while (1) {
  258. UINTN val = 0;
  259. //
  260. // Save the size of the memory.
  261. //
  262. while (MemorySizeStr[Index1] >= '0' && MemorySizeStr[Index1] <= '9') {
  263. val = val * 10 + MemorySizeStr[Index1] - '0';
  264. Index1++;
  265. }
  266. gSystemMemory[Index++].Size = val * 0x100000;
  267. if (MemorySizeStr[Index1] == 0) {
  268. break;
  269. }
  270. Index1++;
  271. }
  272. printf ("\n");
  273. //
  274. // Hand off to SEC
  275. //
  276. SecLoadFromCore ((UINTN)InitialStackMemory, (UINTN)InitialStackMemorySize, (UINTN)gFdInfo[0].Address, SecFile);
  277. //
  278. // If we get here, then the SEC Core returned. This is an error as SEC should
  279. // always hand off to PEI Core and then on to DXE Core.
  280. //
  281. printf ("ERROR : SEC returned\n");
  282. exit (1);
  283. }
  284. EFI_PHYSICAL_ADDRESS *
  285. MapMemory (
  286. IN INTN fd,
  287. IN UINT64 length,
  288. IN INTN prot,
  289. IN INTN flags
  290. )
  291. {
  292. STATIC UINTN base = 0x40000000;
  293. CONST UINTN align = (1 << 24);
  294. VOID *res = NULL;
  295. BOOLEAN isAligned = 0;
  296. //
  297. // Try to get an aligned block somewhere in the address space of this
  298. // process.
  299. //
  300. while ((!isAligned) && (base != 0)) {
  301. res = mmap ((void *)base, length, prot, flags, fd, 0);
  302. if (res == MAP_FAILED) {
  303. return NULL;
  304. }
  305. if ((((UINTN)res) & ~(align-1)) == (UINTN)res) {
  306. isAligned = 1;
  307. } else {
  308. munmap (res, length);
  309. base += align;
  310. }
  311. }
  312. return res;
  313. }
  314. /*++
  315. Routine Description:
  316. Opens and memory maps a file using Unix services. If BaseAddress is non zero
  317. the process will try and allocate the memory starting at BaseAddress.
  318. Arguments:
  319. FileName - The name of the file to open and map
  320. MapSize - The amount of the file to map in bytes
  321. CreationDisposition - The flags to pass to CreateFile(). Use to create new files for
  322. memory emulation, and exiting files for firmware volume emulation
  323. BaseAddress - The base address of the mapped file in the user address space.
  324. If passed in as NULL the a new memory region is used.
  325. If passed in as non NULL the request memory region is used for
  326. the mapping of the file into the process space.
  327. Length - The size of the mapped region in bytes
  328. Returns:
  329. EFI_SUCCESS - The file was opened and mapped.
  330. EFI_NOT_FOUND - FileName was not found in the current directory
  331. EFI_DEVICE_ERROR - An error occurred attempting to map the opened file
  332. **/
  333. EFI_STATUS
  334. MapFile (
  335. IN CHAR8 *FileName,
  336. IN OUT EFI_PHYSICAL_ADDRESS *BaseAddress,
  337. OUT UINT64 *Length
  338. )
  339. {
  340. int fd;
  341. VOID *res;
  342. UINTN FileSize;
  343. fd = open (FileName, O_RDWR);
  344. if (fd < 0) {
  345. return EFI_NOT_FOUND;
  346. }
  347. FileSize = lseek (fd, 0, SEEK_END);
  348. res = MapMemory (fd, FileSize, PROT_READ | PROT_EXEC, MAP_PRIVATE);
  349. close (fd);
  350. if (res == NULL) {
  351. perror ("MapFile() Failed");
  352. return EFI_DEVICE_ERROR;
  353. }
  354. *Length = (UINT64)FileSize;
  355. *BaseAddress = (EFI_PHYSICAL_ADDRESS)(UINTN)res;
  356. return EFI_SUCCESS;
  357. }
  358. EFI_STATUS
  359. MapFd0 (
  360. IN CHAR8 *FileName,
  361. IN OUT EFI_PHYSICAL_ADDRESS *BaseAddress,
  362. OUT UINT64 *Length
  363. )
  364. {
  365. int fd;
  366. void *res, *res2, *res3;
  367. UINTN FileSize;
  368. UINTN FvSize;
  369. void *EmuMagicPage;
  370. fd = open (FileName, O_RDWR);
  371. if (fd < 0) {
  372. return EFI_NOT_FOUND;
  373. }
  374. FileSize = lseek (fd, 0, SEEK_END);
  375. FvSize = FixedPcdGet64 (PcdEmuFlashFvRecoverySize);
  376. // Assume start of FD is Recovery FV, and make it write protected
  377. res = mmap (
  378. (void *)(UINTN)FixedPcdGet64 (PcdEmuFlashFvRecoveryBase),
  379. FvSize,
  380. PROT_READ | PROT_EXEC,
  381. MAP_PRIVATE,
  382. fd,
  383. 0
  384. );
  385. if (res == MAP_FAILED) {
  386. perror ("MapFd0() Failed res =");
  387. close (fd);
  388. return EFI_DEVICE_ERROR;
  389. } else if (res != (void *)(UINTN)FixedPcdGet64 (PcdEmuFlashFvRecoveryBase)) {
  390. // We could not load at the build address, so we need to allow writes
  391. munmap (res, FvSize);
  392. res = mmap (
  393. (void *)(UINTN)FixedPcdGet64 (PcdEmuFlashFvRecoveryBase),
  394. FvSize,
  395. PROT_READ | PROT_WRITE | PROT_EXEC,
  396. MAP_PRIVATE,
  397. fd,
  398. 0
  399. );
  400. if (res == MAP_FAILED) {
  401. perror ("MapFd0() Failed res =");
  402. close (fd);
  403. return EFI_DEVICE_ERROR;
  404. }
  405. }
  406. // Map the rest of the FD as read/write
  407. res2 = mmap (
  408. (void *)(UINTN)(FixedPcdGet64 (PcdEmuFlashFvRecoveryBase) + FvSize),
  409. FileSize - FvSize,
  410. PROT_READ | PROT_WRITE | PROT_EXEC,
  411. MAP_SHARED,
  412. fd,
  413. FvSize
  414. );
  415. close (fd);
  416. if (res2 == MAP_FAILED) {
  417. perror ("MapFd0() Failed res2 =");
  418. return EFI_DEVICE_ERROR;
  419. }
  420. //
  421. // If enabled use the magic page to communicate between modules
  422. // This replaces the PI PeiServicesTable pointer mechanism that
  423. // deos not work in the emulator. It also allows the removal of
  424. // writable globals from SEC, PEI_CORE (libraries), PEIMs
  425. //
  426. EmuMagicPage = (void *)(UINTN)FixedPcdGet64 (PcdPeiServicesTablePage);
  427. if (EmuMagicPage != NULL) {
  428. res3 = mmap (
  429. (void *)EmuMagicPage,
  430. 4096,
  431. PROT_READ | PROT_WRITE,
  432. MAP_PRIVATE | MAP_ANONYMOUS,
  433. 0,
  434. 0
  435. );
  436. if (res3 != EmuMagicPage) {
  437. printf ("MapFd0(): Could not allocate PeiServicesTablePage @ %lx\n", (long unsigned int)EmuMagicPage);
  438. return EFI_DEVICE_ERROR;
  439. }
  440. }
  441. *Length = (UINT64)FileSize;
  442. *BaseAddress = (EFI_PHYSICAL_ADDRESS)(UINTN)res;
  443. return EFI_SUCCESS;
  444. }
  445. /*++
  446. Routine Description:
  447. This is the service to load the SEC Core from the Firmware Volume
  448. Arguments:
  449. LargestRegion - Memory to use for SEC.
  450. LargestRegionSize - Size of Memory to use for PEI
  451. BootFirmwareVolumeBase - Start of the Boot FV
  452. PeiCorePe32File - SEC PE32
  453. Returns:
  454. Success means control is transferred and thus we should never return
  455. **/
  456. VOID
  457. SecLoadFromCore (
  458. IN UINTN LargestRegion,
  459. IN UINTN LargestRegionSize,
  460. IN UINTN BootFirmwareVolumeBase,
  461. IN VOID *PeiCorePe32File
  462. )
  463. {
  464. EFI_STATUS Status;
  465. EFI_PHYSICAL_ADDRESS TopOfMemory;
  466. VOID *TopOfStack;
  467. EFI_PHYSICAL_ADDRESS PeiCoreEntryPoint;
  468. EFI_SEC_PEI_HAND_OFF *SecCoreData;
  469. UINTN PeiStackSize;
  470. //
  471. // Compute Top Of Memory for Stack and PEI Core Allocations
  472. //
  473. TopOfMemory = LargestRegion + LargestRegionSize;
  474. PeiStackSize = (UINTN)RShiftU64 ((UINT64)STACK_SIZE, 1);
  475. //
  476. // |-----------| <---- TemporaryRamBase + TemporaryRamSize
  477. // | Heap |
  478. // | |
  479. // |-----------| <---- StackBase / PeiTemporaryMemoryBase
  480. // | |
  481. // | Stack |
  482. // |-----------| <---- TemporaryRamBase
  483. //
  484. TopOfStack = (VOID *)(LargestRegion + PeiStackSize);
  485. TopOfMemory = LargestRegion + PeiStackSize;
  486. //
  487. // Reservet space for storing PeiCore's parament in stack.
  488. //
  489. TopOfStack = (VOID *)((UINTN)TopOfStack - sizeof (EFI_SEC_PEI_HAND_OFF) - CPU_STACK_ALIGNMENT);
  490. TopOfStack = ALIGN_POINTER (TopOfStack, CPU_STACK_ALIGNMENT);
  491. //
  492. // Bind this information into the SEC hand-off state
  493. //
  494. SecCoreData = (EFI_SEC_PEI_HAND_OFF *)(UINTN)TopOfStack;
  495. SecCoreData->DataSize = sizeof (EFI_SEC_PEI_HAND_OFF);
  496. SecCoreData->BootFirmwareVolumeBase = (VOID *)BootFirmwareVolumeBase;
  497. SecCoreData->BootFirmwareVolumeSize = PcdGet32 (PcdEmuFirmwareFdSize);
  498. SecCoreData->TemporaryRamBase = (VOID *)(UINTN)LargestRegion;
  499. SecCoreData->TemporaryRamSize = STACK_SIZE;
  500. SecCoreData->StackBase = SecCoreData->TemporaryRamBase;
  501. SecCoreData->StackSize = PeiStackSize;
  502. SecCoreData->PeiTemporaryRamBase = (VOID *)((UINTN)SecCoreData->TemporaryRamBase + PeiStackSize);
  503. SecCoreData->PeiTemporaryRamSize = STACK_SIZE - PeiStackSize;
  504. //
  505. // Find the SEC Core Entry Point
  506. //
  507. Status = SecPeCoffGetEntryPoint (PeiCorePe32File, (VOID **)&PeiCoreEntryPoint);
  508. if (EFI_ERROR (Status)) {
  509. return;
  510. }
  511. //
  512. // Transfer control to the SEC Core
  513. //
  514. PeiSwitchStacks (
  515. (SWITCH_STACK_ENTRY_POINT)(UINTN)PeiCoreEntryPoint,
  516. SecCoreData,
  517. (VOID *)gPpiList,
  518. TopOfStack
  519. );
  520. //
  521. // If we get here, then the SEC Core returned. This is an error
  522. //
  523. return;
  524. }
  525. /*++
  526. Routine Description:
  527. This service is called from Index == 0 until it returns EFI_UNSUPPORTED.
  528. It allows discontinuous memory regions to be supported by the emulator.
  529. It uses gSystemMemory[] and gSystemMemoryCount that were created by
  530. parsing the host environment variable EFI_MEMORY_SIZE.
  531. The size comes from the variable and the address comes from the call to
  532. UnixOpenFile.
  533. Arguments:
  534. Index - Which memory region to use
  535. MemoryBase - Return Base address of memory region
  536. MemorySize - Return size in bytes of the memory region
  537. Returns:
  538. EFI_SUCCESS - If memory region was mapped
  539. EFI_UNSUPPORTED - If Index is not supported
  540. **/
  541. EFI_STATUS
  542. SecUnixPeiAutoScan (
  543. IN UINTN Index,
  544. OUT EFI_PHYSICAL_ADDRESS *MemoryBase,
  545. OUT UINT64 *MemorySize
  546. )
  547. {
  548. void *res;
  549. if (Index >= gSystemMemoryCount) {
  550. return EFI_UNSUPPORTED;
  551. }
  552. *MemoryBase = 0;
  553. res = MapMemory (
  554. 0,
  555. gSystemMemory[Index].Size,
  556. PROT_READ | PROT_WRITE | PROT_EXEC,
  557. MAP_PRIVATE | MAP_ANONYMOUS
  558. );
  559. if (res == MAP_FAILED) {
  560. return EFI_DEVICE_ERROR;
  561. }
  562. *MemorySize = gSystemMemory[Index].Size;
  563. *MemoryBase = (UINTN)res;
  564. gSystemMemory[Index].Memory = *MemoryBase;
  565. return EFI_SUCCESS;
  566. }
  567. /*++
  568. Routine Description:
  569. Check to see if an address range is in the EFI GCD memory map.
  570. This is all of GCD for system memory passed to DXE Core. FV
  571. mapping and other device mapped into system memory are not
  572. included in the check.
  573. Arguments:
  574. Index - Which memory region to use
  575. MemoryBase - Return Base address of memory region
  576. MemorySize - Return size in bytes of the memory region
  577. Returns:
  578. TRUE - Address is in the EFI GCD memory map
  579. FALSE - Address is NOT in memory map
  580. **/
  581. BOOLEAN
  582. EfiSystemMemoryRange (
  583. IN VOID *MemoryAddress
  584. )
  585. {
  586. UINTN Index;
  587. EFI_PHYSICAL_ADDRESS MemoryBase;
  588. MemoryBase = (EFI_PHYSICAL_ADDRESS)(UINTN)MemoryAddress;
  589. for (Index = 0; Index < gSystemMemoryCount; Index++) {
  590. if ((MemoryBase >= gSystemMemory[Index].Memory) &&
  591. (MemoryBase < (gSystemMemory[Index].Memory + gSystemMemory[Index].Size)))
  592. {
  593. return TRUE;
  594. }
  595. }
  596. return FALSE;
  597. }
  598. /*++
  599. Routine Description:
  600. Since the SEC is the only Unix program in stack it must export
  601. an interface to do POSIX calls. gUnix is initialized in UnixThunk.c.
  602. Arguments:
  603. InterfaceSize - sizeof (EFI_WIN_NT_THUNK_PROTOCOL);
  604. InterfaceBase - Address of the gUnix global
  605. Returns:
  606. EFI_SUCCESS - Data returned
  607. **/
  608. VOID *
  609. SecEmuThunkAddress (
  610. VOID
  611. )
  612. {
  613. return &gEmuThunkProtocol;
  614. }
  615. RETURN_STATUS
  616. EFIAPI
  617. SecPeCoffGetEntryPoint (
  618. IN VOID *Pe32Data,
  619. IN OUT VOID **EntryPoint
  620. )
  621. {
  622. EFI_STATUS Status;
  623. PE_COFF_LOADER_IMAGE_CONTEXT ImageContext;
  624. ZeroMem (&ImageContext, sizeof (ImageContext));
  625. ImageContext.Handle = Pe32Data;
  626. ImageContext.ImageRead = (PE_COFF_LOADER_READ_FILE)SecImageRead;
  627. Status = PeCoffLoaderGetImageInfo (&ImageContext);
  628. if (EFI_ERROR (Status)) {
  629. return Status;
  630. }
  631. if (ImageContext.ImageAddress != (UINTN)Pe32Data) {
  632. //
  633. // Relocate image to match the address where it resides
  634. //
  635. ImageContext.ImageAddress = (UINTN)Pe32Data;
  636. Status = PeCoffLoaderLoadImage (&ImageContext);
  637. if (EFI_ERROR (Status)) {
  638. return Status;
  639. }
  640. Status = PeCoffLoaderRelocateImage (&ImageContext);
  641. if (EFI_ERROR (Status)) {
  642. return Status;
  643. }
  644. } else {
  645. //
  646. // Or just return image entry point
  647. //
  648. ImageContext.PdbPointer = PeCoffLoaderGetPdbPointer (Pe32Data);
  649. Status = PeCoffLoaderGetEntryPoint (Pe32Data, EntryPoint);
  650. if (EFI_ERROR (Status)) {
  651. return Status;
  652. }
  653. ImageContext.EntryPoint = (UINTN)*EntryPoint;
  654. }
  655. // On Unix a dlopen is done that will change the entry point
  656. SecPeCoffRelocateImageExtraAction (&ImageContext);
  657. *EntryPoint = (VOID *)(UINTN)ImageContext.EntryPoint;
  658. return Status;
  659. }
  660. /*++
  661. Routine Description:
  662. Return the FD Size and base address. Since the FD is loaded from a
  663. file into host memory only the SEC will know its address.
  664. Arguments:
  665. Index - Which FD, starts at zero.
  666. FdSize - Size of the FD in bytes
  667. FdBase - Start address of the FD. Assume it points to an FV Header
  668. FixUp - Difference between actual FD address and build address
  669. Returns:
  670. EFI_SUCCESS - Return the Base address and size of the FV
  671. EFI_UNSUPPORTED - Index does nto map to an FD in the system
  672. **/
  673. EFI_STATUS
  674. SecUnixFdAddress (
  675. IN UINTN Index,
  676. IN OUT EFI_PHYSICAL_ADDRESS *FdBase,
  677. IN OUT UINT64 *FdSize,
  678. IN OUT EFI_PHYSICAL_ADDRESS *FixUp
  679. )
  680. {
  681. if (Index >= gFdInfoCount) {
  682. return EFI_UNSUPPORTED;
  683. }
  684. *FdBase = gFdInfo[Index].Address;
  685. *FdSize = gFdInfo[Index].Size;
  686. *FixUp = 0;
  687. if ((*FdBase == 0) && (*FdSize == 0)) {
  688. return EFI_UNSUPPORTED;
  689. }
  690. if (Index == 0) {
  691. //
  692. // FD 0 has XIP code and well known PCD values
  693. // If the memory buffer could not be allocated at the FD build address
  694. // the Fixup is the difference.
  695. //
  696. *FixUp = *FdBase - PcdGet64 (PcdEmuFdBaseAddress);
  697. }
  698. return EFI_SUCCESS;
  699. }
  700. /*++
  701. Routine Description:
  702. Count the number of separators in String
  703. Arguments:
  704. String - String to process
  705. Separator - Item to count
  706. Returns:
  707. Number of Separator in String
  708. **/
  709. UINTN
  710. CountSeparatorsInString (
  711. IN const CHAR16 *String,
  712. IN CHAR16 Separator
  713. )
  714. {
  715. UINTN Count;
  716. for (Count = 0; *String != '\0'; String++) {
  717. if (*String == Separator) {
  718. Count++;
  719. }
  720. }
  721. return Count;
  722. }
  723. EFI_STATUS
  724. EFIAPI
  725. SecImageRead (
  726. IN VOID *FileHandle,
  727. IN UINTN FileOffset,
  728. IN OUT UINTN *ReadSize,
  729. OUT VOID *Buffer
  730. )
  731. /*++
  732. Routine Description:
  733. Support routine for the PE/COFF Loader that reads a buffer from a PE/COFF file
  734. Arguments:
  735. FileHandle - The handle to the PE/COFF file
  736. FileOffset - The offset, in bytes, into the file to read
  737. ReadSize - The number of bytes to read from the file starting at FileOffset
  738. Buffer - A pointer to the buffer to read the data into.
  739. Returns:
  740. EFI_SUCCESS - ReadSize bytes of data were read into Buffer from the PE/COFF file starting at FileOffset
  741. **/
  742. {
  743. CHAR8 *Destination8;
  744. CHAR8 *Source8;
  745. UINTN Length;
  746. Destination8 = Buffer;
  747. Source8 = (CHAR8 *)((UINTN)FileHandle + FileOffset);
  748. Length = *ReadSize;
  749. while (Length--) {
  750. *(Destination8++) = *(Source8++);
  751. }
  752. return EFI_SUCCESS;
  753. }
  754. /*++
  755. Routine Description:
  756. Store the ModHandle in an array indexed by the Pdb File name.
  757. The ModHandle is needed to unload the image.
  758. Arguments:
  759. ImageContext - Input data returned from PE Loader Library. Used to find the
  760. .PDB file name of the PE Image.
  761. ModHandle - Returned from LoadLibraryEx() and stored for call to
  762. FreeLibrary().
  763. Returns:
  764. EFI_SUCCESS - ModHandle was stored.
  765. **/
  766. EFI_STATUS
  767. AddHandle (
  768. IN PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext,
  769. IN VOID *ModHandle
  770. )
  771. {
  772. UINTN Index;
  773. IMAGE_CONTEXT_TO_MOD_HANDLE *Array;
  774. UINTN PreviousSize;
  775. Array = mImageContextModHandleArray;
  776. for (Index = 0; Index < mImageContextModHandleArraySize; Index++, Array++) {
  777. if (Array->ImageContext == NULL) {
  778. //
  779. // Make a copy of the string and store the ModHandle
  780. //
  781. Array->ImageContext = ImageContext;
  782. Array->ModHandle = ModHandle;
  783. return EFI_SUCCESS;
  784. }
  785. }
  786. //
  787. // No free space in mImageContextModHandleArray so grow it by
  788. // IMAGE_CONTEXT_TO_MOD_HANDLE entires. realloc will
  789. // copy the old values to the new location. But it does
  790. // not zero the new memory area.
  791. //
  792. PreviousSize = mImageContextModHandleArraySize * sizeof (IMAGE_CONTEXT_TO_MOD_HANDLE);
  793. mImageContextModHandleArraySize += MAX_IMAGE_CONTEXT_TO_MOD_HANDLE_ARRAY_SIZE;
  794. mImageContextModHandleArray = ReallocatePool (
  795. (mImageContextModHandleArraySize - 1) * sizeof (IMAGE_CONTEXT_TO_MOD_HANDLE),
  796. mImageContextModHandleArraySize * sizeof (IMAGE_CONTEXT_TO_MOD_HANDLE),
  797. mImageContextModHandleArray
  798. );
  799. if (mImageContextModHandleArray == NULL) {
  800. ASSERT (FALSE);
  801. return EFI_OUT_OF_RESOURCES;
  802. }
  803. memset (mImageContextModHandleArray + PreviousSize, 0, MAX_IMAGE_CONTEXT_TO_MOD_HANDLE_ARRAY_SIZE * sizeof (IMAGE_CONTEXT_TO_MOD_HANDLE));
  804. return AddHandle (ImageContext, ModHandle);
  805. }
  806. /*++
  807. Routine Description:
  808. Return the ModHandle and delete the entry in the array.
  809. Arguments:
  810. ImageContext - Input data returned from PE Loader Library. Used to find the
  811. .PDB file name of the PE Image.
  812. Returns:
  813. ModHandle - ModHandle associated with ImageContext is returned
  814. NULL - No ModHandle associated with ImageContext
  815. **/
  816. VOID *
  817. RemoveHandle (
  818. IN PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
  819. )
  820. {
  821. UINTN Index;
  822. IMAGE_CONTEXT_TO_MOD_HANDLE *Array;
  823. if (ImageContext->PdbPointer == NULL) {
  824. //
  825. // If no PDB pointer there is no ModHandle so return NULL
  826. //
  827. return NULL;
  828. }
  829. Array = mImageContextModHandleArray;
  830. for (Index = 0; Index < mImageContextModHandleArraySize; Index++, Array++) {
  831. if (Array->ImageContext == ImageContext) {
  832. //
  833. // If you find a match return it and delete the entry
  834. //
  835. Array->ImageContext = NULL;
  836. return Array->ModHandle;
  837. }
  838. }
  839. return NULL;
  840. }
  841. BOOLEAN
  842. IsPdbFile (
  843. IN CHAR8 *PdbFileName
  844. )
  845. {
  846. UINTN Len;
  847. if (PdbFileName == NULL) {
  848. return FALSE;
  849. }
  850. Len = strlen (PdbFileName);
  851. if ((Len < 5) || (PdbFileName[Len - 4] != '.')) {
  852. return FALSE;
  853. }
  854. if (((PdbFileName[Len - 3] == 'P') || (PdbFileName[Len - 3] == 'p')) &&
  855. ((PdbFileName[Len - 2] == 'D') || (PdbFileName[Len - 2] == 'd')) &&
  856. ((PdbFileName[Len - 1] == 'B') || (PdbFileName[Len - 1] == 'b')))
  857. {
  858. return TRUE;
  859. }
  860. return FALSE;
  861. }
  862. #define MAX_SPRINT_BUFFER_SIZE 0x200
  863. void
  864. PrintLoadAddress (
  865. IN PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
  866. )
  867. {
  868. if (ImageContext->PdbPointer == NULL) {
  869. fprintf (
  870. stderr,
  871. "0x%08lx Loading NO DEBUG with entry point 0x%08lx\n",
  872. (unsigned long)(ImageContext->ImageAddress),
  873. (unsigned long)ImageContext->EntryPoint
  874. );
  875. } else {
  876. fprintf (
  877. stderr,
  878. "0x%08lx Loading %s with entry point 0x%08lx\n",
  879. (unsigned long)(ImageContext->ImageAddress + ImageContext->SizeOfHeaders),
  880. ImageContext->PdbPointer,
  881. (unsigned long)ImageContext->EntryPoint
  882. );
  883. }
  884. // Keep output synced up
  885. fflush (stderr);
  886. }
  887. /**
  888. Loads the image using dlopen so symbols will be automatically
  889. loaded by gdb.
  890. @param ImageContext The PE/COFF image context
  891. @retval TRUE - The image was successfully loaded
  892. @retval FALSE - The image was successfully loaded
  893. **/
  894. BOOLEAN
  895. DlLoadImage (
  896. IN OUT PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
  897. )
  898. {
  899. #ifdef __APPLE__
  900. return FALSE;
  901. #else
  902. void *Handle = NULL;
  903. void *Entry = NULL;
  904. if (ImageContext->PdbPointer == NULL) {
  905. return FALSE;
  906. }
  907. if (!IsPdbFile (ImageContext->PdbPointer)) {
  908. return FALSE;
  909. }
  910. fprintf (
  911. stderr,
  912. "Loading %s 0x%08lx - entry point 0x%08lx\n",
  913. ImageContext->PdbPointer,
  914. (unsigned long)ImageContext->ImageAddress,
  915. (unsigned long)ImageContext->EntryPoint
  916. );
  917. Handle = dlopen (ImageContext->PdbPointer, RTLD_NOW);
  918. if (Handle != NULL) {
  919. Entry = dlsym (Handle, "_ModuleEntryPoint");
  920. AddHandle (ImageContext, Handle);
  921. } else {
  922. printf ("%s\n", dlerror ());
  923. }
  924. if (Entry != NULL) {
  925. ImageContext->EntryPoint = (UINTN)Entry;
  926. printf ("Change %s Entrypoint to :0x%08lx\n", ImageContext->PdbPointer, (unsigned long)Entry);
  927. return TRUE;
  928. } else {
  929. return FALSE;
  930. }
  931. #endif
  932. }
  933. #ifdef __APPLE__
  934. __attribute__ ((noinline))
  935. #endif
  936. VOID
  937. SecGdbScriptBreak (
  938. char *FileName,
  939. int FileNameLength,
  940. long unsigned int LoadAddress,
  941. int AddSymbolFlag
  942. )
  943. {
  944. return;
  945. }
  946. /**
  947. Adds the image to a gdb script so its symbols can be loaded.
  948. The AddFirmwareSymbolFile helper macro is used.
  949. @param ImageContext The PE/COFF image context
  950. **/
  951. VOID
  952. GdbScriptAddImage (
  953. IN OUT PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
  954. )
  955. {
  956. PrintLoadAddress (ImageContext);
  957. if ((ImageContext->PdbPointer != NULL) && !IsPdbFile (ImageContext->PdbPointer)) {
  958. FILE *GdbTempFile;
  959. if (FeaturePcdGet (PcdEmulatorLazyLoadSymbols)) {
  960. GdbTempFile = fopen (gGdbWorkingFileName, "a");
  961. if (GdbTempFile != NULL) {
  962. long unsigned int SymbolsAddr = (long unsigned int)(ImageContext->ImageAddress + ImageContext->SizeOfHeaders);
  963. mScriptSymbolChangesCount++;
  964. fprintf (
  965. GdbTempFile,
  966. "AddFirmwareSymbolFile 0x%x %s 0x%08lx\n",
  967. mScriptSymbolChangesCount,
  968. ImageContext->PdbPointer,
  969. SymbolsAddr
  970. );
  971. fclose (GdbTempFile);
  972. // This is for the lldb breakpoint only
  973. SecGdbScriptBreak (ImageContext->PdbPointer, strlen (ImageContext->PdbPointer) + 1, (long unsigned int)(ImageContext->ImageAddress + ImageContext->SizeOfHeaders), 1);
  974. } else {
  975. ASSERT (FALSE);
  976. }
  977. } else {
  978. GdbTempFile = fopen (gGdbWorkingFileName, "w");
  979. if (GdbTempFile != NULL) {
  980. fprintf (
  981. GdbTempFile,
  982. "add-symbol-file %s 0x%08lx\n",
  983. ImageContext->PdbPointer,
  984. (long unsigned int)(ImageContext->ImageAddress + ImageContext->SizeOfHeaders)
  985. );
  986. fclose (GdbTempFile);
  987. //
  988. // Target for gdb breakpoint in a script that uses gGdbWorkingFileName to set a breakpoint.
  989. // Hey what can you say scripting in gdb is not that great....
  990. // Also used for the lldb breakpoint script. The lldb breakpoint script does
  991. // not use the file, it uses the arguments.
  992. //
  993. SecGdbScriptBreak (ImageContext->PdbPointer, strlen (ImageContext->PdbPointer) + 1, (long unsigned int)(ImageContext->ImageAddress + ImageContext->SizeOfHeaders), 1);
  994. } else {
  995. ASSERT (FALSE);
  996. }
  997. }
  998. }
  999. }
  1000. VOID
  1001. EFIAPI
  1002. SecPeCoffRelocateImageExtraAction (
  1003. IN OUT PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
  1004. )
  1005. {
  1006. if (!DlLoadImage (ImageContext)) {
  1007. GdbScriptAddImage (ImageContext);
  1008. }
  1009. }
  1010. /**
  1011. Adds the image to a gdb script so its symbols can be unloaded.
  1012. The RemoveFirmwareSymbolFile helper macro is used.
  1013. @param ImageContext The PE/COFF image context
  1014. **/
  1015. VOID
  1016. GdbScriptRemoveImage (
  1017. IN OUT PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
  1018. )
  1019. {
  1020. FILE *GdbTempFile;
  1021. //
  1022. // Need to skip .PDB files created from VC++
  1023. //
  1024. if (IsPdbFile (ImageContext->PdbPointer)) {
  1025. return;
  1026. }
  1027. if (FeaturePcdGet (PcdEmulatorLazyLoadSymbols)) {
  1028. //
  1029. // Write the file we need for the gdb script
  1030. //
  1031. GdbTempFile = fopen (gGdbWorkingFileName, "a");
  1032. if (GdbTempFile != NULL) {
  1033. mScriptSymbolChangesCount++;
  1034. fprintf (
  1035. GdbTempFile,
  1036. "RemoveFirmwareSymbolFile 0x%x %s\n",
  1037. mScriptSymbolChangesCount,
  1038. ImageContext->PdbPointer
  1039. );
  1040. fclose (GdbTempFile);
  1041. SecGdbScriptBreak (ImageContext->PdbPointer, strlen (ImageContext->PdbPointer) + 1, 0, 0);
  1042. } else {
  1043. ASSERT (FALSE);
  1044. }
  1045. } else {
  1046. GdbTempFile = fopen (gGdbWorkingFileName, "w");
  1047. if (GdbTempFile != NULL) {
  1048. fprintf (GdbTempFile, "remove-symbol-file %s\n", ImageContext->PdbPointer);
  1049. fclose (GdbTempFile);
  1050. //
  1051. // Target for gdb breakpoint in a script that uses gGdbWorkingFileName to set a breakpoint.
  1052. // Hey what can you say scripting in gdb is not that great....
  1053. //
  1054. SecGdbScriptBreak (ImageContext->PdbPointer, strlen (ImageContext->PdbPointer) + 1, 0, 0);
  1055. } else {
  1056. ASSERT (FALSE);
  1057. }
  1058. }
  1059. }
  1060. VOID
  1061. EFIAPI
  1062. SecPeCoffUnloadImageExtraAction (
  1063. IN PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
  1064. )
  1065. {
  1066. VOID *Handle;
  1067. //
  1068. // Check to see if the image symbols were loaded with gdb script, or dlopen
  1069. //
  1070. Handle = RemoveHandle (ImageContext);
  1071. if (Handle != NULL) {
  1072. #ifndef __APPLE__
  1073. dlclose (Handle);
  1074. #endif
  1075. return;
  1076. }
  1077. GdbScriptRemoveImage (ImageContext);
  1078. }