GdbStub.c 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242
  1. /** @file
  2. UEFI driver that implements a GDB stub
  3. Note: Any code in the path of the Serial IO output can not call DEBUG as will
  4. will blow out the stack. Serial IO calls DEBUG, debug calls Serial IO, ...
  5. Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
  6. SPDX-License-Identifier: BSD-2-Clause-Patent
  7. **/
  8. #include <GdbStubInternal.h>
  9. #include <Protocol/DebugPort.h>
  10. UINTN gMaxProcessorIndex = 0;
  11. //
  12. // Buffers for basic gdb communication
  13. //
  14. CHAR8 gInBuffer[MAX_BUF_SIZE];
  15. CHAR8 gOutBuffer[MAX_BUF_SIZE];
  16. // Assume gdb does a "qXfer:libraries:read::offset,length" when it connects so we can default
  17. // this value to FALSE. Since gdb can reconnect its self a global default is not good enough
  18. BOOLEAN gSymbolTableUpdate = FALSE;
  19. EFI_EVENT gEvent;
  20. VOID *gGdbSymbolEventHandlerRegistration = NULL;
  21. //
  22. // Globals for returning XML from qXfer:libraries:read packet
  23. //
  24. UINTN gPacketqXferLibraryOffset = 0;
  25. UINTN gEfiDebugImageTableEntry = 0;
  26. EFI_DEBUG_IMAGE_INFO_TABLE_HEADER *gDebugImageTableHeader = NULL;
  27. EFI_DEBUG_IMAGE_INFO *gDebugTable = NULL;
  28. CHAR8 gXferLibraryBuffer[2000];
  29. GLOBAL_REMOVE_IF_UNREFERENCED CONST CHAR8 mHexToStr[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
  30. VOID
  31. EFIAPI
  32. GdbSymbolEventHandler (
  33. IN EFI_EVENT Event,
  34. IN VOID *Context
  35. )
  36. {
  37. }
  38. /**
  39. The user Entry Point for Application. The user code starts with this function
  40. as the real entry point for the image goes into a library that calls this
  41. function.
  42. @param[in] ImageHandle The firmware allocated handle for the EFI image.
  43. @param[in] SystemTable A pointer to the EFI System Table.
  44. @retval EFI_SUCCESS The entry point is executed successfully.
  45. @retval other Some error occurs when executing this entry point.
  46. **/
  47. EFI_STATUS
  48. EFIAPI
  49. GdbStubEntry (
  50. IN EFI_HANDLE ImageHandle,
  51. IN EFI_SYSTEM_TABLE *SystemTable
  52. )
  53. {
  54. EFI_STATUS Status;
  55. EFI_DEBUG_SUPPORT_PROTOCOL *DebugSupport;
  56. UINTN HandleCount;
  57. EFI_HANDLE *Handles;
  58. UINTN Index;
  59. UINTN Processor;
  60. BOOLEAN IsaSupported;
  61. Status = EfiGetSystemConfigurationTable (&gEfiDebugImageInfoTableGuid, (VOID **)&gDebugImageTableHeader);
  62. if (EFI_ERROR (Status)) {
  63. gDebugImageTableHeader = NULL;
  64. }
  65. Status = gBS->LocateHandleBuffer (
  66. ByProtocol,
  67. &gEfiDebugSupportProtocolGuid,
  68. NULL,
  69. &HandleCount,
  70. &Handles
  71. );
  72. if (EFI_ERROR (Status)) {
  73. DEBUG ((DEBUG_ERROR, "Debug Support Protocol not found\n"));
  74. return Status;
  75. }
  76. DebugSupport = NULL;
  77. IsaSupported = FALSE;
  78. do {
  79. HandleCount--;
  80. Status = gBS->HandleProtocol (
  81. Handles[HandleCount],
  82. &gEfiDebugSupportProtocolGuid,
  83. (VOID **)&DebugSupport
  84. );
  85. if (!EFI_ERROR (Status)) {
  86. if (CheckIsa (DebugSupport->Isa)) {
  87. // We found what we are looking for so break out of the loop
  88. IsaSupported = TRUE;
  89. break;
  90. }
  91. }
  92. } while (HandleCount > 0);
  93. FreePool (Handles);
  94. if (!IsaSupported) {
  95. DEBUG ((DEBUG_ERROR, "Debug Support Protocol does not support our ISA\n"));
  96. return EFI_NOT_FOUND;
  97. }
  98. Status = DebugSupport->GetMaximumProcessorIndex (DebugSupport, &gMaxProcessorIndex);
  99. ASSERT_EFI_ERROR (Status);
  100. DEBUG ((DEBUG_INFO, "Debug Support Protocol ISA %x\n", DebugSupport->Isa));
  101. DEBUG ((DEBUG_INFO, "Debug Support Protocol Processor Index %d\n", gMaxProcessorIndex));
  102. // Call processor-specific init routine
  103. InitializeProcessor ();
  104. for (Processor = 0; Processor <= gMaxProcessorIndex; Processor++) {
  105. for (Index = 0; Index < MaxEfiException (); Index++) {
  106. Status = DebugSupport->RegisterExceptionCallback (DebugSupport, Processor, GdbExceptionHandler, gExceptionType[Index].Exception);
  107. ASSERT_EFI_ERROR (Status);
  108. }
  109. //
  110. // Current edk2 DebugPort is not interrupt context safe so we can not use it
  111. //
  112. Status = DebugSupport->RegisterPeriodicCallback (DebugSupport, Processor, GdbPeriodicCallBack);
  113. ASSERT_EFI_ERROR (Status);
  114. }
  115. //
  116. // This even fires every time an image is added. This allows the stub to know when gdb needs
  117. // to update the symbol table.
  118. //
  119. Status = gBS->CreateEvent (
  120. EVT_NOTIFY_SIGNAL,
  121. TPL_CALLBACK,
  122. GdbSymbolEventHandler,
  123. NULL,
  124. &gEvent
  125. );
  126. ASSERT_EFI_ERROR (Status);
  127. //
  128. // Register for protocol notifications on this event
  129. //
  130. Status = gBS->RegisterProtocolNotify (
  131. &gEfiLoadedImageProtocolGuid,
  132. gEvent,
  133. &gGdbSymbolEventHandlerRegistration
  134. );
  135. ASSERT_EFI_ERROR (Status);
  136. if (PcdGetBool (PcdGdbSerial)) {
  137. GdbInitializeSerialConsole ();
  138. }
  139. return EFI_SUCCESS;
  140. }
  141. /**
  142. Transfer length bytes of input buffer, starting at Address, to memory.
  143. @param length the number of the bytes to be transferred/written
  144. @param *address the start address of the transferring/writing the memory
  145. @param *new_data the new data to be written to memory
  146. **/
  147. VOID
  148. TransferFromInBufToMem (
  149. IN UINTN Length,
  150. IN unsigned char *Address,
  151. IN CHAR8 *NewData
  152. )
  153. {
  154. CHAR8 c1;
  155. CHAR8 c2;
  156. while (Length-- > 0) {
  157. c1 = (CHAR8)HexCharToInt (*NewData++);
  158. c2 = (CHAR8)HexCharToInt (*NewData++);
  159. if ((c1 < 0) || (c2 < 0)) {
  160. Print ((CHAR16 *)L"Bad message from write to memory..\n");
  161. SendError (GDB_EBADMEMDATA);
  162. return;
  163. }
  164. *Address++ = (UINT8)((c1 << 4) + c2);
  165. }
  166. SendSuccess ();
  167. }
  168. /**
  169. Transfer Length bytes of memory starting at Address to an output buffer, OutBuffer. This function will finally send the buffer
  170. as a packet.
  171. @param Length the number of the bytes to be transferred/read
  172. @param *address pointer to the start address of the transferring/reading the memory
  173. **/
  174. VOID
  175. TransferFromMemToOutBufAndSend (
  176. IN UINTN Length,
  177. IN unsigned char *Address
  178. )
  179. {
  180. // there are Length bytes and every byte is represented as 2 hex chars
  181. CHAR8 OutBuffer[MAX_BUF_SIZE];
  182. CHAR8 *OutBufPtr; // pointer to the output buffer
  183. CHAR8 Char;
  184. if (ValidateAddress (Address) == FALSE) {
  185. SendError (14);
  186. return;
  187. }
  188. OutBufPtr = OutBuffer;
  189. while (Length > 0) {
  190. Char = mHexToStr[*Address >> 4];
  191. if ((Char >= 'A') && (Char <= 'F')) {
  192. Char = Char - 'A' + 'a';
  193. }
  194. *OutBufPtr++ = Char;
  195. Char = mHexToStr[*Address & 0x0f];
  196. if ((Char >= 'A') && (Char <= 'F')) {
  197. Char = Char - 'A' + 'a';
  198. }
  199. *OutBufPtr++ = Char;
  200. Address++;
  201. Length--;
  202. }
  203. *OutBufPtr = '\0'; // the end of the buffer
  204. SendPacket (OutBuffer);
  205. }
  206. /**
  207. Send a GDB Remote Serial Protocol Packet
  208. $PacketData#checksum PacketData is passed in and this function adds the packet prefix '$',
  209. the packet terminating character '#' and the two digit checksum.
  210. If an ack '+' is not sent resend the packet, but timeout eventually so we don't end up
  211. in an infinite loop. This is so if you unplug the debugger code just keeps running
  212. @param PacketData Payload data for the packet
  213. @retval Number of bytes of packet data sent.
  214. **/
  215. UINTN
  216. SendPacket (
  217. IN CHAR8 *PacketData
  218. )
  219. {
  220. UINT8 CheckSum;
  221. UINTN Timeout;
  222. CHAR8 *Ptr;
  223. CHAR8 TestChar;
  224. UINTN Count;
  225. Timeout = PcdGet32 (PcdGdbMaxPacketRetryCount);
  226. Count = 0;
  227. do {
  228. Ptr = PacketData;
  229. if (Timeout-- == 0) {
  230. // Only try a finite number of times so we don't get stuck in the loop
  231. return Count;
  232. }
  233. // Packet prefix
  234. GdbPutChar ('$');
  235. for (CheckSum = 0, Count = 0; *Ptr != '\0'; Ptr++, Count++) {
  236. GdbPutChar (*Ptr);
  237. CheckSum = CheckSum + *Ptr;
  238. }
  239. // Packet terminating character and checksum
  240. GdbPutChar ('#');
  241. GdbPutChar (mHexToStr[CheckSum >> 4]);
  242. GdbPutChar (mHexToStr[CheckSum & 0x0F]);
  243. TestChar = GdbGetChar ();
  244. } while (TestChar != '+');
  245. return Count;
  246. }
  247. /**
  248. Receive a GDB Remote Serial Protocol Packet
  249. $PacketData#checksum PacketData is passed in and this function adds the packet prefix '$',
  250. the packet terminating character '#' and the two digit checksum.
  251. If host re-starts sending a packet without ending the previous packet, only the last valid packet is processed.
  252. (In other words, if received packet is '$12345$12345$123456#checksum', only '$123456#checksum' will be processed.)
  253. If an ack '+' is not sent resend the packet
  254. @param PacketData Payload data for the packet
  255. @retval Number of bytes of packet data received.
  256. **/
  257. UINTN
  258. ReceivePacket (
  259. OUT CHAR8 *PacketData,
  260. IN UINTN PacketDataSize
  261. )
  262. {
  263. UINT8 CheckSum;
  264. UINTN Index;
  265. CHAR8 Char;
  266. CHAR8 SumString[3];
  267. CHAR8 TestChar;
  268. ZeroMem (PacketData, PacketDataSize);
  269. for ( ; ;) {
  270. // wait for the start of a packet
  271. TestChar = GdbGetChar ();
  272. while (TestChar != '$') {
  273. TestChar = GdbGetChar ();
  274. }
  275. retry:
  276. for (Index = 0, CheckSum = 0; Index < (PacketDataSize - 1); Index++) {
  277. Char = GdbGetChar ();
  278. if (Char == '$') {
  279. goto retry;
  280. }
  281. if (Char == '#') {
  282. break;
  283. }
  284. PacketData[Index] = Char;
  285. CheckSum = CheckSum + Char;
  286. }
  287. PacketData[Index] = '\0';
  288. if (Index == PacketDataSize) {
  289. continue;
  290. }
  291. SumString[0] = GdbGetChar ();
  292. SumString[1] = GdbGetChar ();
  293. SumString[2] = '\0';
  294. if (AsciiStrHexToUintn (SumString) == CheckSum) {
  295. // Ack: Success
  296. GdbPutChar ('+');
  297. // Null terminate the callers string
  298. PacketData[Index] = '\0';
  299. return Index;
  300. } else {
  301. // Ack: Failure
  302. GdbPutChar ('-');
  303. }
  304. }
  305. // return 0;
  306. }
  307. /**
  308. Empties the given buffer
  309. @param Buf pointer to the first element in buffer to be emptied
  310. **/
  311. VOID
  312. EmptyBuffer (
  313. IN CHAR8 *Buf
  314. )
  315. {
  316. *Buf = '\0';
  317. }
  318. /**
  319. Converts an 8-bit Hex Char into a INTN.
  320. @param Char the hex character to be converted into UINTN
  321. @retval a INTN, from 0 to 15, that corresponds to Char
  322. -1 if Char is not a hex character
  323. **/
  324. INTN
  325. HexCharToInt (
  326. IN CHAR8 Char
  327. )
  328. {
  329. if ((Char >= 'A') && (Char <= 'F')) {
  330. return Char - 'A' + 10;
  331. } else if ((Char >= 'a') && (Char <= 'f')) {
  332. return Char - 'a' + 10;
  333. } else if ((Char >= '0') && (Char <= '9')) {
  334. return Char - '0';
  335. } else {
  336. // if not a hex value, return a negative value
  337. return -1;
  338. }
  339. }
  340. // 'E' + the biggest error number is 255, so its 2 hex digits + buffer end
  341. CHAR8 *gError = "E__";
  342. /** 'E NN'
  343. Send an error with the given error number after converting to hex.
  344. The error number is put into the buffer in hex. '255' is the biggest errno we can send.
  345. ex: 162 will be sent as A2.
  346. @param errno the error number that will be sent
  347. **/
  348. VOID
  349. EFIAPI
  350. SendError (
  351. IN UINT8 ErrorNum
  352. )
  353. {
  354. //
  355. // Replace _, or old data, with current errno
  356. //
  357. gError[1] = mHexToStr[ErrorNum >> 4];
  358. gError[2] = mHexToStr[ErrorNum & 0x0f];
  359. SendPacket (gError); // send buffer
  360. }
  361. /**
  362. Send 'OK' when the function is done executing successfully.
  363. **/
  364. VOID
  365. EFIAPI
  366. SendSuccess (
  367. VOID
  368. )
  369. {
  370. SendPacket ("OK"); // send buffer
  371. }
  372. /**
  373. Send empty packet to specify that particular command/functionality is not supported.
  374. **/
  375. VOID
  376. EFIAPI
  377. SendNotSupported (
  378. VOID
  379. )
  380. {
  381. SendPacket ("");
  382. }
  383. /**
  384. Send the T signal with the given exception type (in gdb order) and possibly with n:r pairs related to the watchpoints
  385. @param SystemContext Register content at time of the exception
  386. @param GdbExceptionType GDB exception type
  387. **/
  388. VOID
  389. GdbSendTSignal (
  390. IN EFI_SYSTEM_CONTEXT SystemContext,
  391. IN UINT8 GdbExceptionType
  392. )
  393. {
  394. CHAR8 TSignalBuffer[128];
  395. CHAR8 *TSignalPtr;
  396. UINTN BreakpointDetected;
  397. BREAK_TYPE BreakType;
  398. UINTN DataAddress;
  399. CHAR8 *WatchStrPtr = NULL;
  400. UINTN RegSize;
  401. TSignalPtr = &TSignalBuffer[0];
  402. // Construct TSignal packet
  403. *TSignalPtr++ = 'T';
  404. //
  405. // replace _, or previous value, with Exception type
  406. //
  407. *TSignalPtr++ = mHexToStr[GdbExceptionType >> 4];
  408. *TSignalPtr++ = mHexToStr[GdbExceptionType & 0x0f];
  409. if (GdbExceptionType == GDB_SIGTRAP) {
  410. if (gSymbolTableUpdate) {
  411. //
  412. // We can only send back on reason code. So if the flag is set it means the breakpoint is from our event handler
  413. //
  414. WatchStrPtr = "library:;";
  415. while (*WatchStrPtr != '\0') {
  416. *TSignalPtr++ = *WatchStrPtr++;
  417. }
  418. gSymbolTableUpdate = FALSE;
  419. } else {
  420. //
  421. // possible n:r pairs
  422. //
  423. // Retrieve the breakpoint number
  424. BreakpointDetected = GetBreakpointDetected (SystemContext);
  425. // Figure out if the exception is happend due to watch, rwatch or awatch.
  426. BreakType = GetBreakpointType (SystemContext, BreakpointDetected);
  427. // INFO: rwatch is not supported due to the way IA32 debug registers work
  428. if ((BreakType == DataWrite) || (BreakType == DataRead) || (BreakType == DataReadWrite)) {
  429. // Construct n:r pair
  430. DataAddress = GetBreakpointDataAddress (SystemContext, BreakpointDetected);
  431. // Assign appropriate buffer to print particular watchpoint type
  432. if (BreakType == DataWrite) {
  433. WatchStrPtr = "watch";
  434. } else if (BreakType == DataRead) {
  435. WatchStrPtr = "rwatch";
  436. } else if (BreakType == DataReadWrite) {
  437. WatchStrPtr = "awatch";
  438. }
  439. while (*WatchStrPtr != '\0') {
  440. *TSignalPtr++ = *WatchStrPtr++;
  441. }
  442. *TSignalPtr++ = ':';
  443. // Set up series of bytes in big-endian byte order. "awatch" won't work with little-endian byte order.
  444. RegSize = REG_SIZE;
  445. while (RegSize > 0) {
  446. RegSize = RegSize-4;
  447. *TSignalPtr++ = mHexToStr[(UINT8)(DataAddress >> RegSize) & 0xf];
  448. }
  449. // Always end n:r pair with ';'
  450. *TSignalPtr++ = ';';
  451. }
  452. }
  453. }
  454. *TSignalPtr = '\0';
  455. SendPacket (TSignalBuffer);
  456. }
  457. /**
  458. Translates the EFI mapping to GDB mapping
  459. @param EFIExceptionType EFI Exception that is being processed
  460. @retval UINTN that corresponds to EFIExceptionType's GDB exception type number
  461. **/
  462. UINT8
  463. ConvertEFItoGDBtype (
  464. IN EFI_EXCEPTION_TYPE EFIExceptionType
  465. )
  466. {
  467. UINTN Index;
  468. for (Index = 0; Index < MaxEfiException (); Index++) {
  469. if (gExceptionType[Index].Exception == EFIExceptionType) {
  470. return gExceptionType[Index].SignalNo;
  471. }
  472. }
  473. return GDB_SIGTRAP; // this is a GDB trap
  474. }
  475. /** "m addr,length"
  476. Find the Length of the area to read and the start address. Finally, pass them to
  477. another function, TransferFromMemToOutBufAndSend, that will read from that memory space and
  478. send it as a packet.
  479. **/
  480. VOID
  481. EFIAPI
  482. ReadFromMemory (
  483. CHAR8 *PacketData
  484. )
  485. {
  486. UINTN Address;
  487. UINTN Length;
  488. CHAR8 AddressBuffer[MAX_ADDR_SIZE]; // the buffer that will hold the address in hex chars
  489. CHAR8 *AddrBufPtr; // pointer to the address buffer
  490. CHAR8 *InBufPtr; /// pointer to the input buffer
  491. AddrBufPtr = AddressBuffer;
  492. InBufPtr = &PacketData[1];
  493. while (*InBufPtr != ',') {
  494. *AddrBufPtr++ = *InBufPtr++;
  495. }
  496. *AddrBufPtr = '\0';
  497. InBufPtr++; // this skips ',' in the buffer
  498. /* Error checking */
  499. if (AsciiStrLen (AddressBuffer) >= MAX_ADDR_SIZE) {
  500. Print ((CHAR16 *)L"Address is too long\n");
  501. SendError (GDB_EBADMEMADDRBUFSIZE);
  502. return;
  503. }
  504. // 2 = 'm' + ','
  505. if (AsciiStrLen (PacketData) - AsciiStrLen (AddressBuffer) - 2 >= MAX_LENGTH_SIZE) {
  506. Print ((CHAR16 *)L"Length is too long\n");
  507. SendError (GDB_EBADMEMLENGTH);
  508. return;
  509. }
  510. Address = AsciiStrHexToUintn (AddressBuffer);
  511. Length = AsciiStrHexToUintn (InBufPtr);
  512. TransferFromMemToOutBufAndSend (Length, (unsigned char *)Address);
  513. }
  514. /** "M addr,length :XX..."
  515. Find the Length of the area in bytes to write and the start address. Finally, pass them to
  516. another function, TransferFromInBufToMem, that will write to that memory space the info in
  517. the input buffer.
  518. **/
  519. VOID
  520. EFIAPI
  521. WriteToMemory (
  522. IN CHAR8 *PacketData
  523. )
  524. {
  525. UINTN Address;
  526. UINTN Length;
  527. UINTN MessageLength;
  528. CHAR8 AddressBuffer[MAX_ADDR_SIZE]; // the buffer that will hold the Address in hex chars
  529. CHAR8 LengthBuffer[MAX_LENGTH_SIZE]; // the buffer that will hold the Length in hex chars
  530. CHAR8 *AddrBufPtr; // pointer to the Address buffer
  531. CHAR8 *LengthBufPtr; // pointer to the Length buffer
  532. CHAR8 *InBufPtr; /// pointer to the input buffer
  533. AddrBufPtr = AddressBuffer;
  534. LengthBufPtr = LengthBuffer;
  535. InBufPtr = &PacketData[1];
  536. while (*InBufPtr != ',') {
  537. *AddrBufPtr++ = *InBufPtr++;
  538. }
  539. *AddrBufPtr = '\0';
  540. InBufPtr++; // this skips ',' in the buffer
  541. while (*InBufPtr != ':') {
  542. *LengthBufPtr++ = *InBufPtr++;
  543. }
  544. *LengthBufPtr = '\0';
  545. InBufPtr++; // this skips ':' in the buffer
  546. Address = AsciiStrHexToUintn (AddressBuffer);
  547. Length = AsciiStrHexToUintn (LengthBuffer);
  548. /* Error checking */
  549. // Check if Address is not too long.
  550. if (AsciiStrLen (AddressBuffer) >= MAX_ADDR_SIZE) {
  551. Print ((CHAR16 *)L"Address too long..\n");
  552. SendError (GDB_EBADMEMADDRBUFSIZE);
  553. return;
  554. }
  555. // Check if message length is not too long
  556. if (AsciiStrLen (LengthBuffer) >= MAX_LENGTH_SIZE) {
  557. Print ((CHAR16 *)L"Length too long..\n");
  558. SendError (GDB_EBADMEMLENGBUFSIZE);
  559. return;
  560. }
  561. // Check if Message is not too long/short.
  562. // 3 = 'M' + ',' + ':'
  563. MessageLength = (AsciiStrLen (PacketData) - AsciiStrLen (AddressBuffer) - AsciiStrLen (LengthBuffer) - 3);
  564. if (MessageLength != (2*Length)) {
  565. // Message too long/short. New data is not the right size.
  566. SendError (GDB_EBADMEMDATASIZE);
  567. return;
  568. }
  569. TransferFromInBufToMem (Length, (unsigned char *)Address, InBufPtr);
  570. }
  571. /**
  572. Parses breakpoint packet data and captures Breakpoint type, Address and length.
  573. In case of an error, function returns particular error code. Returning 0 meaning
  574. no error.
  575. @param PacketData Pointer to the payload data for the packet.
  576. @param Type Breakpoint type
  577. @param Address Breakpoint address
  578. @param Length Breakpoint length in Bytes (1 byte, 2 byte, 4 byte)
  579. @retval 1 Success
  580. @retval {other} Particular error code
  581. **/
  582. UINTN
  583. ParseBreakpointPacket (
  584. IN CHAR8 *PacketData,
  585. OUT UINTN *Type,
  586. OUT UINTN *Address,
  587. OUT UINTN *Length
  588. )
  589. {
  590. CHAR8 AddressBuffer[MAX_ADDR_SIZE];
  591. CHAR8 *AddressBufferPtr;
  592. CHAR8 *PacketDataPtr;
  593. PacketDataPtr = &PacketData[1];
  594. AddressBufferPtr = AddressBuffer;
  595. *Type = AsciiStrHexToUintn (PacketDataPtr);
  596. // Breakpoint/watchpoint type should be between 0 to 4
  597. if (*Type > 4) {
  598. Print ((CHAR16 *)L"Type is invalid\n");
  599. return 22; // EINVAL: Invalid argument.
  600. }
  601. // Skip ',' in the buffer.
  602. while (*PacketDataPtr++ != ',') {
  603. }
  604. // Parse Address information
  605. while (*PacketDataPtr != ',') {
  606. *AddressBufferPtr++ = *PacketDataPtr++;
  607. }
  608. *AddressBufferPtr = '\0';
  609. // Check if Address is not too long.
  610. if (AsciiStrLen (AddressBuffer) >= MAX_ADDR_SIZE) {
  611. Print ((CHAR16 *)L"Address too long..\n");
  612. return 40; // EMSGSIZE: Message size too long.
  613. }
  614. *Address = AsciiStrHexToUintn (AddressBuffer);
  615. PacketDataPtr++; // This skips , in the buffer
  616. // Parse Length information
  617. *Length = AsciiStrHexToUintn (PacketDataPtr);
  618. // Length should be 1, 2 or 4 bytes
  619. if (*Length > 4) {
  620. Print ((CHAR16 *)L"Length is invalid\n");
  621. return 22; // EINVAL: Invalid argument
  622. }
  623. return 0; // 0 = No error
  624. }
  625. UINTN
  626. gXferObjectReadResponse (
  627. IN CHAR8 Type,
  628. IN CHAR8 *Str
  629. )
  630. {
  631. CHAR8 *OutBufPtr; // pointer to the output buffer
  632. CHAR8 Char;
  633. UINTN Count;
  634. // Response starts with 'm' or 'l' if it is the end
  635. OutBufPtr = gOutBuffer;
  636. *OutBufPtr++ = Type;
  637. Count = 1;
  638. // Binary data encoding
  639. OutBufPtr = gOutBuffer;
  640. while (*Str != '\0') {
  641. Char = *Str++;
  642. if ((Char == 0x7d) || (Char == 0x23) || (Char == 0x24) || (Char == 0x2a)) {
  643. // escape character
  644. *OutBufPtr++ = 0x7d;
  645. Char ^= 0x20;
  646. }
  647. *OutBufPtr++ = Char;
  648. Count++;
  649. }
  650. *OutBufPtr = '\0'; // the end of the buffer
  651. SendPacket (gOutBuffer);
  652. return Count;
  653. }
  654. /**
  655. Note: This should be a library function. In the Apple case you have to add
  656. the size of the PE/COFF header into the starting address to make things work
  657. right as there is no way to pad the Mach-O for the size of the PE/COFF header.
  658. Returns a pointer to the PDB file name for a PE/COFF image that has been
  659. loaded into system memory with the PE/COFF Loader Library functions.
  660. Returns the PDB file name for the PE/COFF image specified by Pe32Data. If
  661. the PE/COFF image specified by Pe32Data is not a valid, then NULL is
  662. returned. If the PE/COFF image specified by Pe32Data does not contain a
  663. debug directory entry, then NULL is returned. If the debug directory entry
  664. in the PE/COFF image specified by Pe32Data does not contain a PDB file name,
  665. then NULL is returned.
  666. If Pe32Data is NULL, then ASSERT().
  667. @param Pe32Data Pointer to the PE/COFF image that is loaded in system
  668. memory.
  669. @param DebugBase Address that the debugger would use as the base of the image
  670. @return The PDB file name for the PE/COFF image specified by Pe32Data or NULL
  671. if it cannot be retrieved. DebugBase is only valid if PDB file name is
  672. valid.
  673. **/
  674. VOID *
  675. EFIAPI
  676. PeCoffLoaderGetDebuggerInfo (
  677. IN VOID *Pe32Data,
  678. OUT VOID **DebugBase
  679. )
  680. {
  681. EFI_IMAGE_DOS_HEADER *DosHdr;
  682. EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION Hdr;
  683. EFI_IMAGE_DATA_DIRECTORY *DirectoryEntry;
  684. EFI_IMAGE_DEBUG_DIRECTORY_ENTRY *DebugEntry;
  685. UINTN DirCount;
  686. VOID *CodeViewEntryPointer;
  687. INTN TEImageAdjust;
  688. UINT32 NumberOfRvaAndSizes;
  689. UINT16 Magic;
  690. UINTN SizeOfHeaders;
  691. ASSERT (Pe32Data != NULL);
  692. TEImageAdjust = 0;
  693. DirectoryEntry = NULL;
  694. DebugEntry = NULL;
  695. NumberOfRvaAndSizes = 0;
  696. SizeOfHeaders = 0;
  697. DosHdr = (EFI_IMAGE_DOS_HEADER *)Pe32Data;
  698. if (DosHdr->e_magic == EFI_IMAGE_DOS_SIGNATURE) {
  699. //
  700. // DOS image header is present, so read the PE header after the DOS image header.
  701. //
  702. Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *)((UINTN)Pe32Data + (UINTN)((DosHdr->e_lfanew) & 0x0ffff));
  703. } else {
  704. //
  705. // DOS image header is not present, so PE header is at the image base.
  706. //
  707. Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *)Pe32Data;
  708. }
  709. if (Hdr.Te->Signature == EFI_TE_IMAGE_HEADER_SIGNATURE) {
  710. if (Hdr.Te->DataDirectory[EFI_TE_IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress != 0) {
  711. DirectoryEntry = &Hdr.Te->DataDirectory[EFI_TE_IMAGE_DIRECTORY_ENTRY_DEBUG];
  712. TEImageAdjust = sizeof (EFI_TE_IMAGE_HEADER) - Hdr.Te->StrippedSize;
  713. DebugEntry = (EFI_IMAGE_DEBUG_DIRECTORY_ENTRY *)((UINTN)Hdr.Te +
  714. Hdr.Te->DataDirectory[EFI_TE_IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress +
  715. TEImageAdjust);
  716. }
  717. SizeOfHeaders = sizeof (EFI_TE_IMAGE_HEADER) + (UINTN)Hdr.Te->BaseOfCode - (UINTN)Hdr.Te->StrippedSize;
  718. // __APPLE__ check this math...
  719. *DebugBase = ((CHAR8 *)Pe32Data) - TEImageAdjust;
  720. } else if (Hdr.Pe32->Signature == EFI_IMAGE_NT_SIGNATURE) {
  721. *DebugBase = Pe32Data;
  722. //
  723. // NOTE: We use Machine field to identify PE32/PE32+, instead of Magic.
  724. // It is due to backward-compatibility, for some system might
  725. // generate PE32+ image with PE32 Magic.
  726. //
  727. switch (Hdr.Pe32->FileHeader.Machine) {
  728. case EFI_IMAGE_MACHINE_IA32:
  729. //
  730. // Assume PE32 image with IA32 Machine field.
  731. //
  732. Magic = EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC;
  733. break;
  734. case EFI_IMAGE_MACHINE_X64:
  735. case EFI_IMAGE_MACHINE_IA64:
  736. //
  737. // Assume PE32+ image with X64 or IPF Machine field
  738. //
  739. Magic = EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC;
  740. break;
  741. default:
  742. //
  743. // For unknown Machine field, use Magic in optional Header
  744. //
  745. Magic = Hdr.Pe32->OptionalHeader.Magic;
  746. }
  747. if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
  748. //
  749. // Use PE32 offset get Debug Directory Entry
  750. //
  751. SizeOfHeaders = Hdr.Pe32->OptionalHeader.SizeOfHeaders;
  752. NumberOfRvaAndSizes = Hdr.Pe32->OptionalHeader.NumberOfRvaAndSizes;
  753. DirectoryEntry = (EFI_IMAGE_DATA_DIRECTORY *)&(Hdr.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_DEBUG]);
  754. DebugEntry = (EFI_IMAGE_DEBUG_DIRECTORY_ENTRY *)((UINTN)Pe32Data + DirectoryEntry->VirtualAddress);
  755. } else if (Hdr.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
  756. //
  757. // Use PE32+ offset get Debug Directory Entry
  758. //
  759. SizeOfHeaders = Hdr.Pe32Plus->OptionalHeader.SizeOfHeaders;
  760. NumberOfRvaAndSizes = Hdr.Pe32Plus->OptionalHeader.NumberOfRvaAndSizes;
  761. DirectoryEntry = (EFI_IMAGE_DATA_DIRECTORY *)&(Hdr.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_DEBUG]);
  762. DebugEntry = (EFI_IMAGE_DEBUG_DIRECTORY_ENTRY *)((UINTN)Pe32Data + DirectoryEntry->VirtualAddress);
  763. }
  764. if (NumberOfRvaAndSizes <= EFI_IMAGE_DIRECTORY_ENTRY_DEBUG) {
  765. DirectoryEntry = NULL;
  766. DebugEntry = NULL;
  767. }
  768. } else {
  769. return NULL;
  770. }
  771. if ((DebugEntry == NULL) || (DirectoryEntry == NULL)) {
  772. return NULL;
  773. }
  774. for (DirCount = 0; DirCount < DirectoryEntry->Size; DirCount += sizeof (EFI_IMAGE_DEBUG_DIRECTORY_ENTRY), DebugEntry++) {
  775. if (DebugEntry->Type == EFI_IMAGE_DEBUG_TYPE_CODEVIEW) {
  776. if (DebugEntry->SizeOfData > 0) {
  777. CodeViewEntryPointer = (VOID *)((UINTN)DebugEntry->RVA + ((UINTN)Pe32Data) + (UINTN)TEImageAdjust);
  778. switch (*(UINT32 *)CodeViewEntryPointer) {
  779. case CODEVIEW_SIGNATURE_NB10:
  780. return (VOID *)((CHAR8 *)CodeViewEntryPointer + sizeof (EFI_IMAGE_DEBUG_CODEVIEW_NB10_ENTRY));
  781. case CODEVIEW_SIGNATURE_RSDS:
  782. return (VOID *)((CHAR8 *)CodeViewEntryPointer + sizeof (EFI_IMAGE_DEBUG_CODEVIEW_RSDS_ENTRY));
  783. case CODEVIEW_SIGNATURE_MTOC:
  784. *DebugBase = (VOID *)(UINTN)((UINTN)DebugBase - SizeOfHeaders);
  785. return (VOID *)((CHAR8 *)CodeViewEntryPointer + sizeof (EFI_IMAGE_DEBUG_CODEVIEW_MTOC_ENTRY));
  786. default:
  787. break;
  788. }
  789. }
  790. }
  791. }
  792. (void)SizeOfHeaders;
  793. return NULL;
  794. }
  795. /**
  796. Process "qXfer:object:read:annex:offset,length" request.
  797. Returns an XML document that contains loaded libraries. In our case it is
  798. information in the EFI Debug Image Table converted into an XML document.
  799. GDB will call with an arbitrary length (it can't know the real length and
  800. will reply with chunks of XML that are easy for us to deal with. Gdb will
  801. keep calling until we say we are done. XML doc looks like:
  802. <library-list>
  803. <library name="/a/a/c/d.dSYM"><segment address="0x10000000"/></library>
  804. <library name="/a/m/e/e.pdb"><segment address="0x20000000"/></library>
  805. <library name="/a/l/f/f.dll"><segment address="0x30000000"/></library>
  806. </library-list>
  807. Since we can not allocate memory in interrupt context this module has
  808. assumptions about how it will get called:
  809. 1) Length will generally be max remote packet size (big enough)
  810. 2) First Offset of an XML document read needs to be 0
  811. 3) This code will return back small chunks of the XML document on every read.
  812. Each subsequent call will ask for the next available part of the document.
  813. Note: The only variable size element in the XML is:
  814. " <library name=\"%s\"><segment address=\"%p\"/></library>\n" and it is
  815. based on the file path and name of the symbol file. If the symbol file name
  816. is bigger than the max gdb remote packet size we could update this code
  817. to respond back in chunks.
  818. @param Offset offset into special data area
  819. @param Length number of bytes to read starting at Offset
  820. **/
  821. VOID
  822. QxferLibrary (
  823. IN UINTN Offset,
  824. IN UINTN Length
  825. )
  826. {
  827. VOID *LoadAddress;
  828. CHAR8 *Pdb;
  829. UINTN Size;
  830. if (Offset != gPacketqXferLibraryOffset) {
  831. SendError (GDB_EINVALIDARG);
  832. Print (L"\nqXferLibrary (%d, %d) != %d\n", Offset, Length, gPacketqXferLibraryOffset);
  833. // Force a retry from the beginning
  834. gPacketqXferLibraryOffset = 0;
  835. return;
  836. }
  837. if (Offset == 0) {
  838. gPacketqXferLibraryOffset += gXferObjectReadResponse ('m', "<library-list>\n");
  839. // The owner of the table may have had to ralloc it so grab a fresh copy every time
  840. // we assume qXferLibrary will get called over and over again until the entire XML table is
  841. // returned in a tight loop. Since we are in the debugger the table should not get updated
  842. gDebugTable = gDebugImageTableHeader->EfiDebugImageInfoTable;
  843. gEfiDebugImageTableEntry = 0;
  844. return;
  845. }
  846. if (gDebugTable != NULL) {
  847. for ( ; gEfiDebugImageTableEntry < gDebugImageTableHeader->TableSize; gEfiDebugImageTableEntry++, gDebugTable++) {
  848. if (gDebugTable->NormalImage != NULL) {
  849. if ((gDebugTable->NormalImage->ImageInfoType == EFI_DEBUG_IMAGE_INFO_TYPE_NORMAL) &&
  850. (gDebugTable->NormalImage->LoadedImageProtocolInstance != NULL))
  851. {
  852. Pdb = PeCoffLoaderGetDebuggerInfo (
  853. gDebugTable->NormalImage->LoadedImageProtocolInstance->ImageBase,
  854. &LoadAddress
  855. );
  856. if (Pdb != NULL) {
  857. Size = AsciiSPrint (
  858. gXferLibraryBuffer,
  859. sizeof (gXferLibraryBuffer),
  860. " <library name=\"%a\"><segment address=\"0x%p\"/></library>\n",
  861. Pdb,
  862. LoadAddress
  863. );
  864. if ((Size != 0) && (Size != (sizeof (gXferLibraryBuffer) - 1))) {
  865. gPacketqXferLibraryOffset += gXferObjectReadResponse ('m', gXferLibraryBuffer);
  866. // Update loop variables so we are in the right place when we get back
  867. gEfiDebugImageTableEntry++;
  868. gDebugTable++;
  869. return;
  870. } else {
  871. // We could handle <library> entires larger than sizeof (gXferLibraryBuffer) here if
  872. // needed by breaking up into N packets
  873. // "<library name=\"%s
  874. // the rest of the string (as many packets as required
  875. // \"><segment address=\"%d\"/></library> (fixed size)
  876. //
  877. // But right now we just skip any entry that is too big
  878. }
  879. }
  880. }
  881. }
  882. }
  883. }
  884. gXferObjectReadResponse ('l', "</library-list>\n");
  885. gPacketqXferLibraryOffset = 0;
  886. return;
  887. }
  888. /**
  889. Exception Handler for GDB. It will be called for all exceptions
  890. registered via the gExceptionType[] array.
  891. @param ExceptionType Exception that is being processed
  892. @param SystemContext Register content at time of the exception
  893. **/
  894. VOID
  895. EFIAPI
  896. GdbExceptionHandler (
  897. IN EFI_EXCEPTION_TYPE ExceptionType,
  898. IN OUT EFI_SYSTEM_CONTEXT SystemContext
  899. )
  900. {
  901. UINT8 GdbExceptionType;
  902. CHAR8 *Ptr;
  903. if (ValidateException (ExceptionType, SystemContext) == FALSE) {
  904. return;
  905. }
  906. RemoveSingleStep (SystemContext);
  907. GdbExceptionType = ConvertEFItoGDBtype (ExceptionType);
  908. GdbSendTSignal (SystemContext, GdbExceptionType);
  909. for ( ; ; ) {
  910. ReceivePacket (gInBuffer, MAX_BUF_SIZE);
  911. switch (gInBuffer[0]) {
  912. case '?':
  913. GdbSendTSignal (SystemContext, GdbExceptionType);
  914. break;
  915. case 'c':
  916. ContinueAtAddress (SystemContext, gInBuffer);
  917. return;
  918. case 'g':
  919. ReadGeneralRegisters (SystemContext);
  920. break;
  921. case 'G':
  922. WriteGeneralRegisters (SystemContext, gInBuffer);
  923. break;
  924. case 'H':
  925. // Return "OK" packet since we don't have more than one thread.
  926. SendSuccess ();
  927. break;
  928. case 'm':
  929. ReadFromMemory (gInBuffer);
  930. break;
  931. case 'M':
  932. WriteToMemory (gInBuffer);
  933. break;
  934. case 'P':
  935. WriteNthRegister (SystemContext, gInBuffer);
  936. break;
  937. //
  938. // Still debugging this code. Not used in Darwin
  939. //
  940. case 'q':
  941. // General Query Packets
  942. if (AsciiStrnCmp (gInBuffer, "qSupported", 10) == 0) {
  943. // return what we currently support, we don't parse what gdb supports
  944. AsciiSPrint (gOutBuffer, MAX_BUF_SIZE, "qXfer:libraries:read+;PacketSize=%d", MAX_BUF_SIZE);
  945. SendPacket (gOutBuffer);
  946. } else if (AsciiStrnCmp (gInBuffer, "qXfer:libraries:read::", 22) == 0) {
  947. // ‘qXfer:libraries:read::offset,length
  948. // gInBuffer[22] is offset string, ++Ptr is length string’
  949. for (Ptr = &gInBuffer[22]; *Ptr != ','; Ptr++) {
  950. }
  951. // Not sure if multi-radix support is required. Currently only support decimal
  952. QxferLibrary (AsciiStrHexToUintn (&gInBuffer[22]), AsciiStrHexToUintn (++Ptr));
  953. }
  954. if (AsciiStrnCmp (gInBuffer, "qOffsets", 10) == 0) {
  955. AsciiSPrint (gOutBuffer, MAX_BUF_SIZE, "Text=1000;Data=f000;Bss=f000");
  956. SendPacket (gOutBuffer);
  957. } else {
  958. // Send empty packet
  959. SendNotSupported ();
  960. }
  961. break;
  962. case 's':
  963. SingleStep (SystemContext, gInBuffer);
  964. return;
  965. case 'z':
  966. RemoveBreakPoint (SystemContext, gInBuffer);
  967. break;
  968. case 'Z':
  969. InsertBreakPoint (SystemContext, gInBuffer);
  970. break;
  971. default:
  972. // Send empty packet
  973. SendNotSupported ();
  974. break;
  975. }
  976. }
  977. }
  978. /**
  979. Periodic callback for GDB. This function is used to catch a ctrl-c or other
  980. break in type command from GDB.
  981. @param SystemContext Register content at time of the call
  982. **/
  983. VOID
  984. EFIAPI
  985. GdbPeriodicCallBack (
  986. IN OUT EFI_SYSTEM_CONTEXT SystemContext
  987. )
  988. {
  989. //
  990. // gCtrlCBreakFlag may have been set from a previous F response package
  991. // and we set the global as we need to process it at a point where we
  992. // can update the system context. If we are in the middle of processing
  993. // a F Packet it is not safe to read the GDB serial stream so we need
  994. // to skip it on this check
  995. //
  996. if (!gCtrlCBreakFlag && !gProcessingFPacket) {
  997. //
  998. // Ctrl-C was not pending so grab any pending characters and see if they
  999. // are a Ctrl-c (0x03). If so set the Ctrl-C global.
  1000. //
  1001. while (TRUE) {
  1002. if (!GdbIsCharAvailable ()) {
  1003. //
  1004. // No characters are pending so exit the loop
  1005. //
  1006. break;
  1007. }
  1008. if (GdbGetChar () == 0x03) {
  1009. gCtrlCBreakFlag = TRUE;
  1010. //
  1011. // We have a ctrl-c so exit the loop
  1012. //
  1013. break;
  1014. }
  1015. }
  1016. }
  1017. if (gCtrlCBreakFlag) {
  1018. //
  1019. // Update the context to force a single step trap when we exit the GDB
  1020. // stub. This will transfer control to GdbExceptionHandler () and let
  1021. // us break into the program. We don't want to break into the GDB stub.
  1022. //
  1023. AddSingleStep (SystemContext);
  1024. gCtrlCBreakFlag = FALSE;
  1025. }
  1026. }