server.cc 116 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697
  1. /* Main code for remote server for GDB.
  2. Copyright (C) 1989-2022 Free Software Foundation, Inc.
  3. This file is part of GDB.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>. */
  14. #include "server.h"
  15. #include "gdbthread.h"
  16. #include "gdbsupport/agent.h"
  17. #include "notif.h"
  18. #include "tdesc.h"
  19. #include "gdbsupport/rsp-low.h"
  20. #include "gdbsupport/signals-state-save-restore.h"
  21. #include <ctype.h>
  22. #include <unistd.h>
  23. #if HAVE_SIGNAL_H
  24. #include <signal.h>
  25. #endif
  26. #include "gdbsupport/gdb_vecs.h"
  27. #include "gdbsupport/gdb_wait.h"
  28. #include "gdbsupport/btrace-common.h"
  29. #include "gdbsupport/filestuff.h"
  30. #include "tracepoint.h"
  31. #include "dll.h"
  32. #include "hostio.h"
  33. #include <vector>
  34. #include "gdbsupport/common-inferior.h"
  35. #include "gdbsupport/job-control.h"
  36. #include "gdbsupport/environ.h"
  37. #include "filenames.h"
  38. #include "gdbsupport/pathstuff.h"
  39. #ifdef USE_XML
  40. #include "xml-builtin.h"
  41. #endif
  42. #include "gdbsupport/selftest.h"
  43. #include "gdbsupport/scope-exit.h"
  44. #include "gdbsupport/gdb_select.h"
  45. #include "gdbsupport/scoped_restore.h"
  46. #include "gdbsupport/search.h"
  47. #define require_running_or_return(BUF) \
  48. if (!target_running ()) \
  49. { \
  50. write_enn (BUF); \
  51. return; \
  52. }
  53. #define require_running_or_break(BUF) \
  54. if (!target_running ()) \
  55. { \
  56. write_enn (BUF); \
  57. break; \
  58. }
  59. /* The environment to pass to the inferior when creating it. */
  60. static gdb_environ our_environ;
  61. bool server_waiting;
  62. static bool extended_protocol;
  63. static bool response_needed;
  64. static bool exit_requested;
  65. /* --once: Exit after the first connection has closed. */
  66. bool run_once;
  67. /* Whether to report TARGET_WAITKIND_NO_RESUMED events. */
  68. static bool report_no_resumed;
  69. /* The event loop checks this to decide whether to continue accepting
  70. events. */
  71. static bool keep_processing_events = true;
  72. bool non_stop;
  73. static struct {
  74. /* Set the PROGRAM_PATH. Here we adjust the path of the provided
  75. binary if needed. */
  76. void set (gdb::unique_xmalloc_ptr<char> &&path)
  77. {
  78. m_path = std::move (path);
  79. /* Make sure we're using the absolute path of the inferior when
  80. creating it. */
  81. if (!contains_dir_separator (m_path.get ()))
  82. {
  83. int reg_file_errno;
  84. /* Check if the file is in our CWD. If it is, then we prefix
  85. its name with CURRENT_DIRECTORY. Otherwise, we leave the
  86. name as-is because we'll try searching for it in $PATH. */
  87. if (is_regular_file (m_path.get (), &reg_file_errno))
  88. m_path = gdb_abspath (m_path.get ());
  89. }
  90. }
  91. /* Return the PROGRAM_PATH. */
  92. char *get ()
  93. { return m_path.get (); }
  94. private:
  95. /* The program name, adjusted if needed. */
  96. gdb::unique_xmalloc_ptr<char> m_path;
  97. } program_path;
  98. static std::vector<char *> program_args;
  99. static std::string wrapper_argv;
  100. /* The PID of the originally created or attached inferior. Used to
  101. send signals to the process when GDB sends us an asynchronous interrupt
  102. (user hitting Control-C in the client), and to wait for the child to exit
  103. when no longer debugging it. */
  104. unsigned long signal_pid;
  105. /* Set if you want to disable optional thread related packets support
  106. in gdbserver, for the sake of testing GDB against stubs that don't
  107. support them. */
  108. bool disable_packet_vCont;
  109. bool disable_packet_Tthread;
  110. bool disable_packet_qC;
  111. bool disable_packet_qfThreadInfo;
  112. bool disable_packet_T;
  113. static unsigned char *mem_buf;
  114. /* A sub-class of 'struct notif_event' for stop, holding information
  115. relative to a single stop reply. We keep a queue of these to
  116. push to GDB in non-stop mode. */
  117. struct vstop_notif : public notif_event
  118. {
  119. /* Thread or process that got the event. */
  120. ptid_t ptid;
  121. /* Event info. */
  122. struct target_waitstatus status;
  123. };
  124. /* The current btrace configuration. This is gdbserver's mirror of GDB's
  125. btrace configuration. */
  126. static struct btrace_config current_btrace_conf;
  127. /* The client remote protocol state. */
  128. static client_state g_client_state;
  129. client_state &
  130. get_client_state ()
  131. {
  132. client_state &cs = g_client_state;
  133. return cs;
  134. }
  135. /* Put a stop reply to the stop reply queue. */
  136. static void
  137. queue_stop_reply (ptid_t ptid, const target_waitstatus &status)
  138. {
  139. struct vstop_notif *new_notif = new struct vstop_notif;
  140. new_notif->ptid = ptid;
  141. new_notif->status = status;
  142. notif_event_enque (&notif_stop, new_notif);
  143. }
  144. static bool
  145. remove_all_on_match_ptid (struct notif_event *event, ptid_t filter_ptid)
  146. {
  147. struct vstop_notif *vstop_event = (struct vstop_notif *) event;
  148. return vstop_event->ptid.matches (filter_ptid);
  149. }
  150. /* See server.h. */
  151. void
  152. discard_queued_stop_replies (ptid_t ptid)
  153. {
  154. std::list<notif_event *>::iterator iter, next, end;
  155. end = notif_stop.queue.end ();
  156. for (iter = notif_stop.queue.begin (); iter != end; iter = next)
  157. {
  158. next = iter;
  159. ++next;
  160. if (iter == notif_stop.queue.begin ())
  161. {
  162. /* The head of the list contains the notification that was
  163. already sent to GDB. So we can't remove it, otherwise
  164. when GDB sends the vStopped, it would ack the _next_
  165. notification, which hadn't been sent yet! */
  166. continue;
  167. }
  168. if (remove_all_on_match_ptid (*iter, ptid))
  169. {
  170. delete *iter;
  171. notif_stop.queue.erase (iter);
  172. }
  173. }
  174. }
  175. static void
  176. vstop_notif_reply (struct notif_event *event, char *own_buf)
  177. {
  178. struct vstop_notif *vstop = (struct vstop_notif *) event;
  179. prepare_resume_reply (own_buf, vstop->ptid, vstop->status);
  180. }
  181. /* Helper for in_queued_stop_replies. */
  182. static bool
  183. in_queued_stop_replies_ptid (struct notif_event *event, ptid_t filter_ptid)
  184. {
  185. struct vstop_notif *vstop_event = (struct vstop_notif *) event;
  186. if (vstop_event->ptid.matches (filter_ptid))
  187. return true;
  188. /* Don't resume fork children that GDB does not know about yet. */
  189. if ((vstop_event->status.kind () == TARGET_WAITKIND_FORKED
  190. || vstop_event->status.kind () == TARGET_WAITKIND_VFORKED)
  191. && vstop_event->status.child_ptid ().matches (filter_ptid))
  192. return true;
  193. return false;
  194. }
  195. /* See server.h. */
  196. int
  197. in_queued_stop_replies (ptid_t ptid)
  198. {
  199. for (notif_event *event : notif_stop.queue)
  200. {
  201. if (in_queued_stop_replies_ptid (event, ptid))
  202. return true;
  203. }
  204. return false;
  205. }
  206. struct notif_server notif_stop =
  207. {
  208. "vStopped", "Stop", {}, vstop_notif_reply,
  209. };
  210. static int
  211. target_running (void)
  212. {
  213. return get_first_thread () != NULL;
  214. }
  215. /* See gdbsupport/common-inferior.h. */
  216. const char *
  217. get_exec_wrapper ()
  218. {
  219. return !wrapper_argv.empty () ? wrapper_argv.c_str () : NULL;
  220. }
  221. /* See gdbsupport/common-inferior.h. */
  222. const char *
  223. get_exec_file (int err)
  224. {
  225. if (err && program_path.get () == NULL)
  226. error (_("No executable file specified."));
  227. return program_path.get ();
  228. }
  229. /* See server.h. */
  230. gdb_environ *
  231. get_environ ()
  232. {
  233. return &our_environ;
  234. }
  235. static int
  236. attach_inferior (int pid)
  237. {
  238. client_state &cs = get_client_state ();
  239. /* myattach should return -1 if attaching is unsupported,
  240. 0 if it succeeded, and call error() otherwise. */
  241. if (find_process_pid (pid) != nullptr)
  242. error ("Already attached to process %d\n", pid);
  243. if (myattach (pid) != 0)
  244. return -1;
  245. fprintf (stderr, "Attached; pid = %d\n", pid);
  246. fflush (stderr);
  247. /* FIXME - It may be that we should get the SIGNAL_PID from the
  248. attach function, so that it can be the main thread instead of
  249. whichever we were told to attach to. */
  250. signal_pid = pid;
  251. if (!non_stop)
  252. {
  253. cs.last_ptid = mywait (ptid_t (pid), &cs.last_status, 0, 0);
  254. /* GDB knows to ignore the first SIGSTOP after attaching to a running
  255. process using the "attach" command, but this is different; it's
  256. just using "target remote". Pretend it's just starting up. */
  257. if (cs.last_status.kind () == TARGET_WAITKIND_STOPPED
  258. && cs.last_status.sig () == GDB_SIGNAL_STOP)
  259. cs.last_status.set_stopped (GDB_SIGNAL_TRAP);
  260. current_thread->last_resume_kind = resume_stop;
  261. current_thread->last_status = cs.last_status;
  262. }
  263. return 0;
  264. }
  265. /* Decode a qXfer read request. Return 0 if everything looks OK,
  266. or -1 otherwise. */
  267. static int
  268. decode_xfer_read (char *buf, CORE_ADDR *ofs, unsigned int *len)
  269. {
  270. /* After the read marker and annex, qXfer looks like a
  271. traditional 'm' packet. */
  272. decode_m_packet (buf, ofs, len);
  273. return 0;
  274. }
  275. static int
  276. decode_xfer (char *buf, char **object, char **rw, char **annex, char **offset)
  277. {
  278. /* Extract and NUL-terminate the object. */
  279. *object = buf;
  280. while (*buf && *buf != ':')
  281. buf++;
  282. if (*buf == '\0')
  283. return -1;
  284. *buf++ = 0;
  285. /* Extract and NUL-terminate the read/write action. */
  286. *rw = buf;
  287. while (*buf && *buf != ':')
  288. buf++;
  289. if (*buf == '\0')
  290. return -1;
  291. *buf++ = 0;
  292. /* Extract and NUL-terminate the annex. */
  293. *annex = buf;
  294. while (*buf && *buf != ':')
  295. buf++;
  296. if (*buf == '\0')
  297. return -1;
  298. *buf++ = 0;
  299. *offset = buf;
  300. return 0;
  301. }
  302. /* Write the response to a successful qXfer read. Returns the
  303. length of the (binary) data stored in BUF, corresponding
  304. to as much of DATA/LEN as we could fit. IS_MORE controls
  305. the first character of the response. */
  306. static int
  307. write_qxfer_response (char *buf, const gdb_byte *data, int len, int is_more)
  308. {
  309. int out_len;
  310. if (is_more)
  311. buf[0] = 'm';
  312. else
  313. buf[0] = 'l';
  314. return remote_escape_output (data, len, 1, (unsigned char *) buf + 1,
  315. &out_len, PBUFSIZ - 2) + 1;
  316. }
  317. /* Handle btrace enabling in BTS format. */
  318. static void
  319. handle_btrace_enable_bts (struct thread_info *thread)
  320. {
  321. if (thread->btrace != NULL)
  322. error (_("Btrace already enabled."));
  323. current_btrace_conf.format = BTRACE_FORMAT_BTS;
  324. thread->btrace = target_enable_btrace (thread, &current_btrace_conf);
  325. }
  326. /* Handle btrace enabling in Intel Processor Trace format. */
  327. static void
  328. handle_btrace_enable_pt (struct thread_info *thread)
  329. {
  330. if (thread->btrace != NULL)
  331. error (_("Btrace already enabled."));
  332. current_btrace_conf.format = BTRACE_FORMAT_PT;
  333. thread->btrace = target_enable_btrace (thread, &current_btrace_conf);
  334. }
  335. /* Handle btrace disabling. */
  336. static void
  337. handle_btrace_disable (struct thread_info *thread)
  338. {
  339. if (thread->btrace == NULL)
  340. error (_("Branch tracing not enabled."));
  341. if (target_disable_btrace (thread->btrace) != 0)
  342. error (_("Could not disable branch tracing."));
  343. thread->btrace = NULL;
  344. }
  345. /* Handle the "Qbtrace" packet. */
  346. static int
  347. handle_btrace_general_set (char *own_buf)
  348. {
  349. client_state &cs = get_client_state ();
  350. struct thread_info *thread;
  351. char *op;
  352. if (!startswith (own_buf, "Qbtrace:"))
  353. return 0;
  354. op = own_buf + strlen ("Qbtrace:");
  355. if (cs.general_thread == null_ptid
  356. || cs.general_thread == minus_one_ptid)
  357. {
  358. strcpy (own_buf, "E.Must select a single thread.");
  359. return -1;
  360. }
  361. thread = find_thread_ptid (cs.general_thread);
  362. if (thread == NULL)
  363. {
  364. strcpy (own_buf, "E.No such thread.");
  365. return -1;
  366. }
  367. try
  368. {
  369. if (strcmp (op, "bts") == 0)
  370. handle_btrace_enable_bts (thread);
  371. else if (strcmp (op, "pt") == 0)
  372. handle_btrace_enable_pt (thread);
  373. else if (strcmp (op, "off") == 0)
  374. handle_btrace_disable (thread);
  375. else
  376. error (_("Bad Qbtrace operation. Use bts, pt, or off."));
  377. write_ok (own_buf);
  378. }
  379. catch (const gdb_exception_error &exception)
  380. {
  381. sprintf (own_buf, "E.%s", exception.what ());
  382. }
  383. return 1;
  384. }
  385. /* Handle the "Qbtrace-conf" packet. */
  386. static int
  387. handle_btrace_conf_general_set (char *own_buf)
  388. {
  389. client_state &cs = get_client_state ();
  390. struct thread_info *thread;
  391. char *op;
  392. if (!startswith (own_buf, "Qbtrace-conf:"))
  393. return 0;
  394. op = own_buf + strlen ("Qbtrace-conf:");
  395. if (cs.general_thread == null_ptid
  396. || cs.general_thread == minus_one_ptid)
  397. {
  398. strcpy (own_buf, "E.Must select a single thread.");
  399. return -1;
  400. }
  401. thread = find_thread_ptid (cs.general_thread);
  402. if (thread == NULL)
  403. {
  404. strcpy (own_buf, "E.No such thread.");
  405. return -1;
  406. }
  407. if (startswith (op, "bts:size="))
  408. {
  409. unsigned long size;
  410. char *endp = NULL;
  411. errno = 0;
  412. size = strtoul (op + strlen ("bts:size="), &endp, 16);
  413. if (endp == NULL || *endp != 0 || errno != 0 || size > UINT_MAX)
  414. {
  415. strcpy (own_buf, "E.Bad size value.");
  416. return -1;
  417. }
  418. current_btrace_conf.bts.size = (unsigned int) size;
  419. }
  420. else if (strncmp (op, "pt:size=", strlen ("pt:size=")) == 0)
  421. {
  422. unsigned long size;
  423. char *endp = NULL;
  424. errno = 0;
  425. size = strtoul (op + strlen ("pt:size="), &endp, 16);
  426. if (endp == NULL || *endp != 0 || errno != 0 || size > UINT_MAX)
  427. {
  428. strcpy (own_buf, "E.Bad size value.");
  429. return -1;
  430. }
  431. current_btrace_conf.pt.size = (unsigned int) size;
  432. }
  433. else
  434. {
  435. strcpy (own_buf, "E.Bad Qbtrace configuration option.");
  436. return -1;
  437. }
  438. write_ok (own_buf);
  439. return 1;
  440. }
  441. /* Create the qMemTags packet reply given TAGS.
  442. Returns true if parsing succeeded and false otherwise. */
  443. static bool
  444. create_fetch_memtags_reply (char *reply, const gdb::byte_vector &tags)
  445. {
  446. /* It is an error to pass a zero-sized tag vector. */
  447. gdb_assert (tags.size () != 0);
  448. std::string packet ("m");
  449. /* Write the tag data. */
  450. packet += bin2hex (tags.data (), tags.size ());
  451. /* Check if the reply is too big for the packet to handle. */
  452. if (PBUFSIZ < packet.size ())
  453. return false;
  454. strcpy (reply, packet.c_str ());
  455. return true;
  456. }
  457. /* Parse the QMemTags request into ADDR, LEN and TAGS.
  458. Returns true if parsing succeeded and false otherwise. */
  459. static bool
  460. parse_store_memtags_request (char *request, CORE_ADDR *addr, size_t *len,
  461. gdb::byte_vector &tags, int *type)
  462. {
  463. gdb_assert (startswith (request, "QMemTags:"));
  464. const char *p = request + strlen ("QMemTags:");
  465. /* Read address and length. */
  466. unsigned int length = 0;
  467. p = decode_m_packet_params (p, addr, &length, ':');
  468. *len = length;
  469. /* Read the tag type. */
  470. ULONGEST tag_type = 0;
  471. p = unpack_varlen_hex (p, &tag_type);
  472. *type = (int) tag_type;
  473. /* Make sure there is a colon after the type. */
  474. if (*p != ':')
  475. return false;
  476. /* Skip the colon. */
  477. p++;
  478. /* Read the tag data. */
  479. tags = hex2bin (p);
  480. return true;
  481. }
  482. /* Handle all of the extended 'Q' packets. */
  483. static void
  484. handle_general_set (char *own_buf)
  485. {
  486. client_state &cs = get_client_state ();
  487. if (startswith (own_buf, "QPassSignals:"))
  488. {
  489. int numsigs = (int) GDB_SIGNAL_LAST, i;
  490. const char *p = own_buf + strlen ("QPassSignals:");
  491. CORE_ADDR cursig;
  492. p = decode_address_to_semicolon (&cursig, p);
  493. for (i = 0; i < numsigs; i++)
  494. {
  495. if (i == cursig)
  496. {
  497. cs.pass_signals[i] = 1;
  498. if (*p == '\0')
  499. /* Keep looping, to clear the remaining signals. */
  500. cursig = -1;
  501. else
  502. p = decode_address_to_semicolon (&cursig, p);
  503. }
  504. else
  505. cs.pass_signals[i] = 0;
  506. }
  507. strcpy (own_buf, "OK");
  508. return;
  509. }
  510. if (startswith (own_buf, "QProgramSignals:"))
  511. {
  512. int numsigs = (int) GDB_SIGNAL_LAST, i;
  513. const char *p = own_buf + strlen ("QProgramSignals:");
  514. CORE_ADDR cursig;
  515. cs.program_signals_p = 1;
  516. p = decode_address_to_semicolon (&cursig, p);
  517. for (i = 0; i < numsigs; i++)
  518. {
  519. if (i == cursig)
  520. {
  521. cs.program_signals[i] = 1;
  522. if (*p == '\0')
  523. /* Keep looping, to clear the remaining signals. */
  524. cursig = -1;
  525. else
  526. p = decode_address_to_semicolon (&cursig, p);
  527. }
  528. else
  529. cs.program_signals[i] = 0;
  530. }
  531. strcpy (own_buf, "OK");
  532. return;
  533. }
  534. if (startswith (own_buf, "QCatchSyscalls:"))
  535. {
  536. const char *p = own_buf + sizeof ("QCatchSyscalls:") - 1;
  537. int enabled = -1;
  538. CORE_ADDR sysno;
  539. struct process_info *process;
  540. if (!target_running () || !target_supports_catch_syscall ())
  541. {
  542. write_enn (own_buf);
  543. return;
  544. }
  545. if (strcmp (p, "0") == 0)
  546. enabled = 0;
  547. else if (p[0] == '1' && (p[1] == ';' || p[1] == '\0'))
  548. enabled = 1;
  549. else
  550. {
  551. fprintf (stderr, "Unknown catch-syscalls mode requested: %s\n",
  552. own_buf);
  553. write_enn (own_buf);
  554. return;
  555. }
  556. process = current_process ();
  557. process->syscalls_to_catch.clear ();
  558. if (enabled)
  559. {
  560. p += 1;
  561. if (*p == ';')
  562. {
  563. p += 1;
  564. while (*p != '\0')
  565. {
  566. p = decode_address_to_semicolon (&sysno, p);
  567. process->syscalls_to_catch.push_back (sysno);
  568. }
  569. }
  570. else
  571. process->syscalls_to_catch.push_back (ANY_SYSCALL);
  572. }
  573. write_ok (own_buf);
  574. return;
  575. }
  576. if (strcmp (own_buf, "QEnvironmentReset") == 0)
  577. {
  578. our_environ = gdb_environ::from_host_environ ();
  579. write_ok (own_buf);
  580. return;
  581. }
  582. if (startswith (own_buf, "QEnvironmentHexEncoded:"))
  583. {
  584. const char *p = own_buf + sizeof ("QEnvironmentHexEncoded:") - 1;
  585. /* The final form of the environment variable. FINAL_VAR will
  586. hold the 'VAR=VALUE' format. */
  587. std::string final_var = hex2str (p);
  588. std::string var_name, var_value;
  589. remote_debug_printf ("[QEnvironmentHexEncoded received '%s']", p);
  590. remote_debug_printf ("[Environment variable to be set: '%s']",
  591. final_var.c_str ());
  592. size_t pos = final_var.find ('=');
  593. if (pos == std::string::npos)
  594. {
  595. warning (_("Unexpected format for environment variable: '%s'"),
  596. final_var.c_str ());
  597. write_enn (own_buf);
  598. return;
  599. }
  600. var_name = final_var.substr (0, pos);
  601. var_value = final_var.substr (pos + 1, std::string::npos);
  602. our_environ.set (var_name.c_str (), var_value.c_str ());
  603. write_ok (own_buf);
  604. return;
  605. }
  606. if (startswith (own_buf, "QEnvironmentUnset:"))
  607. {
  608. const char *p = own_buf + sizeof ("QEnvironmentUnset:") - 1;
  609. std::string varname = hex2str (p);
  610. remote_debug_printf ("[QEnvironmentUnset received '%s']", p);
  611. remote_debug_printf ("[Environment variable to be unset: '%s']",
  612. varname.c_str ());
  613. our_environ.unset (varname.c_str ());
  614. write_ok (own_buf);
  615. return;
  616. }
  617. if (strcmp (own_buf, "QStartNoAckMode") == 0)
  618. {
  619. remote_debug_printf ("[noack mode enabled]");
  620. cs.noack_mode = 1;
  621. write_ok (own_buf);
  622. return;
  623. }
  624. if (startswith (own_buf, "QNonStop:"))
  625. {
  626. char *mode = own_buf + 9;
  627. int req = -1;
  628. const char *req_str;
  629. if (strcmp (mode, "0") == 0)
  630. req = 0;
  631. else if (strcmp (mode, "1") == 0)
  632. req = 1;
  633. else
  634. {
  635. /* We don't know what this mode is, so complain to
  636. GDB. */
  637. fprintf (stderr, "Unknown non-stop mode requested: %s\n",
  638. own_buf);
  639. write_enn (own_buf);
  640. return;
  641. }
  642. req_str = req ? "non-stop" : "all-stop";
  643. if (the_target->start_non_stop (req == 1) != 0)
  644. {
  645. fprintf (stderr, "Setting %s mode failed\n", req_str);
  646. write_enn (own_buf);
  647. return;
  648. }
  649. non_stop = (req != 0);
  650. remote_debug_printf ("[%s mode enabled]", req_str);
  651. write_ok (own_buf);
  652. return;
  653. }
  654. if (startswith (own_buf, "QDisableRandomization:"))
  655. {
  656. char *packet = own_buf + strlen ("QDisableRandomization:");
  657. ULONGEST setting;
  658. unpack_varlen_hex (packet, &setting);
  659. cs.disable_randomization = setting;
  660. remote_debug_printf (cs.disable_randomization
  661. ? "[address space randomization disabled]"
  662. : "[address space randomization enabled]");
  663. write_ok (own_buf);
  664. return;
  665. }
  666. if (target_supports_tracepoints ()
  667. && handle_tracepoint_general_set (own_buf))
  668. return;
  669. if (startswith (own_buf, "QAgent:"))
  670. {
  671. char *mode = own_buf + strlen ("QAgent:");
  672. int req = 0;
  673. if (strcmp (mode, "0") == 0)
  674. req = 0;
  675. else if (strcmp (mode, "1") == 0)
  676. req = 1;
  677. else
  678. {
  679. /* We don't know what this value is, so complain to GDB. */
  680. sprintf (own_buf, "E.Unknown QAgent value");
  681. return;
  682. }
  683. /* Update the flag. */
  684. use_agent = req;
  685. remote_debug_printf ("[%s agent]", req ? "Enable" : "Disable");
  686. write_ok (own_buf);
  687. return;
  688. }
  689. if (handle_btrace_general_set (own_buf))
  690. return;
  691. if (handle_btrace_conf_general_set (own_buf))
  692. return;
  693. if (startswith (own_buf, "QThreadEvents:"))
  694. {
  695. char *mode = own_buf + strlen ("QThreadEvents:");
  696. enum tribool req = TRIBOOL_UNKNOWN;
  697. if (strcmp (mode, "0") == 0)
  698. req = TRIBOOL_FALSE;
  699. else if (strcmp (mode, "1") == 0)
  700. req = TRIBOOL_TRUE;
  701. else
  702. {
  703. /* We don't know what this mode is, so complain to GDB. */
  704. std::string err
  705. = string_printf ("E.Unknown thread-events mode requested: %s\n",
  706. mode);
  707. strcpy (own_buf, err.c_str ());
  708. return;
  709. }
  710. cs.report_thread_events = (req == TRIBOOL_TRUE);
  711. remote_debug_printf ("[thread events are now %s]\n",
  712. cs.report_thread_events ? "enabled" : "disabled");
  713. write_ok (own_buf);
  714. return;
  715. }
  716. if (startswith (own_buf, "QStartupWithShell:"))
  717. {
  718. const char *value = own_buf + strlen ("QStartupWithShell:");
  719. if (strcmp (value, "1") == 0)
  720. startup_with_shell = true;
  721. else if (strcmp (value, "0") == 0)
  722. startup_with_shell = false;
  723. else
  724. {
  725. /* Unknown value. */
  726. fprintf (stderr, "Unknown value to startup-with-shell: %s\n",
  727. own_buf);
  728. write_enn (own_buf);
  729. return;
  730. }
  731. remote_debug_printf ("[Inferior will %s started with shell]",
  732. startup_with_shell ? "be" : "not be");
  733. write_ok (own_buf);
  734. return;
  735. }
  736. if (startswith (own_buf, "QSetWorkingDir:"))
  737. {
  738. const char *p = own_buf + strlen ("QSetWorkingDir:");
  739. if (*p != '\0')
  740. {
  741. std::string path = hex2str (p);
  742. remote_debug_printf ("[Set the inferior's current directory to %s]",
  743. path.c_str ());
  744. set_inferior_cwd (std::move (path));
  745. }
  746. else
  747. {
  748. /* An empty argument means that we should clear out any
  749. previously set cwd for the inferior. */
  750. set_inferior_cwd ("");
  751. remote_debug_printf ("[Unset the inferior's current directory; will "
  752. "use gdbserver's cwd]");
  753. }
  754. write_ok (own_buf);
  755. return;
  756. }
  757. /* Handle store memory tags packets. */
  758. if (startswith (own_buf, "QMemTags:")
  759. && target_supports_memory_tagging ())
  760. {
  761. gdb::byte_vector tags;
  762. CORE_ADDR addr = 0;
  763. size_t len = 0;
  764. int type = 0;
  765. require_running_or_return (own_buf);
  766. bool ret = parse_store_memtags_request (own_buf, &addr, &len, tags,
  767. &type);
  768. if (ret)
  769. ret = the_target->store_memtags (addr, len, tags, type);
  770. if (!ret)
  771. write_enn (own_buf);
  772. else
  773. write_ok (own_buf);
  774. return;
  775. }
  776. /* Otherwise we didn't know what packet it was. Say we didn't
  777. understand it. */
  778. own_buf[0] = 0;
  779. }
  780. static const char *
  781. get_features_xml (const char *annex)
  782. {
  783. const struct target_desc *desc = current_target_desc ();
  784. /* `desc->xmltarget' defines what to return when looking for the
  785. "target.xml" file. Its contents can either be verbatim XML code
  786. (prefixed with a '@') or else the name of the actual XML file to
  787. be used in place of "target.xml".
  788. This variable is set up from the auto-generated
  789. init_registers_... routine for the current target. */
  790. if (strcmp (annex, "target.xml") == 0)
  791. {
  792. const char *ret = tdesc_get_features_xml (desc);
  793. if (*ret == '@')
  794. return ret + 1;
  795. else
  796. annex = ret;
  797. }
  798. #ifdef USE_XML
  799. {
  800. int i;
  801. /* Look for the annex. */
  802. for (i = 0; xml_builtin[i][0] != NULL; i++)
  803. if (strcmp (annex, xml_builtin[i][0]) == 0)
  804. break;
  805. if (xml_builtin[i][0] != NULL)
  806. return xml_builtin[i][1];
  807. }
  808. #endif
  809. return NULL;
  810. }
  811. static void
  812. monitor_show_help (void)
  813. {
  814. monitor_output ("The following monitor commands are supported:\n");
  815. monitor_output (" set debug <0|1>\n");
  816. monitor_output (" Enable general debugging messages\n");
  817. monitor_output (" set debug-hw-points <0|1>\n");
  818. monitor_output (" Enable h/w breakpoint/watchpoint debugging messages\n");
  819. monitor_output (" set remote-debug <0|1>\n");
  820. monitor_output (" Enable remote protocol debugging messages\n");
  821. monitor_output (" set event-loop-debug <0|1>\n");
  822. monitor_output (" Enable event loop debugging messages\n");
  823. monitor_output (" set debug-format option1[,option2,...]\n");
  824. monitor_output (" Add additional information to debugging messages\n");
  825. monitor_output (" Options: all, none");
  826. monitor_output (", timestamp");
  827. monitor_output ("\n");
  828. monitor_output (" exit\n");
  829. monitor_output (" Quit GDBserver\n");
  830. }
  831. /* Read trace frame or inferior memory. Returns the number of bytes
  832. actually read, zero when no further transfer is possible, and -1 on
  833. error. Return of a positive value smaller than LEN does not
  834. indicate there's no more to be read, only the end of the transfer.
  835. E.g., when GDB reads memory from a traceframe, a first request may
  836. be served from a memory block that does not cover the whole request
  837. length. A following request gets the rest served from either
  838. another block (of the same traceframe) or from the read-only
  839. regions. */
  840. static int
  841. gdb_read_memory (CORE_ADDR memaddr, unsigned char *myaddr, int len)
  842. {
  843. client_state &cs = get_client_state ();
  844. int res;
  845. if (cs.current_traceframe >= 0)
  846. {
  847. ULONGEST nbytes;
  848. ULONGEST length = len;
  849. if (traceframe_read_mem (cs.current_traceframe,
  850. memaddr, myaddr, len, &nbytes))
  851. return -1;
  852. /* Data read from trace buffer, we're done. */
  853. if (nbytes > 0)
  854. return nbytes;
  855. if (!in_readonly_region (memaddr, length))
  856. return -1;
  857. /* Otherwise we have a valid readonly case, fall through. */
  858. /* (assume no half-trace half-real blocks for now) */
  859. }
  860. res = prepare_to_access_memory ();
  861. if (res == 0)
  862. {
  863. if (set_desired_thread ())
  864. res = read_inferior_memory (memaddr, myaddr, len);
  865. else
  866. res = 1;
  867. done_accessing_memory ();
  868. return res == 0 ? len : -1;
  869. }
  870. else
  871. return -1;
  872. }
  873. /* Write trace frame or inferior memory. Actually, writing to trace
  874. frames is forbidden. */
  875. static int
  876. gdb_write_memory (CORE_ADDR memaddr, const unsigned char *myaddr, int len)
  877. {
  878. client_state &cs = get_client_state ();
  879. if (cs.current_traceframe >= 0)
  880. return EIO;
  881. else
  882. {
  883. int ret;
  884. ret = prepare_to_access_memory ();
  885. if (ret == 0)
  886. {
  887. if (set_desired_thread ())
  888. ret = target_write_memory (memaddr, myaddr, len);
  889. else
  890. ret = EIO;
  891. done_accessing_memory ();
  892. }
  893. return ret;
  894. }
  895. }
  896. /* Handle qSearch:memory packets. */
  897. static void
  898. handle_search_memory (char *own_buf, int packet_len)
  899. {
  900. CORE_ADDR start_addr;
  901. CORE_ADDR search_space_len;
  902. gdb_byte *pattern;
  903. unsigned int pattern_len;
  904. int found;
  905. CORE_ADDR found_addr;
  906. int cmd_name_len = sizeof ("qSearch:memory:") - 1;
  907. pattern = (gdb_byte *) malloc (packet_len);
  908. if (pattern == NULL)
  909. error ("Unable to allocate memory to perform the search");
  910. if (decode_search_memory_packet (own_buf + cmd_name_len,
  911. packet_len - cmd_name_len,
  912. &start_addr, &search_space_len,
  913. pattern, &pattern_len) < 0)
  914. {
  915. free (pattern);
  916. error ("Error in parsing qSearch:memory packet");
  917. }
  918. auto read_memory = [] (CORE_ADDR addr, gdb_byte *result, size_t len)
  919. {
  920. return gdb_read_memory (addr, result, len) == len;
  921. };
  922. found = simple_search_memory (read_memory, start_addr, search_space_len,
  923. pattern, pattern_len, &found_addr);
  924. if (found > 0)
  925. sprintf (own_buf, "1,%lx", (long) found_addr);
  926. else if (found == 0)
  927. strcpy (own_buf, "0");
  928. else
  929. strcpy (own_buf, "E00");
  930. free (pattern);
  931. }
  932. /* Handle the "D" packet. */
  933. static void
  934. handle_detach (char *own_buf)
  935. {
  936. client_state &cs = get_client_state ();
  937. process_info *process;
  938. if (cs.multi_process)
  939. {
  940. /* skip 'D;' */
  941. int pid = strtol (&own_buf[2], NULL, 16);
  942. process = find_process_pid (pid);
  943. }
  944. else
  945. {
  946. process = (current_thread != nullptr
  947. ? get_thread_process (current_thread)
  948. : nullptr);
  949. }
  950. if (process == NULL)
  951. {
  952. write_enn (own_buf);
  953. return;
  954. }
  955. if ((tracing && disconnected_tracing) || any_persistent_commands (process))
  956. {
  957. if (tracing && disconnected_tracing)
  958. fprintf (stderr,
  959. "Disconnected tracing in effect, "
  960. "leaving gdbserver attached to the process\n");
  961. if (any_persistent_commands (process))
  962. fprintf (stderr,
  963. "Persistent commands are present, "
  964. "leaving gdbserver attached to the process\n");
  965. /* Make sure we're in non-stop/async mode, so we we can both
  966. wait for an async socket accept, and handle async target
  967. events simultaneously. There's also no point either in
  968. having the target stop all threads, when we're going to
  969. pass signals down without informing GDB. */
  970. if (!non_stop)
  971. {
  972. threads_debug_printf ("Forcing non-stop mode");
  973. non_stop = true;
  974. the_target->start_non_stop (true);
  975. }
  976. process->gdb_detached = 1;
  977. /* Detaching implicitly resumes all threads. */
  978. target_continue_no_signal (minus_one_ptid);
  979. write_ok (own_buf);
  980. return;
  981. }
  982. fprintf (stderr, "Detaching from process %d\n", process->pid);
  983. stop_tracing ();
  984. /* We'll need this after PROCESS has been destroyed. */
  985. int pid = process->pid;
  986. /* If this process has an unreported fork child, that child is not known to
  987. GDB, so GDB won't take care of detaching it. We must do it here.
  988. Here, we specifically don't want to use "safe iteration", as detaching
  989. another process might delete the next thread in the iteration, which is
  990. the one saved by the safe iterator. We will never delete the currently
  991. iterated on thread, so standard iteration should be safe. */
  992. for (thread_info *thread : all_threads)
  993. {
  994. /* Only threads that are of the process we are detaching. */
  995. if (thread->id.pid () != pid)
  996. continue;
  997. /* Only threads that have a pending fork event. */
  998. thread_info *child = target_thread_pending_child (thread);
  999. if (child == nullptr)
  1000. continue;
  1001. process_info *fork_child_process = get_thread_process (child);
  1002. gdb_assert (fork_child_process != nullptr);
  1003. int fork_child_pid = fork_child_process->pid;
  1004. if (detach_inferior (fork_child_process) != 0)
  1005. warning (_("Failed to detach fork child %s, child of %s"),
  1006. target_pid_to_str (ptid_t (fork_child_pid)).c_str (),
  1007. target_pid_to_str (thread->id).c_str ());
  1008. }
  1009. if (detach_inferior (process) != 0)
  1010. write_enn (own_buf);
  1011. else
  1012. {
  1013. discard_queued_stop_replies (ptid_t (pid));
  1014. write_ok (own_buf);
  1015. if (extended_protocol || target_running ())
  1016. {
  1017. /* There is still at least one inferior remaining or
  1018. we are in extended mode, so don't terminate gdbserver,
  1019. and instead treat this like a normal program exit. */
  1020. cs.last_status.set_exited (0);
  1021. cs.last_ptid = ptid_t (pid);
  1022. switch_to_thread (nullptr);
  1023. }
  1024. else
  1025. {
  1026. putpkt (own_buf);
  1027. remote_close ();
  1028. /* If we are attached, then we can exit. Otherwise, we
  1029. need to hang around doing nothing, until the child is
  1030. gone. */
  1031. join_inferior (pid);
  1032. exit (0);
  1033. }
  1034. }
  1035. }
  1036. /* Parse options to --debug-format= and "monitor set debug-format".
  1037. ARG is the text after "--debug-format=" or "monitor set debug-format".
  1038. IS_MONITOR is non-zero if we're invoked via "monitor set debug-format".
  1039. This triggers calls to monitor_output.
  1040. The result is an empty string if all options were parsed ok, otherwise an
  1041. error message which the caller must free.
  1042. N.B. These commands affect all debug format settings, they are not
  1043. cumulative. If a format is not specified, it is turned off.
  1044. However, we don't go to extra trouble with things like
  1045. "monitor set debug-format all,none,timestamp".
  1046. Instead we just parse them one at a time, in order.
  1047. The syntax for "monitor set debug" we support here is not identical
  1048. to gdb's "set debug foo on|off" because we also use this function to
  1049. parse "--debug-format=foo,bar". */
  1050. static std::string
  1051. parse_debug_format_options (const char *arg, int is_monitor)
  1052. {
  1053. /* First turn all debug format options off. */
  1054. debug_timestamp = 0;
  1055. /* First remove leading spaces, for "monitor set debug-format". */
  1056. while (isspace (*arg))
  1057. ++arg;
  1058. std::vector<gdb::unique_xmalloc_ptr<char>> options
  1059. = delim_string_to_char_ptr_vec (arg, ',');
  1060. for (const gdb::unique_xmalloc_ptr<char> &option : options)
  1061. {
  1062. if (strcmp (option.get (), "all") == 0)
  1063. {
  1064. debug_timestamp = 1;
  1065. if (is_monitor)
  1066. monitor_output ("All extra debug format options enabled.\n");
  1067. }
  1068. else if (strcmp (option.get (), "none") == 0)
  1069. {
  1070. debug_timestamp = 0;
  1071. if (is_monitor)
  1072. monitor_output ("All extra debug format options disabled.\n");
  1073. }
  1074. else if (strcmp (option.get (), "timestamp") == 0)
  1075. {
  1076. debug_timestamp = 1;
  1077. if (is_monitor)
  1078. monitor_output ("Timestamps will be added to debug output.\n");
  1079. }
  1080. else if (*option == '\0')
  1081. {
  1082. /* An empty option, e.g., "--debug-format=foo,,bar", is ignored. */
  1083. continue;
  1084. }
  1085. else
  1086. return string_printf ("Unknown debug-format argument: \"%s\"\n",
  1087. option.get ());
  1088. }
  1089. return std::string ();
  1090. }
  1091. /* Handle monitor commands not handled by target-specific handlers. */
  1092. static void
  1093. handle_monitor_command (char *mon, char *own_buf)
  1094. {
  1095. if (strcmp (mon, "set debug 1") == 0)
  1096. {
  1097. debug_threads = true;
  1098. monitor_output ("Debug output enabled.\n");
  1099. }
  1100. else if (strcmp (mon, "set debug 0") == 0)
  1101. {
  1102. debug_threads = false;
  1103. monitor_output ("Debug output disabled.\n");
  1104. }
  1105. else if (strcmp (mon, "set debug-hw-points 1") == 0)
  1106. {
  1107. show_debug_regs = 1;
  1108. monitor_output ("H/W point debugging output enabled.\n");
  1109. }
  1110. else if (strcmp (mon, "set debug-hw-points 0") == 0)
  1111. {
  1112. show_debug_regs = 0;
  1113. monitor_output ("H/W point debugging output disabled.\n");
  1114. }
  1115. else if (strcmp (mon, "set remote-debug 1") == 0)
  1116. {
  1117. remote_debug = true;
  1118. monitor_output ("Protocol debug output enabled.\n");
  1119. }
  1120. else if (strcmp (mon, "set remote-debug 0") == 0)
  1121. {
  1122. remote_debug = false;
  1123. monitor_output ("Protocol debug output disabled.\n");
  1124. }
  1125. else if (strcmp (mon, "set event-loop-debug 1") == 0)
  1126. {
  1127. debug_event_loop = debug_event_loop_kind::ALL;
  1128. monitor_output ("Event loop debug output enabled.\n");
  1129. }
  1130. else if (strcmp (mon, "set event-loop-debug 0") == 0)
  1131. {
  1132. debug_event_loop = debug_event_loop_kind::OFF;
  1133. monitor_output ("Event loop debug output disabled.\n");
  1134. }
  1135. else if (startswith (mon, "set debug-format "))
  1136. {
  1137. std::string error_msg
  1138. = parse_debug_format_options (mon + sizeof ("set debug-format ") - 1,
  1139. 1);
  1140. if (!error_msg.empty ())
  1141. {
  1142. monitor_output (error_msg.c_str ());
  1143. monitor_show_help ();
  1144. write_enn (own_buf);
  1145. }
  1146. }
  1147. else if (strcmp (mon, "set debug-file") == 0)
  1148. debug_set_output (nullptr);
  1149. else if (startswith (mon, "set debug-file "))
  1150. debug_set_output (mon + sizeof ("set debug-file ") - 1);
  1151. else if (strcmp (mon, "help") == 0)
  1152. monitor_show_help ();
  1153. else if (strcmp (mon, "exit") == 0)
  1154. exit_requested = true;
  1155. else
  1156. {
  1157. monitor_output ("Unknown monitor command.\n\n");
  1158. monitor_show_help ();
  1159. write_enn (own_buf);
  1160. }
  1161. }
  1162. /* Associates a callback with each supported qXfer'able object. */
  1163. struct qxfer
  1164. {
  1165. /* The object this handler handles. */
  1166. const char *object;
  1167. /* Request that the target transfer up to LEN 8-bit bytes of the
  1168. target's OBJECT. The OFFSET, for a seekable object, specifies
  1169. the starting point. The ANNEX can be used to provide additional
  1170. data-specific information to the target.
  1171. Return the number of bytes actually transfered, zero when no
  1172. further transfer is possible, -1 on error, -2 when the transfer
  1173. is not supported, and -3 on a verbose error message that should
  1174. be preserved. Return of a positive value smaller than LEN does
  1175. not indicate the end of the object, only the end of the transfer.
  1176. One, and only one, of readbuf or writebuf must be non-NULL. */
  1177. int (*xfer) (const char *annex,
  1178. gdb_byte *readbuf, const gdb_byte *writebuf,
  1179. ULONGEST offset, LONGEST len);
  1180. };
  1181. /* Handle qXfer:auxv:read. */
  1182. static int
  1183. handle_qxfer_auxv (const char *annex,
  1184. gdb_byte *readbuf, const gdb_byte *writebuf,
  1185. ULONGEST offset, LONGEST len)
  1186. {
  1187. if (!the_target->supports_read_auxv () || writebuf != NULL)
  1188. return -2;
  1189. if (annex[0] != '\0' || current_thread == NULL)
  1190. return -1;
  1191. return the_target->read_auxv (offset, readbuf, len);
  1192. }
  1193. /* Handle qXfer:exec-file:read. */
  1194. static int
  1195. handle_qxfer_exec_file (const char *annex,
  1196. gdb_byte *readbuf, const gdb_byte *writebuf,
  1197. ULONGEST offset, LONGEST len)
  1198. {
  1199. ULONGEST pid;
  1200. int total_len;
  1201. if (!the_target->supports_pid_to_exec_file () || writebuf != NULL)
  1202. return -2;
  1203. if (annex[0] == '\0')
  1204. {
  1205. if (current_thread == NULL)
  1206. return -1;
  1207. pid = pid_of (current_thread);
  1208. }
  1209. else
  1210. {
  1211. annex = unpack_varlen_hex (annex, &pid);
  1212. if (annex[0] != '\0')
  1213. return -1;
  1214. }
  1215. if (pid <= 0)
  1216. return -1;
  1217. const char *file = the_target->pid_to_exec_file (pid);
  1218. if (file == NULL)
  1219. return -1;
  1220. total_len = strlen (file);
  1221. if (offset > total_len)
  1222. return -1;
  1223. if (offset + len > total_len)
  1224. len = total_len - offset;
  1225. memcpy (readbuf, file + offset, len);
  1226. return len;
  1227. }
  1228. /* Handle qXfer:features:read. */
  1229. static int
  1230. handle_qxfer_features (const char *annex,
  1231. gdb_byte *readbuf, const gdb_byte *writebuf,
  1232. ULONGEST offset, LONGEST len)
  1233. {
  1234. const char *document;
  1235. size_t total_len;
  1236. if (writebuf != NULL)
  1237. return -2;
  1238. if (!target_running ())
  1239. return -1;
  1240. /* Grab the correct annex. */
  1241. document = get_features_xml (annex);
  1242. if (document == NULL)
  1243. return -1;
  1244. total_len = strlen (document);
  1245. if (offset > total_len)
  1246. return -1;
  1247. if (offset + len > total_len)
  1248. len = total_len - offset;
  1249. memcpy (readbuf, document + offset, len);
  1250. return len;
  1251. }
  1252. /* Handle qXfer:libraries:read. */
  1253. static int
  1254. handle_qxfer_libraries (const char *annex,
  1255. gdb_byte *readbuf, const gdb_byte *writebuf,
  1256. ULONGEST offset, LONGEST len)
  1257. {
  1258. if (writebuf != NULL)
  1259. return -2;
  1260. if (annex[0] != '\0' || current_thread == NULL)
  1261. return -1;
  1262. std::string document = "<library-list version=\"1.0\">\n";
  1263. process_info *proc = current_process ();
  1264. for (const dll_info &dll : proc->all_dlls)
  1265. document += string_printf
  1266. (" <library name=\"%s\"><segment address=\"0x%s\"/></library>\n",
  1267. dll.name.c_str (), paddress (dll.base_addr));
  1268. document += "</library-list>\n";
  1269. if (offset > document.length ())
  1270. return -1;
  1271. if (offset + len > document.length ())
  1272. len = document.length () - offset;
  1273. memcpy (readbuf, &document[offset], len);
  1274. return len;
  1275. }
  1276. /* Handle qXfer:libraries-svr4:read. */
  1277. static int
  1278. handle_qxfer_libraries_svr4 (const char *annex,
  1279. gdb_byte *readbuf, const gdb_byte *writebuf,
  1280. ULONGEST offset, LONGEST len)
  1281. {
  1282. if (writebuf != NULL)
  1283. return -2;
  1284. if (current_thread == NULL
  1285. || !the_target->supports_qxfer_libraries_svr4 ())
  1286. return -1;
  1287. return the_target->qxfer_libraries_svr4 (annex, readbuf, writebuf,
  1288. offset, len);
  1289. }
  1290. /* Handle qXfer:osadata:read. */
  1291. static int
  1292. handle_qxfer_osdata (const char *annex,
  1293. gdb_byte *readbuf, const gdb_byte *writebuf,
  1294. ULONGEST offset, LONGEST len)
  1295. {
  1296. if (!the_target->supports_qxfer_osdata () || writebuf != NULL)
  1297. return -2;
  1298. return the_target->qxfer_osdata (annex, readbuf, NULL, offset, len);
  1299. }
  1300. /* Handle qXfer:siginfo:read and qXfer:siginfo:write. */
  1301. static int
  1302. handle_qxfer_siginfo (const char *annex,
  1303. gdb_byte *readbuf, const gdb_byte *writebuf,
  1304. ULONGEST offset, LONGEST len)
  1305. {
  1306. if (!the_target->supports_qxfer_siginfo ())
  1307. return -2;
  1308. if (annex[0] != '\0' || current_thread == NULL)
  1309. return -1;
  1310. return the_target->qxfer_siginfo (annex, readbuf, writebuf, offset, len);
  1311. }
  1312. /* Handle qXfer:statictrace:read. */
  1313. static int
  1314. handle_qxfer_statictrace (const char *annex,
  1315. gdb_byte *readbuf, const gdb_byte *writebuf,
  1316. ULONGEST offset, LONGEST len)
  1317. {
  1318. client_state &cs = get_client_state ();
  1319. ULONGEST nbytes;
  1320. if (writebuf != NULL)
  1321. return -2;
  1322. if (annex[0] != '\0' || current_thread == NULL
  1323. || cs.current_traceframe == -1)
  1324. return -1;
  1325. if (traceframe_read_sdata (cs.current_traceframe, offset,
  1326. readbuf, len, &nbytes))
  1327. return -1;
  1328. return nbytes;
  1329. }
  1330. /* Helper for handle_qxfer_threads_proper.
  1331. Emit the XML to describe the thread of INF. */
  1332. static void
  1333. handle_qxfer_threads_worker (thread_info *thread, struct buffer *buffer)
  1334. {
  1335. ptid_t ptid = ptid_of (thread);
  1336. char ptid_s[100];
  1337. int core = target_core_of_thread (ptid);
  1338. char core_s[21];
  1339. const char *name = target_thread_name (ptid);
  1340. int handle_len;
  1341. gdb_byte *handle;
  1342. bool handle_status = target_thread_handle (ptid, &handle, &handle_len);
  1343. /* If this is a fork or vfork child (has a fork parent), GDB does not yet
  1344. know about this process, and must not know about it until it gets the
  1345. corresponding (v)fork event. Exclude this thread from the list. */
  1346. if (target_thread_pending_parent (thread) != nullptr)
  1347. return;
  1348. write_ptid (ptid_s, ptid);
  1349. buffer_xml_printf (buffer, "<thread id=\"%s\"", ptid_s);
  1350. if (core != -1)
  1351. {
  1352. sprintf (core_s, "%d", core);
  1353. buffer_xml_printf (buffer, " core=\"%s\"", core_s);
  1354. }
  1355. if (name != NULL)
  1356. buffer_xml_printf (buffer, " name=\"%s\"", name);
  1357. if (handle_status)
  1358. {
  1359. char *handle_s = (char *) alloca (handle_len * 2 + 1);
  1360. bin2hex (handle, handle_s, handle_len);
  1361. buffer_xml_printf (buffer, " handle=\"%s\"", handle_s);
  1362. }
  1363. buffer_xml_printf (buffer, "/>\n");
  1364. }
  1365. /* Helper for handle_qxfer_threads. Return true on success, false
  1366. otherwise. */
  1367. static bool
  1368. handle_qxfer_threads_proper (struct buffer *buffer)
  1369. {
  1370. client_state &cs = get_client_state ();
  1371. scoped_restore_current_thread restore_thread;
  1372. scoped_restore save_current_general_thread
  1373. = make_scoped_restore (&cs.general_thread);
  1374. buffer_grow_str (buffer, "<threads>\n");
  1375. process_info *error_proc = find_process ([&] (process_info *process)
  1376. {
  1377. /* The target may need to access memory and registers (e.g. via
  1378. libthread_db) to fetch thread properties. Prepare for memory
  1379. access here, so that we potentially pause threads just once
  1380. for all accesses. Note that even if someday we stop needing
  1381. to pause threads to access memory, we will need to be able to
  1382. access registers, or other ptrace accesses like
  1383. PTRACE_GET_THREAD_AREA. */
  1384. /* Need to switch to each process in turn, because
  1385. prepare_to_access_memory prepares for an access in the
  1386. current process pointed to by general_thread. */
  1387. switch_to_process (process);
  1388. cs.general_thread = current_thread->id;
  1389. int res = prepare_to_access_memory ();
  1390. if (res == 0)
  1391. {
  1392. for_each_thread (process->pid, [&] (thread_info *thread)
  1393. {
  1394. handle_qxfer_threads_worker (thread, buffer);
  1395. });
  1396. done_accessing_memory ();
  1397. return false;
  1398. }
  1399. else
  1400. return true;
  1401. });
  1402. buffer_grow_str0 (buffer, "</threads>\n");
  1403. return error_proc == nullptr;
  1404. }
  1405. /* Handle qXfer:threads:read. */
  1406. static int
  1407. handle_qxfer_threads (const char *annex,
  1408. gdb_byte *readbuf, const gdb_byte *writebuf,
  1409. ULONGEST offset, LONGEST len)
  1410. {
  1411. static char *result = 0;
  1412. static unsigned int result_length = 0;
  1413. if (writebuf != NULL)
  1414. return -2;
  1415. if (annex[0] != '\0')
  1416. return -1;
  1417. if (offset == 0)
  1418. {
  1419. struct buffer buffer;
  1420. /* When asked for data at offset 0, generate everything and store into
  1421. 'result'. Successive reads will be served off 'result'. */
  1422. if (result)
  1423. free (result);
  1424. buffer_init (&buffer);
  1425. bool res = handle_qxfer_threads_proper (&buffer);
  1426. result = buffer_finish (&buffer);
  1427. result_length = strlen (result);
  1428. buffer_free (&buffer);
  1429. if (!res)
  1430. return -1;
  1431. }
  1432. if (offset >= result_length)
  1433. {
  1434. /* We're out of data. */
  1435. free (result);
  1436. result = NULL;
  1437. result_length = 0;
  1438. return 0;
  1439. }
  1440. if (len > result_length - offset)
  1441. len = result_length - offset;
  1442. memcpy (readbuf, result + offset, len);
  1443. return len;
  1444. }
  1445. /* Handle qXfer:traceframe-info:read. */
  1446. static int
  1447. handle_qxfer_traceframe_info (const char *annex,
  1448. gdb_byte *readbuf, const gdb_byte *writebuf,
  1449. ULONGEST offset, LONGEST len)
  1450. {
  1451. client_state &cs = get_client_state ();
  1452. static char *result = 0;
  1453. static unsigned int result_length = 0;
  1454. if (writebuf != NULL)
  1455. return -2;
  1456. if (!target_running () || annex[0] != '\0' || cs.current_traceframe == -1)
  1457. return -1;
  1458. if (offset == 0)
  1459. {
  1460. struct buffer buffer;
  1461. /* When asked for data at offset 0, generate everything and
  1462. store into 'result'. Successive reads will be served off
  1463. 'result'. */
  1464. free (result);
  1465. buffer_init (&buffer);
  1466. traceframe_read_info (cs.current_traceframe, &buffer);
  1467. result = buffer_finish (&buffer);
  1468. result_length = strlen (result);
  1469. buffer_free (&buffer);
  1470. }
  1471. if (offset >= result_length)
  1472. {
  1473. /* We're out of data. */
  1474. free (result);
  1475. result = NULL;
  1476. result_length = 0;
  1477. return 0;
  1478. }
  1479. if (len > result_length - offset)
  1480. len = result_length - offset;
  1481. memcpy (readbuf, result + offset, len);
  1482. return len;
  1483. }
  1484. /* Handle qXfer:fdpic:read. */
  1485. static int
  1486. handle_qxfer_fdpic (const char *annex, gdb_byte *readbuf,
  1487. const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
  1488. {
  1489. if (!the_target->supports_read_loadmap ())
  1490. return -2;
  1491. if (current_thread == NULL)
  1492. return -1;
  1493. return the_target->read_loadmap (annex, offset, readbuf, len);
  1494. }
  1495. /* Handle qXfer:btrace:read. */
  1496. static int
  1497. handle_qxfer_btrace (const char *annex,
  1498. gdb_byte *readbuf, const gdb_byte *writebuf,
  1499. ULONGEST offset, LONGEST len)
  1500. {
  1501. client_state &cs = get_client_state ();
  1502. static struct buffer cache;
  1503. struct thread_info *thread;
  1504. enum btrace_read_type type;
  1505. int result;
  1506. if (writebuf != NULL)
  1507. return -2;
  1508. if (cs.general_thread == null_ptid
  1509. || cs.general_thread == minus_one_ptid)
  1510. {
  1511. strcpy (cs.own_buf, "E.Must select a single thread.");
  1512. return -3;
  1513. }
  1514. thread = find_thread_ptid (cs.general_thread);
  1515. if (thread == NULL)
  1516. {
  1517. strcpy (cs.own_buf, "E.No such thread.");
  1518. return -3;
  1519. }
  1520. if (thread->btrace == NULL)
  1521. {
  1522. strcpy (cs.own_buf, "E.Btrace not enabled.");
  1523. return -3;
  1524. }
  1525. if (strcmp (annex, "all") == 0)
  1526. type = BTRACE_READ_ALL;
  1527. else if (strcmp (annex, "new") == 0)
  1528. type = BTRACE_READ_NEW;
  1529. else if (strcmp (annex, "delta") == 0)
  1530. type = BTRACE_READ_DELTA;
  1531. else
  1532. {
  1533. strcpy (cs.own_buf, "E.Bad annex.");
  1534. return -3;
  1535. }
  1536. if (offset == 0)
  1537. {
  1538. buffer_free (&cache);
  1539. try
  1540. {
  1541. result = target_read_btrace (thread->btrace, &cache, type);
  1542. if (result != 0)
  1543. memcpy (cs.own_buf, cache.buffer, cache.used_size);
  1544. }
  1545. catch (const gdb_exception_error &exception)
  1546. {
  1547. sprintf (cs.own_buf, "E.%s", exception.what ());
  1548. result = -1;
  1549. }
  1550. if (result != 0)
  1551. return -3;
  1552. }
  1553. else if (offset > cache.used_size)
  1554. {
  1555. buffer_free (&cache);
  1556. return -3;
  1557. }
  1558. if (len > cache.used_size - offset)
  1559. len = cache.used_size - offset;
  1560. memcpy (readbuf, cache.buffer + offset, len);
  1561. return len;
  1562. }
  1563. /* Handle qXfer:btrace-conf:read. */
  1564. static int
  1565. handle_qxfer_btrace_conf (const char *annex,
  1566. gdb_byte *readbuf, const gdb_byte *writebuf,
  1567. ULONGEST offset, LONGEST len)
  1568. {
  1569. client_state &cs = get_client_state ();
  1570. static struct buffer cache;
  1571. struct thread_info *thread;
  1572. int result;
  1573. if (writebuf != NULL)
  1574. return -2;
  1575. if (annex[0] != '\0')
  1576. return -1;
  1577. if (cs.general_thread == null_ptid
  1578. || cs.general_thread == minus_one_ptid)
  1579. {
  1580. strcpy (cs.own_buf, "E.Must select a single thread.");
  1581. return -3;
  1582. }
  1583. thread = find_thread_ptid (cs.general_thread);
  1584. if (thread == NULL)
  1585. {
  1586. strcpy (cs.own_buf, "E.No such thread.");
  1587. return -3;
  1588. }
  1589. if (thread->btrace == NULL)
  1590. {
  1591. strcpy (cs.own_buf, "E.Btrace not enabled.");
  1592. return -3;
  1593. }
  1594. if (offset == 0)
  1595. {
  1596. buffer_free (&cache);
  1597. try
  1598. {
  1599. result = target_read_btrace_conf (thread->btrace, &cache);
  1600. if (result != 0)
  1601. memcpy (cs.own_buf, cache.buffer, cache.used_size);
  1602. }
  1603. catch (const gdb_exception_error &exception)
  1604. {
  1605. sprintf (cs.own_buf, "E.%s", exception.what ());
  1606. result = -1;
  1607. }
  1608. if (result != 0)
  1609. return -3;
  1610. }
  1611. else if (offset > cache.used_size)
  1612. {
  1613. buffer_free (&cache);
  1614. return -3;
  1615. }
  1616. if (len > cache.used_size - offset)
  1617. len = cache.used_size - offset;
  1618. memcpy (readbuf, cache.buffer + offset, len);
  1619. return len;
  1620. }
  1621. static const struct qxfer qxfer_packets[] =
  1622. {
  1623. { "auxv", handle_qxfer_auxv },
  1624. { "btrace", handle_qxfer_btrace },
  1625. { "btrace-conf", handle_qxfer_btrace_conf },
  1626. { "exec-file", handle_qxfer_exec_file},
  1627. { "fdpic", handle_qxfer_fdpic},
  1628. { "features", handle_qxfer_features },
  1629. { "libraries", handle_qxfer_libraries },
  1630. { "libraries-svr4", handle_qxfer_libraries_svr4 },
  1631. { "osdata", handle_qxfer_osdata },
  1632. { "siginfo", handle_qxfer_siginfo },
  1633. { "statictrace", handle_qxfer_statictrace },
  1634. { "threads", handle_qxfer_threads },
  1635. { "traceframe-info", handle_qxfer_traceframe_info },
  1636. };
  1637. static int
  1638. handle_qxfer (char *own_buf, int packet_len, int *new_packet_len_p)
  1639. {
  1640. int i;
  1641. char *object;
  1642. char *rw;
  1643. char *annex;
  1644. char *offset;
  1645. if (!startswith (own_buf, "qXfer:"))
  1646. return 0;
  1647. /* Grab the object, r/w and annex. */
  1648. if (decode_xfer (own_buf + 6, &object, &rw, &annex, &offset) < 0)
  1649. {
  1650. write_enn (own_buf);
  1651. return 1;
  1652. }
  1653. for (i = 0;
  1654. i < sizeof (qxfer_packets) / sizeof (qxfer_packets[0]);
  1655. i++)
  1656. {
  1657. const struct qxfer *q = &qxfer_packets[i];
  1658. if (strcmp (object, q->object) == 0)
  1659. {
  1660. if (strcmp (rw, "read") == 0)
  1661. {
  1662. unsigned char *data;
  1663. int n;
  1664. CORE_ADDR ofs;
  1665. unsigned int len;
  1666. /* Grab the offset and length. */
  1667. if (decode_xfer_read (offset, &ofs, &len) < 0)
  1668. {
  1669. write_enn (own_buf);
  1670. return 1;
  1671. }
  1672. /* Read one extra byte, as an indicator of whether there is
  1673. more. */
  1674. if (len > PBUFSIZ - 2)
  1675. len = PBUFSIZ - 2;
  1676. data = (unsigned char *) malloc (len + 1);
  1677. if (data == NULL)
  1678. {
  1679. write_enn (own_buf);
  1680. return 1;
  1681. }
  1682. n = (*q->xfer) (annex, data, NULL, ofs, len + 1);
  1683. if (n == -2)
  1684. {
  1685. free (data);
  1686. return 0;
  1687. }
  1688. else if (n == -3)
  1689. {
  1690. /* Preserve error message. */
  1691. }
  1692. else if (n < 0)
  1693. write_enn (own_buf);
  1694. else if (n > len)
  1695. *new_packet_len_p = write_qxfer_response (own_buf, data, len, 1);
  1696. else
  1697. *new_packet_len_p = write_qxfer_response (own_buf, data, n, 0);
  1698. free (data);
  1699. return 1;
  1700. }
  1701. else if (strcmp (rw, "write") == 0)
  1702. {
  1703. int n;
  1704. unsigned int len;
  1705. CORE_ADDR ofs;
  1706. unsigned char *data;
  1707. strcpy (own_buf, "E00");
  1708. data = (unsigned char *) malloc (packet_len - (offset - own_buf));
  1709. if (data == NULL)
  1710. {
  1711. write_enn (own_buf);
  1712. return 1;
  1713. }
  1714. if (decode_xfer_write (offset, packet_len - (offset - own_buf),
  1715. &ofs, &len, data) < 0)
  1716. {
  1717. free (data);
  1718. write_enn (own_buf);
  1719. return 1;
  1720. }
  1721. n = (*q->xfer) (annex, NULL, data, ofs, len);
  1722. if (n == -2)
  1723. {
  1724. free (data);
  1725. return 0;
  1726. }
  1727. else if (n == -3)
  1728. {
  1729. /* Preserve error message. */
  1730. }
  1731. else if (n < 0)
  1732. write_enn (own_buf);
  1733. else
  1734. sprintf (own_buf, "%x", n);
  1735. free (data);
  1736. return 1;
  1737. }
  1738. return 0;
  1739. }
  1740. }
  1741. return 0;
  1742. }
  1743. /* Compute 32 bit CRC from inferior memory.
  1744. On success, return 32 bit CRC.
  1745. On failure, return (unsigned long long) -1. */
  1746. static unsigned long long
  1747. crc32 (CORE_ADDR base, int len, unsigned int crc)
  1748. {
  1749. while (len--)
  1750. {
  1751. unsigned char byte = 0;
  1752. /* Return failure if memory read fails. */
  1753. if (read_inferior_memory (base, &byte, 1) != 0)
  1754. return (unsigned long long) -1;
  1755. crc = xcrc32 (&byte, 1, crc);
  1756. base++;
  1757. }
  1758. return (unsigned long long) crc;
  1759. }
  1760. /* Parse the qMemTags packet request into ADDR and LEN. */
  1761. static void
  1762. parse_fetch_memtags_request (char *request, CORE_ADDR *addr, size_t *len,
  1763. int *type)
  1764. {
  1765. gdb_assert (startswith (request, "qMemTags:"));
  1766. const char *p = request + strlen ("qMemTags:");
  1767. /* Read address and length. */
  1768. unsigned int length = 0;
  1769. p = decode_m_packet_params (p, addr, &length, ':');
  1770. *len = length;
  1771. /* Read the tag type. */
  1772. ULONGEST tag_type = 0;
  1773. p = unpack_varlen_hex (p, &tag_type);
  1774. *type = (int) tag_type;
  1775. }
  1776. /* Add supported btrace packets to BUF. */
  1777. static void
  1778. supported_btrace_packets (char *buf)
  1779. {
  1780. strcat (buf, ";Qbtrace:bts+");
  1781. strcat (buf, ";Qbtrace-conf:bts:size+");
  1782. strcat (buf, ";Qbtrace:pt+");
  1783. strcat (buf, ";Qbtrace-conf:pt:size+");
  1784. strcat (buf, ";Qbtrace:off+");
  1785. strcat (buf, ";qXfer:btrace:read+");
  1786. strcat (buf, ";qXfer:btrace-conf:read+");
  1787. }
  1788. /* Handle all of the extended 'q' packets. */
  1789. static void
  1790. handle_query (char *own_buf, int packet_len, int *new_packet_len_p)
  1791. {
  1792. client_state &cs = get_client_state ();
  1793. static std::list<thread_info *>::const_iterator thread_iter;
  1794. /* Reply the current thread id. */
  1795. if (strcmp ("qC", own_buf) == 0 && !disable_packet_qC)
  1796. {
  1797. ptid_t ptid;
  1798. require_running_or_return (own_buf);
  1799. if (cs.general_thread != null_ptid && cs.general_thread != minus_one_ptid)
  1800. ptid = cs.general_thread;
  1801. else
  1802. {
  1803. thread_iter = all_threads.begin ();
  1804. ptid = (*thread_iter)->id;
  1805. }
  1806. sprintf (own_buf, "QC");
  1807. own_buf += 2;
  1808. write_ptid (own_buf, ptid);
  1809. return;
  1810. }
  1811. if (strcmp ("qSymbol::", own_buf) == 0)
  1812. {
  1813. scoped_restore_current_thread restore_thread;
  1814. /* For qSymbol, GDB only changes the current thread if the
  1815. previous current thread was of a different process. So if
  1816. the previous thread is gone, we need to pick another one of
  1817. the same process. This can happen e.g., if we followed an
  1818. exec in a non-leader thread. */
  1819. if (current_thread == NULL)
  1820. {
  1821. thread_info *any_thread
  1822. = find_any_thread_of_pid (cs.general_thread.pid ());
  1823. switch_to_thread (any_thread);
  1824. /* Just in case, if we didn't find a thread, then bail out
  1825. instead of crashing. */
  1826. if (current_thread == NULL)
  1827. {
  1828. write_enn (own_buf);
  1829. return;
  1830. }
  1831. }
  1832. /* GDB is suggesting new symbols have been loaded. This may
  1833. mean a new shared library has been detected as loaded, so
  1834. take the opportunity to check if breakpoints we think are
  1835. inserted, still are. Note that it isn't guaranteed that
  1836. we'll see this when a shared library is loaded, and nor will
  1837. we see this for unloads (although breakpoints in unloaded
  1838. libraries shouldn't trigger), as GDB may not find symbols for
  1839. the library at all. We also re-validate breakpoints when we
  1840. see a second GDB breakpoint for the same address, and or when
  1841. we access breakpoint shadows. */
  1842. validate_breakpoints ();
  1843. if (target_supports_tracepoints ())
  1844. tracepoint_look_up_symbols ();
  1845. if (current_thread != NULL)
  1846. the_target->look_up_symbols ();
  1847. strcpy (own_buf, "OK");
  1848. return;
  1849. }
  1850. if (!disable_packet_qfThreadInfo)
  1851. {
  1852. if (strcmp ("qfThreadInfo", own_buf) == 0)
  1853. {
  1854. require_running_or_return (own_buf);
  1855. thread_iter = all_threads.begin ();
  1856. *own_buf++ = 'm';
  1857. ptid_t ptid = (*thread_iter)->id;
  1858. write_ptid (own_buf, ptid);
  1859. thread_iter++;
  1860. return;
  1861. }
  1862. if (strcmp ("qsThreadInfo", own_buf) == 0)
  1863. {
  1864. require_running_or_return (own_buf);
  1865. if (thread_iter != all_threads.end ())
  1866. {
  1867. *own_buf++ = 'm';
  1868. ptid_t ptid = (*thread_iter)->id;
  1869. write_ptid (own_buf, ptid);
  1870. thread_iter++;
  1871. return;
  1872. }
  1873. else
  1874. {
  1875. sprintf (own_buf, "l");
  1876. return;
  1877. }
  1878. }
  1879. }
  1880. if (the_target->supports_read_offsets ()
  1881. && strcmp ("qOffsets", own_buf) == 0)
  1882. {
  1883. CORE_ADDR text, data;
  1884. require_running_or_return (own_buf);
  1885. if (the_target->read_offsets (&text, &data))
  1886. sprintf (own_buf, "Text=%lX;Data=%lX;Bss=%lX",
  1887. (long)text, (long)data, (long)data);
  1888. else
  1889. write_enn (own_buf);
  1890. return;
  1891. }
  1892. /* Protocol features query. */
  1893. if (startswith (own_buf, "qSupported")
  1894. && (own_buf[10] == ':' || own_buf[10] == '\0'))
  1895. {
  1896. char *p = &own_buf[10];
  1897. int gdb_supports_qRelocInsn = 0;
  1898. /* Process each feature being provided by GDB. The first
  1899. feature will follow a ':', and latter features will follow
  1900. ';'. */
  1901. if (*p == ':')
  1902. {
  1903. std::vector<std::string> qsupported;
  1904. std::vector<const char *> unknowns;
  1905. /* Two passes, to avoid nested strtok calls in
  1906. target_process_qsupported. */
  1907. char *saveptr;
  1908. for (p = strtok_r (p + 1, ";", &saveptr);
  1909. p != NULL;
  1910. p = strtok_r (NULL, ";", &saveptr))
  1911. qsupported.emplace_back (p);
  1912. for (const std::string &feature : qsupported)
  1913. {
  1914. if (feature == "multiprocess+")
  1915. {
  1916. /* GDB supports and wants multi-process support if
  1917. possible. */
  1918. if (target_supports_multi_process ())
  1919. cs.multi_process = 1;
  1920. }
  1921. else if (feature == "qRelocInsn+")
  1922. {
  1923. /* GDB supports relocate instruction requests. */
  1924. gdb_supports_qRelocInsn = 1;
  1925. }
  1926. else if (feature == "swbreak+")
  1927. {
  1928. /* GDB wants us to report whether a trap is caused
  1929. by a software breakpoint and for us to handle PC
  1930. adjustment if necessary on this target. */
  1931. if (target_supports_stopped_by_sw_breakpoint ())
  1932. cs.swbreak_feature = 1;
  1933. }
  1934. else if (feature == "hwbreak+")
  1935. {
  1936. /* GDB wants us to report whether a trap is caused
  1937. by a hardware breakpoint. */
  1938. if (target_supports_stopped_by_hw_breakpoint ())
  1939. cs.hwbreak_feature = 1;
  1940. }
  1941. else if (feature == "fork-events+")
  1942. {
  1943. /* GDB supports and wants fork events if possible. */
  1944. if (target_supports_fork_events ())
  1945. cs.report_fork_events = 1;
  1946. }
  1947. else if (feature == "vfork-events+")
  1948. {
  1949. /* GDB supports and wants vfork events if possible. */
  1950. if (target_supports_vfork_events ())
  1951. cs.report_vfork_events = 1;
  1952. }
  1953. else if (feature == "exec-events+")
  1954. {
  1955. /* GDB supports and wants exec events if possible. */
  1956. if (target_supports_exec_events ())
  1957. cs.report_exec_events = 1;
  1958. }
  1959. else if (feature == "vContSupported+")
  1960. cs.vCont_supported = 1;
  1961. else if (feature == "QThreadEvents+")
  1962. ;
  1963. else if (feature == "no-resumed+")
  1964. {
  1965. /* GDB supports and wants TARGET_WAITKIND_NO_RESUMED
  1966. events. */
  1967. report_no_resumed = true;
  1968. }
  1969. else if (feature == "memory-tagging+")
  1970. {
  1971. /* GDB supports memory tagging features. */
  1972. if (target_supports_memory_tagging ())
  1973. cs.memory_tagging_feature = true;
  1974. }
  1975. else
  1976. {
  1977. /* Move the unknown features all together. */
  1978. unknowns.push_back (feature.c_str ());
  1979. }
  1980. }
  1981. /* Give the target backend a chance to process the unknown
  1982. features. */
  1983. target_process_qsupported (unknowns);
  1984. }
  1985. sprintf (own_buf,
  1986. "PacketSize=%x;QPassSignals+;QProgramSignals+;"
  1987. "QStartupWithShell+;QEnvironmentHexEncoded+;"
  1988. "QEnvironmentReset+;QEnvironmentUnset+;"
  1989. "QSetWorkingDir+",
  1990. PBUFSIZ - 1);
  1991. if (target_supports_catch_syscall ())
  1992. strcat (own_buf, ";QCatchSyscalls+");
  1993. if (the_target->supports_qxfer_libraries_svr4 ())
  1994. strcat (own_buf, ";qXfer:libraries-svr4:read+"
  1995. ";augmented-libraries-svr4-read+");
  1996. else
  1997. {
  1998. /* We do not have any hook to indicate whether the non-SVR4 target
  1999. backend supports qXfer:libraries:read, so always report it. */
  2000. strcat (own_buf, ";qXfer:libraries:read+");
  2001. }
  2002. if (the_target->supports_read_auxv ())
  2003. strcat (own_buf, ";qXfer:auxv:read+");
  2004. if (the_target->supports_qxfer_siginfo ())
  2005. strcat (own_buf, ";qXfer:siginfo:read+;qXfer:siginfo:write+");
  2006. if (the_target->supports_read_loadmap ())
  2007. strcat (own_buf, ";qXfer:fdpic:read+");
  2008. /* We always report qXfer:features:read, as targets may
  2009. install XML files on a subsequent call to arch_setup.
  2010. If we reported to GDB on startup that we don't support
  2011. qXfer:feature:read at all, we will never be re-queried. */
  2012. strcat (own_buf, ";qXfer:features:read+");
  2013. if (cs.transport_is_reliable)
  2014. strcat (own_buf, ";QStartNoAckMode+");
  2015. if (the_target->supports_qxfer_osdata ())
  2016. strcat (own_buf, ";qXfer:osdata:read+");
  2017. if (target_supports_multi_process ())
  2018. strcat (own_buf, ";multiprocess+");
  2019. if (target_supports_fork_events ())
  2020. strcat (own_buf, ";fork-events+");
  2021. if (target_supports_vfork_events ())
  2022. strcat (own_buf, ";vfork-events+");
  2023. if (target_supports_exec_events ())
  2024. strcat (own_buf, ";exec-events+");
  2025. if (target_supports_non_stop ())
  2026. strcat (own_buf, ";QNonStop+");
  2027. if (target_supports_disable_randomization ())
  2028. strcat (own_buf, ";QDisableRandomization+");
  2029. strcat (own_buf, ";qXfer:threads:read+");
  2030. if (target_supports_tracepoints ())
  2031. {
  2032. strcat (own_buf, ";ConditionalTracepoints+");
  2033. strcat (own_buf, ";TraceStateVariables+");
  2034. strcat (own_buf, ";TracepointSource+");
  2035. strcat (own_buf, ";DisconnectedTracing+");
  2036. if (gdb_supports_qRelocInsn && target_supports_fast_tracepoints ())
  2037. strcat (own_buf, ";FastTracepoints+");
  2038. strcat (own_buf, ";StaticTracepoints+");
  2039. strcat (own_buf, ";InstallInTrace+");
  2040. strcat (own_buf, ";qXfer:statictrace:read+");
  2041. strcat (own_buf, ";qXfer:traceframe-info:read+");
  2042. strcat (own_buf, ";EnableDisableTracepoints+");
  2043. strcat (own_buf, ";QTBuffer:size+");
  2044. strcat (own_buf, ";tracenz+");
  2045. }
  2046. if (target_supports_hardware_single_step ()
  2047. || target_supports_software_single_step () )
  2048. {
  2049. strcat (own_buf, ";ConditionalBreakpoints+");
  2050. }
  2051. strcat (own_buf, ";BreakpointCommands+");
  2052. if (target_supports_agent ())
  2053. strcat (own_buf, ";QAgent+");
  2054. supported_btrace_packets (own_buf);
  2055. if (target_supports_stopped_by_sw_breakpoint ())
  2056. strcat (own_buf, ";swbreak+");
  2057. if (target_supports_stopped_by_hw_breakpoint ())
  2058. strcat (own_buf, ";hwbreak+");
  2059. if (the_target->supports_pid_to_exec_file ())
  2060. strcat (own_buf, ";qXfer:exec-file:read+");
  2061. strcat (own_buf, ";vContSupported+");
  2062. strcat (own_buf, ";QThreadEvents+");
  2063. strcat (own_buf, ";no-resumed+");
  2064. if (target_supports_memory_tagging ())
  2065. strcat (own_buf, ";memory-tagging+");
  2066. /* Reinitialize components as needed for the new connection. */
  2067. hostio_handle_new_gdb_connection ();
  2068. target_handle_new_gdb_connection ();
  2069. return;
  2070. }
  2071. /* Thread-local storage support. */
  2072. if (the_target->supports_get_tls_address ()
  2073. && startswith (own_buf, "qGetTLSAddr:"))
  2074. {
  2075. char *p = own_buf + 12;
  2076. CORE_ADDR parts[2], address = 0;
  2077. int i, err;
  2078. ptid_t ptid = null_ptid;
  2079. require_running_or_return (own_buf);
  2080. for (i = 0; i < 3; i++)
  2081. {
  2082. char *p2;
  2083. int len;
  2084. if (p == NULL)
  2085. break;
  2086. p2 = strchr (p, ',');
  2087. if (p2)
  2088. {
  2089. len = p2 - p;
  2090. p2++;
  2091. }
  2092. else
  2093. {
  2094. len = strlen (p);
  2095. p2 = NULL;
  2096. }
  2097. if (i == 0)
  2098. ptid = read_ptid (p, NULL);
  2099. else
  2100. decode_address (&parts[i - 1], p, len);
  2101. p = p2;
  2102. }
  2103. if (p != NULL || i < 3)
  2104. err = 1;
  2105. else
  2106. {
  2107. struct thread_info *thread = find_thread_ptid (ptid);
  2108. if (thread == NULL)
  2109. err = 2;
  2110. else
  2111. err = the_target->get_tls_address (thread, parts[0], parts[1],
  2112. &address);
  2113. }
  2114. if (err == 0)
  2115. {
  2116. strcpy (own_buf, paddress(address));
  2117. return;
  2118. }
  2119. else if (err > 0)
  2120. {
  2121. write_enn (own_buf);
  2122. return;
  2123. }
  2124. /* Otherwise, pretend we do not understand this packet. */
  2125. }
  2126. /* Windows OS Thread Information Block address support. */
  2127. if (the_target->supports_get_tib_address ()
  2128. && startswith (own_buf, "qGetTIBAddr:"))
  2129. {
  2130. const char *annex;
  2131. int n;
  2132. CORE_ADDR tlb;
  2133. ptid_t ptid = read_ptid (own_buf + 12, &annex);
  2134. n = the_target->get_tib_address (ptid, &tlb);
  2135. if (n == 1)
  2136. {
  2137. strcpy (own_buf, paddress(tlb));
  2138. return;
  2139. }
  2140. else if (n == 0)
  2141. {
  2142. write_enn (own_buf);
  2143. return;
  2144. }
  2145. return;
  2146. }
  2147. /* Handle "monitor" commands. */
  2148. if (startswith (own_buf, "qRcmd,"))
  2149. {
  2150. char *mon = (char *) malloc (PBUFSIZ);
  2151. int len = strlen (own_buf + 6);
  2152. if (mon == NULL)
  2153. {
  2154. write_enn (own_buf);
  2155. return;
  2156. }
  2157. if ((len % 2) != 0
  2158. || hex2bin (own_buf + 6, (gdb_byte *) mon, len / 2) != len / 2)
  2159. {
  2160. write_enn (own_buf);
  2161. free (mon);
  2162. return;
  2163. }
  2164. mon[len / 2] = '\0';
  2165. write_ok (own_buf);
  2166. if (the_target->handle_monitor_command (mon) == 0)
  2167. /* Default processing. */
  2168. handle_monitor_command (mon, own_buf);
  2169. free (mon);
  2170. return;
  2171. }
  2172. if (startswith (own_buf, "qSearch:memory:"))
  2173. {
  2174. require_running_or_return (own_buf);
  2175. handle_search_memory (own_buf, packet_len);
  2176. return;
  2177. }
  2178. if (strcmp (own_buf, "qAttached") == 0
  2179. || startswith (own_buf, "qAttached:"))
  2180. {
  2181. struct process_info *process;
  2182. if (own_buf[sizeof ("qAttached") - 1])
  2183. {
  2184. int pid = strtoul (own_buf + sizeof ("qAttached:") - 1, NULL, 16);
  2185. process = find_process_pid (pid);
  2186. }
  2187. else
  2188. {
  2189. require_running_or_return (own_buf);
  2190. process = current_process ();
  2191. }
  2192. if (process == NULL)
  2193. {
  2194. write_enn (own_buf);
  2195. return;
  2196. }
  2197. strcpy (own_buf, process->attached ? "1" : "0");
  2198. return;
  2199. }
  2200. if (startswith (own_buf, "qCRC:"))
  2201. {
  2202. /* CRC check (compare-section). */
  2203. const char *comma;
  2204. ULONGEST base;
  2205. int len;
  2206. unsigned long long crc;
  2207. require_running_or_return (own_buf);
  2208. comma = unpack_varlen_hex (own_buf + 5, &base);
  2209. if (*comma++ != ',')
  2210. {
  2211. write_enn (own_buf);
  2212. return;
  2213. }
  2214. len = strtoul (comma, NULL, 16);
  2215. crc = crc32 (base, len, 0xffffffff);
  2216. /* Check for memory failure. */
  2217. if (crc == (unsigned long long) -1)
  2218. {
  2219. write_enn (own_buf);
  2220. return;
  2221. }
  2222. sprintf (own_buf, "C%lx", (unsigned long) crc);
  2223. return;
  2224. }
  2225. if (handle_qxfer (own_buf, packet_len, new_packet_len_p))
  2226. return;
  2227. if (target_supports_tracepoints () && handle_tracepoint_query (own_buf))
  2228. return;
  2229. /* Handle fetch memory tags packets. */
  2230. if (startswith (own_buf, "qMemTags:")
  2231. && target_supports_memory_tagging ())
  2232. {
  2233. gdb::byte_vector tags;
  2234. CORE_ADDR addr = 0;
  2235. size_t len = 0;
  2236. int type = 0;
  2237. require_running_or_return (own_buf);
  2238. parse_fetch_memtags_request (own_buf, &addr, &len, &type);
  2239. bool ret = the_target->fetch_memtags (addr, len, tags, type);
  2240. if (ret)
  2241. ret = create_fetch_memtags_reply (own_buf, tags);
  2242. if (!ret)
  2243. write_enn (own_buf);
  2244. *new_packet_len_p = strlen (own_buf);
  2245. return;
  2246. }
  2247. /* Otherwise we didn't know what packet it was. Say we didn't
  2248. understand it. */
  2249. own_buf[0] = 0;
  2250. }
  2251. static void gdb_wants_all_threads_stopped (void);
  2252. static void resume (struct thread_resume *actions, size_t n);
  2253. /* The callback that is passed to visit_actioned_threads. */
  2254. typedef int (visit_actioned_threads_callback_ftype)
  2255. (const struct thread_resume *, struct thread_info *);
  2256. /* Call CALLBACK for any thread to which ACTIONS applies to. Returns
  2257. true if CALLBACK returns true. Returns false if no matching thread
  2258. is found or CALLBACK results false.
  2259. Note: This function is itself a callback for find_thread. */
  2260. static bool
  2261. visit_actioned_threads (thread_info *thread,
  2262. const struct thread_resume *actions,
  2263. size_t num_actions,
  2264. visit_actioned_threads_callback_ftype *callback)
  2265. {
  2266. for (size_t i = 0; i < num_actions; i++)
  2267. {
  2268. const struct thread_resume *action = &actions[i];
  2269. if (action->thread == minus_one_ptid
  2270. || action->thread == thread->id
  2271. || ((action->thread.pid ()
  2272. == thread->id.pid ())
  2273. && action->thread.lwp () == -1))
  2274. {
  2275. if ((*callback) (action, thread))
  2276. return true;
  2277. }
  2278. }
  2279. return false;
  2280. }
  2281. /* Callback for visit_actioned_threads. If the thread has a pending
  2282. status to report, report it now. */
  2283. static int
  2284. handle_pending_status (const struct thread_resume *resumption,
  2285. struct thread_info *thread)
  2286. {
  2287. client_state &cs = get_client_state ();
  2288. if (thread->status_pending_p)
  2289. {
  2290. thread->status_pending_p = 0;
  2291. cs.last_status = thread->last_status;
  2292. cs.last_ptid = thread->id;
  2293. prepare_resume_reply (cs.own_buf, cs.last_ptid, cs.last_status);
  2294. return 1;
  2295. }
  2296. return 0;
  2297. }
  2298. /* Parse vCont packets. */
  2299. static void
  2300. handle_v_cont (char *own_buf)
  2301. {
  2302. const char *p;
  2303. int n = 0, i = 0;
  2304. struct thread_resume *resume_info;
  2305. struct thread_resume default_action { null_ptid };
  2306. /* Count the number of semicolons in the packet. There should be one
  2307. for every action. */
  2308. p = &own_buf[5];
  2309. while (p)
  2310. {
  2311. n++;
  2312. p++;
  2313. p = strchr (p, ';');
  2314. }
  2315. resume_info = (struct thread_resume *) malloc (n * sizeof (resume_info[0]));
  2316. if (resume_info == NULL)
  2317. goto err;
  2318. p = &own_buf[5];
  2319. while (*p)
  2320. {
  2321. p++;
  2322. memset (&resume_info[i], 0, sizeof resume_info[i]);
  2323. if (p[0] == 's' || p[0] == 'S')
  2324. resume_info[i].kind = resume_step;
  2325. else if (p[0] == 'r')
  2326. resume_info[i].kind = resume_step;
  2327. else if (p[0] == 'c' || p[0] == 'C')
  2328. resume_info[i].kind = resume_continue;
  2329. else if (p[0] == 't')
  2330. resume_info[i].kind = resume_stop;
  2331. else
  2332. goto err;
  2333. if (p[0] == 'S' || p[0] == 'C')
  2334. {
  2335. char *q;
  2336. int sig = strtol (p + 1, &q, 16);
  2337. if (p == q)
  2338. goto err;
  2339. p = q;
  2340. if (!gdb_signal_to_host_p ((enum gdb_signal) sig))
  2341. goto err;
  2342. resume_info[i].sig = gdb_signal_to_host ((enum gdb_signal) sig);
  2343. }
  2344. else if (p[0] == 'r')
  2345. {
  2346. ULONGEST addr;
  2347. p = unpack_varlen_hex (p + 1, &addr);
  2348. resume_info[i].step_range_start = addr;
  2349. if (*p != ',')
  2350. goto err;
  2351. p = unpack_varlen_hex (p + 1, &addr);
  2352. resume_info[i].step_range_end = addr;
  2353. }
  2354. else
  2355. {
  2356. p = p + 1;
  2357. }
  2358. if (p[0] == 0)
  2359. {
  2360. resume_info[i].thread = minus_one_ptid;
  2361. default_action = resume_info[i];
  2362. /* Note: we don't increment i here, we'll overwrite this entry
  2363. the next time through. */
  2364. }
  2365. else if (p[0] == ':')
  2366. {
  2367. const char *q;
  2368. ptid_t ptid = read_ptid (p + 1, &q);
  2369. if (p == q)
  2370. goto err;
  2371. p = q;
  2372. if (p[0] != ';' && p[0] != 0)
  2373. goto err;
  2374. resume_info[i].thread = ptid;
  2375. i++;
  2376. }
  2377. }
  2378. if (i < n)
  2379. resume_info[i] = default_action;
  2380. resume (resume_info, n);
  2381. free (resume_info);
  2382. return;
  2383. err:
  2384. write_enn (own_buf);
  2385. free (resume_info);
  2386. return;
  2387. }
  2388. /* Resume target with ACTIONS, an array of NUM_ACTIONS elements. */
  2389. static void
  2390. resume (struct thread_resume *actions, size_t num_actions)
  2391. {
  2392. client_state &cs = get_client_state ();
  2393. if (!non_stop)
  2394. {
  2395. /* Check if among the threads that GDB wants actioned, there's
  2396. one with a pending status to report. If so, skip actually
  2397. resuming/stopping and report the pending event
  2398. immediately. */
  2399. thread_info *thread_with_status = find_thread ([&] (thread_info *thread)
  2400. {
  2401. return visit_actioned_threads (thread, actions, num_actions,
  2402. handle_pending_status);
  2403. });
  2404. if (thread_with_status != NULL)
  2405. return;
  2406. enable_async_io ();
  2407. }
  2408. the_target->resume (actions, num_actions);
  2409. if (non_stop)
  2410. write_ok (cs.own_buf);
  2411. else
  2412. {
  2413. cs.last_ptid = mywait (minus_one_ptid, &cs.last_status, 0, 1);
  2414. if (cs.last_status.kind () == TARGET_WAITKIND_NO_RESUMED
  2415. && !report_no_resumed)
  2416. {
  2417. /* The client does not support this stop reply. At least
  2418. return error. */
  2419. sprintf (cs.own_buf, "E.No unwaited-for children left.");
  2420. disable_async_io ();
  2421. return;
  2422. }
  2423. if (cs.last_status.kind () != TARGET_WAITKIND_EXITED
  2424. && cs.last_status.kind () != TARGET_WAITKIND_SIGNALLED
  2425. && cs.last_status.kind () != TARGET_WAITKIND_NO_RESUMED)
  2426. current_thread->last_status = cs.last_status;
  2427. /* From the client's perspective, all-stop mode always stops all
  2428. threads implicitly (and the target backend has already done
  2429. so by now). Tag all threads as "want-stopped", so we don't
  2430. resume them implicitly without the client telling us to. */
  2431. gdb_wants_all_threads_stopped ();
  2432. prepare_resume_reply (cs.own_buf, cs.last_ptid, cs.last_status);
  2433. disable_async_io ();
  2434. if (cs.last_status.kind () == TARGET_WAITKIND_EXITED
  2435. || cs.last_status.kind () == TARGET_WAITKIND_SIGNALLED)
  2436. target_mourn_inferior (cs.last_ptid);
  2437. }
  2438. }
  2439. /* Attach to a new program. */
  2440. static void
  2441. handle_v_attach (char *own_buf)
  2442. {
  2443. client_state &cs = get_client_state ();
  2444. int pid;
  2445. pid = strtol (own_buf + 8, NULL, 16);
  2446. if (pid != 0 && attach_inferior (pid) == 0)
  2447. {
  2448. /* Don't report shared library events after attaching, even if
  2449. some libraries are preloaded. GDB will always poll the
  2450. library list. Avoids the "stopped by shared library event"
  2451. notice on the GDB side. */
  2452. current_process ()->dlls_changed = false;
  2453. if (non_stop)
  2454. {
  2455. /* In non-stop, we don't send a resume reply. Stop events
  2456. will follow up using the normal notification
  2457. mechanism. */
  2458. write_ok (own_buf);
  2459. }
  2460. else
  2461. prepare_resume_reply (own_buf, cs.last_ptid, cs.last_status);
  2462. }
  2463. else
  2464. write_enn (own_buf);
  2465. }
  2466. /* Run a new program. */
  2467. static void
  2468. handle_v_run (char *own_buf)
  2469. {
  2470. client_state &cs = get_client_state ();
  2471. char *p, *next_p;
  2472. std::vector<char *> new_argv;
  2473. char *new_program_name = NULL;
  2474. int i, new_argc;
  2475. new_argc = 0;
  2476. for (p = own_buf + strlen ("vRun;"); p && *p; p = strchr (p, ';'))
  2477. {
  2478. p++;
  2479. new_argc++;
  2480. }
  2481. for (i = 0, p = own_buf + strlen ("vRun;"); *p; p = next_p, ++i)
  2482. {
  2483. next_p = strchr (p, ';');
  2484. if (next_p == NULL)
  2485. next_p = p + strlen (p);
  2486. if (i == 0 && p == next_p)
  2487. {
  2488. /* No program specified. */
  2489. new_program_name = NULL;
  2490. }
  2491. else if (p == next_p)
  2492. {
  2493. /* Empty argument. */
  2494. new_argv.push_back (xstrdup (""));
  2495. }
  2496. else
  2497. {
  2498. size_t len = (next_p - p) / 2;
  2499. /* ARG is the unquoted argument received via the RSP. */
  2500. char *arg = (char *) xmalloc (len + 1);
  2501. /* FULL_ARGS will contain the quoted version of ARG. */
  2502. char *full_arg = (char *) xmalloc ((len + 1) * 2);
  2503. /* These are pointers used to navigate the strings above. */
  2504. char *tmp_arg = arg;
  2505. char *tmp_full_arg = full_arg;
  2506. int need_quote = 0;
  2507. hex2bin (p, (gdb_byte *) arg, len);
  2508. arg[len] = '\0';
  2509. while (*tmp_arg != '\0')
  2510. {
  2511. switch (*tmp_arg)
  2512. {
  2513. case '\n':
  2514. /* Quote \n. */
  2515. *tmp_full_arg = '\'';
  2516. ++tmp_full_arg;
  2517. need_quote = 1;
  2518. break;
  2519. case '\'':
  2520. /* Quote single quote. */
  2521. *tmp_full_arg = '\\';
  2522. ++tmp_full_arg;
  2523. break;
  2524. default:
  2525. break;
  2526. }
  2527. *tmp_full_arg = *tmp_arg;
  2528. ++tmp_full_arg;
  2529. ++tmp_arg;
  2530. }
  2531. if (need_quote)
  2532. *tmp_full_arg++ = '\'';
  2533. /* Finish FULL_ARG and push it into the vector containing
  2534. the argv. */
  2535. *tmp_full_arg = '\0';
  2536. if (i == 0)
  2537. new_program_name = full_arg;
  2538. else
  2539. new_argv.push_back (full_arg);
  2540. xfree (arg);
  2541. }
  2542. if (*next_p)
  2543. next_p++;
  2544. }
  2545. if (new_program_name == NULL)
  2546. {
  2547. /* GDB didn't specify a program to run. Use the program from the
  2548. last run with the new argument list. */
  2549. if (program_path.get () == NULL)
  2550. {
  2551. write_enn (own_buf);
  2552. free_vector_argv (new_argv);
  2553. return;
  2554. }
  2555. }
  2556. else
  2557. program_path.set (gdb::unique_xmalloc_ptr<char> (new_program_name));
  2558. /* Free the old argv and install the new one. */
  2559. free_vector_argv (program_args);
  2560. program_args = new_argv;
  2561. target_create_inferior (program_path.get (), program_args);
  2562. if (cs.last_status.kind () == TARGET_WAITKIND_STOPPED)
  2563. {
  2564. prepare_resume_reply (own_buf, cs.last_ptid, cs.last_status);
  2565. /* In non-stop, sending a resume reply doesn't set the general
  2566. thread, but GDB assumes a vRun sets it (this is so GDB can
  2567. query which is the main thread of the new inferior. */
  2568. if (non_stop)
  2569. cs.general_thread = cs.last_ptid;
  2570. }
  2571. else
  2572. write_enn (own_buf);
  2573. }
  2574. /* Kill process. */
  2575. static void
  2576. handle_v_kill (char *own_buf)
  2577. {
  2578. client_state &cs = get_client_state ();
  2579. int pid;
  2580. char *p = &own_buf[6];
  2581. if (cs.multi_process)
  2582. pid = strtol (p, NULL, 16);
  2583. else
  2584. pid = signal_pid;
  2585. process_info *proc = find_process_pid (pid);
  2586. if (proc != nullptr && kill_inferior (proc) == 0)
  2587. {
  2588. cs.last_status.set_signalled (GDB_SIGNAL_KILL);
  2589. cs.last_ptid = ptid_t (pid);
  2590. discard_queued_stop_replies (cs.last_ptid);
  2591. write_ok (own_buf);
  2592. }
  2593. else
  2594. write_enn (own_buf);
  2595. }
  2596. /* Handle all of the extended 'v' packets. */
  2597. void
  2598. handle_v_requests (char *own_buf, int packet_len, int *new_packet_len)
  2599. {
  2600. client_state &cs = get_client_state ();
  2601. if (!disable_packet_vCont)
  2602. {
  2603. if (strcmp (own_buf, "vCtrlC") == 0)
  2604. {
  2605. the_target->request_interrupt ();
  2606. write_ok (own_buf);
  2607. return;
  2608. }
  2609. if (startswith (own_buf, "vCont;"))
  2610. {
  2611. handle_v_cont (own_buf);
  2612. return;
  2613. }
  2614. if (startswith (own_buf, "vCont?"))
  2615. {
  2616. strcpy (own_buf, "vCont;c;C;t");
  2617. if (target_supports_hardware_single_step ()
  2618. || target_supports_software_single_step ()
  2619. || !cs.vCont_supported)
  2620. {
  2621. /* If target supports single step either by hardware or by
  2622. software, add actions s and S to the list of supported
  2623. actions. On the other hand, if GDB doesn't request the
  2624. supported vCont actions in qSupported packet, add s and
  2625. S to the list too. */
  2626. own_buf = own_buf + strlen (own_buf);
  2627. strcpy (own_buf, ";s;S");
  2628. }
  2629. if (target_supports_range_stepping ())
  2630. {
  2631. own_buf = own_buf + strlen (own_buf);
  2632. strcpy (own_buf, ";r");
  2633. }
  2634. return;
  2635. }
  2636. }
  2637. if (startswith (own_buf, "vFile:")
  2638. && handle_vFile (own_buf, packet_len, new_packet_len))
  2639. return;
  2640. if (startswith (own_buf, "vAttach;"))
  2641. {
  2642. if ((!extended_protocol || !cs.multi_process) && target_running ())
  2643. {
  2644. fprintf (stderr, "Already debugging a process\n");
  2645. write_enn (own_buf);
  2646. return;
  2647. }
  2648. handle_v_attach (own_buf);
  2649. return;
  2650. }
  2651. if (startswith (own_buf, "vRun;"))
  2652. {
  2653. if ((!extended_protocol || !cs.multi_process) && target_running ())
  2654. {
  2655. fprintf (stderr, "Already debugging a process\n");
  2656. write_enn (own_buf);
  2657. return;
  2658. }
  2659. handle_v_run (own_buf);
  2660. return;
  2661. }
  2662. if (startswith (own_buf, "vKill;"))
  2663. {
  2664. if (!target_running ())
  2665. {
  2666. fprintf (stderr, "No process to kill\n");
  2667. write_enn (own_buf);
  2668. return;
  2669. }
  2670. handle_v_kill (own_buf);
  2671. return;
  2672. }
  2673. if (handle_notif_ack (own_buf, packet_len))
  2674. return;
  2675. /* Otherwise we didn't know what packet it was. Say we didn't
  2676. understand it. */
  2677. own_buf[0] = 0;
  2678. return;
  2679. }
  2680. /* Resume thread and wait for another event. In non-stop mode,
  2681. don't really wait here, but return immediatelly to the event
  2682. loop. */
  2683. static void
  2684. myresume (char *own_buf, int step, int sig)
  2685. {
  2686. client_state &cs = get_client_state ();
  2687. struct thread_resume resume_info[2];
  2688. int n = 0;
  2689. int valid_cont_thread;
  2690. valid_cont_thread = (cs.cont_thread != null_ptid
  2691. && cs.cont_thread != minus_one_ptid);
  2692. if (step || sig || valid_cont_thread)
  2693. {
  2694. resume_info[0].thread = current_ptid;
  2695. if (step)
  2696. resume_info[0].kind = resume_step;
  2697. else
  2698. resume_info[0].kind = resume_continue;
  2699. resume_info[0].sig = sig;
  2700. n++;
  2701. }
  2702. if (!valid_cont_thread)
  2703. {
  2704. resume_info[n].thread = minus_one_ptid;
  2705. resume_info[n].kind = resume_continue;
  2706. resume_info[n].sig = 0;
  2707. n++;
  2708. }
  2709. resume (resume_info, n);
  2710. }
  2711. /* Callback for for_each_thread. Make a new stop reply for each
  2712. stopped thread. */
  2713. static void
  2714. queue_stop_reply_callback (thread_info *thread)
  2715. {
  2716. /* For now, assume targets that don't have this callback also don't
  2717. manage the thread's last_status field. */
  2718. if (!the_target->supports_thread_stopped ())
  2719. {
  2720. struct vstop_notif *new_notif = new struct vstop_notif;
  2721. new_notif->ptid = thread->id;
  2722. new_notif->status = thread->last_status;
  2723. /* Pass the last stop reply back to GDB, but don't notify
  2724. yet. */
  2725. notif_event_enque (&notif_stop, new_notif);
  2726. }
  2727. else
  2728. {
  2729. if (target_thread_stopped (thread))
  2730. {
  2731. threads_debug_printf
  2732. ("Reporting thread %s as already stopped with %s",
  2733. target_pid_to_str (thread->id).c_str (),
  2734. thread->last_status.to_string ().c_str ());
  2735. gdb_assert (thread->last_status.kind () != TARGET_WAITKIND_IGNORE);
  2736. /* Pass the last stop reply back to GDB, but don't notify
  2737. yet. */
  2738. queue_stop_reply (thread->id, thread->last_status);
  2739. }
  2740. }
  2741. }
  2742. /* Set this inferior threads's state as "want-stopped". We won't
  2743. resume this thread until the client gives us another action for
  2744. it. */
  2745. static void
  2746. gdb_wants_thread_stopped (thread_info *thread)
  2747. {
  2748. thread->last_resume_kind = resume_stop;
  2749. if (thread->last_status.kind () == TARGET_WAITKIND_IGNORE)
  2750. {
  2751. /* Most threads are stopped implicitly (all-stop); tag that with
  2752. signal 0. */
  2753. thread->last_status.set_stopped (GDB_SIGNAL_0);
  2754. }
  2755. }
  2756. /* Set all threads' states as "want-stopped". */
  2757. static void
  2758. gdb_wants_all_threads_stopped (void)
  2759. {
  2760. for_each_thread (gdb_wants_thread_stopped);
  2761. }
  2762. /* Callback for for_each_thread. If the thread is stopped with an
  2763. interesting event, mark it as having a pending event. */
  2764. static void
  2765. set_pending_status_callback (thread_info *thread)
  2766. {
  2767. if (thread->last_status.kind () != TARGET_WAITKIND_STOPPED
  2768. || (thread->last_status.sig () != GDB_SIGNAL_0
  2769. /* A breakpoint, watchpoint or finished step from a previous
  2770. GDB run isn't considered interesting for a new GDB run.
  2771. If we left those pending, the new GDB could consider them
  2772. random SIGTRAPs. This leaves out real async traps. We'd
  2773. have to peek into the (target-specific) siginfo to
  2774. distinguish those. */
  2775. && thread->last_status.sig () != GDB_SIGNAL_TRAP))
  2776. thread->status_pending_p = 1;
  2777. }
  2778. /* Status handler for the '?' packet. */
  2779. static void
  2780. handle_status (char *own_buf)
  2781. {
  2782. client_state &cs = get_client_state ();
  2783. /* GDB is connected, don't forward events to the target anymore. */
  2784. for_each_process ([] (process_info *process) {
  2785. process->gdb_detached = 0;
  2786. });
  2787. /* In non-stop mode, we must send a stop reply for each stopped
  2788. thread. In all-stop mode, just send one for the first stopped
  2789. thread we find. */
  2790. if (non_stop)
  2791. {
  2792. for_each_thread (queue_stop_reply_callback);
  2793. /* The first is sent immediatly. OK is sent if there is no
  2794. stopped thread, which is the same handling of the vStopped
  2795. packet (by design). */
  2796. notif_write_event (&notif_stop, cs.own_buf);
  2797. }
  2798. else
  2799. {
  2800. thread_info *thread = NULL;
  2801. target_pause_all (false);
  2802. target_stabilize_threads ();
  2803. gdb_wants_all_threads_stopped ();
  2804. /* We can only report one status, but we might be coming out of
  2805. non-stop -- if more than one thread is stopped with
  2806. interesting events, leave events for the threads we're not
  2807. reporting now pending. They'll be reported the next time the
  2808. threads are resumed. Start by marking all interesting events
  2809. as pending. */
  2810. for_each_thread (set_pending_status_callback);
  2811. /* Prefer the last thread that reported an event to GDB (even if
  2812. that was a GDB_SIGNAL_TRAP). */
  2813. if (cs.last_status.kind () != TARGET_WAITKIND_IGNORE
  2814. && cs.last_status.kind () != TARGET_WAITKIND_EXITED
  2815. && cs.last_status.kind () != TARGET_WAITKIND_SIGNALLED)
  2816. thread = find_thread_ptid (cs.last_ptid);
  2817. /* If the last event thread is not found for some reason, look
  2818. for some other thread that might have an event to report. */
  2819. if (thread == NULL)
  2820. thread = find_thread ([] (thread_info *thr_arg)
  2821. {
  2822. return thr_arg->status_pending_p;
  2823. });
  2824. /* If we're still out of luck, simply pick the first thread in
  2825. the thread list. */
  2826. if (thread == NULL)
  2827. thread = get_first_thread ();
  2828. if (thread != NULL)
  2829. {
  2830. struct thread_info *tp = (struct thread_info *) thread;
  2831. /* We're reporting this event, so it's no longer
  2832. pending. */
  2833. tp->status_pending_p = 0;
  2834. /* GDB assumes the current thread is the thread we're
  2835. reporting the status for. */
  2836. cs.general_thread = thread->id;
  2837. set_desired_thread ();
  2838. gdb_assert (tp->last_status.kind () != TARGET_WAITKIND_IGNORE);
  2839. prepare_resume_reply (own_buf, tp->id, tp->last_status);
  2840. }
  2841. else
  2842. strcpy (own_buf, "W00");
  2843. }
  2844. }
  2845. static void
  2846. gdbserver_version (void)
  2847. {
  2848. printf ("GNU gdbserver %s%s\n"
  2849. "Copyright (C) 2022 Free Software Foundation, Inc.\n"
  2850. "gdbserver is free software, covered by the "
  2851. "GNU General Public License.\n"
  2852. "This gdbserver was configured as \"%s\"\n",
  2853. PKGVERSION, version, host_name);
  2854. }
  2855. static void
  2856. gdbserver_usage (FILE *stream)
  2857. {
  2858. fprintf (stream, "Usage:\tgdbserver [OPTIONS] COMM PROG [ARGS ...]\n"
  2859. "\tgdbserver [OPTIONS] --attach COMM PID\n"
  2860. "\tgdbserver [OPTIONS] --multi COMM\n"
  2861. "\n"
  2862. "COMM may either be a tty device (for serial debugging),\n"
  2863. "HOST:PORT to listen for a TCP connection, or '-' or 'stdio' to use \n"
  2864. "stdin/stdout of gdbserver.\n"
  2865. "PROG is the executable program. ARGS are arguments passed to inferior.\n"
  2866. "PID is the process ID to attach to, when --attach is specified.\n"
  2867. "\n"
  2868. "Operating modes:\n"
  2869. "\n"
  2870. " --attach Attach to running process PID.\n"
  2871. " --multi Start server without a specific program, and\n"
  2872. " only quit when explicitly commanded.\n"
  2873. " --once Exit after the first connection has closed.\n"
  2874. " --help Print this message and then exit.\n"
  2875. " --version Display version information and exit.\n"
  2876. "\n"
  2877. "Other options:\n"
  2878. "\n"
  2879. " --wrapper WRAPPER -- Run WRAPPER to start new programs.\n"
  2880. " --disable-randomization\n"
  2881. " Run PROG with address space randomization disabled.\n"
  2882. " --no-disable-randomization\n"
  2883. " Don't disable address space randomization when\n"
  2884. " starting PROG.\n"
  2885. " --startup-with-shell\n"
  2886. " Start PROG using a shell. I.e., execs a shell that\n"
  2887. " then execs PROG. (default)\n"
  2888. " --no-startup-with-shell\n"
  2889. " Exec PROG directly instead of using a shell.\n"
  2890. " Disables argument globbing and variable substitution\n"
  2891. " on UNIX-like systems.\n"
  2892. "\n"
  2893. "Debug options:\n"
  2894. "\n"
  2895. " --debug Enable general debugging output.\n"
  2896. " --debug-format=OPT1[,OPT2,...]\n"
  2897. " Specify extra content in debugging output.\n"
  2898. " Options:\n"
  2899. " all\n"
  2900. " none\n"
  2901. " timestamp\n"
  2902. " --remote-debug Enable remote protocol debugging output.\n"
  2903. " --event-loop-debug Enable event loop debugging output.\n"
  2904. " --disable-packet=OPT1[,OPT2,...]\n"
  2905. " Disable support for RSP packets or features.\n"
  2906. " Options:\n"
  2907. " vCont, T, Tthread, qC, qfThreadInfo and \n"
  2908. " threads (disable all threading packets).\n"
  2909. "\n"
  2910. "For more information, consult the GDB manual (available as on-line \n"
  2911. "info or a printed manual).\n");
  2912. if (REPORT_BUGS_TO[0] && stream == stdout)
  2913. fprintf (stream, "Report bugs to \"%s\".\n", REPORT_BUGS_TO);
  2914. }
  2915. static void
  2916. gdbserver_show_disableable (FILE *stream)
  2917. {
  2918. fprintf (stream, "Disableable packets:\n"
  2919. " vCont \tAll vCont packets\n"
  2920. " qC \tQuerying the current thread\n"
  2921. " qfThreadInfo\tThread listing\n"
  2922. " Tthread \tPassing the thread specifier in the "
  2923. "T stop reply packet\n"
  2924. " threads \tAll of the above\n"
  2925. " T \tAll 'T' packets\n");
  2926. }
  2927. /* Start up the event loop. This is the entry point to the event
  2928. loop. */
  2929. static void
  2930. start_event_loop ()
  2931. {
  2932. /* Loop until there is nothing to do. This is the entry point to
  2933. the event loop engine. If nothing is ready at this time, wait
  2934. for something to happen (via wait_for_event), then process it.
  2935. Return when there are no longer event sources to wait for. */
  2936. keep_processing_events = true;
  2937. while (keep_processing_events)
  2938. {
  2939. /* Any events already waiting in the queue? */
  2940. int res = gdb_do_one_event ();
  2941. /* Was there an error? */
  2942. if (res == -1)
  2943. break;
  2944. }
  2945. /* We are done with the event loop. There are no more event sources
  2946. to listen to. So we exit gdbserver. */
  2947. }
  2948. static void
  2949. kill_inferior_callback (process_info *process)
  2950. {
  2951. kill_inferior (process);
  2952. discard_queued_stop_replies (ptid_t (process->pid));
  2953. }
  2954. /* Call this when exiting gdbserver with possible inferiors that need
  2955. to be killed or detached from. */
  2956. static void
  2957. detach_or_kill_for_exit (void)
  2958. {
  2959. /* First print a list of the inferiors we will be killing/detaching.
  2960. This is to assist the user, for example, in case the inferior unexpectedly
  2961. dies after we exit: did we screw up or did the inferior exit on its own?
  2962. Having this info will save some head-scratching. */
  2963. if (have_started_inferiors_p ())
  2964. {
  2965. fprintf (stderr, "Killing process(es):");
  2966. for_each_process ([] (process_info *process) {
  2967. if (!process->attached)
  2968. fprintf (stderr, " %d", process->pid);
  2969. });
  2970. fprintf (stderr, "\n");
  2971. }
  2972. if (have_attached_inferiors_p ())
  2973. {
  2974. fprintf (stderr, "Detaching process(es):");
  2975. for_each_process ([] (process_info *process) {
  2976. if (process->attached)
  2977. fprintf (stderr, " %d", process->pid);
  2978. });
  2979. fprintf (stderr, "\n");
  2980. }
  2981. /* Now we can kill or detach the inferiors. */
  2982. for_each_process ([] (process_info *process) {
  2983. int pid = process->pid;
  2984. if (process->attached)
  2985. detach_inferior (process);
  2986. else
  2987. kill_inferior (process);
  2988. discard_queued_stop_replies (ptid_t (pid));
  2989. });
  2990. }
  2991. /* Value that will be passed to exit(3) when gdbserver exits. */
  2992. static int exit_code;
  2993. /* Wrapper for detach_or_kill_for_exit that catches and prints
  2994. errors. */
  2995. static void
  2996. detach_or_kill_for_exit_cleanup ()
  2997. {
  2998. try
  2999. {
  3000. detach_or_kill_for_exit ();
  3001. }
  3002. catch (const gdb_exception &exception)
  3003. {
  3004. fflush (stdout);
  3005. fprintf (stderr, "Detach or kill failed: %s\n",
  3006. exception.what ());
  3007. exit_code = 1;
  3008. }
  3009. }
  3010. #if GDB_SELF_TEST
  3011. namespace selftests {
  3012. static void
  3013. test_memory_tagging_functions (void)
  3014. {
  3015. /* Setup testing. */
  3016. gdb::char_vector packet;
  3017. gdb::byte_vector tags, bv;
  3018. std::string expected;
  3019. packet.resize (32000);
  3020. CORE_ADDR addr;
  3021. size_t len;
  3022. int type;
  3023. /* Test parsing a qMemTags request. */
  3024. /* Valid request, addr, len and type updated. */
  3025. addr = 0xff;
  3026. len = 255;
  3027. type = 255;
  3028. strcpy (packet.data (), "qMemTags:0,0:0");
  3029. parse_fetch_memtags_request (packet.data (), &addr, &len, &type);
  3030. SELF_CHECK (addr == 0 && len == 0 && type == 0);
  3031. /* Valid request, addr, len and type updated. */
  3032. addr = 0;
  3033. len = 0;
  3034. type = 0;
  3035. strcpy (packet.data (), "qMemTags:deadbeef,ff:5");
  3036. parse_fetch_memtags_request (packet.data (), &addr, &len, &type);
  3037. SELF_CHECK (addr == 0xdeadbeef && len == 255 && type == 5);
  3038. /* Test creating a qMemTags reply. */
  3039. /* Non-empty tag data. */
  3040. bv.resize (0);
  3041. for (int i = 0; i < 5; i++)
  3042. bv.push_back (i);
  3043. expected = "m0001020304";
  3044. SELF_CHECK (create_fetch_memtags_reply (packet.data (), bv) == true);
  3045. SELF_CHECK (strcmp (packet.data (), expected.c_str ()) == 0);
  3046. /* Test parsing a QMemTags request. */
  3047. /* Valid request and empty tag data: addr, len, type and tags updated. */
  3048. addr = 0xff;
  3049. len = 255;
  3050. type = 255;
  3051. tags.resize (5);
  3052. strcpy (packet.data (), "QMemTags:0,0:0:");
  3053. SELF_CHECK (parse_store_memtags_request (packet.data (),
  3054. &addr, &len, tags, &type) == true);
  3055. SELF_CHECK (addr == 0 && len == 0 && type == 0 && tags.size () == 0);
  3056. /* Valid request and non-empty tag data: addr, len, type
  3057. and tags updated. */
  3058. addr = 0;
  3059. len = 0;
  3060. type = 0;
  3061. tags.resize (0);
  3062. strcpy (packet.data (),
  3063. "QMemTags:deadbeef,ff:5:0001020304");
  3064. SELF_CHECK (parse_store_memtags_request (packet.data (), &addr, &len, tags,
  3065. &type) == true);
  3066. SELF_CHECK (addr == 0xdeadbeef && len == 255 && type == 5
  3067. && tags.size () == 5);
  3068. }
  3069. } // namespace selftests
  3070. #endif /* GDB_SELF_TEST */
  3071. /* Main function. This is called by the real "main" function,
  3072. wrapped in a TRY_CATCH that handles any uncaught exceptions. */
  3073. static void ATTRIBUTE_NORETURN
  3074. captured_main (int argc, char *argv[])
  3075. {
  3076. int bad_attach;
  3077. int pid;
  3078. char *arg_end;
  3079. const char *port = NULL;
  3080. char **next_arg = &argv[1];
  3081. volatile int multi_mode = 0;
  3082. volatile int attach = 0;
  3083. int was_running;
  3084. bool selftest = false;
  3085. #if GDB_SELF_TEST
  3086. std::vector<const char *> selftest_filters;
  3087. selftests::register_test ("remote_memory_tagging",
  3088. selftests::test_memory_tagging_functions);
  3089. #endif
  3090. current_directory = getcwd (NULL, 0);
  3091. client_state &cs = get_client_state ();
  3092. if (current_directory == NULL)
  3093. {
  3094. error (_("Could not find current working directory: %s"),
  3095. safe_strerror (errno));
  3096. }
  3097. while (*next_arg != NULL && **next_arg == '-')
  3098. {
  3099. if (strcmp (*next_arg, "--version") == 0)
  3100. {
  3101. gdbserver_version ();
  3102. exit (0);
  3103. }
  3104. else if (strcmp (*next_arg, "--help") == 0)
  3105. {
  3106. gdbserver_usage (stdout);
  3107. exit (0);
  3108. }
  3109. else if (strcmp (*next_arg, "--attach") == 0)
  3110. attach = 1;
  3111. else if (strcmp (*next_arg, "--multi") == 0)
  3112. multi_mode = 1;
  3113. else if (strcmp (*next_arg, "--wrapper") == 0)
  3114. {
  3115. char **tmp;
  3116. next_arg++;
  3117. tmp = next_arg;
  3118. while (*next_arg != NULL && strcmp (*next_arg, "--") != 0)
  3119. {
  3120. wrapper_argv += *next_arg;
  3121. wrapper_argv += ' ';
  3122. next_arg++;
  3123. }
  3124. if (!wrapper_argv.empty ())
  3125. {
  3126. /* Erase the last whitespace. */
  3127. wrapper_argv.erase (wrapper_argv.end () - 1);
  3128. }
  3129. if (next_arg == tmp || *next_arg == NULL)
  3130. {
  3131. gdbserver_usage (stderr);
  3132. exit (1);
  3133. }
  3134. /* Consume the "--". */
  3135. *next_arg = NULL;
  3136. }
  3137. else if (strcmp (*next_arg, "--debug") == 0)
  3138. debug_threads = true;
  3139. else if (startswith (*next_arg, "--debug-format="))
  3140. {
  3141. std::string error_msg
  3142. = parse_debug_format_options ((*next_arg)
  3143. + sizeof ("--debug-format=") - 1, 0);
  3144. if (!error_msg.empty ())
  3145. {
  3146. fprintf (stderr, "%s", error_msg.c_str ());
  3147. exit (1);
  3148. }
  3149. }
  3150. else if (strcmp (*next_arg, "--remote-debug") == 0)
  3151. remote_debug = true;
  3152. else if (strcmp (*next_arg, "--event-loop-debug") == 0)
  3153. debug_event_loop = debug_event_loop_kind::ALL;
  3154. else if (startswith (*next_arg, "--debug-file="))
  3155. debug_set_output ((*next_arg) + sizeof ("--debug-file=") -1);
  3156. else if (strcmp (*next_arg, "--disable-packet") == 0)
  3157. {
  3158. gdbserver_show_disableable (stdout);
  3159. exit (0);
  3160. }
  3161. else if (startswith (*next_arg, "--disable-packet="))
  3162. {
  3163. char *packets = *next_arg += sizeof ("--disable-packet=") - 1;
  3164. char *saveptr;
  3165. for (char *tok = strtok_r (packets, ",", &saveptr);
  3166. tok != NULL;
  3167. tok = strtok_r (NULL, ",", &saveptr))
  3168. {
  3169. if (strcmp ("vCont", tok) == 0)
  3170. disable_packet_vCont = true;
  3171. else if (strcmp ("Tthread", tok) == 0)
  3172. disable_packet_Tthread = true;
  3173. else if (strcmp ("qC", tok) == 0)
  3174. disable_packet_qC = true;
  3175. else if (strcmp ("qfThreadInfo", tok) == 0)
  3176. disable_packet_qfThreadInfo = true;
  3177. else if (strcmp ("T", tok) == 0)
  3178. disable_packet_T = true;
  3179. else if (strcmp ("threads", tok) == 0)
  3180. {
  3181. disable_packet_vCont = true;
  3182. disable_packet_Tthread = true;
  3183. disable_packet_qC = true;
  3184. disable_packet_qfThreadInfo = true;
  3185. }
  3186. else
  3187. {
  3188. fprintf (stderr, "Don't know how to disable \"%s\".\n\n",
  3189. tok);
  3190. gdbserver_show_disableable (stderr);
  3191. exit (1);
  3192. }
  3193. }
  3194. }
  3195. else if (strcmp (*next_arg, "-") == 0)
  3196. {
  3197. /* "-" specifies a stdio connection and is a form of port
  3198. specification. */
  3199. port = STDIO_CONNECTION_NAME;
  3200. next_arg++;
  3201. break;
  3202. }
  3203. else if (strcmp (*next_arg, "--disable-randomization") == 0)
  3204. cs.disable_randomization = 1;
  3205. else if (strcmp (*next_arg, "--no-disable-randomization") == 0)
  3206. cs.disable_randomization = 0;
  3207. else if (strcmp (*next_arg, "--startup-with-shell") == 0)
  3208. startup_with_shell = true;
  3209. else if (strcmp (*next_arg, "--no-startup-with-shell") == 0)
  3210. startup_with_shell = false;
  3211. else if (strcmp (*next_arg, "--once") == 0)
  3212. run_once = true;
  3213. else if (strcmp (*next_arg, "--selftest") == 0)
  3214. selftest = true;
  3215. else if (startswith (*next_arg, "--selftest="))
  3216. {
  3217. selftest = true;
  3218. #if GDB_SELF_TEST
  3219. const char *filter = *next_arg + strlen ("--selftest=");
  3220. if (*filter == '\0')
  3221. {
  3222. fprintf (stderr, _("Error: selftest filter is empty.\n"));
  3223. exit (1);
  3224. }
  3225. selftest_filters.push_back (filter);
  3226. #endif
  3227. }
  3228. else
  3229. {
  3230. fprintf (stderr, "Unknown argument: %s\n", *next_arg);
  3231. exit (1);
  3232. }
  3233. next_arg++;
  3234. continue;
  3235. }
  3236. if (port == NULL)
  3237. {
  3238. port = *next_arg;
  3239. next_arg++;
  3240. }
  3241. if ((port == NULL || (!attach && !multi_mode && *next_arg == NULL))
  3242. && !selftest)
  3243. {
  3244. gdbserver_usage (stderr);
  3245. exit (1);
  3246. }
  3247. /* Remember stdio descriptors. LISTEN_DESC must not be listed, it will be
  3248. opened by remote_prepare. */
  3249. notice_open_fds ();
  3250. save_original_signals_state (false);
  3251. /* We need to know whether the remote connection is stdio before
  3252. starting the inferior. Inferiors created in this scenario have
  3253. stdin,stdout redirected. So do this here before we call
  3254. start_inferior. */
  3255. if (port != NULL)
  3256. remote_prepare (port);
  3257. bad_attach = 0;
  3258. pid = 0;
  3259. /* --attach used to come after PORT, so allow it there for
  3260. compatibility. */
  3261. if (*next_arg != NULL && strcmp (*next_arg, "--attach") == 0)
  3262. {
  3263. attach = 1;
  3264. next_arg++;
  3265. }
  3266. if (attach
  3267. && (*next_arg == NULL
  3268. || (*next_arg)[0] == '\0'
  3269. || (pid = strtoul (*next_arg, &arg_end, 0)) == 0
  3270. || *arg_end != '\0'
  3271. || next_arg[1] != NULL))
  3272. bad_attach = 1;
  3273. if (bad_attach)
  3274. {
  3275. gdbserver_usage (stderr);
  3276. exit (1);
  3277. }
  3278. /* Gather information about the environment. */
  3279. our_environ = gdb_environ::from_host_environ ();
  3280. initialize_async_io ();
  3281. initialize_low ();
  3282. have_job_control ();
  3283. if (target_supports_tracepoints ())
  3284. initialize_tracepoint ();
  3285. mem_buf = (unsigned char *) xmalloc (PBUFSIZ);
  3286. if (selftest)
  3287. {
  3288. #if GDB_SELF_TEST
  3289. selftests::run_tests (selftest_filters);
  3290. #else
  3291. printf (_("Selftests have been disabled for this build.\n"));
  3292. #endif
  3293. throw_quit ("Quit");
  3294. }
  3295. if (pid == 0 && *next_arg != NULL)
  3296. {
  3297. int i, n;
  3298. n = argc - (next_arg - argv);
  3299. program_path.set (make_unique_xstrdup (next_arg[0]));
  3300. for (i = 1; i < n; i++)
  3301. program_args.push_back (xstrdup (next_arg[i]));
  3302. /* Wait till we are at first instruction in program. */
  3303. target_create_inferior (program_path.get (), program_args);
  3304. /* We are now (hopefully) stopped at the first instruction of
  3305. the target process. This assumes that the target process was
  3306. successfully created. */
  3307. }
  3308. else if (pid != 0)
  3309. {
  3310. if (attach_inferior (pid) == -1)
  3311. error ("Attaching not supported on this target");
  3312. /* Otherwise succeeded. */
  3313. }
  3314. else
  3315. {
  3316. cs.last_status.set_exited (0);
  3317. cs.last_ptid = minus_one_ptid;
  3318. }
  3319. SCOPE_EXIT { detach_or_kill_for_exit_cleanup (); };
  3320. /* Don't report shared library events on the initial connection,
  3321. even if some libraries are preloaded. Avoids the "stopped by
  3322. shared library event" notice on gdb side. */
  3323. if (current_thread != nullptr)
  3324. current_process ()->dlls_changed = false;
  3325. if (cs.last_status.kind () == TARGET_WAITKIND_EXITED
  3326. || cs.last_status.kind () == TARGET_WAITKIND_SIGNALLED)
  3327. was_running = 0;
  3328. else
  3329. was_running = 1;
  3330. if (!was_running && !multi_mode)
  3331. error ("No program to debug");
  3332. while (1)
  3333. {
  3334. cs.noack_mode = 0;
  3335. cs.multi_process = 0;
  3336. cs.report_fork_events = 0;
  3337. cs.report_vfork_events = 0;
  3338. cs.report_exec_events = 0;
  3339. /* Be sure we're out of tfind mode. */
  3340. cs.current_traceframe = -1;
  3341. cs.cont_thread = null_ptid;
  3342. cs.swbreak_feature = 0;
  3343. cs.hwbreak_feature = 0;
  3344. cs.vCont_supported = 0;
  3345. cs.memory_tagging_feature = false;
  3346. remote_open (port);
  3347. try
  3348. {
  3349. /* Wait for events. This will return when all event sources
  3350. are removed from the event loop. */
  3351. start_event_loop ();
  3352. /* If an exit was requested (using the "monitor exit"
  3353. command), terminate now. */
  3354. if (exit_requested)
  3355. throw_quit ("Quit");
  3356. /* The only other way to get here is for getpkt to fail:
  3357. - If --once was specified, we're done.
  3358. - If not in extended-remote mode, and we're no longer
  3359. debugging anything, simply exit: GDB has disconnected
  3360. after processing the last process exit.
  3361. - Otherwise, close the connection and reopen it at the
  3362. top of the loop. */
  3363. if (run_once || (!extended_protocol && !target_running ()))
  3364. throw_quit ("Quit");
  3365. fprintf (stderr,
  3366. "Remote side has terminated connection. "
  3367. "GDBserver will reopen the connection.\n");
  3368. /* Get rid of any pending statuses. An eventual reconnection
  3369. (by the same GDB instance or another) will refresh all its
  3370. state from scratch. */
  3371. discard_queued_stop_replies (minus_one_ptid);
  3372. for_each_thread ([] (thread_info *thread)
  3373. {
  3374. thread->status_pending_p = 0;
  3375. });
  3376. if (tracing)
  3377. {
  3378. if (disconnected_tracing)
  3379. {
  3380. /* Try to enable non-stop/async mode, so we we can
  3381. both wait for an async socket accept, and handle
  3382. async target events simultaneously. There's also
  3383. no point either in having the target always stop
  3384. all threads, when we're going to pass signals
  3385. down without informing GDB. */
  3386. if (!non_stop)
  3387. {
  3388. if (the_target->start_non_stop (true))
  3389. non_stop = 1;
  3390. /* Detaching implicitly resumes all threads;
  3391. simply disconnecting does not. */
  3392. }
  3393. }
  3394. else
  3395. {
  3396. fprintf (stderr,
  3397. "Disconnected tracing disabled; "
  3398. "stopping trace run.\n");
  3399. stop_tracing ();
  3400. }
  3401. }
  3402. }
  3403. catch (const gdb_exception_error &exception)
  3404. {
  3405. fflush (stdout);
  3406. fprintf (stderr, "gdbserver: %s\n", exception.what ());
  3407. if (response_needed)
  3408. {
  3409. write_enn (cs.own_buf);
  3410. putpkt (cs.own_buf);
  3411. }
  3412. if (run_once)
  3413. throw_quit ("Quit");
  3414. }
  3415. }
  3416. }
  3417. /* Main function. */
  3418. int
  3419. main (int argc, char *argv[])
  3420. {
  3421. try
  3422. {
  3423. captured_main (argc, argv);
  3424. }
  3425. catch (const gdb_exception &exception)
  3426. {
  3427. if (exception.reason == RETURN_ERROR)
  3428. {
  3429. fflush (stdout);
  3430. fprintf (stderr, "%s\n", exception.what ());
  3431. fprintf (stderr, "Exiting\n");
  3432. exit_code = 1;
  3433. }
  3434. exit (exit_code);
  3435. }
  3436. gdb_assert_not_reached ("captured_main should never return");
  3437. }
  3438. /* Process options coming from Z packets for a breakpoint. PACKET is
  3439. the packet buffer. *PACKET is updated to point to the first char
  3440. after the last processed option. */
  3441. static void
  3442. process_point_options (struct gdb_breakpoint *bp, const char **packet)
  3443. {
  3444. const char *dataptr = *packet;
  3445. int persist;
  3446. /* Check if data has the correct format. */
  3447. if (*dataptr != ';')
  3448. return;
  3449. dataptr++;
  3450. while (*dataptr)
  3451. {
  3452. if (*dataptr == ';')
  3453. ++dataptr;
  3454. if (*dataptr == 'X')
  3455. {
  3456. /* Conditional expression. */
  3457. threads_debug_printf ("Found breakpoint condition.");
  3458. if (!add_breakpoint_condition (bp, &dataptr))
  3459. dataptr = strchrnul (dataptr, ';');
  3460. }
  3461. else if (startswith (dataptr, "cmds:"))
  3462. {
  3463. dataptr += strlen ("cmds:");
  3464. threads_debug_printf ("Found breakpoint commands %s.", dataptr);
  3465. persist = (*dataptr == '1');
  3466. dataptr += 2;
  3467. if (add_breakpoint_commands (bp, &dataptr, persist))
  3468. dataptr = strchrnul (dataptr, ';');
  3469. }
  3470. else
  3471. {
  3472. fprintf (stderr, "Unknown token %c, ignoring.\n",
  3473. *dataptr);
  3474. /* Skip tokens until we find one that we recognize. */
  3475. dataptr = strchrnul (dataptr, ';');
  3476. }
  3477. }
  3478. *packet = dataptr;
  3479. }
  3480. /* Event loop callback that handles a serial event. The first byte in
  3481. the serial buffer gets us here. We expect characters to arrive at
  3482. a brisk pace, so we read the rest of the packet with a blocking
  3483. getpkt call. */
  3484. static int
  3485. process_serial_event (void)
  3486. {
  3487. client_state &cs = get_client_state ();
  3488. int signal;
  3489. unsigned int len;
  3490. CORE_ADDR mem_addr;
  3491. unsigned char sig;
  3492. int packet_len;
  3493. int new_packet_len = -1;
  3494. disable_async_io ();
  3495. response_needed = false;
  3496. packet_len = getpkt (cs.own_buf);
  3497. if (packet_len <= 0)
  3498. {
  3499. remote_close ();
  3500. /* Force an event loop break. */
  3501. return -1;
  3502. }
  3503. response_needed = true;
  3504. char ch = cs.own_buf[0];
  3505. switch (ch)
  3506. {
  3507. case 'q':
  3508. handle_query (cs.own_buf, packet_len, &new_packet_len);
  3509. break;
  3510. case 'Q':
  3511. handle_general_set (cs.own_buf);
  3512. break;
  3513. case 'D':
  3514. handle_detach (cs.own_buf);
  3515. break;
  3516. case '!':
  3517. extended_protocol = true;
  3518. write_ok (cs.own_buf);
  3519. break;
  3520. case '?':
  3521. handle_status (cs.own_buf);
  3522. break;
  3523. case 'H':
  3524. if (cs.own_buf[1] == 'c' || cs.own_buf[1] == 'g' || cs.own_buf[1] == 's')
  3525. {
  3526. require_running_or_break (cs.own_buf);
  3527. ptid_t thread_id = read_ptid (&cs.own_buf[2], NULL);
  3528. if (thread_id == null_ptid || thread_id == minus_one_ptid)
  3529. thread_id = null_ptid;
  3530. else if (thread_id.is_pid ())
  3531. {
  3532. /* The ptid represents a pid. */
  3533. thread_info *thread = find_any_thread_of_pid (thread_id.pid ());
  3534. if (thread == NULL)
  3535. {
  3536. write_enn (cs.own_buf);
  3537. break;
  3538. }
  3539. thread_id = thread->id;
  3540. }
  3541. else
  3542. {
  3543. /* The ptid represents a lwp/tid. */
  3544. if (find_thread_ptid (thread_id) == NULL)
  3545. {
  3546. write_enn (cs.own_buf);
  3547. break;
  3548. }
  3549. }
  3550. if (cs.own_buf[1] == 'g')
  3551. {
  3552. if (thread_id == null_ptid)
  3553. {
  3554. /* GDB is telling us to choose any thread. Check if
  3555. the currently selected thread is still valid. If
  3556. it is not, select the first available. */
  3557. thread_info *thread = find_thread_ptid (cs.general_thread);
  3558. if (thread == NULL)
  3559. thread = get_first_thread ();
  3560. thread_id = thread->id;
  3561. }
  3562. cs.general_thread = thread_id;
  3563. set_desired_thread ();
  3564. gdb_assert (current_thread != NULL);
  3565. }
  3566. else if (cs.own_buf[1] == 'c')
  3567. cs.cont_thread = thread_id;
  3568. write_ok (cs.own_buf);
  3569. }
  3570. else
  3571. {
  3572. /* Silently ignore it so that gdb can extend the protocol
  3573. without compatibility headaches. */
  3574. cs.own_buf[0] = '\0';
  3575. }
  3576. break;
  3577. case 'g':
  3578. require_running_or_break (cs.own_buf);
  3579. if (cs.current_traceframe >= 0)
  3580. {
  3581. struct regcache *regcache
  3582. = new_register_cache (current_target_desc ());
  3583. if (fetch_traceframe_registers (cs.current_traceframe,
  3584. regcache, -1) == 0)
  3585. registers_to_string (regcache, cs.own_buf);
  3586. else
  3587. write_enn (cs.own_buf);
  3588. free_register_cache (regcache);
  3589. }
  3590. else
  3591. {
  3592. struct regcache *regcache;
  3593. if (!set_desired_thread ())
  3594. write_enn (cs.own_buf);
  3595. else
  3596. {
  3597. regcache = get_thread_regcache (current_thread, 1);
  3598. registers_to_string (regcache, cs.own_buf);
  3599. }
  3600. }
  3601. break;
  3602. case 'G':
  3603. require_running_or_break (cs.own_buf);
  3604. if (cs.current_traceframe >= 0)
  3605. write_enn (cs.own_buf);
  3606. else
  3607. {
  3608. struct regcache *regcache;
  3609. if (!set_desired_thread ())
  3610. write_enn (cs.own_buf);
  3611. else
  3612. {
  3613. regcache = get_thread_regcache (current_thread, 1);
  3614. registers_from_string (regcache, &cs.own_buf[1]);
  3615. write_ok (cs.own_buf);
  3616. }
  3617. }
  3618. break;
  3619. case 'm':
  3620. {
  3621. require_running_or_break (cs.own_buf);
  3622. decode_m_packet (&cs.own_buf[1], &mem_addr, &len);
  3623. int res = gdb_read_memory (mem_addr, mem_buf, len);
  3624. if (res < 0)
  3625. write_enn (cs.own_buf);
  3626. else
  3627. bin2hex (mem_buf, cs.own_buf, res);
  3628. }
  3629. break;
  3630. case 'M':
  3631. require_running_or_break (cs.own_buf);
  3632. decode_M_packet (&cs.own_buf[1], &mem_addr, &len, &mem_buf);
  3633. if (gdb_write_memory (mem_addr, mem_buf, len) == 0)
  3634. write_ok (cs.own_buf);
  3635. else
  3636. write_enn (cs.own_buf);
  3637. break;
  3638. case 'X':
  3639. require_running_or_break (cs.own_buf);
  3640. if (decode_X_packet (&cs.own_buf[1], packet_len - 1,
  3641. &mem_addr, &len, &mem_buf) < 0
  3642. || gdb_write_memory (mem_addr, mem_buf, len) != 0)
  3643. write_enn (cs.own_buf);
  3644. else
  3645. write_ok (cs.own_buf);
  3646. break;
  3647. case 'C':
  3648. require_running_or_break (cs.own_buf);
  3649. hex2bin (cs.own_buf + 1, &sig, 1);
  3650. if (gdb_signal_to_host_p ((enum gdb_signal) sig))
  3651. signal = gdb_signal_to_host ((enum gdb_signal) sig);
  3652. else
  3653. signal = 0;
  3654. myresume (cs.own_buf, 0, signal);
  3655. break;
  3656. case 'S':
  3657. require_running_or_break (cs.own_buf);
  3658. hex2bin (cs.own_buf + 1, &sig, 1);
  3659. if (gdb_signal_to_host_p ((enum gdb_signal) sig))
  3660. signal = gdb_signal_to_host ((enum gdb_signal) sig);
  3661. else
  3662. signal = 0;
  3663. myresume (cs.own_buf, 1, signal);
  3664. break;
  3665. case 'c':
  3666. require_running_or_break (cs.own_buf);
  3667. signal = 0;
  3668. myresume (cs.own_buf, 0, signal);
  3669. break;
  3670. case 's':
  3671. require_running_or_break (cs.own_buf);
  3672. signal = 0;
  3673. myresume (cs.own_buf, 1, signal);
  3674. break;
  3675. case 'Z': /* insert_ ... */
  3676. /* Fallthrough. */
  3677. case 'z': /* remove_ ... */
  3678. {
  3679. char *dataptr;
  3680. ULONGEST addr;
  3681. int kind;
  3682. char type = cs.own_buf[1];
  3683. int res;
  3684. const int insert = ch == 'Z';
  3685. const char *p = &cs.own_buf[3];
  3686. p = unpack_varlen_hex (p, &addr);
  3687. kind = strtol (p + 1, &dataptr, 16);
  3688. if (insert)
  3689. {
  3690. struct gdb_breakpoint *bp;
  3691. bp = set_gdb_breakpoint (type, addr, kind, &res);
  3692. if (bp != NULL)
  3693. {
  3694. res = 0;
  3695. /* GDB may have sent us a list of *point parameters to
  3696. be evaluated on the target's side. Read such list
  3697. here. If we already have a list of parameters, GDB
  3698. is telling us to drop that list and use this one
  3699. instead. */
  3700. clear_breakpoint_conditions_and_commands (bp);
  3701. const char *options = dataptr;
  3702. process_point_options (bp, &options);
  3703. }
  3704. }
  3705. else
  3706. res = delete_gdb_breakpoint (type, addr, kind);
  3707. if (res == 0)
  3708. write_ok (cs.own_buf);
  3709. else if (res == 1)
  3710. /* Unsupported. */
  3711. cs.own_buf[0] = '\0';
  3712. else
  3713. write_enn (cs.own_buf);
  3714. break;
  3715. }
  3716. case 'k':
  3717. response_needed = false;
  3718. if (!target_running ())
  3719. /* The packet we received doesn't make sense - but we can't
  3720. reply to it, either. */
  3721. return 0;
  3722. fprintf (stderr, "Killing all inferiors\n");
  3723. for_each_process (kill_inferior_callback);
  3724. /* When using the extended protocol, we wait with no program
  3725. running. The traditional protocol will exit instead. */
  3726. if (extended_protocol)
  3727. {
  3728. cs.last_status.set_exited (GDB_SIGNAL_KILL);
  3729. return 0;
  3730. }
  3731. else
  3732. exit (0);
  3733. case 'T':
  3734. {
  3735. require_running_or_break (cs.own_buf);
  3736. ptid_t thread_id = read_ptid (&cs.own_buf[1], NULL);
  3737. if (find_thread_ptid (thread_id) == NULL)
  3738. {
  3739. write_enn (cs.own_buf);
  3740. break;
  3741. }
  3742. if (mythread_alive (thread_id))
  3743. write_ok (cs.own_buf);
  3744. else
  3745. write_enn (cs.own_buf);
  3746. }
  3747. break;
  3748. case 'R':
  3749. response_needed = false;
  3750. /* Restarting the inferior is only supported in the extended
  3751. protocol. */
  3752. if (extended_protocol)
  3753. {
  3754. if (target_running ())
  3755. for_each_process (kill_inferior_callback);
  3756. fprintf (stderr, "GDBserver restarting\n");
  3757. /* Wait till we are at 1st instruction in prog. */
  3758. if (program_path.get () != NULL)
  3759. {
  3760. target_create_inferior (program_path.get (), program_args);
  3761. if (cs.last_status.kind () == TARGET_WAITKIND_STOPPED)
  3762. {
  3763. /* Stopped at the first instruction of the target
  3764. process. */
  3765. cs.general_thread = cs.last_ptid;
  3766. }
  3767. else
  3768. {
  3769. /* Something went wrong. */
  3770. cs.general_thread = null_ptid;
  3771. }
  3772. }
  3773. else
  3774. {
  3775. cs.last_status.set_exited (GDB_SIGNAL_KILL);
  3776. }
  3777. return 0;
  3778. }
  3779. else
  3780. {
  3781. /* It is a request we don't understand. Respond with an
  3782. empty packet so that gdb knows that we don't support this
  3783. request. */
  3784. cs.own_buf[0] = '\0';
  3785. break;
  3786. }
  3787. case 'v':
  3788. /* Extended (long) request. */
  3789. handle_v_requests (cs.own_buf, packet_len, &new_packet_len);
  3790. break;
  3791. default:
  3792. /* It is a request we don't understand. Respond with an empty
  3793. packet so that gdb knows that we don't support this
  3794. request. */
  3795. cs.own_buf[0] = '\0';
  3796. break;
  3797. }
  3798. if (new_packet_len != -1)
  3799. putpkt_binary (cs.own_buf, new_packet_len);
  3800. else
  3801. putpkt (cs.own_buf);
  3802. response_needed = false;
  3803. if (exit_requested)
  3804. return -1;
  3805. return 0;
  3806. }
  3807. /* Event-loop callback for serial events. */
  3808. void
  3809. handle_serial_event (int err, gdb_client_data client_data)
  3810. {
  3811. threads_debug_printf ("handling possible serial event");
  3812. /* Really handle it. */
  3813. if (process_serial_event () < 0)
  3814. {
  3815. keep_processing_events = false;
  3816. return;
  3817. }
  3818. /* Be sure to not change the selected thread behind GDB's back.
  3819. Important in the non-stop mode asynchronous protocol. */
  3820. set_desired_thread ();
  3821. }
  3822. /* Push a stop notification on the notification queue. */
  3823. static void
  3824. push_stop_notification (ptid_t ptid, const target_waitstatus &status)
  3825. {
  3826. struct vstop_notif *vstop_notif = new struct vstop_notif;
  3827. vstop_notif->status = status;
  3828. vstop_notif->ptid = ptid;
  3829. /* Push Stop notification. */
  3830. notif_push (&notif_stop, vstop_notif);
  3831. }
  3832. /* Event-loop callback for target events. */
  3833. void
  3834. handle_target_event (int err, gdb_client_data client_data)
  3835. {
  3836. client_state &cs = get_client_state ();
  3837. threads_debug_printf ("handling possible target event");
  3838. cs.last_ptid = mywait (minus_one_ptid, &cs.last_status,
  3839. TARGET_WNOHANG, 1);
  3840. if (cs.last_status.kind () == TARGET_WAITKIND_NO_RESUMED)
  3841. {
  3842. if (gdb_connected () && report_no_resumed)
  3843. push_stop_notification (null_ptid, cs.last_status);
  3844. }
  3845. else if (cs.last_status.kind () != TARGET_WAITKIND_IGNORE)
  3846. {
  3847. int pid = cs.last_ptid.pid ();
  3848. struct process_info *process = find_process_pid (pid);
  3849. int forward_event = !gdb_connected () || process->gdb_detached;
  3850. if (cs.last_status.kind () == TARGET_WAITKIND_EXITED
  3851. || cs.last_status.kind () == TARGET_WAITKIND_SIGNALLED)
  3852. {
  3853. mark_breakpoints_out (process);
  3854. target_mourn_inferior (cs.last_ptid);
  3855. }
  3856. else if (cs.last_status.kind () == TARGET_WAITKIND_THREAD_EXITED)
  3857. ;
  3858. else
  3859. {
  3860. /* We're reporting this thread as stopped. Update its
  3861. "want-stopped" state to what the client wants, until it
  3862. gets a new resume action. */
  3863. current_thread->last_resume_kind = resume_stop;
  3864. current_thread->last_status = cs.last_status;
  3865. }
  3866. if (forward_event)
  3867. {
  3868. if (!target_running ())
  3869. {
  3870. /* The last process exited. We're done. */
  3871. exit (0);
  3872. }
  3873. if (cs.last_status.kind () == TARGET_WAITKIND_EXITED
  3874. || cs.last_status.kind () == TARGET_WAITKIND_SIGNALLED
  3875. || cs.last_status.kind () == TARGET_WAITKIND_THREAD_EXITED)
  3876. ;
  3877. else
  3878. {
  3879. /* A thread stopped with a signal, but gdb isn't
  3880. connected to handle it. Pass it down to the
  3881. inferior, as if it wasn't being traced. */
  3882. enum gdb_signal signal;
  3883. threads_debug_printf ("GDB not connected; forwarding event %d for"
  3884. " [%s]",
  3885. (int) cs.last_status.kind (),
  3886. target_pid_to_str (cs.last_ptid).c_str ());
  3887. if (cs.last_status.kind () == TARGET_WAITKIND_STOPPED)
  3888. signal = cs.last_status.sig ();
  3889. else
  3890. signal = GDB_SIGNAL_0;
  3891. target_continue (cs.last_ptid, signal);
  3892. }
  3893. }
  3894. else
  3895. push_stop_notification (cs.last_ptid, cs.last_status);
  3896. }
  3897. /* Be sure to not change the selected thread behind GDB's back.
  3898. Important in the non-stop mode asynchronous protocol. */
  3899. set_desired_thread ();
  3900. }
  3901. /* See gdbsupport/event-loop.h. */
  3902. int
  3903. invoke_async_signal_handlers ()
  3904. {
  3905. return 0;
  3906. }
  3907. /* See gdbsupport/event-loop.h. */
  3908. int
  3909. check_async_event_handlers ()
  3910. {
  3911. return 0;
  3912. }
  3913. /* See gdbsupport/errors.h */
  3914. void
  3915. flush_streams ()
  3916. {
  3917. fflush (stdout);
  3918. fflush (stderr);
  3919. }
  3920. /* See gdbsupport/gdb_select.h. */
  3921. int
  3922. gdb_select (int n, fd_set *readfds, fd_set *writefds,
  3923. fd_set *exceptfds, struct timeval *timeout)
  3924. {
  3925. return select (n, readfds, writefds, exceptfds, timeout);
  3926. }
  3927. #if GDB_SELF_TEST
  3928. namespace selftests
  3929. {
  3930. void
  3931. reset ()
  3932. {}
  3933. } // namespace selftests
  3934. #endif /* GDB_SELF_TEST */