GdbStub.c 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251
  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 Serail 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 ((EFI_D_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 ((EFI_D_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 ((EFI_D_INFO, "Debug Support Protocol ISA %x\n", DebugSupport->Isa));
  101. DEBUG ((EFI_D_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 teminating 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 infinit 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 teminating 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 corressponds 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 { // if not a hex value, return a negative value
  336. return -1;
  337. }
  338. }
  339. // 'E' + the biggest error number is 255, so its 2 hex digits + buffer end
  340. CHAR8 *gError = "E__";
  341. /** 'E NN'
  342. Send an error with the given error number after converting to hex.
  343. The error number is put into the buffer in hex. '255' is the biggest errno we can send.
  344. ex: 162 will be sent as A2.
  345. @param errno the error number that will be sent
  346. **/
  347. VOID
  348. EFIAPI
  349. SendError (
  350. IN UINT8 ErrorNum
  351. )
  352. {
  353. //
  354. // Replace _, or old data, with current errno
  355. //
  356. gError[1] = mHexToStr [ErrorNum >> 4];
  357. gError[2] = mHexToStr [ErrorNum & 0x0f];
  358. SendPacket (gError); // send buffer
  359. }
  360. /**
  361. Send 'OK' when the function is done executing successfully.
  362. **/
  363. VOID
  364. EFIAPI
  365. SendSuccess (
  366. VOID
  367. )
  368. {
  369. SendPacket ("OK"); // send buffer
  370. }
  371. /**
  372. Send empty packet to specify that particular command/functionality is not supported.
  373. **/
  374. VOID
  375. EFIAPI
  376. SendNotSupported (
  377. VOID
  378. )
  379. {
  380. SendPacket ("");
  381. }
  382. /**
  383. Send the T signal with the given exception type (in gdb order) and possibly with n:r pairs related to the watchpoints
  384. @param SystemContext Register content at time of the exception
  385. @param GdbExceptionType GDB exception type
  386. **/
  387. VOID
  388. GdbSendTSignal (
  389. IN EFI_SYSTEM_CONTEXT SystemContext,
  390. IN UINT8 GdbExceptionType
  391. )
  392. {
  393. CHAR8 TSignalBuffer[128];
  394. CHAR8 *TSignalPtr;
  395. UINTN BreakpointDetected;
  396. BREAK_TYPE BreakType;
  397. UINTN DataAddress;
  398. CHAR8 *WatchStrPtr = NULL;
  399. UINTN RegSize;
  400. TSignalPtr = &TSignalBuffer[0];
  401. //Construct TSignal packet
  402. *TSignalPtr++ = 'T';
  403. //
  404. // replace _, or previous value, with Exception type
  405. //
  406. *TSignalPtr++ = mHexToStr [GdbExceptionType >> 4];
  407. *TSignalPtr++ = mHexToStr [GdbExceptionType & 0x0f];
  408. if (GdbExceptionType == GDB_SIGTRAP) {
  409. if (gSymbolTableUpdate) {
  410. //
  411. // We can only send back on reason code. So if the flag is set it means the breakpoint is from our event handler
  412. //
  413. WatchStrPtr = "library:;";
  414. while (*WatchStrPtr != '\0') {
  415. *TSignalPtr++ = *WatchStrPtr++;
  416. }
  417. gSymbolTableUpdate = FALSE;
  418. } else {
  419. //
  420. // possible n:r pairs
  421. //
  422. //Retrieve the breakpoint number
  423. BreakpointDetected = GetBreakpointDetected (SystemContext);
  424. //Figure out if the exception is happend due to watch, rwatch or awatch.
  425. BreakType = GetBreakpointType (SystemContext, BreakpointDetected);
  426. //INFO: rwatch is not supported due to the way IA32 debug registers work
  427. if ((BreakType == DataWrite) || (BreakType == DataRead) || (BreakType == DataReadWrite)) {
  428. //Construct n:r pair
  429. DataAddress = GetBreakpointDataAddress (SystemContext, BreakpointDetected);
  430. //Assign appropriate buffer to print particular watchpoint type
  431. if (BreakType == DataWrite) {
  432. WatchStrPtr = "watch";
  433. } else if (BreakType == DataRead) {
  434. WatchStrPtr = "rwatch";
  435. } else if (BreakType == DataReadWrite) {
  436. WatchStrPtr = "awatch";
  437. }
  438. while (*WatchStrPtr != '\0') {
  439. *TSignalPtr++ = *WatchStrPtr++;
  440. }
  441. *TSignalPtr++ = ':';
  442. //Set up series of bytes in big-endian byte order. "awatch" won't work with little-endian byte order.
  443. RegSize = REG_SIZE;
  444. while (RegSize > 0) {
  445. RegSize = RegSize-4;
  446. *TSignalPtr++ = mHexToStr[(UINT8)(DataAddress >> RegSize) & 0xf];
  447. }
  448. //Always end n:r pair with ';'
  449. *TSignalPtr++ = ';';
  450. }
  451. }
  452. }
  453. *TSignalPtr = '\0';
  454. SendPacket (TSignalBuffer);
  455. }
  456. /**
  457. Translates the EFI mapping to GDB mapping
  458. @param EFIExceptionType EFI Exception that is being processed
  459. @retval UINTN that corresponds to EFIExceptionType's GDB exception type number
  460. **/
  461. UINT8
  462. ConvertEFItoGDBtype (
  463. IN EFI_EXCEPTION_TYPE EFIExceptionType
  464. )
  465. {
  466. UINTN Index;
  467. for (Index = 0; Index < MaxEfiException () ; Index++) {
  468. if (gExceptionType[Index].Exception == EFIExceptionType) {
  469. return gExceptionType[Index].SignalNo;
  470. }
  471. }
  472. return GDB_SIGTRAP; // this is a GDB trap
  473. }
  474. /** "m addr,length"
  475. Find the Length of the area to read and the start addres. Finally, pass them to
  476. another function, TransferFromMemToOutBufAndSend, that will read from that memory space and
  477. send it as a packet.
  478. **/
  479. VOID
  480. EFIAPI
  481. ReadFromMemory (
  482. CHAR8 *PacketData
  483. )
  484. {
  485. UINTN Address;
  486. UINTN Length;
  487. CHAR8 AddressBuffer[MAX_ADDR_SIZE]; // the buffer that will hold the address in hex chars
  488. CHAR8 *AddrBufPtr; // pointer to the address buffer
  489. CHAR8 *InBufPtr; /// pointer to the input buffer
  490. AddrBufPtr = AddressBuffer;
  491. InBufPtr = &PacketData[1];
  492. while (*InBufPtr != ',') {
  493. *AddrBufPtr++ = *InBufPtr++;
  494. }
  495. *AddrBufPtr = '\0';
  496. InBufPtr++; // this skips ',' in the buffer
  497. /* Error checking */
  498. if (AsciiStrLen (AddressBuffer) >= MAX_ADDR_SIZE) {
  499. Print((CHAR16 *)L"Address is too long\n");
  500. SendError (GDB_EBADMEMADDRBUFSIZE);
  501. return;
  502. }
  503. // 2 = 'm' + ','
  504. if (AsciiStrLen (PacketData) - AsciiStrLen (AddressBuffer) - 2 >= MAX_LENGTH_SIZE) {
  505. Print((CHAR16 *)L"Length is too long\n");
  506. SendError (GDB_EBADMEMLENGTH);
  507. return;
  508. }
  509. Address = AsciiStrHexToUintn (AddressBuffer);
  510. Length = AsciiStrHexToUintn (InBufPtr);
  511. TransferFromMemToOutBufAndSend (Length, (unsigned char *)Address);
  512. }
  513. /** "M addr,length :XX..."
  514. Find the Length of the area in bytes to write and the start addres. Finally, pass them to
  515. another function, TransferFromInBufToMem, that will write to that memory space the info in
  516. the input buffer.
  517. **/
  518. VOID
  519. EFIAPI
  520. WriteToMemory (
  521. IN CHAR8 *PacketData
  522. )
  523. {
  524. UINTN Address;
  525. UINTN Length;
  526. UINTN MessageLength;
  527. CHAR8 AddressBuffer[MAX_ADDR_SIZE]; // the buffer that will hold the Address in hex chars
  528. CHAR8 LengthBuffer[MAX_LENGTH_SIZE]; // the buffer that will hold the Length in hex chars
  529. CHAR8 *AddrBufPtr; // pointer to the Address buffer
  530. CHAR8 *LengthBufPtr; // pointer to the Length buffer
  531. CHAR8 *InBufPtr; /// pointer to the input buffer
  532. AddrBufPtr = AddressBuffer;
  533. LengthBufPtr = LengthBuffer;
  534. InBufPtr = &PacketData[1];
  535. while (*InBufPtr != ',') {
  536. *AddrBufPtr++ = *InBufPtr++;
  537. }
  538. *AddrBufPtr = '\0';
  539. InBufPtr++; // this skips ',' in the buffer
  540. while (*InBufPtr != ':') {
  541. *LengthBufPtr++ = *InBufPtr++;
  542. }
  543. *LengthBufPtr = '\0';
  544. InBufPtr++; // this skips ':' in the buffer
  545. Address = AsciiStrHexToUintn (AddressBuffer);
  546. Length = AsciiStrHexToUintn (LengthBuffer);
  547. /* Error checking */
  548. //Check if Address is not too long.
  549. if (AsciiStrLen (AddressBuffer) >= MAX_ADDR_SIZE) {
  550. Print ((CHAR16 *)L"Address too long..\n");
  551. SendError (GDB_EBADMEMADDRBUFSIZE);
  552. return;
  553. }
  554. //Check if message length is not too long
  555. if (AsciiStrLen (LengthBuffer) >= MAX_LENGTH_SIZE) {
  556. Print ((CHAR16 *)L"Length too long..\n");
  557. SendError (GDB_EBADMEMLENGBUFSIZE);
  558. return;
  559. }
  560. // Check if Message is not too long/short.
  561. // 3 = 'M' + ',' + ':'
  562. MessageLength = (AsciiStrLen (PacketData) - AsciiStrLen (AddressBuffer) - AsciiStrLen (LengthBuffer) - 3);
  563. if (MessageLength != (2*Length)) {
  564. //Message too long/short. New data is not the right size.
  565. SendError (GDB_EBADMEMDATASIZE);
  566. return;
  567. }
  568. TransferFromInBufToMem (Length, (unsigned char *)Address, InBufPtr);
  569. }
  570. /**
  571. Parses breakpoint packet data and captures Breakpoint type, Address and length.
  572. In case of an error, function returns particular error code. Returning 0 meaning
  573. no error.
  574. @param PacketData Pointer to the payload data for the packet.
  575. @param Type Breakpoint type
  576. @param Address Breakpoint address
  577. @param Length Breakpoint length in Bytes (1 byte, 2 byte, 4 byte)
  578. @retval 1 Success
  579. @retval {other} Particular error code
  580. **/
  581. UINTN
  582. ParseBreakpointPacket (
  583. IN CHAR8 *PacketData,
  584. OUT UINTN *Type,
  585. OUT UINTN *Address,
  586. OUT UINTN *Length
  587. )
  588. {
  589. CHAR8 AddressBuffer[MAX_ADDR_SIZE];
  590. CHAR8 *AddressBufferPtr;
  591. CHAR8 *PacketDataPtr;
  592. PacketDataPtr = &PacketData[1];
  593. AddressBufferPtr = AddressBuffer;
  594. *Type = AsciiStrHexToUintn (PacketDataPtr);
  595. //Breakpoint/watchpoint type should be between 0 to 4
  596. if (*Type > 4) {
  597. Print ((CHAR16 *)L"Type is invalid\n");
  598. return 22; //EINVAL: Invalid argument.
  599. }
  600. //Skip ',' in the buffer.
  601. while (*PacketDataPtr++ != ',');
  602. //Parse Address information
  603. while (*PacketDataPtr != ',') {
  604. *AddressBufferPtr++ = *PacketDataPtr++;
  605. }
  606. *AddressBufferPtr = '\0';
  607. //Check if Address is not too long.
  608. if (AsciiStrLen (AddressBuffer) >= MAX_ADDR_SIZE) {
  609. Print ((CHAR16 *)L"Address too long..\n");
  610. return 40; //EMSGSIZE: Message size too long.
  611. }
  612. *Address = AsciiStrHexToUintn (AddressBuffer);
  613. PacketDataPtr++; //This skips , in the buffer
  614. //Parse Length information
  615. *Length = AsciiStrHexToUintn (PacketDataPtr);
  616. //Length should be 1, 2 or 4 bytes
  617. if (*Length > 4) {
  618. Print ((CHAR16 *)L"Length is invalid\n");
  619. return 22; //EINVAL: Invalid argument
  620. }
  621. return 0; //0 = No error
  622. }
  623. UINTN
  624. gXferObjectReadResponse (
  625. IN CHAR8 Type,
  626. IN CHAR8 *Str
  627. )
  628. {
  629. CHAR8 *OutBufPtr; // pointer to the output buffer
  630. CHAR8 Char;
  631. UINTN Count;
  632. // Response starts with 'm' or 'l' if it is the end
  633. OutBufPtr = gOutBuffer;
  634. *OutBufPtr++ = Type;
  635. Count = 1;
  636. // Binary data encoding
  637. OutBufPtr = gOutBuffer;
  638. while (*Str != '\0') {
  639. Char = *Str++;
  640. if ((Char == 0x7d) || (Char == 0x23) || (Char == 0x24) || (Char == 0x2a)) {
  641. // escape character
  642. *OutBufPtr++ = 0x7d;
  643. Char ^= 0x20;
  644. }
  645. *OutBufPtr++ = Char;
  646. Count++;
  647. }
  648. *OutBufPtr = '\0' ; // the end of the buffer
  649. SendPacket (gOutBuffer);
  650. return Count;
  651. }
  652. /**
  653. Note: This should be a library function. In the Apple case you have to add
  654. the size of the PE/COFF header into the starting address to make things work
  655. right as there is no way to pad the Mach-O for the size of the PE/COFF header.
  656. Returns a pointer to the PDB file name for a PE/COFF image that has been
  657. loaded into system memory with the PE/COFF Loader Library functions.
  658. Returns the PDB file name for the PE/COFF image specified by Pe32Data. If
  659. the PE/COFF image specified by Pe32Data is not a valid, then NULL is
  660. returned. If the PE/COFF image specified by Pe32Data does not contain a
  661. debug directory entry, then NULL is returned. If the debug directory entry
  662. in the PE/COFF image specified by Pe32Data does not contain a PDB file name,
  663. then NULL is returned.
  664. If Pe32Data is NULL, then ASSERT().
  665. @param Pe32Data Pointer to the PE/COFF image that is loaded in system
  666. memory.
  667. @param DebugBase Address that the debugger would use as the base of the image
  668. @return The PDB file name for the PE/COFF image specified by Pe32Data or NULL
  669. if it cannot be retrieved. DebugBase is only valid if PDB file name is
  670. valid.
  671. **/
  672. VOID *
  673. EFIAPI
  674. PeCoffLoaderGetDebuggerInfo (
  675. IN VOID *Pe32Data,
  676. OUT VOID **DebugBase
  677. )
  678. {
  679. EFI_IMAGE_DOS_HEADER *DosHdr;
  680. EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION Hdr;
  681. EFI_IMAGE_DATA_DIRECTORY *DirectoryEntry;
  682. EFI_IMAGE_DEBUG_DIRECTORY_ENTRY *DebugEntry;
  683. UINTN DirCount;
  684. VOID *CodeViewEntryPointer;
  685. INTN TEImageAdjust;
  686. UINT32 NumberOfRvaAndSizes;
  687. UINT16 Magic;
  688. UINTN SizeOfHeaders;
  689. ASSERT (Pe32Data != NULL);
  690. TEImageAdjust = 0;
  691. DirectoryEntry = NULL;
  692. DebugEntry = NULL;
  693. NumberOfRvaAndSizes = 0;
  694. SizeOfHeaders = 0;
  695. DosHdr = (EFI_IMAGE_DOS_HEADER *)Pe32Data;
  696. if (DosHdr->e_magic == EFI_IMAGE_DOS_SIGNATURE) {
  697. //
  698. // DOS image header is present, so read the PE header after the DOS image header.
  699. //
  700. Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *)((UINTN) Pe32Data + (UINTN) ((DosHdr->e_lfanew) & 0x0ffff));
  701. } else {
  702. //
  703. // DOS image header is not present, so PE header is at the image base.
  704. //
  705. Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *)Pe32Data;
  706. }
  707. if (Hdr.Te->Signature == EFI_TE_IMAGE_HEADER_SIGNATURE) {
  708. if (Hdr.Te->DataDirectory[EFI_TE_IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress != 0) {
  709. DirectoryEntry = &Hdr.Te->DataDirectory[EFI_TE_IMAGE_DIRECTORY_ENTRY_DEBUG];
  710. TEImageAdjust = sizeof (EFI_TE_IMAGE_HEADER) - Hdr.Te->StrippedSize;
  711. DebugEntry = (EFI_IMAGE_DEBUG_DIRECTORY_ENTRY *)((UINTN) Hdr.Te +
  712. Hdr.Te->DataDirectory[EFI_TE_IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress +
  713. TEImageAdjust);
  714. }
  715. SizeOfHeaders = sizeof (EFI_TE_IMAGE_HEADER) + (UINTN)Hdr.Te->BaseOfCode - (UINTN)Hdr.Te->StrippedSize;
  716. // __APPLE__ check this math...
  717. *DebugBase = ((CHAR8 *)Pe32Data) - TEImageAdjust;
  718. } else if (Hdr.Pe32->Signature == EFI_IMAGE_NT_SIGNATURE) {
  719. *DebugBase = Pe32Data;
  720. //
  721. // NOTE: We use Machine field to identify PE32/PE32+, instead of Magic.
  722. // It is due to backward-compatibility, for some system might
  723. // generate PE32+ image with PE32 Magic.
  724. //
  725. switch (Hdr.Pe32->FileHeader.Machine) {
  726. case EFI_IMAGE_MACHINE_IA32:
  727. //
  728. // Assume PE32 image with IA32 Machine field.
  729. //
  730. Magic = EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC;
  731. break;
  732. case EFI_IMAGE_MACHINE_X64:
  733. case EFI_IMAGE_MACHINE_IA64:
  734. //
  735. // Assume PE32+ image with X64 or IPF Machine field
  736. //
  737. Magic = EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC;
  738. break;
  739. default:
  740. //
  741. // For unknow Machine field, use Magic in optional Header
  742. //
  743. Magic = Hdr.Pe32->OptionalHeader.Magic;
  744. }
  745. if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
  746. //
  747. // Use PE32 offset get Debug Directory Entry
  748. //
  749. SizeOfHeaders = Hdr.Pe32->OptionalHeader.SizeOfHeaders;
  750. NumberOfRvaAndSizes = Hdr.Pe32->OptionalHeader.NumberOfRvaAndSizes;
  751. DirectoryEntry = (EFI_IMAGE_DATA_DIRECTORY *)&(Hdr.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_DEBUG]);
  752. DebugEntry = (EFI_IMAGE_DEBUG_DIRECTORY_ENTRY *) ((UINTN) Pe32Data + DirectoryEntry->VirtualAddress);
  753. } else if (Hdr.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
  754. //
  755. // Use PE32+ offset get Debug Directory Entry
  756. //
  757. SizeOfHeaders = Hdr.Pe32Plus->OptionalHeader.SizeOfHeaders;
  758. NumberOfRvaAndSizes = Hdr.Pe32Plus->OptionalHeader.NumberOfRvaAndSizes;
  759. DirectoryEntry = (EFI_IMAGE_DATA_DIRECTORY *)&(Hdr.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_DEBUG]);
  760. DebugEntry = (EFI_IMAGE_DEBUG_DIRECTORY_ENTRY *) ((UINTN) Pe32Data + DirectoryEntry->VirtualAddress);
  761. }
  762. if (NumberOfRvaAndSizes <= EFI_IMAGE_DIRECTORY_ENTRY_DEBUG) {
  763. DirectoryEntry = NULL;
  764. DebugEntry = NULL;
  765. }
  766. } else {
  767. return NULL;
  768. }
  769. if (DebugEntry == NULL || DirectoryEntry == NULL) {
  770. return NULL;
  771. }
  772. for (DirCount = 0; DirCount < DirectoryEntry->Size; DirCount += sizeof (EFI_IMAGE_DEBUG_DIRECTORY_ENTRY), DebugEntry++) {
  773. if (DebugEntry->Type == EFI_IMAGE_DEBUG_TYPE_CODEVIEW) {
  774. if (DebugEntry->SizeOfData > 0) {
  775. CodeViewEntryPointer = (VOID *) ((UINTN) DebugEntry->RVA + ((UINTN)Pe32Data) + (UINTN)TEImageAdjust);
  776. switch (* (UINT32 *) CodeViewEntryPointer) {
  777. case CODEVIEW_SIGNATURE_NB10:
  778. return (VOID *) ((CHAR8 *)CodeViewEntryPointer + sizeof (EFI_IMAGE_DEBUG_CODEVIEW_NB10_ENTRY));
  779. case CODEVIEW_SIGNATURE_RSDS:
  780. return (VOID *) ((CHAR8 *)CodeViewEntryPointer + sizeof (EFI_IMAGE_DEBUG_CODEVIEW_RSDS_ENTRY));
  781. case CODEVIEW_SIGNATURE_MTOC:
  782. *DebugBase = (VOID *)(UINTN)((UINTN)DebugBase - SizeOfHeaders);
  783. return (VOID *) ((CHAR8 *)CodeViewEntryPointer + sizeof (EFI_IMAGE_DEBUG_CODEVIEW_MTOC_ENTRY));
  784. default:
  785. break;
  786. }
  787. }
  788. }
  789. }
  790. (void)SizeOfHeaders;
  791. return NULL;
  792. }
  793. /**
  794. Process "qXfer:object:read:annex:offset,length" request.
  795. Returns an XML document that contains loaded libraries. In our case it is
  796. information in the EFI Debug Image Table converted into an XML document.
  797. GDB will call with an arbitrary length (it can't know the real length and
  798. will reply with chunks of XML that are easy for us to deal with. Gdb will
  799. keep calling until we say we are done. XML doc looks like:
  800. <library-list>
  801. <library name="/a/a/c/d.dSYM"><segment address="0x10000000"/></library>
  802. <library name="/a/m/e/e.pdb"><segment address="0x20000000"/></library>
  803. <library name="/a/l/f/f.dll"><segment address="0x30000000"/></library>
  804. </library-list>
  805. Since we can not allocate memory in interrupt context this module has
  806. assumptions about how it will get called:
  807. 1) Length will generally be max remote packet size (big enough)
  808. 2) First Offset of an XML document read needs to be 0
  809. 3) This code will return back small chunks of the XML document on every read.
  810. Each subsequent call will ask for the next available part of the document.
  811. Note: The only variable size element in the XML is:
  812. " <library name=\"%s\"><segment address=\"%p\"/></library>\n" and it is
  813. based on the file path and name of the symbol file. If the symbol file name
  814. is bigger than the max gdb remote packet size we could update this code
  815. to respond back in chunks.
  816. @param Offset offset into special data area
  817. @param Length number of bytes to read starting at Offset
  818. **/
  819. VOID
  820. QxferLibrary (
  821. IN UINTN Offset,
  822. IN UINTN Length
  823. )
  824. {
  825. VOID *LoadAddress;
  826. CHAR8 *Pdb;
  827. UINTN Size;
  828. if (Offset != gPacketqXferLibraryOffset) {
  829. SendError (GDB_EINVALIDARG);
  830. Print (L"\nqXferLibrary (%d, %d) != %d\n", Offset, Length, gPacketqXferLibraryOffset);
  831. // Force a retry from the beginning
  832. gPacketqXferLibraryOffset = 0;
  833. return;
  834. }
  835. if (Offset == 0) {
  836. gPacketqXferLibraryOffset += gXferObjectReadResponse ('m', "<library-list>\n");
  837. // The owner of the table may have had to ralloc it so grab a fresh copy every time
  838. // we assume qXferLibrary will get called over and over again until the entire XML table is
  839. // returned in a tight loop. Since we are in the debugger the table should not get updated
  840. gDebugTable = gDebugImageTableHeader->EfiDebugImageInfoTable;
  841. gEfiDebugImageTableEntry = 0;
  842. return;
  843. }
  844. if (gDebugTable != NULL) {
  845. for (; gEfiDebugImageTableEntry < gDebugImageTableHeader->TableSize; gEfiDebugImageTableEntry++, gDebugTable++) {
  846. if (gDebugTable->NormalImage != NULL) {
  847. if ((gDebugTable->NormalImage->ImageInfoType == EFI_DEBUG_IMAGE_INFO_TYPE_NORMAL) &&
  848. (gDebugTable->NormalImage->LoadedImageProtocolInstance != NULL)) {
  849. Pdb = PeCoffLoaderGetDebuggerInfo (
  850. gDebugTable->NormalImage->LoadedImageProtocolInstance->ImageBase,
  851. &LoadAddress
  852. );
  853. if (Pdb != NULL) {
  854. Size = AsciiSPrint (
  855. gXferLibraryBuffer,
  856. sizeof (gXferLibraryBuffer),
  857. " <library name=\"%a\"><segment address=\"0x%p\"/></library>\n",
  858. Pdb,
  859. LoadAddress
  860. );
  861. if ((Size != 0) && (Size != (sizeof (gXferLibraryBuffer) - 1))) {
  862. gPacketqXferLibraryOffset += gXferObjectReadResponse ('m', gXferLibraryBuffer);
  863. // Update loop variables so we are in the right place when we get back
  864. gEfiDebugImageTableEntry++;
  865. gDebugTable++;
  866. return;
  867. } else {
  868. // We could handle <library> entires larger than sizeof (gXferLibraryBuffer) here if
  869. // needed by breaking up into N packets
  870. // "<library name=\"%s
  871. // the rest of the string (as many packets as required
  872. // \"><segment address=\"%d\"/></library> (fixed size)
  873. //
  874. // But right now we just skip any entry that is too big
  875. }
  876. }
  877. }
  878. }
  879. }
  880. }
  881. gXferObjectReadResponse ('l', "</library-list>\n");
  882. gPacketqXferLibraryOffset = 0;
  883. return;
  884. }
  885. /**
  886. Exception Hanldler for GDB. It will be called for all exceptions
  887. registered via the gExceptionType[] array.
  888. @param ExceptionType Exception that is being processed
  889. @param SystemContext Register content at time of the exception
  890. **/
  891. VOID
  892. EFIAPI
  893. GdbExceptionHandler (
  894. IN EFI_EXCEPTION_TYPE ExceptionType,
  895. IN OUT EFI_SYSTEM_CONTEXT SystemContext
  896. )
  897. {
  898. UINT8 GdbExceptionType;
  899. CHAR8 *Ptr;
  900. if (ValidateException (ExceptionType, SystemContext) == FALSE) {
  901. return;
  902. }
  903. RemoveSingleStep (SystemContext);
  904. GdbExceptionType = ConvertEFItoGDBtype (ExceptionType);
  905. GdbSendTSignal (SystemContext, GdbExceptionType);
  906. for( ; ; ) {
  907. ReceivePacket (gInBuffer, MAX_BUF_SIZE);
  908. switch (gInBuffer[0]) {
  909. case '?':
  910. GdbSendTSignal (SystemContext, GdbExceptionType);
  911. break;
  912. case 'c':
  913. ContinueAtAddress (SystemContext, gInBuffer);
  914. return;
  915. case 'g':
  916. ReadGeneralRegisters (SystemContext);
  917. break;
  918. case 'G':
  919. WriteGeneralRegisters (SystemContext, gInBuffer);
  920. break;
  921. case 'H':
  922. //Return "OK" packet since we don't have more than one thread.
  923. SendSuccess ();
  924. break;
  925. case 'm':
  926. ReadFromMemory (gInBuffer);
  927. break;
  928. case 'M':
  929. WriteToMemory (gInBuffer);
  930. break;
  931. case 'P':
  932. WriteNthRegister (SystemContext, gInBuffer);
  933. break;
  934. //
  935. // Still debugging this code. Not used in Darwin
  936. //
  937. case 'q':
  938. // General Query Packets
  939. if (AsciiStrnCmp (gInBuffer, "qSupported", 10) == 0) {
  940. // return what we currently support, we don't parse what gdb suports
  941. AsciiSPrint (gOutBuffer, MAX_BUF_SIZE, "qXfer:libraries:read+;PacketSize=%d", MAX_BUF_SIZE);
  942. SendPacket (gOutBuffer);
  943. } else if (AsciiStrnCmp (gInBuffer, "qXfer:libraries:read::", 22) == 0) {
  944. // ‘qXfer:libraries:read::offset,length
  945. // gInBuffer[22] is offset string, ++Ptr is length string’
  946. for (Ptr = &gInBuffer[22]; *Ptr != ','; Ptr++);
  947. // Not sure if multi-radix support is required. Currently only support decimal
  948. QxferLibrary (AsciiStrHexToUintn (&gInBuffer[22]), AsciiStrHexToUintn (++Ptr));
  949. } if (AsciiStrnCmp (gInBuffer, "qOffsets", 10) == 0) {
  950. AsciiSPrint (gOutBuffer, MAX_BUF_SIZE, "Text=1000;Data=f000;Bss=f000");
  951. SendPacket (gOutBuffer);
  952. } else {
  953. //Send empty packet
  954. SendNotSupported ();
  955. }
  956. break;
  957. case 's':
  958. SingleStep (SystemContext, gInBuffer);
  959. return;
  960. case 'z':
  961. RemoveBreakPoint (SystemContext, gInBuffer);
  962. break;
  963. case 'Z':
  964. InsertBreakPoint (SystemContext, gInBuffer);
  965. break;
  966. default:
  967. //Send empty packet
  968. SendNotSupported ();
  969. break;
  970. }
  971. }
  972. }
  973. /**
  974. Periodic callback for GDB. This function is used to catch a ctrl-c or other
  975. break in type command from GDB.
  976. @param SystemContext Register content at time of the call
  977. **/
  978. VOID
  979. EFIAPI
  980. GdbPeriodicCallBack (
  981. IN OUT EFI_SYSTEM_CONTEXT SystemContext
  982. )
  983. {
  984. //
  985. // gCtrlCBreakFlag may have been set from a previous F response package
  986. // and we set the global as we need to process it at a point where we
  987. // can update the system context. If we are in the middle of processing
  988. // a F Packet it is not safe to read the GDB serial stream so we need
  989. // to skip it on this check
  990. //
  991. if (!gCtrlCBreakFlag && !gProcessingFPacket) {
  992. //
  993. // Ctrl-C was not pending so grab any pending characters and see if they
  994. // are a Ctrl-c (0x03). If so set the Ctrl-C global.
  995. //
  996. while (TRUE) {
  997. if (!GdbIsCharAvailable ()) {
  998. //
  999. // No characters are pending so exit the loop
  1000. //
  1001. break;
  1002. }
  1003. if (GdbGetChar () == 0x03) {
  1004. gCtrlCBreakFlag = TRUE;
  1005. //
  1006. // We have a ctrl-c so exit the loop
  1007. //
  1008. break;
  1009. }
  1010. }
  1011. }
  1012. if (gCtrlCBreakFlag) {
  1013. //
  1014. // Update the context to force a single step trap when we exit the GDB
  1015. // stub. This will transfer control to GdbExceptionHandler () and let
  1016. // us break into the program. We don't want to break into the GDB stub.
  1017. //
  1018. AddSingleStep (SystemContext);
  1019. gCtrlCBreakFlag = FALSE;
  1020. }
  1021. }