windows-nat.c 92 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247
  1. /* Target-vector operations for controlling windows child processes, for GDB.
  2. Copyright (C) 1995-2022 Free Software Foundation, Inc.
  3. Contributed by Cygnus Solutions, A Red Hat Company.
  4. This file is part of GDB.
  5. This program is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation; either version 3 of the License, or
  8. (at your option) any later version.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with this program. If not, see <http://www.gnu.org/licenses/>. */
  15. /* Originally by Steve Chamberlain, sac@cygnus.com */
  16. #include "defs.h"
  17. #include "frame.h" /* required by inferior.h */
  18. #include "inferior.h"
  19. #include "infrun.h"
  20. #include "target.h"
  21. #include "gdbcore.h"
  22. #include "command.h"
  23. #include "completer.h"
  24. #include "regcache.h"
  25. #include "top.h"
  26. #include <signal.h>
  27. #include <sys/types.h>
  28. #include <fcntl.h>
  29. #include <windows.h>
  30. #include <imagehlp.h>
  31. #ifdef __CYGWIN__
  32. #include <wchar.h>
  33. #include <sys/cygwin.h>
  34. #include <cygwin/version.h>
  35. #endif
  36. #include <algorithm>
  37. #include <vector>
  38. #include "filenames.h"
  39. #include "symfile.h"
  40. #include "objfiles.h"
  41. #include "gdb_bfd.h"
  42. #include "gdbsupport/gdb_obstack.h"
  43. #include "gdbthread.h"
  44. #include "gdbcmd.h"
  45. #include <unistd.h>
  46. #include "exec.h"
  47. #include "solist.h"
  48. #include "solib.h"
  49. #include "xml-support.h"
  50. #include "inttypes.h"
  51. #include "i386-tdep.h"
  52. #include "i387-tdep.h"
  53. #include "windows-tdep.h"
  54. #include "windows-nat.h"
  55. #include "x86-nat.h"
  56. #include "complaints.h"
  57. #include "inf-child.h"
  58. #include "gdbsupport/gdb_tilde_expand.h"
  59. #include "gdbsupport/pathstuff.h"
  60. #include "gdbsupport/gdb_wait.h"
  61. #include "nat/windows-nat.h"
  62. #include "gdbsupport/symbol.h"
  63. using namespace windows_nat;
  64. /* The current process. */
  65. static windows_process_info windows_process;
  66. #undef STARTUPINFO
  67. #undef CreateProcess
  68. #undef GetModuleFileNameEx
  69. #ifndef __CYGWIN__
  70. # define __PMAX (MAX_PATH + 1)
  71. # define GetModuleFileNameEx GetModuleFileNameExA
  72. # define STARTUPINFO STARTUPINFOA
  73. # define CreateProcess CreateProcessA
  74. #else
  75. # define __PMAX PATH_MAX
  76. /* The starting and ending address of the cygwin1.dll text segment. */
  77. static CORE_ADDR cygwin_load_start;
  78. static CORE_ADDR cygwin_load_end;
  79. # define __USEWIDE
  80. typedef wchar_t cygwin_buf_t;
  81. # define GetModuleFileNameEx GetModuleFileNameExW
  82. # define STARTUPINFO STARTUPINFOW
  83. # define CreateProcess CreateProcessW
  84. #endif
  85. static int have_saved_context; /* True if we've saved context from a
  86. cygwin signal. */
  87. #ifdef __CYGWIN__
  88. static CONTEXT saved_context; /* Contains the saved context from a
  89. cygwin signal. */
  90. #endif
  91. /* If we're not using the old Cygwin header file set, define the
  92. following which never should have been in the generic Win32 API
  93. headers in the first place since they were our own invention... */
  94. #ifndef _GNU_H_WINDOWS_H
  95. enum
  96. {
  97. FLAG_TRACE_BIT = 0x100,
  98. };
  99. #endif
  100. #ifndef CONTEXT_EXTENDED_REGISTERS
  101. /* This macro is only defined on ia32. It only makes sense on this target,
  102. so define it as zero if not already defined. */
  103. #define CONTEXT_EXTENDED_REGISTERS 0
  104. #endif
  105. #define CONTEXT_DEBUGGER_DR CONTEXT_FULL | CONTEXT_FLOATING_POINT \
  106. | CONTEXT_SEGMENTS | CONTEXT_DEBUG_REGISTERS \
  107. | CONTEXT_EXTENDED_REGISTERS
  108. static uintptr_t dr[8];
  109. static int windows_initialization_done;
  110. #define DR6_CLEAR_VALUE 0xffff0ff0
  111. /* The string sent by cygwin when it processes a signal.
  112. FIXME: This should be in a cygwin include file. */
  113. #ifndef _CYGWIN_SIGNAL_STRING
  114. #define _CYGWIN_SIGNAL_STRING "cYgSiGw00f"
  115. #endif
  116. #define CHECK(x) check (x, __FILE__,__LINE__)
  117. #define DEBUG_EXEC(fmt, ...) \
  118. debug_prefixed_printf_cond (debug_exec, "windows exec", fmt, ## __VA_ARGS__)
  119. #define DEBUG_EVENTS(fmt, ...) \
  120. debug_prefixed_printf_cond (debug_events, "windows events", fmt, \
  121. ## __VA_ARGS__)
  122. #define DEBUG_MEM(fmt, ...) \
  123. debug_prefixed_printf_cond (debug_memory, "windows mem", fmt, \
  124. ## __VA_ARGS__)
  125. #define DEBUG_EXCEPT(fmt, ...) \
  126. debug_prefixed_printf_cond (debug_exceptions, "windows except", fmt, \
  127. ## __VA_ARGS__)
  128. static void cygwin_set_dr (int i, CORE_ADDR addr);
  129. static void cygwin_set_dr7 (unsigned long val);
  130. static CORE_ADDR cygwin_get_dr (int i);
  131. static unsigned long cygwin_get_dr6 (void);
  132. static unsigned long cygwin_get_dr7 (void);
  133. static std::vector<std::unique_ptr<windows_thread_info>> thread_list;
  134. /* Counts of things. */
  135. static int saw_create;
  136. static int open_process_used = 0;
  137. #ifdef __x86_64__
  138. static void *wow64_dbgbreak;
  139. #endif
  140. /* User options. */
  141. static bool new_console = false;
  142. #ifdef __CYGWIN__
  143. static bool cygwin_exceptions = false;
  144. #endif
  145. static bool new_group = true;
  146. static bool debug_exec = false; /* show execution */
  147. static bool debug_events = false; /* show events from kernel */
  148. static bool debug_memory = false; /* show target memory accesses */
  149. static bool debug_exceptions = false; /* show target exceptions */
  150. static bool useshell = false; /* use shell for subprocesses */
  151. /* This vector maps GDB's idea of a register's number into an offset
  152. in the windows exception context vector.
  153. It also contains the bit mask needed to load the register in question.
  154. The contents of this table can only be computed by the units
  155. that provide CPU-specific support for Windows native debugging.
  156. These units should set the table by calling
  157. windows_set_context_register_offsets.
  158. One day we could read a reg, we could inspect the context we
  159. already have loaded, if it doesn't have the bit set that we need,
  160. we read that set of registers in using GetThreadContext. If the
  161. context already contains what we need, we just unpack it. Then to
  162. write a register, first we have to ensure that the context contains
  163. the other regs of the group, and then we copy the info in and set
  164. out bit. */
  165. static const int *mappings;
  166. /* The function to use in order to determine whether a register is
  167. a segment register or not. */
  168. static segment_register_p_ftype *segment_register_p;
  169. /* See windows_nat_target::resume to understand why this is commented
  170. out. */
  171. #if 0
  172. /* This vector maps the target's idea of an exception (extracted
  173. from the DEBUG_EVENT structure) to GDB's idea. */
  174. struct xlate_exception
  175. {
  176. DWORD them;
  177. enum gdb_signal us;
  178. };
  179. static const struct xlate_exception xlate[] =
  180. {
  181. {EXCEPTION_ACCESS_VIOLATION, GDB_SIGNAL_SEGV},
  182. {STATUS_STACK_OVERFLOW, GDB_SIGNAL_SEGV},
  183. {EXCEPTION_BREAKPOINT, GDB_SIGNAL_TRAP},
  184. {DBG_CONTROL_C, GDB_SIGNAL_INT},
  185. {EXCEPTION_SINGLE_STEP, GDB_SIGNAL_TRAP},
  186. {STATUS_FLOAT_DIVIDE_BY_ZERO, GDB_SIGNAL_FPE}
  187. };
  188. #endif /* 0 */
  189. struct windows_nat_target final : public x86_nat_target<inf_child_target>
  190. {
  191. void close () override;
  192. void attach (const char *, int) override;
  193. bool attach_no_wait () override
  194. { return true; }
  195. void detach (inferior *, int) override;
  196. void resume (ptid_t, int , enum gdb_signal) override;
  197. ptid_t wait (ptid_t, struct target_waitstatus *, target_wait_flags) override;
  198. void fetch_registers (struct regcache *, int) override;
  199. void store_registers (struct regcache *, int) override;
  200. bool stopped_by_sw_breakpoint () override
  201. {
  202. windows_thread_info *th
  203. = windows_process.thread_rec (inferior_ptid, DONT_INVALIDATE_CONTEXT);
  204. return th->stopped_at_software_breakpoint;
  205. }
  206. bool supports_stopped_by_sw_breakpoint () override
  207. {
  208. return true;
  209. }
  210. enum target_xfer_status xfer_partial (enum target_object object,
  211. const char *annex,
  212. gdb_byte *readbuf,
  213. const gdb_byte *writebuf,
  214. ULONGEST offset, ULONGEST len,
  215. ULONGEST *xfered_len) override;
  216. void files_info () override;
  217. void kill () override;
  218. void create_inferior (const char *, const std::string &,
  219. char **, int) override;
  220. void mourn_inferior () override;
  221. bool thread_alive (ptid_t ptid) override;
  222. std::string pid_to_str (ptid_t) override;
  223. void interrupt () override;
  224. char *pid_to_exec_file (int pid) override;
  225. ptid_t get_ada_task_ptid (long lwp, ULONGEST thread) override;
  226. bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
  227. const char *thread_name (struct thread_info *) override;
  228. int get_windows_debug_event (int pid, struct target_waitstatus *ourstatus);
  229. void do_initial_windows_stuff (DWORD pid, bool attaching);
  230. };
  231. static windows_nat_target the_windows_nat_target;
  232. /* Set the MAPPINGS static global to OFFSETS.
  233. See the description of MAPPINGS for more details. */
  234. static void
  235. windows_set_context_register_offsets (const int *offsets)
  236. {
  237. mappings = offsets;
  238. }
  239. /* Set the function that should be used by this module to determine
  240. whether a given register is a segment register or not. */
  241. static void
  242. windows_set_segment_register_p (segment_register_p_ftype *fun)
  243. {
  244. segment_register_p = fun;
  245. }
  246. static void
  247. check (BOOL ok, const char *file, int line)
  248. {
  249. if (!ok)
  250. gdb_printf ("error return %s:%d was %u\n", file, line,
  251. (unsigned) GetLastError ());
  252. }
  253. /* See nat/windows-nat.h. */
  254. windows_thread_info *
  255. windows_nat::windows_process_info::thread_rec
  256. (ptid_t ptid, thread_disposition_type disposition)
  257. {
  258. for (auto &th : thread_list)
  259. if (th->tid == ptid.lwp ())
  260. {
  261. if (!th->suspended)
  262. {
  263. switch (disposition)
  264. {
  265. case DONT_INVALIDATE_CONTEXT:
  266. /* Nothing. */
  267. break;
  268. case INVALIDATE_CONTEXT:
  269. if (ptid.lwp () != current_event.dwThreadId)
  270. th->suspend ();
  271. th->reload_context = true;
  272. break;
  273. case DONT_SUSPEND:
  274. th->reload_context = true;
  275. th->suspended = -1;
  276. break;
  277. }
  278. }
  279. return th.get ();
  280. }
  281. return NULL;
  282. }
  283. /* Add a thread to the thread list.
  284. PTID is the ptid of the thread to be added.
  285. H is its Windows handle.
  286. TLB is its thread local base.
  287. MAIN_THREAD_P should be true if the thread to be added is
  288. the main thread, false otherwise. */
  289. static windows_thread_info *
  290. windows_add_thread (ptid_t ptid, HANDLE h, void *tlb, bool main_thread_p)
  291. {
  292. windows_thread_info *th;
  293. gdb_assert (ptid.lwp () != 0);
  294. if ((th = windows_process.thread_rec (ptid, DONT_INVALIDATE_CONTEXT)))
  295. return th;
  296. CORE_ADDR base = (CORE_ADDR) (uintptr_t) tlb;
  297. #ifdef __x86_64__
  298. /* For WOW64 processes, this is actually the pointer to the 64bit TIB,
  299. and the 32bit TIB is exactly 2 pages after it. */
  300. if (windows_process.wow64_process)
  301. base += 0x2000;
  302. #endif
  303. th = new windows_thread_info (ptid.lwp (), h, base);
  304. thread_list.emplace_back (th);
  305. /* Add this new thread to the list of threads.
  306. To be consistent with what's done on other platforms, we add
  307. the main thread silently (in reality, this thread is really
  308. more of a process to the user than a thread). */
  309. if (main_thread_p)
  310. add_thread_silent (&the_windows_nat_target, ptid);
  311. else
  312. add_thread (&the_windows_nat_target, ptid);
  313. /* It's simplest to always set this and update the debug
  314. registers. */
  315. th->debug_registers_changed = true;
  316. return th;
  317. }
  318. /* Clear out any old thread list and reinitialize it to a
  319. pristine state. */
  320. static void
  321. windows_init_thread_list (void)
  322. {
  323. DEBUG_EVENTS ("called");
  324. thread_list.clear ();
  325. }
  326. /* Delete a thread from the list of threads.
  327. PTID is the ptid of the thread to be deleted.
  328. EXIT_CODE is the thread's exit code.
  329. MAIN_THREAD_P should be true if the thread to be deleted is
  330. the main thread, false otherwise. */
  331. static void
  332. windows_delete_thread (ptid_t ptid, DWORD exit_code, bool main_thread_p)
  333. {
  334. DWORD id;
  335. gdb_assert (ptid.lwp () != 0);
  336. id = ptid.lwp ();
  337. /* Emit a notification about the thread being deleted.
  338. Note that no notification was printed when the main thread
  339. was created, and thus, unless in verbose mode, we should be
  340. symmetrical, and avoid that notification for the main thread
  341. here as well. */
  342. if (info_verbose)
  343. gdb_printf ("[Deleting %s]\n", target_pid_to_str (ptid).c_str ());
  344. else if (print_thread_events && !main_thread_p)
  345. gdb_printf (_("[%s exited with code %u]\n"),
  346. target_pid_to_str (ptid).c_str (),
  347. (unsigned) exit_code);
  348. delete_thread (find_thread_ptid (&the_windows_nat_target, ptid));
  349. auto iter = std::find_if (thread_list.begin (), thread_list.end (),
  350. [=] (auto &th)
  351. {
  352. return th->tid == id;
  353. });
  354. if (iter != thread_list.end ())
  355. thread_list.erase (iter);
  356. }
  357. /* Fetches register number R from the given windows_thread_info,
  358. and supplies its value to the given regcache.
  359. This function assumes that R is non-negative. A failed assertion
  360. is raised if that is not true.
  361. This function assumes that TH->RELOAD_CONTEXT is not set, meaning
  362. that the windows_thread_info has an up-to-date context. A failed
  363. assertion is raised if that assumption is violated. */
  364. static void
  365. windows_fetch_one_register (struct regcache *regcache,
  366. windows_thread_info *th, int r)
  367. {
  368. gdb_assert (r >= 0);
  369. gdb_assert (!th->reload_context);
  370. char *context_ptr = (char *) &th->context;
  371. #ifdef __x86_64__
  372. if (windows_process.wow64_process)
  373. context_ptr = (char *) &th->wow64_context;
  374. #endif
  375. char *context_offset = context_ptr + mappings[r];
  376. struct gdbarch *gdbarch = regcache->arch ();
  377. i386_gdbarch_tdep *tdep = (i386_gdbarch_tdep *) gdbarch_tdep (gdbarch);
  378. gdb_assert (!gdbarch_read_pc_p (gdbarch));
  379. gdb_assert (gdbarch_pc_regnum (gdbarch) >= 0);
  380. gdb_assert (!gdbarch_write_pc_p (gdbarch));
  381. if (r == I387_FISEG_REGNUM (tdep))
  382. {
  383. long l = *((long *) context_offset) & 0xffff;
  384. regcache->raw_supply (r, (char *) &l);
  385. }
  386. else if (r == I387_FOP_REGNUM (tdep))
  387. {
  388. long l = (*((long *) context_offset) >> 16) & ((1 << 11) - 1);
  389. regcache->raw_supply (r, (char *) &l);
  390. }
  391. else if (segment_register_p (r))
  392. {
  393. /* GDB treats segment registers as 32bit registers, but they are
  394. in fact only 16 bits long. Make sure we do not read extra
  395. bits from our source buffer. */
  396. long l = *((long *) context_offset) & 0xffff;
  397. regcache->raw_supply (r, (char *) &l);
  398. }
  399. else
  400. {
  401. if (th->stopped_at_software_breakpoint
  402. && !th->pc_adjusted
  403. && r == gdbarch_pc_regnum (gdbarch))
  404. {
  405. int size = register_size (gdbarch, r);
  406. if (size == 4)
  407. {
  408. uint32_t value;
  409. memcpy (&value, context_offset, size);
  410. value -= gdbarch_decr_pc_after_break (gdbarch);
  411. memcpy (context_offset, &value, size);
  412. }
  413. else
  414. {
  415. gdb_assert (size == 8);
  416. uint64_t value;
  417. memcpy (&value, context_offset, size);
  418. value -= gdbarch_decr_pc_after_break (gdbarch);
  419. memcpy (context_offset, &value, size);
  420. }
  421. /* Make sure we only rewrite the PC a single time. */
  422. th->pc_adjusted = true;
  423. }
  424. regcache->raw_supply (r, context_offset);
  425. }
  426. }
  427. void
  428. windows_nat_target::fetch_registers (struct regcache *regcache, int r)
  429. {
  430. windows_thread_info *th
  431. = windows_process.thread_rec (regcache->ptid (), INVALIDATE_CONTEXT);
  432. /* Check if TH exists. Windows sometimes uses a non-existent
  433. thread id in its events. */
  434. if (th == NULL)
  435. return;
  436. if (th->reload_context)
  437. {
  438. #ifdef __CYGWIN__
  439. if (have_saved_context)
  440. {
  441. /* Lie about where the program actually is stopped since
  442. cygwin has informed us that we should consider the signal
  443. to have occurred at another location which is stored in
  444. "saved_context. */
  445. memcpy (&th->context, &saved_context,
  446. __COPY_CONTEXT_SIZE);
  447. have_saved_context = 0;
  448. }
  449. else
  450. #endif
  451. #ifdef __x86_64__
  452. if (windows_process.wow64_process)
  453. {
  454. th->wow64_context.ContextFlags = CONTEXT_DEBUGGER_DR;
  455. CHECK (Wow64GetThreadContext (th->h, &th->wow64_context));
  456. /* Copy dr values from that thread.
  457. But only if there were not modified since last stop.
  458. PR gdb/2388 */
  459. if (!th->debug_registers_changed)
  460. {
  461. dr[0] = th->wow64_context.Dr0;
  462. dr[1] = th->wow64_context.Dr1;
  463. dr[2] = th->wow64_context.Dr2;
  464. dr[3] = th->wow64_context.Dr3;
  465. dr[6] = th->wow64_context.Dr6;
  466. dr[7] = th->wow64_context.Dr7;
  467. }
  468. }
  469. else
  470. #endif
  471. {
  472. th->context.ContextFlags = CONTEXT_DEBUGGER_DR;
  473. CHECK (GetThreadContext (th->h, &th->context));
  474. /* Copy dr values from that thread.
  475. But only if there were not modified since last stop.
  476. PR gdb/2388 */
  477. if (!th->debug_registers_changed)
  478. {
  479. dr[0] = th->context.Dr0;
  480. dr[1] = th->context.Dr1;
  481. dr[2] = th->context.Dr2;
  482. dr[3] = th->context.Dr3;
  483. dr[6] = th->context.Dr6;
  484. dr[7] = th->context.Dr7;
  485. }
  486. }
  487. th->reload_context = false;
  488. }
  489. if (r < 0)
  490. for (r = 0; r < gdbarch_num_regs (regcache->arch()); r++)
  491. windows_fetch_one_register (regcache, th, r);
  492. else
  493. windows_fetch_one_register (regcache, th, r);
  494. }
  495. /* Collect the register number R from the given regcache, and store
  496. its value into the corresponding area of the given thread's context.
  497. This function assumes that R is non-negative. A failed assertion
  498. assertion is raised if that is not true. */
  499. static void
  500. windows_store_one_register (const struct regcache *regcache,
  501. windows_thread_info *th, int r)
  502. {
  503. gdb_assert (r >= 0);
  504. char *context_ptr = (char *) &th->context;
  505. #ifdef __x86_64__
  506. if (windows_process.wow64_process)
  507. context_ptr = (char *) &th->wow64_context;
  508. #endif
  509. regcache->raw_collect (r, context_ptr + mappings[r]);
  510. }
  511. /* Store a new register value into the context of the thread tied to
  512. REGCACHE. */
  513. void
  514. windows_nat_target::store_registers (struct regcache *regcache, int r)
  515. {
  516. windows_thread_info *th
  517. = windows_process.thread_rec (regcache->ptid (), INVALIDATE_CONTEXT);
  518. /* Check if TH exists. Windows sometimes uses a non-existent
  519. thread id in its events. */
  520. if (th == NULL)
  521. return;
  522. if (r < 0)
  523. for (r = 0; r < gdbarch_num_regs (regcache->arch ()); r++)
  524. windows_store_one_register (regcache, th, r);
  525. else
  526. windows_store_one_register (regcache, th, r);
  527. }
  528. /* Maintain a linked list of "so" information. */
  529. struct windows_solib
  530. {
  531. LPVOID load_addr = 0;
  532. CORE_ADDR text_offset = 0;
  533. /* Original name. */
  534. std::string original_name;
  535. /* Expanded form of the name. */
  536. std::string name;
  537. };
  538. static std::vector<windows_solib> solibs;
  539. /* See nat/windows-nat.h. */
  540. static windows_solib *
  541. windows_make_so (const char *name, LPVOID load_addr)
  542. {
  543. char *p;
  544. #ifndef __CYGWIN__
  545. char buf[__PMAX];
  546. char cwd[__PMAX];
  547. WIN32_FIND_DATA w32_fd;
  548. HANDLE h = FindFirstFile(name, &w32_fd);
  549. if (h == INVALID_HANDLE_VALUE)
  550. strcpy (buf, name);
  551. else
  552. {
  553. FindClose (h);
  554. strcpy (buf, name);
  555. if (GetCurrentDirectory (MAX_PATH + 1, cwd))
  556. {
  557. p = strrchr (buf, '\\');
  558. if (p)
  559. p[1] = '\0';
  560. SetCurrentDirectory (buf);
  561. GetFullPathName (w32_fd.cFileName, MAX_PATH, buf, &p);
  562. SetCurrentDirectory (cwd);
  563. }
  564. }
  565. if (strcasecmp (buf, "ntdll.dll") == 0)
  566. {
  567. GetSystemDirectory (buf, sizeof (buf));
  568. strcat (buf, "\\ntdll.dll");
  569. }
  570. #else
  571. cygwin_buf_t buf[__PMAX];
  572. buf[0] = 0;
  573. if (access (name, F_OK) != 0)
  574. {
  575. if (strcasecmp (name, "ntdll.dll") == 0)
  576. #ifdef __USEWIDE
  577. {
  578. GetSystemDirectoryW (buf, sizeof (buf) / sizeof (wchar_t));
  579. wcscat (buf, L"\\ntdll.dll");
  580. }
  581. #else
  582. {
  583. GetSystemDirectoryA (buf, sizeof (buf) / sizeof (wchar_t));
  584. strcat (buf, "\\ntdll.dll");
  585. }
  586. #endif
  587. }
  588. #endif
  589. solibs.emplace_back ();
  590. windows_solib *so = &solibs.back ();
  591. so->load_addr = load_addr;
  592. so->original_name = name;
  593. #ifndef __CYGWIN__
  594. so->name = buf;
  595. #else
  596. if (buf[0])
  597. {
  598. char name[SO_NAME_MAX_PATH_SIZE];
  599. cygwin_conv_path (CCP_WIN_W_TO_POSIX, buf, name,
  600. SO_NAME_MAX_PATH_SIZE);
  601. so->name = name;
  602. }
  603. else
  604. {
  605. char *rname = realpath (name, NULL);
  606. if (rname && strlen (rname) < SO_NAME_MAX_PATH_SIZE)
  607. {
  608. so->name = rname;
  609. free (rname);
  610. }
  611. else
  612. {
  613. warning (_("dll path for \"%s\" too long or inaccessible"), name);
  614. so->name = so->original_name;
  615. }
  616. }
  617. /* Record cygwin1.dll .text start/end. */
  618. size_t len = sizeof ("/cygwin1.dll") - 1;
  619. if (so->name.size () >= len
  620. && strcasecmp (so->name.c_str () + so->name.size () - len,
  621. "/cygwin1.dll") == 0)
  622. {
  623. asection *text = NULL;
  624. gdb_bfd_ref_ptr abfd (gdb_bfd_open (so->name, "pei-i386"));
  625. if (abfd == NULL)
  626. return so;
  627. if (bfd_check_format (abfd.get (), bfd_object))
  628. text = bfd_get_section_by_name (abfd.get (), ".text");
  629. if (!text)
  630. return so;
  631. /* The symbols in a dll are offset by 0x1000, which is the
  632. offset from 0 of the first byte in an image - because of the
  633. file header and the section alignment. */
  634. cygwin_load_start = (CORE_ADDR) (uintptr_t) ((char *)
  635. load_addr + 0x1000);
  636. cygwin_load_end = cygwin_load_start + bfd_section_size (text);
  637. }
  638. #endif
  639. return so;
  640. }
  641. /* See nat/windows-nat.h. */
  642. void
  643. windows_nat::windows_process_info::handle_load_dll (const char *dll_name,
  644. LPVOID base)
  645. {
  646. windows_solib *solib = windows_make_so (dll_name, base);
  647. DEBUG_EVENTS ("Loading dll \"%s\" at %s.", solib->name.c_str (),
  648. host_address_to_string (solib->load_addr));
  649. }
  650. /* See nat/windows-nat.h. */
  651. void
  652. windows_nat::windows_process_info::handle_unload_dll ()
  653. {
  654. LPVOID lpBaseOfDll = current_event.u.UnloadDll.lpBaseOfDll;
  655. auto iter = std::remove_if (solibs.begin (), solibs.end (),
  656. [&] (windows_solib &lib)
  657. {
  658. if (lib.load_addr == lpBaseOfDll)
  659. {
  660. DEBUG_EVENTS ("Unloading dll \"%s\".", lib.name.c_str ());
  661. return true;
  662. }
  663. return false;
  664. });
  665. if (iter != solibs.end ())
  666. {
  667. solibs.erase (iter, solibs.end ());
  668. return;
  669. }
  670. /* We did not find any DLL that was previously loaded at this address,
  671. so register a complaint. We do not report an error, because we have
  672. observed that this may be happening under some circumstances. For
  673. instance, running 32bit applications on x64 Windows causes us to receive
  674. 4 mysterious UNLOAD_DLL_DEBUG_EVENTs during the startup phase (these
  675. events are apparently caused by the WOW layer, the interface between
  676. 32bit and 64bit worlds). */
  677. complaint (_("dll starting at %s not found."),
  678. host_address_to_string (lpBaseOfDll));
  679. }
  680. /* Clear list of loaded DLLs. */
  681. static void
  682. windows_clear_solib (void)
  683. {
  684. solibs.clear ();
  685. }
  686. static void
  687. signal_event_command (const char *args, int from_tty)
  688. {
  689. uintptr_t event_id = 0;
  690. char *endargs = NULL;
  691. if (args == NULL)
  692. error (_("signal-event requires an argument (integer event id)"));
  693. event_id = strtoumax (args, &endargs, 10);
  694. if ((errno == ERANGE) || (event_id == 0) || (event_id > UINTPTR_MAX) ||
  695. ((HANDLE) event_id == INVALID_HANDLE_VALUE))
  696. error (_("Failed to convert `%s' to event id"), args);
  697. SetEvent ((HANDLE) event_id);
  698. CloseHandle ((HANDLE) event_id);
  699. }
  700. /* See nat/windows-nat.h. */
  701. int
  702. windows_nat::windows_process_info::handle_output_debug_string
  703. (struct target_waitstatus *ourstatus)
  704. {
  705. int retval = 0;
  706. gdb::unique_xmalloc_ptr<char> s
  707. = (target_read_string
  708. ((CORE_ADDR) (uintptr_t) current_event.u.DebugString.lpDebugStringData,
  709. 1024));
  710. if (s == nullptr || !*(s.get ()))
  711. /* nothing to do */;
  712. else if (!startswith (s.get (), _CYGWIN_SIGNAL_STRING))
  713. {
  714. #ifdef __CYGWIN__
  715. if (!startswith (s.get (), "cYg"))
  716. #endif
  717. {
  718. char *p = strchr (s.get (), '\0');
  719. if (p > s.get () && *--p == '\n')
  720. *p = '\0';
  721. warning (("%s"), s.get ());
  722. }
  723. }
  724. #ifdef __CYGWIN__
  725. else
  726. {
  727. /* Got a cygwin signal marker. A cygwin signal is followed by
  728. the signal number itself and then optionally followed by the
  729. thread id and address to saved context within the DLL. If
  730. these are supplied, then the given thread is assumed to have
  731. issued the signal and the context from the thread is assumed
  732. to be stored at the given address in the inferior. Tell gdb
  733. to treat this like a real signal. */
  734. char *p;
  735. int sig = strtol (s.get () + sizeof (_CYGWIN_SIGNAL_STRING) - 1, &p, 0);
  736. gdb_signal gotasig = gdb_signal_from_host (sig);
  737. if (gotasig)
  738. {
  739. LPCVOID x;
  740. SIZE_T n;
  741. ourstatus->set_stopped (gotasig);
  742. retval = strtoul (p, &p, 0);
  743. if (!retval)
  744. retval = current_event.dwThreadId;
  745. else if ((x = (LPCVOID) (uintptr_t) strtoull (p, NULL, 0))
  746. && ReadProcessMemory (current_process_handle, x,
  747. &saved_context,
  748. __COPY_CONTEXT_SIZE, &n)
  749. && n == __COPY_CONTEXT_SIZE)
  750. have_saved_context = 1;
  751. }
  752. }
  753. #endif
  754. return retval;
  755. }
  756. static int
  757. display_selector (HANDLE thread, DWORD sel)
  758. {
  759. LDT_ENTRY info;
  760. BOOL ret;
  761. #ifdef __x86_64__
  762. if (windows_process.wow64_process)
  763. ret = Wow64GetThreadSelectorEntry (thread, sel, &info);
  764. else
  765. #endif
  766. ret = GetThreadSelectorEntry (thread, sel, &info);
  767. if (ret)
  768. {
  769. int base, limit;
  770. gdb_printf ("0x%03x: ", (unsigned) sel);
  771. if (!info.HighWord.Bits.Pres)
  772. {
  773. gdb_puts ("Segment not present\n");
  774. return 0;
  775. }
  776. base = (info.HighWord.Bits.BaseHi << 24) +
  777. (info.HighWord.Bits.BaseMid << 16)
  778. + info.BaseLow;
  779. limit = (info.HighWord.Bits.LimitHi << 16) + info.LimitLow;
  780. if (info.HighWord.Bits.Granularity)
  781. limit = (limit << 12) | 0xfff;
  782. gdb_printf ("base=0x%08x limit=0x%08x", base, limit);
  783. if (info.HighWord.Bits.Default_Big)
  784. gdb_puts(" 32-bit ");
  785. else
  786. gdb_puts(" 16-bit ");
  787. switch ((info.HighWord.Bits.Type & 0xf) >> 1)
  788. {
  789. case 0:
  790. gdb_puts ("Data (Read-Only, Exp-up");
  791. break;
  792. case 1:
  793. gdb_puts ("Data (Read/Write, Exp-up");
  794. break;
  795. case 2:
  796. gdb_puts ("Unused segment (");
  797. break;
  798. case 3:
  799. gdb_puts ("Data (Read/Write, Exp-down");
  800. break;
  801. case 4:
  802. gdb_puts ("Code (Exec-Only, N.Conf");
  803. break;
  804. case 5:
  805. gdb_puts ("Code (Exec/Read, N.Conf");
  806. break;
  807. case 6:
  808. gdb_puts ("Code (Exec-Only, Conf");
  809. break;
  810. case 7:
  811. gdb_puts ("Code (Exec/Read, Conf");
  812. break;
  813. default:
  814. gdb_printf ("Unknown type 0x%lx",
  815. (unsigned long) info.HighWord.Bits.Type);
  816. }
  817. if ((info.HighWord.Bits.Type & 0x1) == 0)
  818. gdb_puts(", N.Acc");
  819. gdb_puts (")\n");
  820. if ((info.HighWord.Bits.Type & 0x10) == 0)
  821. gdb_puts("System selector ");
  822. gdb_printf ("Priviledge level = %ld. ",
  823. (unsigned long) info.HighWord.Bits.Dpl);
  824. if (info.HighWord.Bits.Granularity)
  825. gdb_puts ("Page granular.\n");
  826. else
  827. gdb_puts ("Byte granular.\n");
  828. return 1;
  829. }
  830. else
  831. {
  832. DWORD err = GetLastError ();
  833. if (err == ERROR_NOT_SUPPORTED)
  834. gdb_printf ("Function not supported\n");
  835. else
  836. gdb_printf ("Invalid selector 0x%x.\n", (unsigned) sel);
  837. return 0;
  838. }
  839. }
  840. static void
  841. display_selectors (const char * args, int from_tty)
  842. {
  843. if (inferior_ptid == null_ptid)
  844. {
  845. gdb_puts ("Impossible to display selectors now.\n");
  846. return;
  847. }
  848. windows_thread_info *current_windows_thread
  849. = windows_process.thread_rec (inferior_ptid, DONT_INVALIDATE_CONTEXT);
  850. if (!args)
  851. {
  852. #ifdef __x86_64__
  853. if (windows_process.wow64_process)
  854. {
  855. gdb_puts ("Selector $cs\n");
  856. display_selector (current_windows_thread->h,
  857. current_windows_thread->wow64_context.SegCs);
  858. gdb_puts ("Selector $ds\n");
  859. display_selector (current_windows_thread->h,
  860. current_windows_thread->wow64_context.SegDs);
  861. gdb_puts ("Selector $es\n");
  862. display_selector (current_windows_thread->h,
  863. current_windows_thread->wow64_context.SegEs);
  864. gdb_puts ("Selector $ss\n");
  865. display_selector (current_windows_thread->h,
  866. current_windows_thread->wow64_context.SegSs);
  867. gdb_puts ("Selector $fs\n");
  868. display_selector (current_windows_thread->h,
  869. current_windows_thread->wow64_context.SegFs);
  870. gdb_puts ("Selector $gs\n");
  871. display_selector (current_windows_thread->h,
  872. current_windows_thread->wow64_context.SegGs);
  873. }
  874. else
  875. #endif
  876. {
  877. gdb_puts ("Selector $cs\n");
  878. display_selector (current_windows_thread->h,
  879. current_windows_thread->context.SegCs);
  880. gdb_puts ("Selector $ds\n");
  881. display_selector (current_windows_thread->h,
  882. current_windows_thread->context.SegDs);
  883. gdb_puts ("Selector $es\n");
  884. display_selector (current_windows_thread->h,
  885. current_windows_thread->context.SegEs);
  886. gdb_puts ("Selector $ss\n");
  887. display_selector (current_windows_thread->h,
  888. current_windows_thread->context.SegSs);
  889. gdb_puts ("Selector $fs\n");
  890. display_selector (current_windows_thread->h,
  891. current_windows_thread->context.SegFs);
  892. gdb_puts ("Selector $gs\n");
  893. display_selector (current_windows_thread->h,
  894. current_windows_thread->context.SegGs);
  895. }
  896. }
  897. else
  898. {
  899. int sel;
  900. sel = parse_and_eval_long (args);
  901. gdb_printf ("Selector \"%s\"\n",args);
  902. display_selector (current_windows_thread->h, sel);
  903. }
  904. }
  905. /* See nat/windows-nat.h. */
  906. bool
  907. windows_nat::windows_process_info::handle_ms_vc_exception
  908. (const EXCEPTION_RECORD *rec)
  909. {
  910. if (rec->NumberParameters >= 3
  911. && (rec->ExceptionInformation[0] & 0xffffffff) == 0x1000)
  912. {
  913. DWORD named_thread_id;
  914. windows_thread_info *named_thread;
  915. CORE_ADDR thread_name_target;
  916. thread_name_target = rec->ExceptionInformation[1];
  917. named_thread_id = (DWORD) (0xffffffff & rec->ExceptionInformation[2]);
  918. if (named_thread_id == (DWORD) -1)
  919. named_thread_id = current_event.dwThreadId;
  920. named_thread = thread_rec (ptid_t (current_event.dwProcessId,
  921. named_thread_id, 0),
  922. DONT_INVALIDATE_CONTEXT);
  923. if (named_thread != NULL)
  924. {
  925. int thread_name_len;
  926. gdb::unique_xmalloc_ptr<char> thread_name
  927. = target_read_string (thread_name_target, 1025, &thread_name_len);
  928. if (thread_name_len > 0)
  929. {
  930. thread_name.get ()[thread_name_len - 1] = '\0';
  931. named_thread->name = std::move (thread_name);
  932. }
  933. }
  934. return true;
  935. }
  936. return false;
  937. }
  938. /* See nat/windows-nat.h. */
  939. bool
  940. windows_nat::windows_process_info::handle_access_violation
  941. (const EXCEPTION_RECORD *rec)
  942. {
  943. #ifdef __CYGWIN__
  944. /* See if the access violation happened within the cygwin DLL
  945. itself. Cygwin uses a kind of exception handling to deal with
  946. passed-in invalid addresses. gdb should not treat these as real
  947. SEGVs since they will be silently handled by cygwin. A real SEGV
  948. will (theoretically) be caught by cygwin later in the process and
  949. will be sent as a cygwin-specific-signal. So, ignore SEGVs if
  950. they show up within the text segment of the DLL itself. */
  951. const char *fn;
  952. CORE_ADDR addr = (CORE_ADDR) (uintptr_t) rec->ExceptionAddress;
  953. if ((!cygwin_exceptions && (addr >= cygwin_load_start
  954. && addr < cygwin_load_end))
  955. || (find_pc_partial_function (addr, &fn, NULL, NULL)
  956. && startswith (fn, "KERNEL32!IsBad")))
  957. return true;
  958. #endif
  959. return false;
  960. }
  961. /* Resume thread specified by ID, or all artificially suspended
  962. threads, if we are continuing execution. KILLED non-zero means we
  963. have killed the inferior, so we should ignore weird errors due to
  964. threads shutting down. */
  965. static BOOL
  966. windows_continue (DWORD continue_status, int id, int killed)
  967. {
  968. BOOL res;
  969. windows_process.desired_stop_thread_id = id;
  970. if (windows_process.matching_pending_stop (debug_events))
  971. return TRUE;
  972. for (auto &th : thread_list)
  973. if (id == -1 || id == (int) th->tid)
  974. {
  975. #ifdef __x86_64__
  976. if (windows_process.wow64_process)
  977. {
  978. if (th->debug_registers_changed)
  979. {
  980. th->wow64_context.ContextFlags |= CONTEXT_DEBUG_REGISTERS;
  981. th->wow64_context.Dr0 = dr[0];
  982. th->wow64_context.Dr1 = dr[1];
  983. th->wow64_context.Dr2 = dr[2];
  984. th->wow64_context.Dr3 = dr[3];
  985. th->wow64_context.Dr6 = DR6_CLEAR_VALUE;
  986. th->wow64_context.Dr7 = dr[7];
  987. th->debug_registers_changed = false;
  988. }
  989. if (th->wow64_context.ContextFlags)
  990. {
  991. DWORD ec = 0;
  992. if (GetExitCodeThread (th->h, &ec)
  993. && ec == STILL_ACTIVE)
  994. {
  995. BOOL status = Wow64SetThreadContext (th->h,
  996. &th->wow64_context);
  997. if (!killed)
  998. CHECK (status);
  999. }
  1000. th->wow64_context.ContextFlags = 0;
  1001. }
  1002. }
  1003. else
  1004. #endif
  1005. {
  1006. if (th->debug_registers_changed)
  1007. {
  1008. th->context.ContextFlags |= CONTEXT_DEBUG_REGISTERS;
  1009. th->context.Dr0 = dr[0];
  1010. th->context.Dr1 = dr[1];
  1011. th->context.Dr2 = dr[2];
  1012. th->context.Dr3 = dr[3];
  1013. th->context.Dr6 = DR6_CLEAR_VALUE;
  1014. th->context.Dr7 = dr[7];
  1015. th->debug_registers_changed = false;
  1016. }
  1017. if (th->context.ContextFlags)
  1018. {
  1019. DWORD ec = 0;
  1020. if (GetExitCodeThread (th->h, &ec)
  1021. && ec == STILL_ACTIVE)
  1022. {
  1023. BOOL status = SetThreadContext (th->h, &th->context);
  1024. if (!killed)
  1025. CHECK (status);
  1026. }
  1027. th->context.ContextFlags = 0;
  1028. }
  1029. }
  1030. th->resume ();
  1031. }
  1032. else
  1033. {
  1034. /* When single-stepping a specific thread, other threads must
  1035. be suspended. */
  1036. th->suspend ();
  1037. }
  1038. res = continue_last_debug_event (continue_status, debug_events);
  1039. if (!res)
  1040. error (_("Failed to resume program execution"
  1041. " (ContinueDebugEvent failed, error %u)"),
  1042. (unsigned int) GetLastError ());
  1043. return res;
  1044. }
  1045. /* Called in pathological case where Windows fails to send a
  1046. CREATE_PROCESS_DEBUG_EVENT after an attach. */
  1047. static DWORD
  1048. fake_create_process (void)
  1049. {
  1050. windows_process.handle
  1051. = OpenProcess (PROCESS_ALL_ACCESS, FALSE,
  1052. windows_process.current_event.dwProcessId);
  1053. if (windows_process.handle != NULL)
  1054. open_process_used = 1;
  1055. else
  1056. {
  1057. error (_("OpenProcess call failed, GetLastError = %u"),
  1058. (unsigned) GetLastError ());
  1059. /* We can not debug anything in that case. */
  1060. }
  1061. windows_add_thread (ptid_t (windows_process.current_event.dwProcessId, 0,
  1062. windows_process.current_event.dwThreadId),
  1063. windows_process.current_event.u.CreateThread.hThread,
  1064. windows_process.current_event.u.CreateThread.lpThreadLocalBase,
  1065. true /* main_thread_p */);
  1066. return windows_process.current_event.dwThreadId;
  1067. }
  1068. void
  1069. windows_nat_target::resume (ptid_t ptid, int step, enum gdb_signal sig)
  1070. {
  1071. windows_thread_info *th;
  1072. DWORD continue_status = DBG_CONTINUE;
  1073. /* A specific PTID means `step only this thread id'. */
  1074. int resume_all = ptid == minus_one_ptid;
  1075. /* If we're continuing all threads, it's the current inferior that
  1076. should be handled specially. */
  1077. if (resume_all)
  1078. ptid = inferior_ptid;
  1079. if (sig != GDB_SIGNAL_0)
  1080. {
  1081. if (windows_process.current_event.dwDebugEventCode
  1082. != EXCEPTION_DEBUG_EVENT)
  1083. {
  1084. DEBUG_EXCEPT ("Cannot continue with signal %d here.", sig);
  1085. }
  1086. else if (sig == windows_process.last_sig)
  1087. continue_status = DBG_EXCEPTION_NOT_HANDLED;
  1088. else
  1089. #if 0
  1090. /* This code does not seem to work, because
  1091. the kernel does probably not consider changes in the ExceptionRecord
  1092. structure when passing the exception to the inferior.
  1093. Note that this seems possible in the exception handler itself. */
  1094. {
  1095. for (const xlate_exception &x : xlate)
  1096. if (x.us == sig)
  1097. {
  1098. current_event.u.Exception.ExceptionRecord.ExceptionCode
  1099. = x.them;
  1100. continue_status = DBG_EXCEPTION_NOT_HANDLED;
  1101. break;
  1102. }
  1103. if (continue_status == DBG_CONTINUE)
  1104. {
  1105. DEBUG_EXCEPT ("Cannot continue with signal %d.", sig);
  1106. }
  1107. }
  1108. #endif
  1109. DEBUG_EXCEPT ("Can only continue with received signal %d.",
  1110. windows_process.last_sig);
  1111. }
  1112. windows_process.last_sig = GDB_SIGNAL_0;
  1113. DEBUG_EXEC ("pid=%d, tid=0x%x, step=%d, sig=%d",
  1114. ptid.pid (), (unsigned) ptid.lwp (), step, sig);
  1115. /* Get context for currently selected thread. */
  1116. th = windows_process.thread_rec (inferior_ptid, DONT_INVALIDATE_CONTEXT);
  1117. if (th)
  1118. {
  1119. #ifdef __x86_64__
  1120. if (windows_process.wow64_process)
  1121. {
  1122. if (step)
  1123. {
  1124. /* Single step by setting t bit. */
  1125. struct regcache *regcache = get_current_regcache ();
  1126. struct gdbarch *gdbarch = regcache->arch ();
  1127. fetch_registers (regcache, gdbarch_ps_regnum (gdbarch));
  1128. th->wow64_context.EFlags |= FLAG_TRACE_BIT;
  1129. }
  1130. if (th->wow64_context.ContextFlags)
  1131. {
  1132. if (th->debug_registers_changed)
  1133. {
  1134. th->wow64_context.Dr0 = dr[0];
  1135. th->wow64_context.Dr1 = dr[1];
  1136. th->wow64_context.Dr2 = dr[2];
  1137. th->wow64_context.Dr3 = dr[3];
  1138. th->wow64_context.Dr6 = DR6_CLEAR_VALUE;
  1139. th->wow64_context.Dr7 = dr[7];
  1140. th->debug_registers_changed = false;
  1141. }
  1142. CHECK (Wow64SetThreadContext (th->h, &th->wow64_context));
  1143. th->wow64_context.ContextFlags = 0;
  1144. }
  1145. }
  1146. else
  1147. #endif
  1148. {
  1149. if (step)
  1150. {
  1151. /* Single step by setting t bit. */
  1152. struct regcache *regcache = get_current_regcache ();
  1153. struct gdbarch *gdbarch = regcache->arch ();
  1154. fetch_registers (regcache, gdbarch_ps_regnum (gdbarch));
  1155. th->context.EFlags |= FLAG_TRACE_BIT;
  1156. }
  1157. if (th->context.ContextFlags)
  1158. {
  1159. if (th->debug_registers_changed)
  1160. {
  1161. th->context.Dr0 = dr[0];
  1162. th->context.Dr1 = dr[1];
  1163. th->context.Dr2 = dr[2];
  1164. th->context.Dr3 = dr[3];
  1165. th->context.Dr6 = DR6_CLEAR_VALUE;
  1166. th->context.Dr7 = dr[7];
  1167. th->debug_registers_changed = false;
  1168. }
  1169. CHECK (SetThreadContext (th->h, &th->context));
  1170. th->context.ContextFlags = 0;
  1171. }
  1172. }
  1173. }
  1174. /* Allow continuing with the same signal that interrupted us.
  1175. Otherwise complain. */
  1176. if (resume_all)
  1177. windows_continue (continue_status, -1, 0);
  1178. else
  1179. windows_continue (continue_status, ptid.lwp (), 0);
  1180. }
  1181. /* Ctrl-C handler used when the inferior is not run in the same console. The
  1182. handler is in charge of interrupting the inferior using DebugBreakProcess.
  1183. Note that this function is not available prior to Windows XP. In this case
  1184. we emit a warning. */
  1185. static BOOL WINAPI
  1186. ctrl_c_handler (DWORD event_type)
  1187. {
  1188. const int attach_flag = current_inferior ()->attach_flag;
  1189. /* Only handle Ctrl-C and Ctrl-Break events. Ignore others. */
  1190. if (event_type != CTRL_C_EVENT && event_type != CTRL_BREAK_EVENT)
  1191. return FALSE;
  1192. /* If the inferior and the debugger share the same console, do nothing as
  1193. the inferior has also received the Ctrl-C event. */
  1194. if (!new_console && !attach_flag)
  1195. return TRUE;
  1196. #ifdef __x86_64__
  1197. if (windows_process.wow64_process)
  1198. {
  1199. /* Call DbgUiRemoteBreakin of the 32bit ntdll.dll in the target process.
  1200. DebugBreakProcess would call the one of the 64bit ntdll.dll, which
  1201. can't be correctly handled by gdb. */
  1202. if (wow64_dbgbreak == nullptr)
  1203. {
  1204. CORE_ADDR addr;
  1205. if (!find_minimal_symbol_address ("ntdll!DbgUiRemoteBreakin",
  1206. &addr, 0))
  1207. wow64_dbgbreak = (void *) addr;
  1208. }
  1209. if (wow64_dbgbreak != nullptr)
  1210. {
  1211. HANDLE thread = CreateRemoteThread (windows_process.handle, NULL,
  1212. 0, (LPTHREAD_START_ROUTINE)
  1213. wow64_dbgbreak, NULL, 0, NULL);
  1214. if (thread)
  1215. CloseHandle (thread);
  1216. }
  1217. }
  1218. else
  1219. #endif
  1220. {
  1221. if (!DebugBreakProcess (windows_process.handle))
  1222. warning (_("Could not interrupt program. "
  1223. "Press Ctrl-c in the program console."));
  1224. }
  1225. /* Return true to tell that Ctrl-C has been handled. */
  1226. return TRUE;
  1227. }
  1228. /* Get the next event from the child. Returns a non-zero thread id if the event
  1229. requires handling by WFI (or whatever). */
  1230. int
  1231. windows_nat_target::get_windows_debug_event (int pid,
  1232. struct target_waitstatus *ourstatus)
  1233. {
  1234. BOOL debug_event;
  1235. DWORD continue_status, event_code;
  1236. DWORD thread_id = 0;
  1237. /* If there is a relevant pending stop, report it now. See the
  1238. comment by the definition of "pending_stops" for details on why
  1239. this is needed. */
  1240. gdb::optional<pending_stop> stop
  1241. = windows_process.fetch_pending_stop (debug_events);
  1242. if (stop.has_value ())
  1243. {
  1244. thread_id = stop->thread_id;
  1245. *ourstatus = stop->status;
  1246. ptid_t ptid (windows_process.current_event.dwProcessId, thread_id);
  1247. windows_thread_info *th
  1248. = windows_process.thread_rec (ptid, INVALIDATE_CONTEXT);
  1249. th->reload_context = true;
  1250. return thread_id;
  1251. }
  1252. windows_process.last_sig = GDB_SIGNAL_0;
  1253. DEBUG_EVENT *current_event = &windows_process.current_event;
  1254. if (!(debug_event = wait_for_debug_event (&windows_process.current_event,
  1255. 1000)))
  1256. goto out;
  1257. continue_status = DBG_CONTINUE;
  1258. event_code = windows_process.current_event.dwDebugEventCode;
  1259. ourstatus->set_spurious ();
  1260. have_saved_context = 0;
  1261. switch (event_code)
  1262. {
  1263. case CREATE_THREAD_DEBUG_EVENT:
  1264. DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
  1265. (unsigned) current_event->dwProcessId,
  1266. (unsigned) current_event->dwThreadId,
  1267. "CREATE_THREAD_DEBUG_EVENT");
  1268. if (saw_create != 1)
  1269. {
  1270. inferior *inf = find_inferior_pid (this, current_event->dwProcessId);
  1271. if (!saw_create && inf->attach_flag)
  1272. {
  1273. /* Kludge around a Windows bug where first event is a create
  1274. thread event. Caused when attached process does not have
  1275. a main thread. */
  1276. thread_id = fake_create_process ();
  1277. if (thread_id)
  1278. saw_create++;
  1279. }
  1280. break;
  1281. }
  1282. /* Record the existence of this thread. */
  1283. thread_id = current_event->dwThreadId;
  1284. windows_add_thread
  1285. (ptid_t (current_event->dwProcessId, current_event->dwThreadId, 0),
  1286. current_event->u.CreateThread.hThread,
  1287. current_event->u.CreateThread.lpThreadLocalBase,
  1288. false /* main_thread_p */);
  1289. break;
  1290. case EXIT_THREAD_DEBUG_EVENT:
  1291. DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
  1292. (unsigned) current_event->dwProcessId,
  1293. (unsigned) current_event->dwThreadId,
  1294. "EXIT_THREAD_DEBUG_EVENT");
  1295. windows_delete_thread (ptid_t (current_event->dwProcessId,
  1296. current_event->dwThreadId, 0),
  1297. current_event->u.ExitThread.dwExitCode,
  1298. false /* main_thread_p */);
  1299. break;
  1300. case CREATE_PROCESS_DEBUG_EVENT:
  1301. DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
  1302. (unsigned) current_event->dwProcessId,
  1303. (unsigned) current_event->dwThreadId,
  1304. "CREATE_PROCESS_DEBUG_EVENT");
  1305. CloseHandle (current_event->u.CreateProcessInfo.hFile);
  1306. if (++saw_create != 1)
  1307. break;
  1308. windows_process.handle = current_event->u.CreateProcessInfo.hProcess;
  1309. /* Add the main thread. */
  1310. windows_add_thread
  1311. (ptid_t (current_event->dwProcessId,
  1312. current_event->dwThreadId, 0),
  1313. current_event->u.CreateProcessInfo.hThread,
  1314. current_event->u.CreateProcessInfo.lpThreadLocalBase,
  1315. true /* main_thread_p */);
  1316. thread_id = current_event->dwThreadId;
  1317. break;
  1318. case EXIT_PROCESS_DEBUG_EVENT:
  1319. DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
  1320. (unsigned) current_event->dwProcessId,
  1321. (unsigned) current_event->dwThreadId,
  1322. "EXIT_PROCESS_DEBUG_EVENT");
  1323. if (!windows_initialization_done)
  1324. {
  1325. target_terminal::ours ();
  1326. target_mourn_inferior (inferior_ptid);
  1327. error (_("During startup program exited with code 0x%x."),
  1328. (unsigned int) current_event->u.ExitProcess.dwExitCode);
  1329. }
  1330. else if (saw_create == 1)
  1331. {
  1332. windows_delete_thread (ptid_t (current_event->dwProcessId,
  1333. current_event->dwThreadId, 0),
  1334. 0, true /* main_thread_p */);
  1335. DWORD exit_status = current_event->u.ExitProcess.dwExitCode;
  1336. /* If the exit status looks like a fatal exception, but we
  1337. don't recognize the exception's code, make the original
  1338. exit status value available, to avoid losing
  1339. information. */
  1340. int exit_signal
  1341. = WIFSIGNALED (exit_status) ? WTERMSIG (exit_status) : -1;
  1342. if (exit_signal == -1)
  1343. ourstatus->set_exited (exit_status);
  1344. else
  1345. ourstatus->set_signalled (gdb_signal_from_host (exit_signal));
  1346. thread_id = current_event->dwThreadId;
  1347. }
  1348. break;
  1349. case LOAD_DLL_DEBUG_EVENT:
  1350. DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
  1351. (unsigned) current_event->dwProcessId,
  1352. (unsigned) current_event->dwThreadId,
  1353. "LOAD_DLL_DEBUG_EVENT");
  1354. CloseHandle (current_event->u.LoadDll.hFile);
  1355. if (saw_create != 1 || ! windows_initialization_done)
  1356. break;
  1357. try
  1358. {
  1359. windows_process.dll_loaded_event ();
  1360. }
  1361. catch (const gdb_exception &ex)
  1362. {
  1363. exception_print (gdb_stderr, ex);
  1364. }
  1365. ourstatus->set_loaded ();
  1366. thread_id = current_event->dwThreadId;
  1367. break;
  1368. case UNLOAD_DLL_DEBUG_EVENT:
  1369. DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
  1370. (unsigned) current_event->dwProcessId,
  1371. (unsigned) current_event->dwThreadId,
  1372. "UNLOAD_DLL_DEBUG_EVENT");
  1373. if (saw_create != 1 || ! windows_initialization_done)
  1374. break;
  1375. try
  1376. {
  1377. windows_process.handle_unload_dll ();
  1378. }
  1379. catch (const gdb_exception &ex)
  1380. {
  1381. exception_print (gdb_stderr, ex);
  1382. }
  1383. ourstatus->set_loaded ();
  1384. thread_id = current_event->dwThreadId;
  1385. break;
  1386. case EXCEPTION_DEBUG_EVENT:
  1387. DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
  1388. (unsigned) current_event->dwProcessId,
  1389. (unsigned) current_event->dwThreadId,
  1390. "EXCEPTION_DEBUG_EVENT");
  1391. if (saw_create != 1)
  1392. break;
  1393. switch (windows_process.handle_exception (ourstatus, debug_exceptions))
  1394. {
  1395. case HANDLE_EXCEPTION_UNHANDLED:
  1396. default:
  1397. continue_status = DBG_EXCEPTION_NOT_HANDLED;
  1398. break;
  1399. case HANDLE_EXCEPTION_HANDLED:
  1400. thread_id = current_event->dwThreadId;
  1401. break;
  1402. case HANDLE_EXCEPTION_IGNORED:
  1403. continue_status = DBG_CONTINUE;
  1404. break;
  1405. }
  1406. break;
  1407. case OUTPUT_DEBUG_STRING_EVENT: /* Message from the kernel. */
  1408. DEBUG_EVENTS ("kernel event for pid=%u tid=0x%x code=%s",
  1409. (unsigned) current_event->dwProcessId,
  1410. (unsigned) current_event->dwThreadId,
  1411. "OUTPUT_DEBUG_STRING_EVENT");
  1412. if (saw_create != 1)
  1413. break;
  1414. thread_id = windows_process.handle_output_debug_string (ourstatus);
  1415. break;
  1416. default:
  1417. if (saw_create != 1)
  1418. break;
  1419. gdb_printf ("gdb: kernel event for pid=%u tid=0x%x\n",
  1420. (unsigned) current_event->dwProcessId,
  1421. (unsigned) current_event->dwThreadId);
  1422. gdb_printf (" unknown event code %u\n",
  1423. (unsigned) current_event->dwDebugEventCode);
  1424. break;
  1425. }
  1426. if (!thread_id || saw_create != 1)
  1427. {
  1428. CHECK (windows_continue (continue_status,
  1429. windows_process.desired_stop_thread_id, 0));
  1430. }
  1431. else if (windows_process.desired_stop_thread_id != -1
  1432. && windows_process.desired_stop_thread_id != thread_id)
  1433. {
  1434. /* Pending stop. See the comment by the definition of
  1435. "pending_stops" for details on why this is needed. */
  1436. DEBUG_EVENTS ("get_windows_debug_event - "
  1437. "unexpected stop in 0x%x (expecting 0x%x)",
  1438. thread_id, windows_process.desired_stop_thread_id);
  1439. if (current_event->dwDebugEventCode == EXCEPTION_DEBUG_EVENT
  1440. && ((current_event->u.Exception.ExceptionRecord.ExceptionCode
  1441. == EXCEPTION_BREAKPOINT)
  1442. || (current_event->u.Exception.ExceptionRecord.ExceptionCode
  1443. == STATUS_WX86_BREAKPOINT))
  1444. && windows_initialization_done)
  1445. {
  1446. ptid_t ptid = ptid_t (current_event->dwProcessId, thread_id, 0);
  1447. windows_thread_info *th
  1448. = windows_process.thread_rec (ptid, INVALIDATE_CONTEXT);
  1449. th->stopped_at_software_breakpoint = true;
  1450. th->pc_adjusted = false;
  1451. }
  1452. windows_process.pending_stops.push_back
  1453. ({thread_id, *ourstatus, windows_process.current_event});
  1454. thread_id = 0;
  1455. CHECK (windows_continue (continue_status,
  1456. windows_process.desired_stop_thread_id, 0));
  1457. }
  1458. out:
  1459. return thread_id;
  1460. }
  1461. /* Wait for interesting events to occur in the target process. */
  1462. ptid_t
  1463. windows_nat_target::wait (ptid_t ptid, struct target_waitstatus *ourstatus,
  1464. target_wait_flags options)
  1465. {
  1466. int pid = -1;
  1467. /* We loop when we get a non-standard exception rather than return
  1468. with a SPURIOUS because resume can try and step or modify things,
  1469. which needs a current_thread->h. But some of these exceptions mark
  1470. the birth or death of threads, which mean that the current thread
  1471. isn't necessarily what you think it is. */
  1472. while (1)
  1473. {
  1474. int retval;
  1475. /* If the user presses Ctrl-c while the debugger is waiting
  1476. for an event, he expects the debugger to interrupt his program
  1477. and to get the prompt back. There are two possible situations:
  1478. - The debugger and the program do not share the console, in
  1479. which case the Ctrl-c event only reached the debugger.
  1480. In that case, the ctrl_c handler will take care of interrupting
  1481. the inferior. Note that this case is working starting with
  1482. Windows XP. For Windows 2000, Ctrl-C should be pressed in the
  1483. inferior console.
  1484. - The debugger and the program share the same console, in which
  1485. case both debugger and inferior will receive the Ctrl-c event.
  1486. In that case the ctrl_c handler will ignore the event, as the
  1487. Ctrl-c event generated inside the inferior will trigger the
  1488. expected debug event.
  1489. FIXME: brobecker/2008-05-20: If the inferior receives the
  1490. signal first and the delay until GDB receives that signal
  1491. is sufficiently long, GDB can sometimes receive the SIGINT
  1492. after we have unblocked the CTRL+C handler. This would
  1493. lead to the debugger stopping prematurely while handling
  1494. the new-thread event that comes with the handling of the SIGINT
  1495. inside the inferior, and then stop again immediately when
  1496. the user tries to resume the execution in the inferior.
  1497. This is a classic race that we should try to fix one day. */
  1498. SetConsoleCtrlHandler (&ctrl_c_handler, TRUE);
  1499. retval = get_windows_debug_event (pid, ourstatus);
  1500. SetConsoleCtrlHandler (&ctrl_c_handler, FALSE);
  1501. if (retval)
  1502. {
  1503. ptid_t result = ptid_t (windows_process.current_event.dwProcessId,
  1504. retval, 0);
  1505. if (ourstatus->kind () != TARGET_WAITKIND_EXITED
  1506. && ourstatus->kind () != TARGET_WAITKIND_SIGNALLED)
  1507. {
  1508. windows_thread_info *th
  1509. = windows_process.thread_rec (result, INVALIDATE_CONTEXT);
  1510. if (th != nullptr)
  1511. {
  1512. th->stopped_at_software_breakpoint = false;
  1513. if (windows_process.current_event.dwDebugEventCode
  1514. == EXCEPTION_DEBUG_EVENT
  1515. && ((windows_process.current_event.u.Exception.ExceptionRecord.ExceptionCode
  1516. == EXCEPTION_BREAKPOINT)
  1517. || (windows_process.current_event.u.Exception.ExceptionRecord.ExceptionCode
  1518. == STATUS_WX86_BREAKPOINT))
  1519. && windows_initialization_done)
  1520. {
  1521. th->stopped_at_software_breakpoint = true;
  1522. th->pc_adjusted = false;
  1523. }
  1524. }
  1525. }
  1526. return result;
  1527. }
  1528. else
  1529. {
  1530. int detach = 0;
  1531. if (deprecated_ui_loop_hook != NULL)
  1532. detach = deprecated_ui_loop_hook (0);
  1533. if (detach)
  1534. kill ();
  1535. }
  1536. }
  1537. }
  1538. void
  1539. windows_nat_target::do_initial_windows_stuff (DWORD pid, bool attaching)
  1540. {
  1541. int i;
  1542. struct inferior *inf;
  1543. windows_process.last_sig = GDB_SIGNAL_0;
  1544. open_process_used = 0;
  1545. for (i = 0; i < sizeof (dr) / sizeof (dr[0]); i++)
  1546. dr[i] = 0;
  1547. #ifdef __CYGWIN__
  1548. cygwin_load_start = cygwin_load_end = 0;
  1549. #endif
  1550. windows_process.current_event.dwProcessId = pid;
  1551. memset (&windows_process.current_event, 0,
  1552. sizeof (windows_process.current_event));
  1553. inf = current_inferior ();
  1554. if (!inf->target_is_pushed (this))
  1555. inf->push_target (this);
  1556. disable_breakpoints_in_shlibs ();
  1557. windows_clear_solib ();
  1558. clear_proceed_status (0);
  1559. init_wait_for_inferior ();
  1560. #ifdef __x86_64__
  1561. windows_process.ignore_first_breakpoint
  1562. = !attaching && windows_process.wow64_process;
  1563. if (!windows_process.wow64_process)
  1564. {
  1565. windows_set_context_register_offsets (amd64_mappings);
  1566. windows_set_segment_register_p (amd64_windows_segment_register_p);
  1567. }
  1568. else
  1569. #endif
  1570. {
  1571. windows_set_context_register_offsets (i386_mappings);
  1572. windows_set_segment_register_p (i386_windows_segment_register_p);
  1573. }
  1574. inferior_appeared (inf, pid);
  1575. inf->attach_flag = attaching;
  1576. target_terminal::init ();
  1577. target_terminal::inferior ();
  1578. windows_initialization_done = 0;
  1579. ptid_t last_ptid;
  1580. while (1)
  1581. {
  1582. struct target_waitstatus status;
  1583. last_ptid = this->wait (minus_one_ptid, &status, 0);
  1584. /* Note windows_wait returns TARGET_WAITKIND_SPURIOUS for thread
  1585. events. */
  1586. if (status.kind () != TARGET_WAITKIND_LOADED
  1587. && status.kind () != TARGET_WAITKIND_SPURIOUS)
  1588. break;
  1589. this->resume (minus_one_ptid, 0, GDB_SIGNAL_0);
  1590. }
  1591. switch_to_thread (find_thread_ptid (this, last_ptid));
  1592. /* Now that the inferior has been started and all DLLs have been mapped,
  1593. we can iterate over all DLLs and load them in.
  1594. We avoid doing it any earlier because, on certain versions of Windows,
  1595. LOAD_DLL_DEBUG_EVENTs are sometimes not complete. In particular,
  1596. we have seen on Windows 8.1 that the ntdll.dll load event does not
  1597. include the DLL name, preventing us from creating an associated SO.
  1598. A possible explanation is that ntdll.dll might be mapped before
  1599. the SO info gets created by the Windows system -- ntdll.dll is
  1600. the first DLL to be reported via LOAD_DLL_DEBUG_EVENT and other DLLs
  1601. do not seem to suffer from that problem.
  1602. Rather than try to work around this sort of issue, it is much
  1603. simpler to just ignore DLL load/unload events during the startup
  1604. phase, and then process them all in one batch now. */
  1605. windows_process.add_all_dlls ();
  1606. windows_initialization_done = 1;
  1607. return;
  1608. }
  1609. /* Try to set or remove a user privilege to the current process. Return -1
  1610. if that fails, the previous setting of that privilege otherwise.
  1611. This code is copied from the Cygwin source code and rearranged to allow
  1612. dynamically loading of the needed symbols from advapi32 which is only
  1613. available on NT/2K/XP. */
  1614. static int
  1615. set_process_privilege (const char *privilege, BOOL enable)
  1616. {
  1617. HANDLE token_hdl = NULL;
  1618. LUID restore_priv;
  1619. TOKEN_PRIVILEGES new_priv, orig_priv;
  1620. int ret = -1;
  1621. DWORD size;
  1622. if (!OpenProcessToken (GetCurrentProcess (),
  1623. TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
  1624. &token_hdl))
  1625. goto out;
  1626. if (!LookupPrivilegeValueA (NULL, privilege, &restore_priv))
  1627. goto out;
  1628. new_priv.PrivilegeCount = 1;
  1629. new_priv.Privileges[0].Luid = restore_priv;
  1630. new_priv.Privileges[0].Attributes = enable ? SE_PRIVILEGE_ENABLED : 0;
  1631. if (!AdjustTokenPrivileges (token_hdl, FALSE, &new_priv,
  1632. sizeof orig_priv, &orig_priv, &size))
  1633. goto out;
  1634. #if 0
  1635. /* Disabled, otherwise every `attach' in an unprivileged user session
  1636. would raise the "Failed to get SE_DEBUG_NAME privilege" warning in
  1637. windows_attach(). */
  1638. /* AdjustTokenPrivileges returns TRUE even if the privilege could not
  1639. be enabled. GetLastError () returns an correct error code, though. */
  1640. if (enable && GetLastError () == ERROR_NOT_ALL_ASSIGNED)
  1641. goto out;
  1642. #endif
  1643. ret = orig_priv.Privileges[0].Attributes == SE_PRIVILEGE_ENABLED ? 1 : 0;
  1644. out:
  1645. if (token_hdl)
  1646. CloseHandle (token_hdl);
  1647. return ret;
  1648. }
  1649. /* Attach to process PID, then initialize for debugging it. */
  1650. void
  1651. windows_nat_target::attach (const char *args, int from_tty)
  1652. {
  1653. BOOL ok;
  1654. DWORD pid;
  1655. pid = parse_pid_to_attach (args);
  1656. if (set_process_privilege (SE_DEBUG_NAME, TRUE) < 0)
  1657. warning ("Failed to get SE_DEBUG_NAME privilege\n"
  1658. "This can cause attach to fail on Windows NT/2K/XP");
  1659. windows_init_thread_list ();
  1660. ok = DebugActiveProcess (pid);
  1661. saw_create = 0;
  1662. #ifdef __CYGWIN__
  1663. if (!ok)
  1664. {
  1665. /* Try fall back to Cygwin pid. */
  1666. pid = cygwin_internal (CW_CYGWIN_PID_TO_WINPID, pid);
  1667. if (pid > 0)
  1668. ok = DebugActiveProcess (pid);
  1669. }
  1670. #endif
  1671. if (!ok)
  1672. error (_("Can't attach to process %u (error %u)"),
  1673. (unsigned) pid, (unsigned) GetLastError ());
  1674. DebugSetProcessKillOnExit (FALSE);
  1675. target_announce_attach (from_tty, pid);
  1676. #ifdef __x86_64__
  1677. HANDLE h = OpenProcess (PROCESS_QUERY_INFORMATION, FALSE, pid);
  1678. if (h != NULL)
  1679. {
  1680. BOOL wow64;
  1681. if (IsWow64Process (h, &wow64))
  1682. windows_process.wow64_process = wow64;
  1683. CloseHandle (h);
  1684. }
  1685. #endif
  1686. do_initial_windows_stuff (pid, 1);
  1687. target_terminal::ours ();
  1688. }
  1689. void
  1690. windows_nat_target::detach (inferior *inf, int from_tty)
  1691. {
  1692. int detached = 1;
  1693. ptid_t ptid = minus_one_ptid;
  1694. resume (ptid, 0, GDB_SIGNAL_0);
  1695. if (!DebugActiveProcessStop (windows_process.current_event.dwProcessId))
  1696. {
  1697. error (_("Can't detach process %u (error %u)"),
  1698. (unsigned) windows_process.current_event.dwProcessId,
  1699. (unsigned) GetLastError ());
  1700. detached = 0;
  1701. }
  1702. DebugSetProcessKillOnExit (FALSE);
  1703. if (detached)
  1704. target_announce_detach (from_tty);
  1705. x86_cleanup_dregs ();
  1706. switch_to_no_thread ();
  1707. detach_inferior (inf);
  1708. maybe_unpush_target ();
  1709. }
  1710. /* Try to determine the executable filename.
  1711. EXE_NAME_RET is a pointer to a buffer whose size is EXE_NAME_MAX_LEN.
  1712. Upon success, the filename is stored inside EXE_NAME_RET, and
  1713. this function returns nonzero.
  1714. Otherwise, this function returns zero and the contents of
  1715. EXE_NAME_RET is undefined. */
  1716. static int
  1717. windows_get_exec_module_filename (char *exe_name_ret, size_t exe_name_max_len)
  1718. {
  1719. DWORD len;
  1720. HMODULE dh_buf;
  1721. DWORD cbNeeded;
  1722. cbNeeded = 0;
  1723. #ifdef __x86_64__
  1724. if (windows_process.wow64_process)
  1725. {
  1726. if (!EnumProcessModulesEx (windows_process.handle,
  1727. &dh_buf, sizeof (HMODULE), &cbNeeded,
  1728. LIST_MODULES_32BIT)
  1729. || !cbNeeded)
  1730. return 0;
  1731. }
  1732. else
  1733. #endif
  1734. {
  1735. if (!EnumProcessModules (windows_process.handle,
  1736. &dh_buf, sizeof (HMODULE), &cbNeeded)
  1737. || !cbNeeded)
  1738. return 0;
  1739. }
  1740. /* We know the executable is always first in the list of modules,
  1741. which we just fetched. So no need to fetch more. */
  1742. #ifdef __CYGWIN__
  1743. {
  1744. /* Cygwin prefers that the path be in /x/y/z format, so extract
  1745. the filename into a temporary buffer first, and then convert it
  1746. to POSIX format into the destination buffer. */
  1747. cygwin_buf_t *pathbuf = (cygwin_buf_t *) alloca (exe_name_max_len * sizeof (cygwin_buf_t));
  1748. len = GetModuleFileNameEx (current_process_handle,
  1749. dh_buf, pathbuf, exe_name_max_len);
  1750. if (len == 0)
  1751. error (_("Error getting executable filename: %u."),
  1752. (unsigned) GetLastError ());
  1753. if (cygwin_conv_path (CCP_WIN_W_TO_POSIX, pathbuf, exe_name_ret,
  1754. exe_name_max_len) < 0)
  1755. error (_("Error converting executable filename to POSIX: %d."), errno);
  1756. }
  1757. #else
  1758. len = GetModuleFileNameEx (windows_process.handle,
  1759. dh_buf, exe_name_ret, exe_name_max_len);
  1760. if (len == 0)
  1761. error (_("Error getting executable filename: %u."),
  1762. (unsigned) GetLastError ());
  1763. #endif
  1764. return 1; /* success */
  1765. }
  1766. /* The pid_to_exec_file target_ops method for this platform. */
  1767. char *
  1768. windows_nat_target::pid_to_exec_file (int pid)
  1769. {
  1770. static char path[__PMAX];
  1771. #ifdef __CYGWIN__
  1772. /* Try to find exe name as symlink target of /proc/<pid>/exe. */
  1773. int nchars;
  1774. char procexe[sizeof ("/proc/4294967295/exe")];
  1775. xsnprintf (procexe, sizeof (procexe), "/proc/%u/exe", pid);
  1776. nchars = readlink (procexe, path, sizeof(path));
  1777. if (nchars > 0 && nchars < sizeof (path))
  1778. {
  1779. path[nchars] = '\0'; /* Got it */
  1780. return path;
  1781. }
  1782. #endif
  1783. /* If we get here then either Cygwin is hosed, this isn't a Cygwin version
  1784. of gdb, or we're trying to debug a non-Cygwin windows executable. */
  1785. if (!windows_get_exec_module_filename (path, sizeof (path)))
  1786. path[0] = '\0';
  1787. return path;
  1788. }
  1789. /* Print status information about what we're accessing. */
  1790. void
  1791. windows_nat_target::files_info ()
  1792. {
  1793. struct inferior *inf = current_inferior ();
  1794. gdb_printf ("\tUsing the running image of %s %s.\n",
  1795. inf->attach_flag ? "attached" : "child",
  1796. target_pid_to_str (inferior_ptid).c_str ());
  1797. }
  1798. /* Modify CreateProcess parameters for use of a new separate console.
  1799. Parameters are:
  1800. *FLAGS: DWORD parameter for general process creation flags.
  1801. *SI: STARTUPINFO structure, for which the console window size and
  1802. console buffer size is filled in if GDB is running in a console.
  1803. to create the new console.
  1804. The size of the used font is not available on all versions of
  1805. Windows OS. Furthermore, the current font might not be the default
  1806. font, but this is still better than before.
  1807. If the windows and buffer sizes are computed,
  1808. SI->DWFLAGS is changed so that this information is used
  1809. by CreateProcess function. */
  1810. static void
  1811. windows_set_console_info (STARTUPINFO *si, DWORD *flags)
  1812. {
  1813. HANDLE hconsole = CreateFile ("CONOUT$", GENERIC_READ | GENERIC_WRITE,
  1814. FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
  1815. if (hconsole != INVALID_HANDLE_VALUE)
  1816. {
  1817. CONSOLE_SCREEN_BUFFER_INFO sbinfo;
  1818. COORD font_size;
  1819. CONSOLE_FONT_INFO cfi;
  1820. GetCurrentConsoleFont (hconsole, FALSE, &cfi);
  1821. font_size = GetConsoleFontSize (hconsole, cfi.nFont);
  1822. GetConsoleScreenBufferInfo(hconsole, &sbinfo);
  1823. si->dwXSize = sbinfo.srWindow.Right - sbinfo.srWindow.Left + 1;
  1824. si->dwYSize = sbinfo.srWindow.Bottom - sbinfo.srWindow.Top + 1;
  1825. if (font_size.X)
  1826. si->dwXSize *= font_size.X;
  1827. else
  1828. si->dwXSize *= 8;
  1829. if (font_size.Y)
  1830. si->dwYSize *= font_size.Y;
  1831. else
  1832. si->dwYSize *= 12;
  1833. si->dwXCountChars = sbinfo.dwSize.X;
  1834. si->dwYCountChars = sbinfo.dwSize.Y;
  1835. si->dwFlags |= STARTF_USESIZE | STARTF_USECOUNTCHARS;
  1836. }
  1837. *flags |= CREATE_NEW_CONSOLE;
  1838. }
  1839. #ifndef __CYGWIN__
  1840. /* Function called by qsort to sort environment strings. */
  1841. static int
  1842. envvar_cmp (const void *a, const void *b)
  1843. {
  1844. const char **p = (const char **) a;
  1845. const char **q = (const char **) b;
  1846. return strcasecmp (*p, *q);
  1847. }
  1848. #endif
  1849. #ifdef __CYGWIN__
  1850. static void
  1851. clear_win32_environment (char **env)
  1852. {
  1853. int i;
  1854. size_t len;
  1855. wchar_t *copy = NULL, *equalpos;
  1856. for (i = 0; env[i] && *env[i]; i++)
  1857. {
  1858. len = mbstowcs (NULL, env[i], 0) + 1;
  1859. copy = (wchar_t *) xrealloc (copy, len * sizeof (wchar_t));
  1860. mbstowcs (copy, env[i], len);
  1861. equalpos = wcschr (copy, L'=');
  1862. if (equalpos)
  1863. *equalpos = L'\0';
  1864. SetEnvironmentVariableW (copy, NULL);
  1865. }
  1866. xfree (copy);
  1867. }
  1868. #endif
  1869. #ifndef __CYGWIN__
  1870. /* Redirection of inferior I/O streams for native MS-Windows programs.
  1871. Unlike on Unix, where this is handled by invoking the inferior via
  1872. the shell, on MS-Windows we need to emulate the cmd.exe shell.
  1873. The official documentation of the cmd.exe redirection features is here:
  1874. http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/redirection.mspx
  1875. (That page talks about Windows XP, but there's no newer
  1876. documentation, so we assume later versions of cmd.exe didn't change
  1877. anything.)
  1878. Caveat: the documentation on that page seems to include a few lies.
  1879. For example, it describes strange constructs 1<&2 and 2<&1, which
  1880. seem to work only when 1>&2 resp. 2>&1 would make sense, and so I
  1881. think the cmd.exe parser of the redirection symbols simply doesn't
  1882. care about the < vs > distinction in these cases. Therefore, the
  1883. supported features are explicitly documented below.
  1884. The emulation below aims at supporting all the valid use cases
  1885. supported by cmd.exe, which include:
  1886. < FILE redirect standard input from FILE
  1887. 0< FILE redirect standard input from FILE
  1888. <&N redirect standard input from file descriptor N
  1889. 0<&N redirect standard input from file descriptor N
  1890. > FILE redirect standard output to FILE
  1891. >> FILE append standard output to FILE
  1892. 1>> FILE append standard output to FILE
  1893. >&N redirect standard output to file descriptor N
  1894. 1>&N redirect standard output to file descriptor N
  1895. >>&N append standard output to file descriptor N
  1896. 1>>&N append standard output to file descriptor N
  1897. 2> FILE redirect standard error to FILE
  1898. 2>> FILE append standard error to FILE
  1899. 2>&N redirect standard error to file descriptor N
  1900. 2>>&N append standard error to file descriptor N
  1901. Note that using N > 2 in the above construct is supported, but
  1902. requires that the corresponding file descriptor be open by some
  1903. means elsewhere or outside GDB. Also note that using ">&0" or
  1904. "<&2" will generally fail, because the file descriptor redirected
  1905. from is normally open in an incompatible mode (e.g., FD 0 is open
  1906. for reading only). IOW, use of such tricks is not recommended;
  1907. you are on your own.
  1908. We do NOT support redirection of file descriptors above 2, as in
  1909. "3>SOME-FILE", because MinGW compiled programs don't (supporting
  1910. that needs special handling in the startup code that MinGW
  1911. doesn't have). Pipes are also not supported.
  1912. As for invalid use cases, where the redirection contains some
  1913. error, the emulation below will detect that and produce some
  1914. error and/or failure. But the behavior in those cases is not
  1915. bug-for-bug compatible with what cmd.exe does in those cases.
  1916. That's because what cmd.exe does then is not well defined, and
  1917. seems to be a side effect of the cmd.exe parsing of the command
  1918. line more than anything else. For example, try redirecting to an
  1919. invalid file name, as in "> foo:bar".
  1920. There are also minor syntactic deviations from what cmd.exe does
  1921. in some corner cases. For example, it doesn't support the likes
  1922. of "> &foo" to mean redirect to file named literally "&foo"; we
  1923. do support that here, because that, too, sounds like some issue
  1924. with the cmd.exe parser. Another nicety is that we support
  1925. redirection targets that use file names with forward slashes,
  1926. something cmd.exe doesn't -- this comes in handy since GDB
  1927. file-name completion can be used when typing the command line for
  1928. the inferior. */
  1929. /* Support routines for redirecting standard handles of the inferior. */
  1930. /* Parse a single redirection spec, open/duplicate the specified
  1931. file/fd, and assign the appropriate value to one of the 3 standard
  1932. file descriptors. */
  1933. static int
  1934. redir_open (const char *redir_string, int *inp, int *out, int *err)
  1935. {
  1936. int *fd, ref_fd = -2;
  1937. int mode;
  1938. const char *fname = redir_string + 1;
  1939. int rc = *redir_string;
  1940. switch (rc)
  1941. {
  1942. case '0':
  1943. fname++;
  1944. /* FALLTHROUGH */
  1945. case '<':
  1946. fd = inp;
  1947. mode = O_RDONLY;
  1948. break;
  1949. case '1': case '2':
  1950. fname++;
  1951. /* FALLTHROUGH */
  1952. case '>':
  1953. fd = (rc == '2') ? err : out;
  1954. mode = O_WRONLY | O_CREAT;
  1955. if (*fname == '>')
  1956. {
  1957. fname++;
  1958. mode |= O_APPEND;
  1959. }
  1960. else
  1961. mode |= O_TRUNC;
  1962. break;
  1963. default:
  1964. return -1;
  1965. }
  1966. if (*fname == '&' && '0' <= fname[1] && fname[1] <= '9')
  1967. {
  1968. /* A reference to a file descriptor. */
  1969. char *fdtail;
  1970. ref_fd = (int) strtol (fname + 1, &fdtail, 10);
  1971. if (fdtail > fname + 1 && *fdtail == '\0')
  1972. {
  1973. /* Don't allow redirection when open modes are incompatible. */
  1974. if ((ref_fd == 0 && (fd == out || fd == err))
  1975. || ((ref_fd == 1 || ref_fd == 2) && fd == inp))
  1976. {
  1977. errno = EPERM;
  1978. return -1;
  1979. }
  1980. if (ref_fd == 0)
  1981. ref_fd = *inp;
  1982. else if (ref_fd == 1)
  1983. ref_fd = *out;
  1984. else if (ref_fd == 2)
  1985. ref_fd = *err;
  1986. }
  1987. else
  1988. {
  1989. errno = EBADF;
  1990. return -1;
  1991. }
  1992. }
  1993. else
  1994. fname++; /* skip the separator space */
  1995. /* If the descriptor is already open, close it. This allows
  1996. multiple specs of redirections for the same stream, which is
  1997. somewhat nonsensical, but still valid and supported by cmd.exe.
  1998. (But cmd.exe only opens a single file in this case, the one
  1999. specified by the last redirection spec on the command line.) */
  2000. if (*fd >= 0)
  2001. _close (*fd);
  2002. if (ref_fd == -2)
  2003. {
  2004. *fd = _open (fname, mode, _S_IREAD | _S_IWRITE);
  2005. if (*fd < 0)
  2006. return -1;
  2007. }
  2008. else if (ref_fd == -1)
  2009. *fd = -1; /* reset to default destination */
  2010. else
  2011. {
  2012. *fd = _dup (ref_fd);
  2013. if (*fd < 0)
  2014. return -1;
  2015. }
  2016. /* _open just sets a flag for O_APPEND, which won't be passed to the
  2017. inferior, so we need to actually move the file pointer. */
  2018. if ((mode & O_APPEND) != 0)
  2019. _lseek (*fd, 0L, SEEK_END);
  2020. return 0;
  2021. }
  2022. /* Canonicalize a single redirection spec and set up the corresponding
  2023. file descriptor as specified. */
  2024. static int
  2025. redir_set_redirection (const char *s, int *inp, int *out, int *err)
  2026. {
  2027. char buf[__PMAX + 2 + 5]; /* extra space for quotes & redirection string */
  2028. char *d = buf;
  2029. const char *start = s;
  2030. int quote = 0;
  2031. *d++ = *s++; /* copy the 1st character, < or > or a digit */
  2032. if ((*start == '>' || *start == '1' || *start == '2')
  2033. && *s == '>')
  2034. {
  2035. *d++ = *s++;
  2036. if (*s == '>' && *start != '>')
  2037. *d++ = *s++;
  2038. }
  2039. else if (*start == '0' && *s == '<')
  2040. *d++ = *s++;
  2041. /* cmd.exe recognizes "&N" only immediately after the redirection symbol. */
  2042. if (*s != '&')
  2043. {
  2044. while (isspace (*s)) /* skip whitespace before file name */
  2045. s++;
  2046. *d++ = ' '; /* separate file name with a single space */
  2047. }
  2048. /* Copy the file name. */
  2049. while (*s)
  2050. {
  2051. /* Remove quoting characters from the file name in buf[]. */
  2052. if (*s == '"') /* could support '..' quoting here */
  2053. {
  2054. if (!quote)
  2055. quote = *s++;
  2056. else if (*s == quote)
  2057. {
  2058. quote = 0;
  2059. s++;
  2060. }
  2061. else
  2062. *d++ = *s++;
  2063. }
  2064. else if (*s == '\\')
  2065. {
  2066. if (s[1] == '"') /* could support '..' here */
  2067. s++;
  2068. *d++ = *s++;
  2069. }
  2070. else if (isspace (*s) && !quote)
  2071. break;
  2072. else
  2073. *d++ = *s++;
  2074. if (d - buf >= sizeof (buf) - 1)
  2075. {
  2076. errno = ENAMETOOLONG;
  2077. return 0;
  2078. }
  2079. }
  2080. *d = '\0';
  2081. /* Windows doesn't allow redirection characters in file names, so we
  2082. can bail out early if they use them, or if there's no target file
  2083. name after the redirection symbol. */
  2084. if (d[-1] == '>' || d[-1] == '<')
  2085. {
  2086. errno = ENOENT;
  2087. return 0;
  2088. }
  2089. if (redir_open (buf, inp, out, err) == 0)
  2090. return s - start;
  2091. return 0;
  2092. }
  2093. /* Parse the command line for redirection specs and prepare the file
  2094. descriptors for the 3 standard streams accordingly. */
  2095. static bool
  2096. redirect_inferior_handles (const char *cmd_orig, char *cmd,
  2097. int *inp, int *out, int *err)
  2098. {
  2099. const char *s = cmd_orig;
  2100. char *d = cmd;
  2101. int quote = 0;
  2102. bool retval = false;
  2103. while (isspace (*s))
  2104. *d++ = *s++;
  2105. while (*s)
  2106. {
  2107. if (*s == '"') /* could also support '..' quoting here */
  2108. {
  2109. if (!quote)
  2110. quote = *s;
  2111. else if (*s == quote)
  2112. quote = 0;
  2113. }
  2114. else if (*s == '\\')
  2115. {
  2116. if (s[1] == '"') /* escaped quote char */
  2117. s++;
  2118. }
  2119. else if (!quote)
  2120. {
  2121. /* Process a single redirection candidate. */
  2122. if (*s == '<' || *s == '>'
  2123. || ((*s == '1' || *s == '2') && s[1] == '>')
  2124. || (*s == '0' && s[1] == '<'))
  2125. {
  2126. int skip = redir_set_redirection (s, inp, out, err);
  2127. if (skip <= 0)
  2128. return false;
  2129. retval = true;
  2130. s += skip;
  2131. }
  2132. }
  2133. if (*s)
  2134. *d++ = *s++;
  2135. }
  2136. *d = '\0';
  2137. return retval;
  2138. }
  2139. #endif /* !__CYGWIN__ */
  2140. /* Start an inferior windows child process and sets inferior_ptid to its pid.
  2141. EXEC_FILE is the file to run.
  2142. ALLARGS is a string containing the arguments to the program.
  2143. ENV is the environment vector to pass. Errors reported with error(). */
  2144. void
  2145. windows_nat_target::create_inferior (const char *exec_file,
  2146. const std::string &origallargs,
  2147. char **in_env, int from_tty)
  2148. {
  2149. STARTUPINFO si;
  2150. #ifdef __CYGWIN__
  2151. cygwin_buf_t real_path[__PMAX];
  2152. cygwin_buf_t shell[__PMAX]; /* Path to shell */
  2153. cygwin_buf_t infcwd[__PMAX];
  2154. const char *sh;
  2155. cygwin_buf_t *toexec;
  2156. cygwin_buf_t *cygallargs;
  2157. cygwin_buf_t *args;
  2158. char **old_env = NULL;
  2159. PWCHAR w32_env;
  2160. size_t len;
  2161. int tty;
  2162. int ostdin, ostdout, ostderr;
  2163. #else /* !__CYGWIN__ */
  2164. char shell[__PMAX]; /* Path to shell */
  2165. const char *toexec;
  2166. char *args, *allargs_copy;
  2167. size_t args_len, allargs_len;
  2168. int fd_inp = -1, fd_out = -1, fd_err = -1;
  2169. HANDLE tty = INVALID_HANDLE_VALUE;
  2170. bool redirected = false;
  2171. char *w32env;
  2172. char *temp;
  2173. size_t envlen;
  2174. int i;
  2175. size_t envsize;
  2176. char **env;
  2177. #endif /* !__CYGWIN__ */
  2178. const char *allargs = origallargs.c_str ();
  2179. PROCESS_INFORMATION pi;
  2180. BOOL ret;
  2181. DWORD flags = 0;
  2182. const std::string &inferior_tty = current_inferior ()->tty ();
  2183. if (!exec_file)
  2184. error (_("No executable specified, use `target exec'."));
  2185. const char *inferior_cwd = current_inferior ()->cwd ().c_str ();
  2186. std::string expanded_infcwd;
  2187. if (*inferior_cwd == '\0')
  2188. inferior_cwd = nullptr;
  2189. else
  2190. {
  2191. expanded_infcwd = gdb_tilde_expand (inferior_cwd);
  2192. /* Mirror slashes on inferior's cwd. */
  2193. std::replace (expanded_infcwd.begin (), expanded_infcwd.end (),
  2194. '/', '\\');
  2195. inferior_cwd = expanded_infcwd.c_str ();
  2196. }
  2197. memset (&si, 0, sizeof (si));
  2198. si.cb = sizeof (si);
  2199. if (new_group)
  2200. flags |= CREATE_NEW_PROCESS_GROUP;
  2201. if (new_console)
  2202. windows_set_console_info (&si, &flags);
  2203. #ifdef __CYGWIN__
  2204. if (!useshell)
  2205. {
  2206. flags |= DEBUG_ONLY_THIS_PROCESS;
  2207. if (cygwin_conv_path (CCP_POSIX_TO_WIN_W, exec_file, real_path,
  2208. __PMAX * sizeof (cygwin_buf_t)) < 0)
  2209. error (_("Error starting executable: %d"), errno);
  2210. toexec = real_path;
  2211. #ifdef __USEWIDE
  2212. len = mbstowcs (NULL, allargs, 0) + 1;
  2213. if (len == (size_t) -1)
  2214. error (_("Error starting executable: %d"), errno);
  2215. cygallargs = (wchar_t *) alloca (len * sizeof (wchar_t));
  2216. mbstowcs (cygallargs, allargs, len);
  2217. #else /* !__USEWIDE */
  2218. cygallargs = allargs;
  2219. #endif
  2220. }
  2221. else
  2222. {
  2223. sh = get_shell ();
  2224. if (cygwin_conv_path (CCP_POSIX_TO_WIN_W, sh, shell, __PMAX) < 0)
  2225. error (_("Error starting executable via shell: %d"), errno);
  2226. #ifdef __USEWIDE
  2227. len = sizeof (L" -c 'exec '") + mbstowcs (NULL, exec_file, 0)
  2228. + mbstowcs (NULL, allargs, 0) + 2;
  2229. cygallargs = (wchar_t *) alloca (len * sizeof (wchar_t));
  2230. swprintf (cygallargs, len, L" -c 'exec %s %s'", exec_file, allargs);
  2231. #else /* !__USEWIDE */
  2232. len = (sizeof (" -c 'exec '") + strlen (exec_file)
  2233. + strlen (allargs) + 2);
  2234. cygallargs = (char *) alloca (len);
  2235. xsnprintf (cygallargs, len, " -c 'exec %s %s'", exec_file, allargs);
  2236. #endif /* __USEWIDE */
  2237. toexec = shell;
  2238. flags |= DEBUG_PROCESS;
  2239. }
  2240. if (inferior_cwd != NULL
  2241. && cygwin_conv_path (CCP_POSIX_TO_WIN_W, inferior_cwd,
  2242. infcwd, strlen (inferior_cwd)) < 0)
  2243. error (_("Error converting inferior cwd: %d"), errno);
  2244. #ifdef __USEWIDE
  2245. args = (cygwin_buf_t *) alloca ((wcslen (toexec) + wcslen (cygallargs) + 2)
  2246. * sizeof (wchar_t));
  2247. wcscpy (args, toexec);
  2248. wcscat (args, L" ");
  2249. wcscat (args, cygallargs);
  2250. #else /* !__USEWIDE */
  2251. args = (cygwin_buf_t *) alloca (strlen (toexec) + strlen (cygallargs) + 2);
  2252. strcpy (args, toexec);
  2253. strcat (args, " ");
  2254. strcat (args, cygallargs);
  2255. #endif /* !__USEWIDE */
  2256. #ifdef CW_CVT_ENV_TO_WINENV
  2257. /* First try to create a direct Win32 copy of the POSIX environment. */
  2258. w32_env = (PWCHAR) cygwin_internal (CW_CVT_ENV_TO_WINENV, in_env);
  2259. if (w32_env != (PWCHAR) -1)
  2260. flags |= CREATE_UNICODE_ENVIRONMENT;
  2261. else
  2262. /* If that fails, fall back to old method tweaking GDB's environment. */
  2263. #endif /* CW_CVT_ENV_TO_WINENV */
  2264. {
  2265. /* Reset all Win32 environment variables to avoid leftover on next run. */
  2266. clear_win32_environment (environ);
  2267. /* Prepare the environment vars for CreateProcess. */
  2268. old_env = environ;
  2269. environ = in_env;
  2270. cygwin_internal (CW_SYNC_WINENV);
  2271. w32_env = NULL;
  2272. }
  2273. if (inferior_tty.empty ())
  2274. tty = ostdin = ostdout = ostderr = -1;
  2275. else
  2276. {
  2277. tty = open (inferior_tty.c_str (), O_RDWR | O_NOCTTY);
  2278. if (tty < 0)
  2279. {
  2280. print_sys_errmsg (inferior_tty.c_str (), errno);
  2281. ostdin = ostdout = ostderr = -1;
  2282. }
  2283. else
  2284. {
  2285. ostdin = dup (0);
  2286. ostdout = dup (1);
  2287. ostderr = dup (2);
  2288. dup2 (tty, 0);
  2289. dup2 (tty, 1);
  2290. dup2 (tty, 2);
  2291. }
  2292. }
  2293. windows_init_thread_list ();
  2294. ret = CreateProcess (0,
  2295. args, /* command line */
  2296. NULL, /* Security */
  2297. NULL, /* thread */
  2298. TRUE, /* inherit handles */
  2299. flags, /* start flags */
  2300. w32_env, /* environment */
  2301. inferior_cwd != NULL ? infcwd : NULL, /* current
  2302. directory */
  2303. &si,
  2304. &pi);
  2305. if (w32_env)
  2306. /* Just free the Win32 environment, if it could be created. */
  2307. free (w32_env);
  2308. else
  2309. {
  2310. /* Reset all environment variables to avoid leftover on next run. */
  2311. clear_win32_environment (in_env);
  2312. /* Restore normal GDB environment variables. */
  2313. environ = old_env;
  2314. cygwin_internal (CW_SYNC_WINENV);
  2315. }
  2316. if (tty >= 0)
  2317. {
  2318. ::close (tty);
  2319. dup2 (ostdin, 0);
  2320. dup2 (ostdout, 1);
  2321. dup2 (ostderr, 2);
  2322. ::close (ostdin);
  2323. ::close (ostdout);
  2324. ::close (ostderr);
  2325. }
  2326. #else /* !__CYGWIN__ */
  2327. allargs_len = strlen (allargs);
  2328. allargs_copy = strcpy ((char *) alloca (allargs_len + 1), allargs);
  2329. if (strpbrk (allargs_copy, "<>") != NULL)
  2330. {
  2331. int e = errno;
  2332. errno = 0;
  2333. redirected =
  2334. redirect_inferior_handles (allargs, allargs_copy,
  2335. &fd_inp, &fd_out, &fd_err);
  2336. if (errno)
  2337. warning (_("Error in redirection: %s."), safe_strerror (errno));
  2338. else
  2339. errno = e;
  2340. allargs_len = strlen (allargs_copy);
  2341. }
  2342. /* If not all the standard streams are redirected by the command
  2343. line, use INFERIOR_TTY for those which aren't. */
  2344. if (!inferior_tty.empty ()
  2345. && !(fd_inp >= 0 && fd_out >= 0 && fd_err >= 0))
  2346. {
  2347. SECURITY_ATTRIBUTES sa;
  2348. sa.nLength = sizeof(sa);
  2349. sa.lpSecurityDescriptor = 0;
  2350. sa.bInheritHandle = TRUE;
  2351. tty = CreateFileA (inferior_tty.c_str (), GENERIC_READ | GENERIC_WRITE,
  2352. 0, &sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  2353. if (tty == INVALID_HANDLE_VALUE)
  2354. warning (_("Warning: Failed to open TTY %s, error %#x."),
  2355. inferior_tty.c_str (), (unsigned) GetLastError ());
  2356. }
  2357. if (redirected || tty != INVALID_HANDLE_VALUE)
  2358. {
  2359. if (fd_inp >= 0)
  2360. si.hStdInput = (HANDLE) _get_osfhandle (fd_inp);
  2361. else if (tty != INVALID_HANDLE_VALUE)
  2362. si.hStdInput = tty;
  2363. else
  2364. si.hStdInput = GetStdHandle (STD_INPUT_HANDLE);
  2365. if (fd_out >= 0)
  2366. si.hStdOutput = (HANDLE) _get_osfhandle (fd_out);
  2367. else if (tty != INVALID_HANDLE_VALUE)
  2368. si.hStdOutput = tty;
  2369. else
  2370. si.hStdOutput = GetStdHandle (STD_OUTPUT_HANDLE);
  2371. if (fd_err >= 0)
  2372. si.hStdError = (HANDLE) _get_osfhandle (fd_err);
  2373. else if (tty != INVALID_HANDLE_VALUE)
  2374. si.hStdError = tty;
  2375. else
  2376. si.hStdError = GetStdHandle (STD_ERROR_HANDLE);
  2377. si.dwFlags |= STARTF_USESTDHANDLES;
  2378. }
  2379. toexec = exec_file;
  2380. /* Build the command line, a space-separated list of tokens where
  2381. the first token is the name of the module to be executed.
  2382. To avoid ambiguities introduced by spaces in the module name,
  2383. we quote it. */
  2384. args_len = strlen (toexec) + 2 /* quotes */ + allargs_len + 2;
  2385. args = (char *) alloca (args_len);
  2386. xsnprintf (args, args_len, "\"%s\" %s", toexec, allargs_copy);
  2387. flags |= DEBUG_ONLY_THIS_PROCESS;
  2388. /* CreateProcess takes the environment list as a null terminated set of
  2389. strings (i.e. two nulls terminate the list). */
  2390. /* Get total size for env strings. */
  2391. for (envlen = 0, i = 0; in_env[i] && *in_env[i]; i++)
  2392. envlen += strlen (in_env[i]) + 1;
  2393. envsize = sizeof (in_env[0]) * (i + 1);
  2394. env = (char **) alloca (envsize);
  2395. memcpy (env, in_env, envsize);
  2396. /* Windows programs expect the environment block to be sorted. */
  2397. qsort (env, i, sizeof (char *), envvar_cmp);
  2398. w32env = (char *) alloca (envlen + 1);
  2399. /* Copy env strings into new buffer. */
  2400. for (temp = w32env, i = 0; env[i] && *env[i]; i++)
  2401. {
  2402. strcpy (temp, env[i]);
  2403. temp += strlen (temp) + 1;
  2404. }
  2405. /* Final nil string to terminate new env. */
  2406. *temp = 0;
  2407. windows_init_thread_list ();
  2408. ret = CreateProcessA (0,
  2409. args, /* command line */
  2410. NULL, /* Security */
  2411. NULL, /* thread */
  2412. TRUE, /* inherit handles */
  2413. flags, /* start flags */
  2414. w32env, /* environment */
  2415. inferior_cwd, /* current directory */
  2416. &si,
  2417. &pi);
  2418. if (tty != INVALID_HANDLE_VALUE)
  2419. CloseHandle (tty);
  2420. if (fd_inp >= 0)
  2421. _close (fd_inp);
  2422. if (fd_out >= 0)
  2423. _close (fd_out);
  2424. if (fd_err >= 0)
  2425. _close (fd_err);
  2426. #endif /* !__CYGWIN__ */
  2427. if (!ret)
  2428. error (_("Error creating process %s, (error %u)."),
  2429. exec_file, (unsigned) GetLastError ());
  2430. #ifdef __x86_64__
  2431. BOOL wow64;
  2432. if (IsWow64Process (pi.hProcess, &wow64))
  2433. windows_process.wow64_process = wow64;
  2434. #endif
  2435. CloseHandle (pi.hThread);
  2436. CloseHandle (pi.hProcess);
  2437. if (useshell && shell[0] != '\0')
  2438. saw_create = -1;
  2439. else
  2440. saw_create = 0;
  2441. do_initial_windows_stuff (pi.dwProcessId, 0);
  2442. /* windows_continue (DBG_CONTINUE, -1, 0); */
  2443. }
  2444. void
  2445. windows_nat_target::mourn_inferior ()
  2446. {
  2447. (void) windows_continue (DBG_CONTINUE, -1, 0);
  2448. x86_cleanup_dregs();
  2449. if (open_process_used)
  2450. {
  2451. CHECK (CloseHandle (windows_process.handle));
  2452. open_process_used = 0;
  2453. }
  2454. windows_process.siginfo_er.ExceptionCode = 0;
  2455. inf_child_target::mourn_inferior ();
  2456. }
  2457. /* Send a SIGINT to the process group. This acts just like the user typed a
  2458. ^C on the controlling terminal. */
  2459. void
  2460. windows_nat_target::interrupt ()
  2461. {
  2462. DEBUG_EVENTS ("GenerateConsoleCtrlEvent (CTRLC_EVENT, 0)");
  2463. CHECK (GenerateConsoleCtrlEvent (CTRL_C_EVENT,
  2464. windows_process.current_event.dwProcessId));
  2465. registers_changed (); /* refresh register state */
  2466. }
  2467. /* Helper for windows_xfer_partial that handles memory transfers.
  2468. Arguments are like target_xfer_partial. */
  2469. static enum target_xfer_status
  2470. windows_xfer_memory (gdb_byte *readbuf, const gdb_byte *writebuf,
  2471. ULONGEST memaddr, ULONGEST len, ULONGEST *xfered_len)
  2472. {
  2473. SIZE_T done = 0;
  2474. BOOL success;
  2475. DWORD lasterror = 0;
  2476. if (writebuf != NULL)
  2477. {
  2478. DEBUG_MEM ("write target memory, %s bytes at %s",
  2479. pulongest (len), core_addr_to_string (memaddr));
  2480. success = WriteProcessMemory (windows_process.handle,
  2481. (LPVOID) (uintptr_t) memaddr, writebuf,
  2482. len, &done);
  2483. if (!success)
  2484. lasterror = GetLastError ();
  2485. FlushInstructionCache (windows_process.handle,
  2486. (LPCVOID) (uintptr_t) memaddr, len);
  2487. }
  2488. else
  2489. {
  2490. DEBUG_MEM ("read target memory, %s bytes at %s",
  2491. pulongest (len), core_addr_to_string (memaddr));
  2492. success = ReadProcessMemory (windows_process.handle,
  2493. (LPCVOID) (uintptr_t) memaddr, readbuf,
  2494. len, &done);
  2495. if (!success)
  2496. lasterror = GetLastError ();
  2497. }
  2498. *xfered_len = (ULONGEST) done;
  2499. if (!success && lasterror == ERROR_PARTIAL_COPY && done > 0)
  2500. return TARGET_XFER_OK;
  2501. else
  2502. return success ? TARGET_XFER_OK : TARGET_XFER_E_IO;
  2503. }
  2504. void
  2505. windows_nat_target::kill ()
  2506. {
  2507. CHECK (TerminateProcess (windows_process.handle, 0));
  2508. for (;;)
  2509. {
  2510. if (!windows_continue (DBG_CONTINUE, -1, 1))
  2511. break;
  2512. if (!wait_for_debug_event (&windows_process.current_event, INFINITE))
  2513. break;
  2514. if (windows_process.current_event.dwDebugEventCode
  2515. == EXIT_PROCESS_DEBUG_EVENT)
  2516. break;
  2517. }
  2518. target_mourn_inferior (inferior_ptid); /* Or just windows_mourn_inferior? */
  2519. }
  2520. void
  2521. windows_nat_target::close ()
  2522. {
  2523. DEBUG_EVENTS ("inferior_ptid=%d\n", inferior_ptid.pid ());
  2524. }
  2525. /* Convert pid to printable format. */
  2526. std::string
  2527. windows_nat_target::pid_to_str (ptid_t ptid)
  2528. {
  2529. if (ptid.lwp () != 0)
  2530. return string_printf ("Thread %d.0x%lx", ptid.pid (), ptid.lwp ());
  2531. return normal_pid_to_str (ptid);
  2532. }
  2533. static enum target_xfer_status
  2534. windows_xfer_shared_libraries (struct target_ops *ops,
  2535. enum target_object object, const char *annex,
  2536. gdb_byte *readbuf, const gdb_byte *writebuf,
  2537. ULONGEST offset, ULONGEST len,
  2538. ULONGEST *xfered_len)
  2539. {
  2540. auto_obstack obstack;
  2541. const char *buf;
  2542. LONGEST len_avail;
  2543. if (writebuf)
  2544. return TARGET_XFER_E_IO;
  2545. obstack_grow_str (&obstack, "<library-list>\n");
  2546. for (windows_solib &so : solibs)
  2547. windows_xfer_shared_library (so.name.c_str (),
  2548. (CORE_ADDR) (uintptr_t) so.load_addr,
  2549. &so.text_offset,
  2550. target_gdbarch (), &obstack);
  2551. obstack_grow_str0 (&obstack, "</library-list>\n");
  2552. buf = (const char *) obstack_finish (&obstack);
  2553. len_avail = strlen (buf);
  2554. if (offset >= len_avail)
  2555. len= 0;
  2556. else
  2557. {
  2558. if (len > len_avail - offset)
  2559. len = len_avail - offset;
  2560. memcpy (readbuf, buf + offset, len);
  2561. }
  2562. *xfered_len = (ULONGEST) len;
  2563. return len != 0 ? TARGET_XFER_OK : TARGET_XFER_EOF;
  2564. }
  2565. /* Helper for windows_nat_target::xfer_partial that handles signal info. */
  2566. static enum target_xfer_status
  2567. windows_xfer_siginfo (gdb_byte *readbuf, ULONGEST offset, ULONGEST len,
  2568. ULONGEST *xfered_len)
  2569. {
  2570. char *buf = (char *) &windows_process.siginfo_er;
  2571. size_t bufsize = sizeof (windows_process.siginfo_er);
  2572. #ifdef __x86_64__
  2573. EXCEPTION_RECORD32 er32;
  2574. if (windows_process.wow64_process)
  2575. {
  2576. buf = (char *) &er32;
  2577. bufsize = sizeof (er32);
  2578. er32.ExceptionCode = windows_process.siginfo_er.ExceptionCode;
  2579. er32.ExceptionFlags = windows_process.siginfo_er.ExceptionFlags;
  2580. er32.ExceptionRecord
  2581. = (uintptr_t) windows_process.siginfo_er.ExceptionRecord;
  2582. er32.ExceptionAddress
  2583. = (uintptr_t) windows_process.siginfo_er.ExceptionAddress;
  2584. er32.NumberParameters = windows_process.siginfo_er.NumberParameters;
  2585. int i;
  2586. for (i = 0; i < EXCEPTION_MAXIMUM_PARAMETERS; i++)
  2587. er32.ExceptionInformation[i]
  2588. = windows_process.siginfo_er.ExceptionInformation[i];
  2589. }
  2590. #endif
  2591. if (windows_process.siginfo_er.ExceptionCode == 0)
  2592. return TARGET_XFER_E_IO;
  2593. if (readbuf == nullptr)
  2594. return TARGET_XFER_E_IO;
  2595. if (offset > bufsize)
  2596. return TARGET_XFER_E_IO;
  2597. if (offset + len > bufsize)
  2598. len = bufsize - offset;
  2599. memcpy (readbuf, buf + offset, len);
  2600. *xfered_len = len;
  2601. return TARGET_XFER_OK;
  2602. }
  2603. enum target_xfer_status
  2604. windows_nat_target::xfer_partial (enum target_object object,
  2605. const char *annex, gdb_byte *readbuf,
  2606. const gdb_byte *writebuf, ULONGEST offset,
  2607. ULONGEST len, ULONGEST *xfered_len)
  2608. {
  2609. switch (object)
  2610. {
  2611. case TARGET_OBJECT_MEMORY:
  2612. return windows_xfer_memory (readbuf, writebuf, offset, len, xfered_len);
  2613. case TARGET_OBJECT_LIBRARIES:
  2614. return windows_xfer_shared_libraries (this, object, annex, readbuf,
  2615. writebuf, offset, len, xfered_len);
  2616. case TARGET_OBJECT_SIGNAL_INFO:
  2617. return windows_xfer_siginfo (readbuf, offset, len, xfered_len);
  2618. default:
  2619. if (beneath () == NULL)
  2620. {
  2621. /* This can happen when requesting the transfer of unsupported
  2622. objects before a program has been started (and therefore
  2623. with the current_target having no target beneath). */
  2624. return TARGET_XFER_E_IO;
  2625. }
  2626. return beneath ()->xfer_partial (object, annex,
  2627. readbuf, writebuf, offset, len,
  2628. xfered_len);
  2629. }
  2630. }
  2631. /* Provide thread local base, i.e. Thread Information Block address.
  2632. Returns 1 if ptid is found and sets *ADDR to thread_local_base. */
  2633. bool
  2634. windows_nat_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
  2635. {
  2636. windows_thread_info *th;
  2637. th = windows_process.thread_rec (ptid, DONT_INVALIDATE_CONTEXT);
  2638. if (th == NULL)
  2639. return false;
  2640. if (addr != NULL)
  2641. *addr = th->thread_local_base;
  2642. return true;
  2643. }
  2644. ptid_t
  2645. windows_nat_target::get_ada_task_ptid (long lwp, ULONGEST thread)
  2646. {
  2647. return ptid_t (inferior_ptid.pid (), lwp, 0);
  2648. }
  2649. /* Implementation of the to_thread_name method. */
  2650. const char *
  2651. windows_nat_target::thread_name (struct thread_info *thr)
  2652. {
  2653. return windows_process.thread_rec (thr->ptid,
  2654. DONT_INVALIDATE_CONTEXT)->name.get ();
  2655. }
  2656. void _initialize_windows_nat ();
  2657. void
  2658. _initialize_windows_nat ()
  2659. {
  2660. x86_dr_low.set_control = cygwin_set_dr7;
  2661. x86_dr_low.set_addr = cygwin_set_dr;
  2662. x86_dr_low.get_addr = cygwin_get_dr;
  2663. x86_dr_low.get_status = cygwin_get_dr6;
  2664. x86_dr_low.get_control = cygwin_get_dr7;
  2665. /* x86_dr_low.debug_register_length field is set by
  2666. calling x86_set_debug_register_length function
  2667. in processor windows specific native file. */
  2668. add_inf_child_target (&the_windows_nat_target);
  2669. #ifdef __CYGWIN__
  2670. cygwin_internal (CW_SET_DOS_FILE_WARNING, 0);
  2671. #endif
  2672. add_com ("signal-event", class_run, signal_event_command, _("\
  2673. Signal a crashed process with event ID, to allow its debugging.\n\
  2674. This command is needed in support of setting up GDB as JIT debugger on \
  2675. MS-Windows. The command should be invoked from the GDB command line using \
  2676. the '-ex' command-line option. The ID of the event that blocks the \
  2677. crashed process will be supplied by the Windows JIT debugging mechanism."));
  2678. #ifdef __CYGWIN__
  2679. add_setshow_boolean_cmd ("shell", class_support, &useshell, _("\
  2680. Set use of shell to start subprocess."), _("\
  2681. Show use of shell to start subprocess."), NULL,
  2682. NULL,
  2683. NULL, /* FIXME: i18n: */
  2684. &setlist, &showlist);
  2685. add_setshow_boolean_cmd ("cygwin-exceptions", class_support,
  2686. &cygwin_exceptions, _("\
  2687. Break when an exception is detected in the Cygwin DLL itself."), _("\
  2688. Show whether gdb breaks on exceptions in the Cygwin DLL itself."), NULL,
  2689. NULL,
  2690. NULL, /* FIXME: i18n: */
  2691. &setlist, &showlist);
  2692. #endif
  2693. add_setshow_boolean_cmd ("new-console", class_support, &new_console, _("\
  2694. Set creation of new console when creating child process."), _("\
  2695. Show creation of new console when creating child process."), NULL,
  2696. NULL,
  2697. NULL, /* FIXME: i18n: */
  2698. &setlist, &showlist);
  2699. add_setshow_boolean_cmd ("new-group", class_support, &new_group, _("\
  2700. Set creation of new group when creating child process."), _("\
  2701. Show creation of new group when creating child process."), NULL,
  2702. NULL,
  2703. NULL, /* FIXME: i18n: */
  2704. &setlist, &showlist);
  2705. add_setshow_boolean_cmd ("debugexec", class_support, &debug_exec, _("\
  2706. Set whether to display execution in child process."), _("\
  2707. Show whether to display execution in child process."), NULL,
  2708. NULL,
  2709. NULL, /* FIXME: i18n: */
  2710. &setlist, &showlist);
  2711. add_setshow_boolean_cmd ("debugevents", class_support, &debug_events, _("\
  2712. Set whether to display kernel events in child process."), _("\
  2713. Show whether to display kernel events in child process."), NULL,
  2714. NULL,
  2715. NULL, /* FIXME: i18n: */
  2716. &setlist, &showlist);
  2717. add_setshow_boolean_cmd ("debugmemory", class_support, &debug_memory, _("\
  2718. Set whether to display memory accesses in child process."), _("\
  2719. Show whether to display memory accesses in child process."), NULL,
  2720. NULL,
  2721. NULL, /* FIXME: i18n: */
  2722. &setlist, &showlist);
  2723. add_setshow_boolean_cmd ("debugexceptions", class_support,
  2724. &debug_exceptions, _("\
  2725. Set whether to display kernel exceptions in child process."), _("\
  2726. Show whether to display kernel exceptions in child process."), NULL,
  2727. NULL,
  2728. NULL, /* FIXME: i18n: */
  2729. &setlist, &showlist);
  2730. init_w32_command_list ();
  2731. add_cmd ("selector", class_info, display_selectors,
  2732. _("Display selectors infos."),
  2733. &info_w32_cmdlist);
  2734. if (!initialize_loadable ())
  2735. {
  2736. /* This will probably fail on Windows 9x/Me. Let the user know
  2737. that we're missing some functionality. */
  2738. warning(_("\
  2739. cannot automatically find executable file or library to read symbols.\n\
  2740. Use \"file\" or \"dll\" command to load executable/libraries directly."));
  2741. }
  2742. }
  2743. /* Hardware watchpoint support, adapted from go32-nat.c code. */
  2744. /* Pass the address ADDR to the inferior in the I'th debug register.
  2745. Here we just store the address in dr array, the registers will be
  2746. actually set up when windows_continue is called. */
  2747. static void
  2748. cygwin_set_dr (int i, CORE_ADDR addr)
  2749. {
  2750. if (i < 0 || i > 3)
  2751. internal_error (__FILE__, __LINE__,
  2752. _("Invalid register %d in cygwin_set_dr.\n"), i);
  2753. dr[i] = addr;
  2754. for (auto &th : thread_list)
  2755. th->debug_registers_changed = true;
  2756. }
  2757. /* Pass the value VAL to the inferior in the DR7 debug control
  2758. register. Here we just store the address in D_REGS, the watchpoint
  2759. will be actually set up in windows_wait. */
  2760. static void
  2761. cygwin_set_dr7 (unsigned long val)
  2762. {
  2763. dr[7] = (CORE_ADDR) val;
  2764. for (auto &th : thread_list)
  2765. th->debug_registers_changed = true;
  2766. }
  2767. /* Get the value of debug register I from the inferior. */
  2768. static CORE_ADDR
  2769. cygwin_get_dr (int i)
  2770. {
  2771. return dr[i];
  2772. }
  2773. /* Get the value of the DR6 debug status register from the inferior.
  2774. Here we just return the value stored in dr[6]
  2775. by the last call to thread_rec for current_event.dwThreadId id. */
  2776. static unsigned long
  2777. cygwin_get_dr6 (void)
  2778. {
  2779. return (unsigned long) dr[6];
  2780. }
  2781. /* Get the value of the DR7 debug status register from the inferior.
  2782. Here we just return the value stored in dr[7] by the last call to
  2783. thread_rec for current_event.dwThreadId id. */
  2784. static unsigned long
  2785. cygwin_get_dr7 (void)
  2786. {
  2787. return (unsigned long) dr[7];
  2788. }
  2789. /* Determine if the thread referenced by "ptid" is alive
  2790. by "polling" it. If WaitForSingleObject returns WAIT_OBJECT_0
  2791. it means that the thread has died. Otherwise it is assumed to be alive. */
  2792. bool
  2793. windows_nat_target::thread_alive (ptid_t ptid)
  2794. {
  2795. gdb_assert (ptid.lwp () != 0);
  2796. windows_thread_info *th
  2797. = windows_process.thread_rec (ptid, DONT_INVALIDATE_CONTEXT);
  2798. return WaitForSingleObject (th->h, 0) != WAIT_OBJECT_0;
  2799. }
  2800. void _initialize_check_for_gdb_ini ();
  2801. void
  2802. _initialize_check_for_gdb_ini ()
  2803. {
  2804. char *homedir;
  2805. if (inhibit_gdbinit)
  2806. return;
  2807. homedir = getenv ("HOME");
  2808. if (homedir)
  2809. {
  2810. char *p;
  2811. char *oldini = (char *) alloca (strlen (homedir) +
  2812. sizeof ("gdb.ini") + 1);
  2813. strcpy (oldini, homedir);
  2814. p = strchr (oldini, '\0');
  2815. if (p > oldini && !IS_DIR_SEPARATOR (p[-1]))
  2816. *p++ = '/';
  2817. strcpy (p, "gdb.ini");
  2818. if (access (oldini, 0) == 0)
  2819. {
  2820. int len = strlen (oldini);
  2821. char *newini = (char *) alloca (len + 2);
  2822. xsnprintf (newini, len + 2, "%.*s.gdbinit",
  2823. (int) (len - (sizeof ("gdb.ini") - 1)), oldini);
  2824. warning (_("obsolete '%s' found. Rename to '%s'."), oldini, newini);
  2825. }
  2826. }
  2827. }