Host.c 34 KB

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