darwin-nat.c 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495
  1. /* Darwin support for GDB, the GNU debugger.
  2. Copyright (C) 2008-2022 Free Software Foundation, Inc.
  3. Contributed by AdaCore.
  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. #include "defs.h"
  16. #include "top.h"
  17. #include "inferior.h"
  18. #include "target.h"
  19. #include "symfile.h"
  20. #include "symtab.h"
  21. #include "objfiles.h"
  22. #include "gdbcmd.h"
  23. #include "gdbcore.h"
  24. #include "gdbthread.h"
  25. #include "regcache.h"
  26. #include "event-top.h"
  27. #include "inf-loop.h"
  28. #include <sys/stat.h>
  29. #include "inf-child.h"
  30. #include "value.h"
  31. #include "arch-utils.h"
  32. #include "bfd.h"
  33. #include "bfd/mach-o.h"
  34. #include "gdbarch.h"
  35. #include <copyfile.h>
  36. #include <sys/ptrace.h>
  37. #include <sys/signal.h>
  38. #include <setjmp.h>
  39. #include <sys/types.h>
  40. #include <unistd.h>
  41. #include <signal.h>
  42. #include <ctype.h>
  43. #include <sys/sysctl.h>
  44. #include <sys/proc.h>
  45. #include <libproc.h>
  46. #include <sys/syscall.h>
  47. #include <spawn.h>
  48. #include <mach/mach_error.h>
  49. #include <mach/mach_vm.h>
  50. #include <mach/mach_init.h>
  51. #include <mach/vm_map.h>
  52. #include <mach/task.h>
  53. #include <mach/mach_port.h>
  54. #include <mach/thread_act.h>
  55. #include <mach/port.h>
  56. #include "darwin-nat.h"
  57. #include "filenames.h"
  58. #include "gdbsupport/filestuff.h"
  59. #include "gdbsupport/gdb_unlinker.h"
  60. #include "gdbsupport/pathstuff.h"
  61. #include "gdbsupport/scoped_fd.h"
  62. #include "nat/fork-inferior.h"
  63. /* Quick overview.
  64. Darwin kernel is Mach + BSD derived kernel. Note that they share the
  65. same memory space and are linked together (ie there is no micro-kernel).
  66. Although ptrace(2) is available on Darwin, it is not complete. We have
  67. to use Mach calls to read and write memory and to modify registers. We
  68. also use Mach to get inferior faults. As we cannot use select(2) or
  69. signals with Mach port (the Mach communication channel), signals are
  70. reported to gdb as an exception. Furthermore we detect death of the
  71. inferior through a Mach notification message. This way we only wait
  72. on Mach ports.
  73. Some Mach documentation is available for Apple xnu source package or
  74. from the web. */
  75. #define PTRACE(CMD, PID, ADDR, SIG) \
  76. darwin_ptrace(#CMD, CMD, (PID), (ADDR), (SIG))
  77. static void darwin_ptrace_me (void);
  78. static void darwin_encode_reply (mig_reply_error_t *reply,
  79. mach_msg_header_t *hdr, integer_t code);
  80. static void darwin_setup_request_notification (struct inferior *inf);
  81. static void darwin_deallocate_exception_ports (darwin_inferior *inf);
  82. static void darwin_setup_exceptions (struct inferior *inf);
  83. static void darwin_deallocate_threads (struct inferior *inf);
  84. /* Task identifier of gdb. */
  85. static task_t gdb_task;
  86. /* A copy of mach_host_self (). */
  87. mach_port_t darwin_host_self;
  88. /* Exception port. */
  89. mach_port_t darwin_ex_port;
  90. /* Port set, to wait for answer on all ports. */
  91. mach_port_t darwin_port_set;
  92. /* Page size. */
  93. static vm_size_t mach_page_size;
  94. /* If Set, catch all mach exceptions (before they are converted to signals
  95. by the kernel). */
  96. static bool enable_mach_exceptions;
  97. /* Inferior that should report a fake stop event. */
  98. static struct inferior *darwin_inf_fake_stop;
  99. /* If non-NULL, the shell we actually invoke. See maybe_cache_shell
  100. for details. */
  101. static const char *copied_shell;
  102. #define PAGE_TRUNC(x) ((x) & ~(mach_page_size - 1))
  103. #define PAGE_ROUND(x) PAGE_TRUNC((x) + mach_page_size - 1)
  104. /* This controls output of inferior debugging. */
  105. static unsigned int darwin_debug_flag = 0;
  106. /* Create a __TEXT __info_plist section in the executable so that gdb could
  107. be signed. This is required to get an authorization for task_for_pid.
  108. Once gdb is built, you must codesign it with any system-trusted signing
  109. authority. See taskgated(8) for details. */
  110. static const unsigned char info_plist[]
  111. __attribute__ ((section ("__TEXT,__info_plist"),used)) =
  112. "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
  113. "<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\""
  114. " \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
  115. "<plist version=\"1.0\">\n"
  116. "<dict>\n"
  117. " <key>CFBundleIdentifier</key>\n"
  118. " <string>org.gnu.gdb</string>\n"
  119. " <key>CFBundleName</key>\n"
  120. " <string>gdb</string>\n"
  121. " <key>CFBundleVersion</key>\n"
  122. " <string>1.0</string>\n"
  123. " <key>SecTaskAccess</key>\n"
  124. " <array>\n"
  125. " <string>allowed</string>\n"
  126. " <string>debug</string>\n"
  127. " </array>\n"
  128. "</dict>\n"
  129. "</plist>\n";
  130. static void inferior_debug (int level, const char *fmt, ...)
  131. ATTRIBUTE_PRINTF (2, 3);
  132. static void
  133. inferior_debug (int level, const char *fmt, ...)
  134. {
  135. va_list ap;
  136. if (darwin_debug_flag < level)
  137. return;
  138. va_start (ap, fmt);
  139. gdb_printf (gdb_stdlog, _("[%d inferior]: "), getpid ());
  140. gdb_vprintf (gdb_stdlog, fmt, ap);
  141. va_end (ap);
  142. }
  143. void
  144. mach_check_error (kern_return_t ret, const char *file,
  145. unsigned int line, const char *func)
  146. {
  147. if (ret == KERN_SUCCESS)
  148. return;
  149. if (func == NULL)
  150. func = _("[UNKNOWN]");
  151. warning (_("Mach error at \"%s:%u\" in function \"%s\": %s (0x%lx)"),
  152. file, line, func, mach_error_string (ret), (unsigned long) ret);
  153. }
  154. static const char *
  155. unparse_exception_type (unsigned int i)
  156. {
  157. static char unknown_exception_buf[32];
  158. switch (i)
  159. {
  160. case EXC_BAD_ACCESS:
  161. return "EXC_BAD_ACCESS";
  162. case EXC_BAD_INSTRUCTION:
  163. return "EXC_BAD_INSTRUCTION";
  164. case EXC_ARITHMETIC:
  165. return "EXC_ARITHMETIC";
  166. case EXC_EMULATION:
  167. return "EXC_EMULATION";
  168. case EXC_SOFTWARE:
  169. return "EXC_SOFTWARE";
  170. case EXC_BREAKPOINT:
  171. return "EXC_BREAKPOINT";
  172. case EXC_SYSCALL:
  173. return "EXC_SYSCALL";
  174. case EXC_MACH_SYSCALL:
  175. return "EXC_MACH_SYSCALL";
  176. case EXC_RPC_ALERT:
  177. return "EXC_RPC_ALERT";
  178. case EXC_CRASH:
  179. return "EXC_CRASH";
  180. default:
  181. snprintf (unknown_exception_buf, 32, _("unknown (%d)"), i);
  182. return unknown_exception_buf;
  183. }
  184. }
  185. /* Set errno to zero, and then call ptrace with the given arguments.
  186. If inferior debugging traces are on, then also print a debug
  187. trace.
  188. The returned value is the same as the value returned by ptrace,
  189. except in the case where that value is -1 but errno is zero.
  190. This case is documented to be a non-error situation, so we
  191. return zero in that case. */
  192. static int
  193. darwin_ptrace (const char *name,
  194. int request, int pid, caddr_t arg3, int arg4)
  195. {
  196. int ret;
  197. errno = 0;
  198. ret = ptrace (request, pid, arg3, arg4);
  199. if (ret == -1 && errno == 0)
  200. ret = 0;
  201. inferior_debug (4, _("ptrace (%s, %d, 0x%lx, %d): %d (%s)\n"),
  202. name, pid, (unsigned long) arg3, arg4, ret,
  203. (ret != 0) ? safe_strerror (errno) : _("no error"));
  204. return ret;
  205. }
  206. static int
  207. cmp_thread_t (const void *l, const void *r)
  208. {
  209. thread_t tl = *(const thread_t *)l;
  210. thread_t tr = *(const thread_t *)r;
  211. return (int)(tl - tr);
  212. }
  213. void
  214. darwin_nat_target::check_new_threads (inferior *inf)
  215. {
  216. kern_return_t kret;
  217. thread_array_t thread_list;
  218. unsigned int new_nbr;
  219. unsigned int old_nbr;
  220. unsigned int new_ix, old_ix;
  221. darwin_inferior *darwin_inf = get_darwin_inferior (inf);
  222. std::vector<darwin_thread_t *> new_thread_vec;
  223. if (darwin_inf == nullptr)
  224. return;
  225. /* Get list of threads. */
  226. kret = task_threads (darwin_inf->task, &thread_list, &new_nbr);
  227. MACH_CHECK_ERROR (kret);
  228. if (kret != KERN_SUCCESS)
  229. return;
  230. /* Sort the list. */
  231. if (new_nbr > 1)
  232. qsort (thread_list, new_nbr, sizeof (thread_t), cmp_thread_t);
  233. old_nbr = darwin_inf->threads.size ();
  234. /* Quick check for no changes. */
  235. if (old_nbr == new_nbr)
  236. {
  237. size_t i;
  238. for (i = 0; i < new_nbr; i++)
  239. if (thread_list[i] != darwin_inf->threads[i]->gdb_port)
  240. break;
  241. if (i == new_nbr)
  242. {
  243. /* Deallocate ports. */
  244. for (i = 0; i < new_nbr; i++)
  245. {
  246. kret = mach_port_deallocate (mach_task_self (), thread_list[i]);
  247. MACH_CHECK_ERROR (kret);
  248. }
  249. /* Deallocate the buffer. */
  250. kret = vm_deallocate (gdb_task, (vm_address_t) thread_list,
  251. new_nbr * sizeof (int));
  252. MACH_CHECK_ERROR (kret);
  253. return;
  254. }
  255. }
  256. /* Full handling: detect new threads, remove dead threads. */
  257. new_thread_vec.reserve (new_nbr);
  258. for (new_ix = 0, old_ix = 0; new_ix < new_nbr || old_ix < old_nbr;)
  259. {
  260. thread_t new_id = (new_ix < new_nbr) ? thread_list[new_ix] : THREAD_NULL;
  261. darwin_thread_t *old
  262. = (old_ix < old_nbr) ? darwin_inf->threads[old_ix] : NULL;
  263. thread_t old_id = old != NULL ? old->gdb_port : THREAD_NULL;
  264. inferior_debug
  265. (12, _(" new_ix:%d/%d, old_ix:%d/%d, new_id:0x%x old_id:0x%x\n"),
  266. new_ix, new_nbr, old_ix, old_nbr, new_id, old_id);
  267. if (old_id == new_id)
  268. {
  269. /* Thread still exist. */
  270. new_thread_vec.push_back (old);
  271. new_ix++;
  272. old_ix++;
  273. /* Deallocate the port. */
  274. kret = mach_port_deallocate (gdb_task, new_id);
  275. MACH_CHECK_ERROR (kret);
  276. continue;
  277. }
  278. if (new_ix < new_nbr && new_id == MACH_PORT_DEAD)
  279. {
  280. /* Ignore dead ports.
  281. In some weird cases, we might get dead ports. They should
  282. correspond to dead thread so they could safely be ignored. */
  283. new_ix++;
  284. continue;
  285. }
  286. if (new_ix < new_nbr && (old_ix == old_nbr || new_id < old_id))
  287. {
  288. /* A thread was created. */
  289. darwin_thread_info *pti = new darwin_thread_info;
  290. pti->gdb_port = new_id;
  291. pti->msg_state = DARWIN_RUNNING;
  292. /* Add the new thread. */
  293. add_thread_with_info (this, ptid_t (inf->pid, 0, new_id), pti);
  294. new_thread_vec.push_back (pti);
  295. new_ix++;
  296. continue;
  297. }
  298. if (old_ix < old_nbr && (new_ix == new_nbr || new_id > old_id))
  299. {
  300. /* A thread was removed. */
  301. struct thread_info *thr
  302. = find_thread_ptid (this, ptid_t (inf->pid, 0, old_id));
  303. delete_thread (thr);
  304. kret = mach_port_deallocate (gdb_task, old_id);
  305. MACH_CHECK_ERROR (kret);
  306. old_ix++;
  307. continue;
  308. }
  309. gdb_assert_not_reached ("unexpected thread case");
  310. }
  311. darwin_inf->threads = std::move (new_thread_vec);
  312. /* Deallocate the buffer. */
  313. kret = vm_deallocate (gdb_task, (vm_address_t) thread_list,
  314. new_nbr * sizeof (int));
  315. MACH_CHECK_ERROR (kret);
  316. }
  317. /* Return an inferior by task port. */
  318. static struct inferior *
  319. darwin_find_inferior_by_task (task_t port)
  320. {
  321. for (inferior *inf : all_inferiors ())
  322. {
  323. darwin_inferior *priv = get_darwin_inferior (inf);
  324. if (priv != nullptr && priv->task == port)
  325. return inf;
  326. }
  327. return nullptr;
  328. }
  329. /* Return an inferior by pid port. */
  330. static struct inferior *
  331. darwin_find_inferior_by_pid (int pid)
  332. {
  333. for (inferior *inf : all_inferiors ())
  334. {
  335. if (inf->pid == pid)
  336. return inf;
  337. }
  338. return nullptr;
  339. }
  340. /* Return a thread by port. */
  341. static darwin_thread_t *
  342. darwin_find_thread (struct inferior *inf, thread_t thread)
  343. {
  344. darwin_inferior *priv = get_darwin_inferior (inf);
  345. if (priv != nullptr)
  346. for (darwin_thread_t *t : priv->threads)
  347. {
  348. if (t->gdb_port == thread)
  349. return t;
  350. }
  351. return NULL;
  352. }
  353. /* Suspend (ie stop) an inferior at Mach level. */
  354. static void
  355. darwin_suspend_inferior (struct inferior *inf)
  356. {
  357. darwin_inferior *priv = get_darwin_inferior (inf);
  358. if (priv != nullptr && !priv->suspended)
  359. {
  360. kern_return_t kret;
  361. kret = task_suspend (priv->task);
  362. MACH_CHECK_ERROR (kret);
  363. priv->suspended = 1;
  364. }
  365. }
  366. /* Resume an inferior at Mach level. */
  367. static void
  368. darwin_resume_inferior (struct inferior *inf)
  369. {
  370. darwin_inferior *priv = get_darwin_inferior (inf);
  371. if (priv != nullptr && priv->suspended)
  372. {
  373. kern_return_t kret;
  374. kret = task_resume (priv->task);
  375. MACH_CHECK_ERROR (kret);
  376. priv->suspended = 0;
  377. }
  378. }
  379. static void
  380. darwin_dump_message (mach_msg_header_t *hdr, int disp_body)
  381. {
  382. gdb_printf (gdb_stdlog,
  383. _("message header:\n"));
  384. gdb_printf (gdb_stdlog,
  385. _(" bits: 0x%x\n"), hdr->msgh_bits);
  386. gdb_printf (gdb_stdlog,
  387. _(" size: 0x%x\n"), hdr->msgh_size);
  388. gdb_printf (gdb_stdlog,
  389. _(" remote-port: 0x%x\n"), hdr->msgh_remote_port);
  390. gdb_printf (gdb_stdlog,
  391. _(" local-port: 0x%x\n"), hdr->msgh_local_port);
  392. gdb_printf (gdb_stdlog,
  393. _(" reserved: 0x%x\n"), hdr->msgh_reserved);
  394. gdb_printf (gdb_stdlog,
  395. _(" id: 0x%x\n"), hdr->msgh_id);
  396. if (disp_body)
  397. {
  398. const unsigned char *data;
  399. const unsigned int *ldata;
  400. int size;
  401. int i;
  402. data = (unsigned char *)(hdr + 1);
  403. size = hdr->msgh_size - sizeof (mach_msg_header_t);
  404. if (hdr->msgh_bits & MACH_MSGH_BITS_COMPLEX)
  405. {
  406. mach_msg_body_t *bod = (mach_msg_body_t*)data;
  407. mach_msg_port_descriptor_t *desc =
  408. (mach_msg_port_descriptor_t *)(bod + 1);
  409. int k;
  410. NDR_record_t *ndr;
  411. gdb_printf (gdb_stdlog,
  412. _("body: descriptor_count=%u\n"),
  413. bod->msgh_descriptor_count);
  414. data += sizeof (mach_msg_body_t);
  415. size -= sizeof (mach_msg_body_t);
  416. for (k = 0; k < bod->msgh_descriptor_count; k++)
  417. switch (desc[k].type)
  418. {
  419. case MACH_MSG_PORT_DESCRIPTOR:
  420. gdb_printf
  421. (gdb_stdlog,
  422. _(" descr %d: type=%u (port) name=0x%x, dispo=%d\n"),
  423. k, desc[k].type, desc[k].name, desc[k].disposition);
  424. break;
  425. default:
  426. gdb_printf (gdb_stdlog,
  427. _(" descr %d: type=%u\n"),
  428. k, desc[k].type);
  429. break;
  430. }
  431. data += bod->msgh_descriptor_count
  432. * sizeof (mach_msg_port_descriptor_t);
  433. size -= bod->msgh_descriptor_count
  434. * sizeof (mach_msg_port_descriptor_t);
  435. ndr = (NDR_record_t *)(desc + bod->msgh_descriptor_count);
  436. gdb_printf
  437. (gdb_stdlog,
  438. _("NDR: mig=%02x if=%02x encod=%02x "
  439. "int=%02x char=%02x float=%02x\n"),
  440. ndr->mig_vers, ndr->if_vers, ndr->mig_encoding,
  441. ndr->int_rep, ndr->char_rep, ndr->float_rep);
  442. data += sizeof (NDR_record_t);
  443. size -= sizeof (NDR_record_t);
  444. }
  445. gdb_printf (gdb_stdlog, _(" data:"));
  446. ldata = (const unsigned int *)data;
  447. for (i = 0; i < size / sizeof (unsigned int); i++)
  448. gdb_printf (gdb_stdlog, " %08x", ldata[i]);
  449. gdb_printf (gdb_stdlog, _("\n"));
  450. }
  451. }
  452. /* Adjust inferior data when a new task was created. */
  453. static struct inferior *
  454. darwin_find_new_inferior (task_t task_port, thread_t thread_port)
  455. {
  456. int task_pid;
  457. struct inferior *inf;
  458. kern_return_t kret;
  459. mach_port_t prev;
  460. /* Find the corresponding pid. */
  461. kret = pid_for_task (task_port, &task_pid);
  462. if (kret != KERN_SUCCESS)
  463. {
  464. MACH_CHECK_ERROR (kret);
  465. return NULL;
  466. }
  467. /* Find the inferior for this pid. */
  468. inf = darwin_find_inferior_by_pid (task_pid);
  469. if (inf == NULL)
  470. return NULL;
  471. darwin_inferior *priv = get_darwin_inferior (inf);
  472. /* Deallocate saved exception ports. */
  473. darwin_deallocate_exception_ports (priv);
  474. /* No need to remove dead_name notification, but still... */
  475. kret = mach_port_request_notification (gdb_task, priv->task,
  476. MACH_NOTIFY_DEAD_NAME, 0,
  477. MACH_PORT_NULL,
  478. MACH_MSG_TYPE_MAKE_SEND_ONCE,
  479. &prev);
  480. if (kret != KERN_INVALID_ARGUMENT)
  481. MACH_CHECK_ERROR (kret);
  482. /* Replace old task port. */
  483. kret = mach_port_deallocate (gdb_task, priv->task);
  484. MACH_CHECK_ERROR (kret);
  485. priv->task = task_port;
  486. darwin_setup_request_notification (inf);
  487. darwin_setup_exceptions (inf);
  488. return inf;
  489. }
  490. /* Check data representation. */
  491. static int
  492. darwin_check_message_ndr (NDR_record_t *ndr)
  493. {
  494. if (ndr->mig_vers != NDR_PROTOCOL_2_0
  495. || ndr->if_vers != NDR_PROTOCOL_2_0
  496. || ndr->mig_encoding != NDR_record.mig_encoding
  497. || ndr->int_rep != NDR_record.int_rep
  498. || ndr->char_rep != NDR_record.char_rep
  499. || ndr->float_rep != NDR_record.float_rep)
  500. return -1;
  501. return 0;
  502. }
  503. /* Decode an exception message. */
  504. int
  505. darwin_nat_target::decode_exception_message (mach_msg_header_t *hdr,
  506. inferior **pinf,
  507. darwin_thread_t **pthread)
  508. {
  509. mach_msg_body_t *bod = (mach_msg_body_t*)(hdr + 1);
  510. mach_msg_port_descriptor_t *desc = (mach_msg_port_descriptor_t *)(bod + 1);
  511. NDR_record_t *ndr;
  512. integer_t *data;
  513. struct inferior *inf;
  514. darwin_thread_t *thread;
  515. task_t task_port;
  516. thread_t thread_port;
  517. kern_return_t kret;
  518. int i;
  519. /* Check message destination. */
  520. if (hdr->msgh_local_port != darwin_ex_port)
  521. return -1;
  522. /* Check message header. */
  523. if (!(hdr->msgh_bits & MACH_MSGH_BITS_COMPLEX))
  524. return -1;
  525. /* Check descriptors. */
  526. if (hdr->msgh_size < (sizeof (*hdr) + sizeof (*bod) + 2 * sizeof (*desc)
  527. + sizeof (*ndr) + 2 * sizeof (integer_t))
  528. || bod->msgh_descriptor_count != 2
  529. || desc[0].type != MACH_MSG_PORT_DESCRIPTOR
  530. || desc[0].disposition != MACH_MSG_TYPE_MOVE_SEND
  531. || desc[1].type != MACH_MSG_PORT_DESCRIPTOR
  532. || desc[1].disposition != MACH_MSG_TYPE_MOVE_SEND)
  533. return -1;
  534. /* Check data representation. */
  535. ndr = (NDR_record_t *)(desc + 2);
  536. if (darwin_check_message_ndr (ndr) != 0)
  537. return -1;
  538. /* Ok, the hard work. */
  539. data = (integer_t *)(ndr + 1);
  540. task_port = desc[1].name;
  541. thread_port = desc[0].name;
  542. /* Find process by port. */
  543. inf = darwin_find_inferior_by_task (task_port);
  544. *pinf = inf;
  545. if (inf == NULL && data[0] == EXC_SOFTWARE && data[1] == 2
  546. && data[2] == EXC_SOFT_SIGNAL && data[3] == SIGTRAP)
  547. {
  548. /* Not a known inferior, but a sigtrap. This happens on darwin 16.1.0,
  549. as a new Mach task is created when a process exec. */
  550. inf = darwin_find_new_inferior (task_port, thread_port);
  551. *pinf = inf;
  552. if (inf == NULL)
  553. {
  554. /* Deallocate task_port, unless it was saved. */
  555. kret = mach_port_deallocate (mach_task_self (), task_port);
  556. MACH_CHECK_ERROR (kret);
  557. }
  558. }
  559. else
  560. {
  561. /* We got new rights to the task, get rid of it. Do not get rid of
  562. thread right, as we will need it to find the thread. */
  563. kret = mach_port_deallocate (mach_task_self (), task_port);
  564. MACH_CHECK_ERROR (kret);
  565. }
  566. if (inf == NULL)
  567. {
  568. /* Not a known inferior. This could happen if the child fork, as
  569. the created process will inherit its exception port.
  570. FIXME: should the exception port be restored ? */
  571. mig_reply_error_t reply;
  572. inferior_debug
  573. (4, _("darwin_decode_exception_message: unknown task 0x%x\n"),
  574. task_port);
  575. /* Free thread port (we don't know it). */
  576. kret = mach_port_deallocate (mach_task_self (), thread_port);
  577. MACH_CHECK_ERROR (kret);
  578. darwin_encode_reply (&reply, hdr, KERN_SUCCESS);
  579. kret = mach_msg (&reply.Head, MACH_SEND_MSG | MACH_SEND_INTERRUPT,
  580. reply.Head.msgh_size, 0,
  581. MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE,
  582. MACH_PORT_NULL);
  583. MACH_CHECK_ERROR (kret);
  584. return 0;
  585. }
  586. /* Find thread by port. */
  587. /* Check for new threads. Do it early so that the port in the exception
  588. message can be deallocated. */
  589. check_new_threads (inf);
  590. /* Free the thread port (as gdb knows the thread, it has already has a right
  591. for it, so this just decrement a reference counter). */
  592. kret = mach_port_deallocate (mach_task_self (), thread_port);
  593. MACH_CHECK_ERROR (kret);
  594. thread = darwin_find_thread (inf, thread_port);
  595. if (thread == NULL)
  596. return -1;
  597. *pthread = thread;
  598. /* The thread should be running. However we have observed cases where a
  599. thread got a SIGTTIN message after being stopped. */
  600. gdb_assert (thread->msg_state != DARWIN_MESSAGE);
  601. /* Finish decoding. */
  602. thread->event.header = *hdr;
  603. thread->event.thread_port = thread_port;
  604. thread->event.task_port = task_port;
  605. thread->event.ex_type = data[0];
  606. thread->event.data_count = data[1];
  607. if (hdr->msgh_size < (sizeof (*hdr) + sizeof (*bod) + 2 * sizeof (*desc)
  608. + sizeof (*ndr) + 2 * sizeof (integer_t)
  609. + data[1] * sizeof (integer_t)))
  610. return -1;
  611. for (i = 0; i < data[1]; i++)
  612. thread->event.ex_data[i] = data[2 + i];
  613. thread->msg_state = DARWIN_MESSAGE;
  614. return 0;
  615. }
  616. /* Decode dead_name notify message. */
  617. static int
  618. darwin_decode_notify_message (mach_msg_header_t *hdr, struct inferior **pinf)
  619. {
  620. NDR_record_t *ndr = (NDR_record_t *)(hdr + 1);
  621. integer_t *data = (integer_t *)(ndr + 1);
  622. struct inferior *inf;
  623. task_t task_port;
  624. /* Check message header. */
  625. if (hdr->msgh_bits & MACH_MSGH_BITS_COMPLEX)
  626. return -1;
  627. /* Check descriptors. */
  628. if (hdr->msgh_size < (sizeof (*hdr) + sizeof (*ndr) + sizeof (integer_t)))
  629. return -2;
  630. /* Check data representation. */
  631. if (darwin_check_message_ndr (ndr) != 0)
  632. return -3;
  633. task_port = data[0];
  634. /* Find process by port. */
  635. inf = darwin_find_inferior_by_task (task_port);
  636. *pinf = inf;
  637. /* Check message destination. */
  638. if (inf != NULL)
  639. {
  640. darwin_inferior *priv = get_darwin_inferior (inf);
  641. if (hdr->msgh_local_port != priv->notify_port)
  642. return -4;
  643. }
  644. return 0;
  645. }
  646. static void
  647. darwin_encode_reply (mig_reply_error_t *reply, mach_msg_header_t *hdr,
  648. integer_t code)
  649. {
  650. mach_msg_header_t *rh = &reply->Head;
  651. rh->msgh_bits = MACH_MSGH_BITS (MACH_MSGH_BITS_REMOTE (hdr->msgh_bits), 0);
  652. rh->msgh_remote_port = hdr->msgh_remote_port;
  653. rh->msgh_size = (mach_msg_size_t) sizeof (mig_reply_error_t);
  654. rh->msgh_local_port = MACH_PORT_NULL;
  655. rh->msgh_id = hdr->msgh_id + 100;
  656. reply->NDR = NDR_record;
  657. reply->RetCode = code;
  658. }
  659. static void
  660. darwin_send_reply (struct inferior *inf, darwin_thread_t *thread)
  661. {
  662. kern_return_t kret;
  663. mig_reply_error_t reply;
  664. darwin_inferior *priv = get_darwin_inferior (inf);
  665. darwin_encode_reply (&reply, &thread->event.header, KERN_SUCCESS);
  666. kret = mach_msg (&reply.Head, MACH_SEND_MSG | MACH_SEND_INTERRUPT,
  667. reply.Head.msgh_size, 0,
  668. MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE,
  669. MACH_PORT_NULL);
  670. MACH_CHECK_ERROR (kret);
  671. priv->pending_messages--;
  672. }
  673. /* Wrapper around the __pthread_kill syscall. We use this instead of the
  674. pthread_kill function to be able to send a signal to any kind of thread,
  675. including GCD threads. */
  676. static int
  677. darwin_pthread_kill (darwin_thread_t *thread, int nsignal)
  678. {
  679. DIAGNOSTIC_PUSH;
  680. DIAGNOSTIC_IGNORE_DEPRECATED_DECLARATIONS;
  681. int res = syscall (SYS___pthread_kill, thread->gdb_port, nsignal);
  682. DIAGNOSTIC_POP;
  683. return res;
  684. }
  685. static void
  686. darwin_resume_thread (struct inferior *inf, darwin_thread_t *thread,
  687. int step, int nsignal)
  688. {
  689. inferior_debug
  690. (3, _("darwin_resume_thread: state=%d, thread=0x%x, step=%d nsignal=%d\n"),
  691. thread->msg_state, thread->gdb_port, step, nsignal);
  692. switch (thread->msg_state)
  693. {
  694. case DARWIN_MESSAGE:
  695. if (thread->event.ex_type == EXC_SOFTWARE
  696. && thread->event.ex_data[0] == EXC_SOFT_SIGNAL)
  697. {
  698. /* Either deliver a new signal or cancel the signal received. */
  699. int res = PTRACE (PT_THUPDATE, inf->pid,
  700. (caddr_t) (uintptr_t) thread->gdb_port, nsignal);
  701. if (res < 0)
  702. inferior_debug (1, _("ptrace THUP: res=%d\n"), res);
  703. }
  704. else if (nsignal)
  705. {
  706. /* Note: ptrace is allowed only if the process is stopped.
  707. Directly send the signal to the thread. */
  708. int res = darwin_pthread_kill (thread, nsignal);
  709. inferior_debug (4, _("darwin_resume_thread: kill 0x%x %d: %d\n"),
  710. thread->gdb_port, nsignal, res);
  711. thread->signaled = 1;
  712. }
  713. /* Set or reset single step. */
  714. inferior_debug (4, _("darwin_set_sstep (thread=0x%x, enable=%d)\n"),
  715. thread->gdb_port, step);
  716. darwin_set_sstep (thread->gdb_port, step);
  717. thread->single_step = step;
  718. darwin_send_reply (inf, thread);
  719. thread->msg_state = DARWIN_RUNNING;
  720. break;
  721. case DARWIN_RUNNING:
  722. break;
  723. case DARWIN_STOPPED:
  724. kern_return_t kret = thread_resume (thread->gdb_port);
  725. MACH_CHECK_ERROR (kret);
  726. thread->msg_state = DARWIN_RUNNING;
  727. break;
  728. }
  729. }
  730. /* Resume all threads of the inferior. */
  731. static void
  732. darwin_resume_inferior_threads (struct inferior *inf, int step, int nsignal)
  733. {
  734. darwin_inferior *priv = get_darwin_inferior (inf);
  735. if (priv != nullptr)
  736. for (darwin_thread_t *thread : priv->threads)
  737. darwin_resume_thread (inf, thread, step, nsignal);
  738. }
  739. /* Suspend all threads of INF. */
  740. static void
  741. darwin_suspend_inferior_threads (struct inferior *inf)
  742. {
  743. darwin_inferior *priv = get_darwin_inferior (inf);
  744. for (darwin_thread_t *thread : priv->threads)
  745. {
  746. switch (thread->msg_state)
  747. {
  748. case DARWIN_STOPPED:
  749. case DARWIN_MESSAGE:
  750. break;
  751. case DARWIN_RUNNING:
  752. {
  753. kern_return_t kret = thread_suspend (thread->gdb_port);
  754. MACH_CHECK_ERROR (kret);
  755. thread->msg_state = DARWIN_STOPPED;
  756. break;
  757. }
  758. }
  759. }
  760. }
  761. void
  762. darwin_nat_target::resume (ptid_t ptid, int step, enum gdb_signal signal)
  763. {
  764. int nsignal;
  765. inferior_debug
  766. (2, _("darwin_resume: ptid=%s, step=%d, signal=%d\n"),
  767. ptid.to_string ().c_str (), step, signal);
  768. if (signal == GDB_SIGNAL_0)
  769. nsignal = 0;
  770. else
  771. nsignal = gdb_signal_to_host (signal);
  772. /* Don't try to single step all threads. */
  773. if (step)
  774. ptid = inferior_ptid;
  775. /* minus_one_ptid is RESUME_ALL. */
  776. if (ptid == minus_one_ptid)
  777. {
  778. /* Resume threads. */
  779. for (inferior *inf : all_inferiors ())
  780. darwin_resume_inferior_threads (inf, step, nsignal);
  781. /* Resume tasks. */
  782. for (inferior *inf : all_inferiors ())
  783. darwin_resume_inferior (inf);
  784. }
  785. else
  786. {
  787. inferior *inf = find_inferior_ptid (this, ptid);
  788. long tid = ptid.tid ();
  789. /* Stop the inferior (should be useless). */
  790. darwin_suspend_inferior (inf);
  791. if (tid == 0)
  792. darwin_resume_inferior_threads (inf, step, nsignal);
  793. else
  794. {
  795. darwin_thread_t *thread;
  796. /* Suspend threads of the task. */
  797. darwin_suspend_inferior_threads (inf);
  798. /* Resume the selected thread. */
  799. thread = darwin_find_thread (inf, tid);
  800. gdb_assert (thread);
  801. darwin_resume_thread (inf, thread, step, nsignal);
  802. }
  803. /* Resume the task. */
  804. darwin_resume_inferior (inf);
  805. }
  806. }
  807. ptid_t
  808. darwin_nat_target::decode_message (mach_msg_header_t *hdr,
  809. darwin_thread_t **pthread,
  810. inferior **pinf,
  811. target_waitstatus *status)
  812. {
  813. darwin_thread_t *thread;
  814. struct inferior *inf;
  815. /* Exception message. 2401 == 0x961 is exc. */
  816. if (hdr->msgh_id == 2401)
  817. {
  818. int res;
  819. /* Decode message. */
  820. res = decode_exception_message (hdr, &inf, &thread);
  821. if (res < 0)
  822. {
  823. /* Should not happen... */
  824. warning (_("darwin_wait: ill-formatted message (id=0x%x)\n"),
  825. hdr->msgh_id);
  826. /* FIXME: send a failure reply? */
  827. status->set_ignore ();
  828. return minus_one_ptid;
  829. }
  830. if (inf == NULL)
  831. {
  832. status->set_ignore ();
  833. return minus_one_ptid;
  834. }
  835. *pinf = inf;
  836. *pthread = thread;
  837. darwin_inferior *priv = get_darwin_inferior (inf);
  838. priv->pending_messages++;
  839. thread->msg_state = DARWIN_MESSAGE;
  840. inferior_debug (4, _("darwin_wait: thread=0x%x, got %s\n"),
  841. thread->gdb_port,
  842. unparse_exception_type (thread->event.ex_type));
  843. switch (thread->event.ex_type)
  844. {
  845. case EXC_BAD_ACCESS:
  846. status->set_stopped (GDB_EXC_BAD_ACCESS);
  847. break;
  848. case EXC_BAD_INSTRUCTION:
  849. status->set_stopped (GDB_EXC_BAD_INSTRUCTION);
  850. break;
  851. case EXC_ARITHMETIC:
  852. status->set_stopped (GDB_EXC_ARITHMETIC);
  853. break;
  854. case EXC_EMULATION:
  855. status->set_stopped (GDB_EXC_EMULATION);
  856. break;
  857. case EXC_SOFTWARE:
  858. if (thread->event.ex_data[0] == EXC_SOFT_SIGNAL)
  859. {
  860. status->set_stopped
  861. (gdb_signal_from_host (thread->event.ex_data[1]));
  862. inferior_debug (5, _(" (signal %d: %s)\n"),
  863. thread->event.ex_data[1],
  864. gdb_signal_to_name (status->sig ()));
  865. /* If the thread is stopped because it has received a signal
  866. that gdb has just sent, continue. */
  867. if (thread->signaled)
  868. {
  869. thread->signaled = 0;
  870. darwin_send_reply (inf, thread);
  871. thread->msg_state = DARWIN_RUNNING;
  872. status->set_ignore ();
  873. }
  874. }
  875. else
  876. status->set_stopped (GDB_EXC_SOFTWARE);
  877. break;
  878. case EXC_BREAKPOINT:
  879. /* Many internal GDB routines expect breakpoints to be reported
  880. as GDB_SIGNAL_TRAP, and will report GDB_EXC_BREAKPOINT
  881. as a spurious signal. */
  882. status->set_stopped (GDB_SIGNAL_TRAP);
  883. break;
  884. default:
  885. status->set_stopped (GDB_SIGNAL_UNKNOWN);
  886. break;
  887. }
  888. return ptid_t (inf->pid, 0, thread->gdb_port);
  889. }
  890. else if (hdr->msgh_id == 0x48)
  891. {
  892. /* MACH_NOTIFY_DEAD_NAME: notification for exit *or* WIFSTOPPED. */
  893. int res;
  894. res = darwin_decode_notify_message (hdr, &inf);
  895. if (res < 0)
  896. {
  897. /* Should not happen... */
  898. warning
  899. (_("darwin_wait: ill-formatted message (id=0x%x, res=%d)\n"),
  900. hdr->msgh_id, res);
  901. }
  902. *pinf = NULL;
  903. *pthread = NULL;
  904. if (res < 0 || inf == NULL)
  905. {
  906. status->set_ignore ();
  907. return minus_one_ptid;
  908. }
  909. if (inf != NULL)
  910. {
  911. darwin_inferior *priv = get_darwin_inferior (inf);
  912. if (!priv->no_ptrace)
  913. {
  914. pid_t res_pid;
  915. int wstatus;
  916. res_pid = wait4 (inf->pid, &wstatus, 0, NULL);
  917. if (res_pid < 0 || res_pid != inf->pid)
  918. {
  919. warning (_("wait4: res=%d: %s\n"),
  920. res_pid, safe_strerror (errno));
  921. status->set_ignore ();
  922. return minus_one_ptid;
  923. }
  924. if (WIFEXITED (wstatus))
  925. {
  926. status->set_exited (WEXITSTATUS (wstatus));
  927. inferior_debug (4, _("darwin_wait: pid=%d exit, status=0x%x\n"),
  928. res_pid, wstatus);
  929. }
  930. else if (WIFSTOPPED (wstatus))
  931. {
  932. /* Ignore stopped state, it will be handled by the next
  933. exception. */
  934. status->set_ignore ();
  935. inferior_debug (4, _("darwin_wait: pid %d received WIFSTOPPED\n"),
  936. res_pid);
  937. return minus_one_ptid;
  938. }
  939. else if (WIFSIGNALED (wstatus))
  940. {
  941. status->set_signalled
  942. (gdb_signal_from_host (WTERMSIG (wstatus)));
  943. inferior_debug (4, _("darwin_wait: pid=%d received signal %d\n"),
  944. res_pid, status->sig());
  945. }
  946. else
  947. {
  948. status->set_ignore ();
  949. warning (_("Unexpected wait status after MACH_NOTIFY_DEAD_NAME "
  950. "notification: 0x%x"), wstatus);
  951. return minus_one_ptid;
  952. }
  953. return ptid_t (inf->pid);
  954. }
  955. else
  956. {
  957. inferior_debug (4, _("darwin_wait: pid=%d\n"), inf->pid);
  958. status->set_exited (0 /* Don't know. */);
  959. return ptid_t (inf->pid, 0, 0);
  960. }
  961. }
  962. }
  963. /* Unknown message. */
  964. warning (_("darwin: got unknown message, id: 0x%x"), hdr->msgh_id);
  965. status->set_ignore ();
  966. return minus_one_ptid;
  967. }
  968. int
  969. darwin_nat_target::cancel_breakpoint (ptid_t ptid)
  970. {
  971. /* Arrange for a breakpoint to be hit again later. We will handle
  972. the current event, eventually we will resume this thread, and this
  973. breakpoint will trap again.
  974. If we do not do this, then we run the risk that the user will
  975. delete or disable the breakpoint, but the thread will have already
  976. tripped on it. */
  977. struct regcache *regcache = get_thread_regcache (this, ptid);
  978. struct gdbarch *gdbarch = regcache->arch ();
  979. CORE_ADDR pc;
  980. pc = regcache_read_pc (regcache) - gdbarch_decr_pc_after_break (gdbarch);
  981. if (breakpoint_inserted_here_p (regcache->aspace (), pc))
  982. {
  983. inferior_debug (4, "cancel_breakpoint for thread 0x%lx\n",
  984. (unsigned long) ptid.tid ());
  985. /* Back up the PC if necessary. */
  986. if (gdbarch_decr_pc_after_break (gdbarch))
  987. regcache_write_pc (regcache, pc);
  988. return 1;
  989. }
  990. return 0;
  991. }
  992. ptid_t
  993. darwin_nat_target::wait_1 (ptid_t ptid, struct target_waitstatus *status)
  994. {
  995. kern_return_t kret;
  996. union
  997. {
  998. mach_msg_header_t hdr;
  999. char data[0x100];
  1000. } msgin;
  1001. mach_msg_header_t *hdr = &msgin.hdr;
  1002. ptid_t res;
  1003. darwin_thread_t *thread;
  1004. inferior_debug
  1005. (2, _("darwin_wait: waiting for a message ptid=%s\n"),
  1006. ptid.to_string ().c_str ());
  1007. /* Handle fake stop events at first. */
  1008. if (darwin_inf_fake_stop != NULL)
  1009. {
  1010. inferior *inf = darwin_inf_fake_stop;
  1011. darwin_inf_fake_stop = NULL;
  1012. darwin_inferior *priv = get_darwin_inferior (inf);
  1013. status->set_stopped (GDB_SIGNAL_TRAP);
  1014. thread = priv->threads[0];
  1015. thread->msg_state = DARWIN_STOPPED;
  1016. return ptid_t (inf->pid, 0, thread->gdb_port);
  1017. }
  1018. do
  1019. {
  1020. /* set_sigint_trap (); */
  1021. /* Wait for a message. */
  1022. kret = mach_msg (&msgin.hdr, MACH_RCV_MSG | MACH_RCV_INTERRUPT, 0,
  1023. sizeof (msgin.data), darwin_port_set, 0, MACH_PORT_NULL);
  1024. /* clear_sigint_trap (); */
  1025. if (kret == MACH_RCV_INTERRUPTED)
  1026. {
  1027. status->set_ignore ();
  1028. return minus_one_ptid;
  1029. }
  1030. if (kret != MACH_MSG_SUCCESS)
  1031. {
  1032. inferior_debug (5, _("mach_msg: ret=0x%x\n"), kret);
  1033. status->set_spurious ();
  1034. return minus_one_ptid;
  1035. }
  1036. /* Debug: display message. */
  1037. if (darwin_debug_flag > 10)
  1038. darwin_dump_message (hdr, darwin_debug_flag > 11);
  1039. inferior *inf;
  1040. res = decode_message (hdr, &thread, &inf, status);
  1041. if (res == minus_one_ptid)
  1042. continue;
  1043. /* Early return in case an inferior has exited. */
  1044. if (inf == NULL)
  1045. return res;
  1046. }
  1047. while (status->kind () == TARGET_WAITKIND_IGNORE);
  1048. /* Stop all tasks. */
  1049. for (inferior *inf : all_inferiors (this))
  1050. {
  1051. darwin_suspend_inferior (inf);
  1052. check_new_threads (inf);
  1053. }
  1054. /* Read pending messages. */
  1055. while (1)
  1056. {
  1057. struct target_waitstatus status2;
  1058. ptid_t ptid2;
  1059. kret = mach_msg (&msgin.hdr,
  1060. MACH_RCV_MSG | MACH_RCV_TIMEOUT, 0,
  1061. sizeof (msgin.data), darwin_port_set, 1, MACH_PORT_NULL);
  1062. if (kret == MACH_RCV_TIMED_OUT)
  1063. break;
  1064. if (kret != MACH_MSG_SUCCESS)
  1065. {
  1066. inferior_debug
  1067. (5, _("darwin_wait: mach_msg(pending) ret=0x%x\n"), kret);
  1068. break;
  1069. }
  1070. /* Debug: display message. */
  1071. if (darwin_debug_flag > 10)
  1072. darwin_dump_message (hdr, darwin_debug_flag > 11);
  1073. inferior *inf;
  1074. ptid2 = decode_message (hdr, &thread, &inf, &status2);
  1075. if (inf != NULL && thread != NULL
  1076. && thread->event.ex_type == EXC_BREAKPOINT)
  1077. {
  1078. if (thread->single_step
  1079. || cancel_breakpoint (ptid_t (inf->pid, 0, thread->gdb_port)))
  1080. {
  1081. gdb_assert (thread->msg_state == DARWIN_MESSAGE);
  1082. darwin_send_reply (inf, thread);
  1083. thread->msg_state = DARWIN_RUNNING;
  1084. }
  1085. else
  1086. inferior_debug
  1087. (3, _("darwin_wait: thread 0x%x hit a non-gdb breakpoint\n"),
  1088. thread->gdb_port);
  1089. }
  1090. else
  1091. inferior_debug (3, _("darwin_wait: unhandled pending message\n"));
  1092. }
  1093. return res;
  1094. }
  1095. ptid_t
  1096. darwin_nat_target::wait (ptid_t ptid, struct target_waitstatus *status,
  1097. target_wait_flags options)
  1098. {
  1099. return wait_1 (ptid, status);
  1100. }
  1101. void
  1102. darwin_nat_target::interrupt ()
  1103. {
  1104. struct inferior *inf = current_inferior ();
  1105. darwin_inferior *priv = get_darwin_inferior (inf);
  1106. /* FIXME: handle in no_ptrace mode. */
  1107. gdb_assert (!priv->no_ptrace);
  1108. ::kill (inf->pid, SIGINT);
  1109. }
  1110. /* Deallocate threads port and vector. */
  1111. static void
  1112. darwin_deallocate_threads (struct inferior *inf)
  1113. {
  1114. darwin_inferior *priv = get_darwin_inferior (inf);
  1115. for (darwin_thread_t *t : priv->threads)
  1116. {
  1117. kern_return_t kret = mach_port_deallocate (gdb_task, t->gdb_port);
  1118. MACH_CHECK_ERROR (kret);
  1119. }
  1120. priv->threads.clear ();
  1121. }
  1122. void
  1123. darwin_nat_target::mourn_inferior ()
  1124. {
  1125. struct inferior *inf = current_inferior ();
  1126. darwin_inferior *priv = get_darwin_inferior (inf);
  1127. kern_return_t kret;
  1128. mach_port_t prev;
  1129. /* Deallocate threads. */
  1130. darwin_deallocate_threads (inf);
  1131. /* Remove notify_port from darwin_port_set. */
  1132. kret = mach_port_move_member (gdb_task,
  1133. priv->notify_port, MACH_PORT_NULL);
  1134. MACH_CHECK_ERROR (kret);
  1135. /* Remove task port dead_name notification. */
  1136. kret = mach_port_request_notification (gdb_task, priv->task,
  1137. MACH_NOTIFY_DEAD_NAME, 0,
  1138. MACH_PORT_NULL,
  1139. MACH_MSG_TYPE_MAKE_SEND_ONCE,
  1140. &prev);
  1141. /* This can fail if the task is dead. */
  1142. inferior_debug (4, "task=0x%x, prev=0x%x, notify_port=0x%x\n",
  1143. priv->task, prev, priv->notify_port);
  1144. if (kret == KERN_SUCCESS)
  1145. {
  1146. kret = mach_port_deallocate (gdb_task, prev);
  1147. MACH_CHECK_ERROR (kret);
  1148. }
  1149. /* Destroy notify_port. */
  1150. kret = mach_port_destroy (gdb_task, priv->notify_port);
  1151. MACH_CHECK_ERROR (kret);
  1152. /* Deallocate saved exception ports. */
  1153. darwin_deallocate_exception_ports (priv);
  1154. /* Deallocate task port. */
  1155. kret = mach_port_deallocate (gdb_task, priv->task);
  1156. MACH_CHECK_ERROR (kret);
  1157. inf->priv = NULL;
  1158. inf_child_target::mourn_inferior ();
  1159. }
  1160. static void
  1161. darwin_reply_to_all_pending_messages (struct inferior *inf)
  1162. {
  1163. darwin_inferior *priv = get_darwin_inferior (inf);
  1164. for (darwin_thread_t *t : priv->threads)
  1165. {
  1166. if (t->msg_state == DARWIN_MESSAGE)
  1167. darwin_resume_thread (inf, t, 0, 0);
  1168. }
  1169. }
  1170. void
  1171. darwin_nat_target::stop_inferior (inferior *inf)
  1172. {
  1173. struct target_waitstatus wstatus;
  1174. ptid_t ptid;
  1175. int res;
  1176. darwin_inferior *priv = get_darwin_inferior (inf);
  1177. gdb_assert (inf != NULL);
  1178. darwin_suspend_inferior (inf);
  1179. darwin_reply_to_all_pending_messages (inf);
  1180. if (priv->no_ptrace)
  1181. return;
  1182. res = ::kill (inf->pid, SIGSTOP);
  1183. if (res != 0)
  1184. warning (_("cannot kill: %s"), safe_strerror (errno));
  1185. /* Wait until the process is really stopped. */
  1186. while (1)
  1187. {
  1188. ptid = wait_1 (ptid_t (inf->pid), &wstatus);
  1189. if (wstatus.kind () == TARGET_WAITKIND_STOPPED
  1190. && wstatus.sig () == GDB_SIGNAL_STOP)
  1191. break;
  1192. }
  1193. }
  1194. static kern_return_t
  1195. darwin_save_exception_ports (darwin_inferior *inf)
  1196. {
  1197. kern_return_t kret;
  1198. inf->exception_info.count =
  1199. sizeof (inf->exception_info.ports) / sizeof (inf->exception_info.ports[0]);
  1200. kret = task_get_exception_ports
  1201. (inf->task, EXC_MASK_ALL, inf->exception_info.masks,
  1202. &inf->exception_info.count, inf->exception_info.ports,
  1203. inf->exception_info.behaviors, inf->exception_info.flavors);
  1204. return kret;
  1205. }
  1206. static kern_return_t
  1207. darwin_restore_exception_ports (darwin_inferior *inf)
  1208. {
  1209. int i;
  1210. kern_return_t kret;
  1211. for (i = 0; i < inf->exception_info.count; i++)
  1212. {
  1213. kret = task_set_exception_ports
  1214. (inf->task, inf->exception_info.masks[i], inf->exception_info.ports[i],
  1215. inf->exception_info.behaviors[i], inf->exception_info.flavors[i]);
  1216. if (kret != KERN_SUCCESS)
  1217. return kret;
  1218. }
  1219. return KERN_SUCCESS;
  1220. }
  1221. /* Deallocate saved exception ports. */
  1222. static void
  1223. darwin_deallocate_exception_ports (darwin_inferior *inf)
  1224. {
  1225. int i;
  1226. kern_return_t kret;
  1227. for (i = 0; i < inf->exception_info.count; i++)
  1228. {
  1229. kret = mach_port_deallocate (gdb_task, inf->exception_info.ports[i]);
  1230. MACH_CHECK_ERROR (kret);
  1231. }
  1232. inf->exception_info.count = 0;
  1233. }
  1234. static void
  1235. darwin_setup_exceptions (struct inferior *inf)
  1236. {
  1237. darwin_inferior *priv = get_darwin_inferior (inf);
  1238. kern_return_t kret;
  1239. exception_mask_t mask;
  1240. kret = darwin_save_exception_ports (priv);
  1241. if (kret != KERN_SUCCESS)
  1242. error (_("Unable to save exception ports, task_get_exception_ports"
  1243. "returned: %d"),
  1244. kret);
  1245. /* Set exception port. */
  1246. if (enable_mach_exceptions)
  1247. mask = EXC_MASK_ALL;
  1248. else
  1249. mask = EXC_MASK_SOFTWARE | EXC_MASK_BREAKPOINT;
  1250. kret = task_set_exception_ports (priv->task, mask, darwin_ex_port,
  1251. EXCEPTION_DEFAULT, THREAD_STATE_NONE);
  1252. if (kret != KERN_SUCCESS)
  1253. error (_("Unable to set exception ports, task_set_exception_ports"
  1254. "returned: %d"),
  1255. kret);
  1256. }
  1257. void
  1258. darwin_nat_target::kill ()
  1259. {
  1260. struct inferior *inf = current_inferior ();
  1261. darwin_inferior *priv = get_darwin_inferior (inf);
  1262. struct target_waitstatus wstatus;
  1263. ptid_t ptid;
  1264. kern_return_t kret;
  1265. int res;
  1266. if (inferior_ptid == null_ptid)
  1267. return;
  1268. gdb_assert (inf != NULL);
  1269. kret = darwin_restore_exception_ports (priv);
  1270. MACH_CHECK_ERROR (kret);
  1271. darwin_reply_to_all_pending_messages (inf);
  1272. res = ::kill (inf->pid, 9);
  1273. if (res == 0)
  1274. {
  1275. /* On MacOS version Sierra, the darwin_restore_exception_ports call
  1276. does not work as expected.
  1277. When the kill function is called, the SIGKILL signal is received
  1278. by gdb whereas it should have been received by the kernel since
  1279. the exception ports have been restored.
  1280. This behavior is not the expected one thus gdb does not reply to
  1281. the received SIGKILL message. This situation leads to a "busy"
  1282. resource from the kernel point of view and the inferior is never
  1283. released, causing it to remain as a zombie process, even after
  1284. GDB exits.
  1285. To work around this, we mark all the threads of the inferior as
  1286. signaled thus darwin_decode_message function knows that the kill
  1287. signal was sent by gdb and will take the appropriate action
  1288. (cancel signal and reply to the signal message). */
  1289. for (darwin_thread_t *thread : priv->threads)
  1290. thread->signaled = 1;
  1291. darwin_resume_inferior (inf);
  1292. ptid = wait_1 (ptid_t (inf->pid), &wstatus);
  1293. }
  1294. else if (errno != ESRCH)
  1295. warning (_("Failed to kill inferior: kill (%d, 9) returned [%s]"),
  1296. inf->pid, safe_strerror (errno));
  1297. target_mourn_inferior (ptid_t (inf->pid));
  1298. }
  1299. static void
  1300. darwin_setup_request_notification (struct inferior *inf)
  1301. {
  1302. darwin_inferior *priv = get_darwin_inferior (inf);
  1303. kern_return_t kret;
  1304. mach_port_t prev_not;
  1305. kret = mach_port_request_notification (gdb_task, priv->task,
  1306. MACH_NOTIFY_DEAD_NAME, 0,
  1307. priv->notify_port,
  1308. MACH_MSG_TYPE_MAKE_SEND_ONCE,
  1309. &prev_not);
  1310. if (kret != KERN_SUCCESS)
  1311. error (_("Termination notification request failed, "
  1312. "mach_port_request_notification\n"
  1313. "returned: %d"),
  1314. kret);
  1315. if (prev_not != MACH_PORT_NULL)
  1316. {
  1317. /* This is unexpected, as there should not be any previously
  1318. registered notification request. But this is not a fatal
  1319. issue, so just emit a warning. */
  1320. warning (_("\
  1321. A task termination request was registered before the debugger registered\n\
  1322. its own. This is unexpected, but should otherwise not have any actual\n\
  1323. impact on the debugging session."));
  1324. }
  1325. }
  1326. static void
  1327. darwin_attach_pid (struct inferior *inf)
  1328. {
  1329. kern_return_t kret;
  1330. darwin_inferior *priv = new darwin_inferior;
  1331. inf->priv.reset (priv);
  1332. try
  1333. {
  1334. kret = task_for_pid (gdb_task, inf->pid, &priv->task);
  1335. if (kret != KERN_SUCCESS)
  1336. {
  1337. int status;
  1338. if (!inf->attach_flag)
  1339. {
  1340. kill (inf->pid, 9);
  1341. waitpid (inf->pid, &status, 0);
  1342. }
  1343. error
  1344. (_("Unable to find Mach task port for process-id %d: %s (0x%lx).\n"
  1345. " (please check gdb is codesigned - see taskgated(8))"),
  1346. inf->pid, mach_error_string (kret), (unsigned long) kret);
  1347. }
  1348. inferior_debug (2, _("inferior task: 0x%x, pid: %d\n"),
  1349. priv->task, inf->pid);
  1350. if (darwin_ex_port == MACH_PORT_NULL)
  1351. {
  1352. /* Create a port to get exceptions. */
  1353. kret = mach_port_allocate (gdb_task, MACH_PORT_RIGHT_RECEIVE,
  1354. &darwin_ex_port);
  1355. if (kret != KERN_SUCCESS)
  1356. error (_("Unable to create exception port, mach_port_allocate "
  1357. "returned: %d"),
  1358. kret);
  1359. kret = mach_port_insert_right (gdb_task, darwin_ex_port,
  1360. darwin_ex_port,
  1361. MACH_MSG_TYPE_MAKE_SEND);
  1362. if (kret != KERN_SUCCESS)
  1363. error (_("Unable to create exception port, mach_port_insert_right "
  1364. "returned: %d"),
  1365. kret);
  1366. /* Create a port set and put ex_port in it. */
  1367. kret = mach_port_allocate (gdb_task, MACH_PORT_RIGHT_PORT_SET,
  1368. &darwin_port_set);
  1369. if (kret != KERN_SUCCESS)
  1370. error (_("Unable to create port set, mach_port_allocate "
  1371. "returned: %d"),
  1372. kret);
  1373. kret = mach_port_move_member (gdb_task, darwin_ex_port,
  1374. darwin_port_set);
  1375. if (kret != KERN_SUCCESS)
  1376. error (_("Unable to move exception port into new port set, "
  1377. "mach_port_move_member\n"
  1378. "returned: %d"),
  1379. kret);
  1380. }
  1381. /* Create a port to be notified when the child task terminates. */
  1382. kret = mach_port_allocate (gdb_task, MACH_PORT_RIGHT_RECEIVE,
  1383. &priv->notify_port);
  1384. if (kret != KERN_SUCCESS)
  1385. error (_("Unable to create notification port, mach_port_allocate "
  1386. "returned: %d"),
  1387. kret);
  1388. kret = mach_port_move_member (gdb_task,
  1389. priv->notify_port, darwin_port_set);
  1390. if (kret != KERN_SUCCESS)
  1391. error (_("Unable to move notification port into new port set, "
  1392. "mach_port_move_member\n"
  1393. "returned: %d"),
  1394. kret);
  1395. darwin_setup_request_notification (inf);
  1396. darwin_setup_exceptions (inf);
  1397. }
  1398. catch (const gdb_exception &ex)
  1399. {
  1400. exit_inferior (inf);
  1401. switch_to_no_thread ();
  1402. throw;
  1403. }
  1404. target_ops *darwin_ops = get_native_target ();
  1405. if (!inf->target_is_pushed (darwin_ops))
  1406. inf->push_target (darwin_ops);
  1407. }
  1408. /* Get the thread_info object corresponding to this darwin_thread_info. */
  1409. static struct thread_info *
  1410. thread_info_from_private_thread_info (darwin_thread_info *pti)
  1411. {
  1412. for (struct thread_info *it : all_threads ())
  1413. {
  1414. darwin_thread_info *iter_pti = get_darwin_thread_info (it);
  1415. if (iter_pti->gdb_port == pti->gdb_port)
  1416. return it;
  1417. }
  1418. gdb_assert_not_reached ("did not find gdb thread for darwin thread");
  1419. }
  1420. void
  1421. darwin_nat_target::init_thread_list (inferior *inf)
  1422. {
  1423. check_new_threads (inf);
  1424. darwin_inferior *priv = get_darwin_inferior (inf);
  1425. gdb_assert (!priv->threads.empty ());
  1426. darwin_thread_info *first_pti = priv->threads.front ();
  1427. struct thread_info *first_thread
  1428. = thread_info_from_private_thread_info (first_pti);
  1429. switch_to_thread (first_thread);
  1430. }
  1431. /* The child must synchronize with gdb: gdb must set the exception port
  1432. before the child call PTRACE_SIGEXC. We use a pipe to achieve this.
  1433. FIXME: is there a lighter way ? */
  1434. static int ptrace_fds[2];
  1435. static void
  1436. darwin_ptrace_me (void)
  1437. {
  1438. int res;
  1439. char c;
  1440. /* Close write end point. */
  1441. if (close (ptrace_fds[1]) < 0)
  1442. trace_start_error_with_name ("close");
  1443. /* Wait until gdb is ready. */
  1444. res = read (ptrace_fds[0], &c, 1);
  1445. if (res != 0)
  1446. trace_start_error (_("unable to read from pipe, read returned: %d"), res);
  1447. if (close (ptrace_fds[0]) < 0)
  1448. trace_start_error_with_name ("close");
  1449. /* Get rid of privileges. */
  1450. if (setegid (getgid ()) < 0)
  1451. trace_start_error_with_name ("setegid");
  1452. /* Set TRACEME. */
  1453. if (PTRACE (PT_TRACE_ME, 0, 0, 0) < 0)
  1454. trace_start_error_with_name ("PTRACE");
  1455. /* Redirect signals to exception port. */
  1456. if (PTRACE (PT_SIGEXC, 0, 0, 0) < 0)
  1457. trace_start_error_with_name ("PTRACE");
  1458. }
  1459. /* Dummy function to be sure fork_inferior uses fork(2) and not vfork(2). */
  1460. static void
  1461. darwin_pre_ptrace (void)
  1462. {
  1463. if (pipe (ptrace_fds) != 0)
  1464. {
  1465. ptrace_fds[0] = -1;
  1466. ptrace_fds[1] = -1;
  1467. error (_("unable to create a pipe: %s"), safe_strerror (errno));
  1468. }
  1469. mark_fd_no_cloexec (ptrace_fds[0]);
  1470. mark_fd_no_cloexec (ptrace_fds[1]);
  1471. }
  1472. void
  1473. darwin_nat_target::ptrace_him (int pid)
  1474. {
  1475. struct inferior *inf = current_inferior ();
  1476. darwin_attach_pid (inf);
  1477. /* Let's the child run. */
  1478. ::close (ptrace_fds[0]);
  1479. ::close (ptrace_fds[1]);
  1480. unmark_fd_no_cloexec (ptrace_fds[0]);
  1481. unmark_fd_no_cloexec (ptrace_fds[1]);
  1482. init_thread_list (inf);
  1483. gdb_startup_inferior (pid, START_INFERIOR_TRAPS_EXPECTED);
  1484. }
  1485. static void
  1486. darwin_execvp (const char *file, char * const argv[], char * const env[])
  1487. {
  1488. posix_spawnattr_t attr;
  1489. short ps_flags = 0;
  1490. int res;
  1491. res = posix_spawnattr_init (&attr);
  1492. if (res != 0)
  1493. {
  1494. gdb_printf
  1495. (gdb_stderr, "Cannot initialize attribute for posix_spawn\n");
  1496. return;
  1497. }
  1498. /* Do like execve: replace the image. */
  1499. ps_flags = POSIX_SPAWN_SETEXEC;
  1500. /* Disable ASLR. The constant doesn't look to be available outside the
  1501. kernel include files. */
  1502. #ifndef _POSIX_SPAWN_DISABLE_ASLR
  1503. #define _POSIX_SPAWN_DISABLE_ASLR 0x0100
  1504. #endif
  1505. ps_flags |= _POSIX_SPAWN_DISABLE_ASLR;
  1506. res = posix_spawnattr_setflags (&attr, ps_flags);
  1507. if (res != 0)
  1508. {
  1509. gdb_printf (gdb_stderr, "Cannot set posix_spawn flags\n");
  1510. return;
  1511. }
  1512. posix_spawnp (NULL, argv[0], NULL, &attr, argv, env);
  1513. }
  1514. /* Read kernel version, and return TRUE if this host may have System
  1515. Integrity Protection (Sierra or later). */
  1516. static bool
  1517. may_have_sip ()
  1518. {
  1519. char str[16];
  1520. size_t sz = sizeof (str);
  1521. int ret;
  1522. ret = sysctlbyname ("kern.osrelease", str, &sz, NULL, 0);
  1523. if (ret == 0 && sz < sizeof (str))
  1524. {
  1525. unsigned long ver = strtoul (str, NULL, 10);
  1526. if (ver >= 16)
  1527. return true;
  1528. }
  1529. return false;
  1530. }
  1531. /* A helper for maybe_cache_shell. This copies the shell to the
  1532. cache. It will throw an exception on any failure. */
  1533. static void
  1534. copy_shell_to_cache (const char *shell, const std::string &new_name)
  1535. {
  1536. scoped_fd from_fd = gdb_open_cloexec (shell, O_RDONLY, 0);
  1537. if (from_fd.get () < 0)
  1538. error (_("Could not open shell (%s) for reading: %s"),
  1539. shell, safe_strerror (errno));
  1540. std::string new_dir = ldirname (new_name.c_str ());
  1541. if (!mkdir_recursive (new_dir.c_str ()))
  1542. error (_("Could not make cache directory \"%s\": %s"),
  1543. new_dir.c_str (), safe_strerror (errno));
  1544. gdb::char_vector temp_name = make_temp_filename (new_name);
  1545. scoped_fd to_fd = gdb_mkostemp_cloexec (&temp_name[0]);
  1546. gdb::unlinker unlink_file_on_error (temp_name.data ());
  1547. if (to_fd.get () < 0)
  1548. error (_("Could not open temporary file \"%s\" for writing: %s"),
  1549. temp_name.data (), safe_strerror (errno));
  1550. if (fcopyfile (from_fd.get (), to_fd.get (), nullptr,
  1551. COPYFILE_STAT | COPYFILE_DATA) != 0)
  1552. error (_("Could not copy shell to cache as \"%s\": %s"),
  1553. temp_name.data (), safe_strerror (errno));
  1554. /* Be sure that the caching is atomic so that we don't get bad
  1555. results from multiple copies of gdb running at the same time. */
  1556. if (rename (temp_name.data (), new_name.c_str ()) != 0)
  1557. error (_("Could not rename shell cache file to \"%s\": %s"),
  1558. new_name.c_str (), safe_strerror (errno));
  1559. unlink_file_on_error.keep ();
  1560. }
  1561. /* If $SHELL is restricted, try to cache a copy. Starting with El
  1562. Capitan, macOS introduced System Integrity Protection. Among other
  1563. things, this prevents certain executables from being ptrace'd. In
  1564. particular, executables in /bin, like most shells, are affected.
  1565. To work around this, while preserving command-line glob expansion
  1566. and redirections, gdb will cache a copy of the shell. Return true
  1567. if all is well -- either the shell is not subject to SIP or it has
  1568. been successfully cached. Returns false if something failed. */
  1569. static bool
  1570. maybe_cache_shell ()
  1571. {
  1572. /* SF_RESTRICTED is defined in sys/stat.h and lets us determine if a
  1573. given file is subject to SIP. */
  1574. #ifdef SF_RESTRICTED
  1575. /* If a check fails we want to revert -- maybe the user deleted the
  1576. cache while gdb was running, or something like that. */
  1577. copied_shell = nullptr;
  1578. const char *shell = get_shell ();
  1579. if (!IS_ABSOLUTE_PATH (shell))
  1580. {
  1581. warning (_("This version of macOS has System Integrity Protection.\n\
  1582. Normally gdb would try to work around this by caching a copy of your shell,\n\
  1583. but because your shell (%s) is not an absolute path, this is being skipped."),
  1584. shell);
  1585. return false;
  1586. }
  1587. struct stat sb;
  1588. if (stat (shell, &sb) < 0)
  1589. {
  1590. warning (_("This version of macOS has System Integrity Protection.\n\
  1591. Normally gdb would try to work around this by caching a copy of your shell,\n\
  1592. but because gdb could not stat your shell (%s), this is being skipped.\n\
  1593. The error was: %s"),
  1594. shell, safe_strerror (errno));
  1595. return false;
  1596. }
  1597. if ((sb.st_flags & SF_RESTRICTED) == 0)
  1598. return true;
  1599. /* Put the copy somewhere like ~/Library/Caches/gdb/bin/sh. */
  1600. std::string new_name = get_standard_cache_dir ();
  1601. /* There's no need to insert a directory separator here, because
  1602. SHELL is known to be absolute. */
  1603. new_name.append (shell);
  1604. /* Maybe it was cached by some earlier gdb. */
  1605. if (stat (new_name.c_str (), &sb) != 0 || !S_ISREG (sb.st_mode))
  1606. {
  1607. try
  1608. {
  1609. copy_shell_to_cache (shell, new_name);
  1610. }
  1611. catch (const gdb_exception_error &ex)
  1612. {
  1613. warning (_("This version of macOS has System Integrity Protection.\n\
  1614. Because `startup-with-shell' is enabled, gdb tried to work around SIP by\n\
  1615. caching a copy of your shell. However, this failed:\n\
  1616. %s\n\
  1617. If you correct the problem, gdb will automatically try again the next time\n\
  1618. you \"run\". To prevent these attempts, you can use:\n\
  1619. set startup-with-shell off"),
  1620. ex.what ());
  1621. return false;
  1622. }
  1623. gdb_printf (_("Note: this version of macOS has System Integrity Protection.\n\
  1624. Because `startup-with-shell' is enabled, gdb has worked around this by\n\
  1625. caching a copy of your shell. The shell used by \"run\" is now:\n\
  1626. %s\n"),
  1627. new_name.c_str ());
  1628. }
  1629. /* We need to make sure that the new name has the correct lifetime. */
  1630. static std::string saved_shell = std::move (new_name);
  1631. copied_shell = saved_shell.c_str ();
  1632. #endif /* SF_RESTRICTED */
  1633. return true;
  1634. }
  1635. void
  1636. darwin_nat_target::create_inferior (const char *exec_file,
  1637. const std::string &allargs,
  1638. char **env, int from_tty)
  1639. {
  1640. gdb::optional<scoped_restore_tmpl<bool>> restore_startup_with_shell;
  1641. darwin_nat_target *the_target = this;
  1642. if (startup_with_shell && may_have_sip ())
  1643. {
  1644. if (!maybe_cache_shell ())
  1645. {
  1646. warning (_("startup-with-shell is now temporarily disabled"));
  1647. restore_startup_with_shell.emplace (&startup_with_shell, 0);
  1648. }
  1649. }
  1650. /* Do the hard work. */
  1651. fork_inferior (exec_file, allargs, env, darwin_ptrace_me,
  1652. [the_target] (int pid)
  1653. {
  1654. the_target->ptrace_him (pid);
  1655. },
  1656. darwin_pre_ptrace, copied_shell,
  1657. darwin_execvp);
  1658. }
  1659. /* Set things up such that the next call to darwin_wait will immediately
  1660. return a fake stop event for inferior INF.
  1661. This assumes that the inferior's thread list has been initialized,
  1662. as it will suspend the inferior's first thread. */
  1663. static void
  1664. darwin_setup_fake_stop_event (struct inferior *inf)
  1665. {
  1666. darwin_inferior *priv = get_darwin_inferior (inf);
  1667. darwin_thread_t *thread;
  1668. kern_return_t kret;
  1669. gdb_assert (darwin_inf_fake_stop == NULL);
  1670. darwin_inf_fake_stop = inf;
  1671. /* When detecting a fake pending stop event, darwin_wait returns
  1672. an event saying that the first thread is in a DARWIN_STOPPED
  1673. state. To make that accurate, we need to suspend that thread
  1674. as well. Otherwise, we'll try resuming it when resuming the
  1675. inferior, and get a warning because the thread's suspend count
  1676. is already zero, making the resume request useless. */
  1677. thread = priv->threads[0];
  1678. kret = thread_suspend (thread->gdb_port);
  1679. MACH_CHECK_ERROR (kret);
  1680. }
  1681. /* Attach to process PID, then initialize for debugging it
  1682. and wait for the trace-trap that results from attaching. */
  1683. void
  1684. darwin_nat_target::attach (const char *args, int from_tty)
  1685. {
  1686. pid_t pid;
  1687. struct inferior *inf;
  1688. pid = parse_pid_to_attach (args);
  1689. if (pid == getpid ()) /* Trying to masturbate? */
  1690. error (_("I refuse to debug myself!"));
  1691. target_announce_attach (from_tty, pid);
  1692. if (pid == 0 || ::kill (pid, 0) < 0)
  1693. error (_("Can't attach to process %d: %s (%d)"),
  1694. pid, safe_strerror (errno), errno);
  1695. inf = current_inferior ();
  1696. inferior_appeared (inf, pid);
  1697. inf->attach_flag = 1;
  1698. darwin_attach_pid (inf);
  1699. darwin_suspend_inferior (inf);
  1700. init_thread_list (inf);
  1701. darwin_inferior *priv = get_darwin_inferior (inf);
  1702. darwin_check_osabi (priv, inferior_ptid.tid ());
  1703. darwin_setup_fake_stop_event (inf);
  1704. priv->no_ptrace = 1;
  1705. }
  1706. /* Take a program previously attached to and detaches it.
  1707. The program resumes execution and will no longer stop
  1708. on signals, etc. We'd better not have left any breakpoints
  1709. in the program or it'll die when it hits one. For this
  1710. to work, it may be necessary for the process to have been
  1711. previously attached. It *might* work if the program was
  1712. started via fork. */
  1713. void
  1714. darwin_nat_target::detach (inferior *inf, int from_tty)
  1715. {
  1716. darwin_inferior *priv = get_darwin_inferior (inf);
  1717. kern_return_t kret;
  1718. int res;
  1719. /* Display message. */
  1720. target_announce_detach (from_tty);
  1721. /* If ptrace() is in use, stop the process. */
  1722. if (!priv->no_ptrace)
  1723. stop_inferior (inf);
  1724. kret = darwin_restore_exception_ports (priv);
  1725. MACH_CHECK_ERROR (kret);
  1726. if (!priv->no_ptrace)
  1727. {
  1728. res = PTRACE (PT_DETACH, inf->pid, 0, 0);
  1729. if (res != 0)
  1730. warning (_("Unable to detach from process-id %d: %s (%d)"),
  1731. inf->pid, safe_strerror (errno), errno);
  1732. }
  1733. darwin_reply_to_all_pending_messages (inf);
  1734. /* When using ptrace, we have just performed a PT_DETACH, which
  1735. resumes the inferior. On the other hand, when we are not using
  1736. ptrace, we need to resume its execution ourselves. */
  1737. if (priv->no_ptrace)
  1738. darwin_resume_inferior (inf);
  1739. mourn_inferior ();
  1740. }
  1741. std::string
  1742. darwin_nat_target::pid_to_str (ptid_t ptid)
  1743. {
  1744. long tid = ptid.tid ();
  1745. if (tid != 0)
  1746. return string_printf (_("Thread 0x%lx of process %u"),
  1747. tid, ptid.pid ());
  1748. return normal_pid_to_str (ptid);
  1749. }
  1750. bool
  1751. darwin_nat_target::thread_alive (ptid_t ptid)
  1752. {
  1753. return true;
  1754. }
  1755. /* If RDADDR is not NULL, read inferior task's LEN bytes from ADDR and
  1756. copy it to RDADDR in gdb's address space.
  1757. If WRADDR is not NULL, write gdb's LEN bytes from WRADDR and copy it
  1758. to ADDR in inferior task's address space.
  1759. Return 0 on failure; number of bytes read / written otherwise. */
  1760. static int
  1761. darwin_read_write_inferior (task_t task, CORE_ADDR addr,
  1762. gdb_byte *rdaddr, const gdb_byte *wraddr,
  1763. ULONGEST length)
  1764. {
  1765. kern_return_t kret;
  1766. mach_vm_size_t res_length = 0;
  1767. inferior_debug (8, _("darwin_read_write_inferior(task=0x%x, %s, len=%s)\n"),
  1768. task, core_addr_to_string (addr), pulongest (length));
  1769. /* First read. */
  1770. if (rdaddr != NULL)
  1771. {
  1772. mach_vm_size_t count;
  1773. /* According to target.h(to_xfer_partial), one and only one may be
  1774. non-null. */
  1775. gdb_assert (wraddr == NULL);
  1776. kret = mach_vm_read_overwrite (task, addr, length,
  1777. (mach_vm_address_t) rdaddr, &count);
  1778. if (kret != KERN_SUCCESS)
  1779. {
  1780. inferior_debug
  1781. (1, _("darwin_read_write_inferior: mach_vm_read failed at %s: %s"),
  1782. core_addr_to_string (addr), mach_error_string (kret));
  1783. return 0;
  1784. }
  1785. return count;
  1786. }
  1787. /* See above. */
  1788. gdb_assert (wraddr != NULL);
  1789. while (length != 0)
  1790. {
  1791. mach_vm_address_t offset = addr & (mach_page_size - 1);
  1792. mach_vm_address_t region_address = (mach_vm_address_t) (addr - offset);
  1793. mach_vm_size_t aligned_length =
  1794. (mach_vm_size_t) PAGE_ROUND (offset + length);
  1795. vm_region_submap_short_info_data_64_t info;
  1796. mach_msg_type_number_t count = VM_REGION_SUBMAP_SHORT_INFO_COUNT_64;
  1797. natural_t region_depth = 1000;
  1798. mach_vm_address_t region_start = region_address;
  1799. mach_vm_size_t region_length;
  1800. mach_vm_size_t write_length;
  1801. /* Read page protection. */
  1802. kret = mach_vm_region_recurse
  1803. (task, &region_start, &region_length, &region_depth,
  1804. (vm_region_recurse_info_t) &info, &count);
  1805. if (kret != KERN_SUCCESS)
  1806. {
  1807. inferior_debug (1, _("darwin_read_write_inferior: "
  1808. "mach_vm_region_recurse failed at %s: %s\n"),
  1809. core_addr_to_string (region_address),
  1810. mach_error_string (kret));
  1811. return res_length;
  1812. }
  1813. inferior_debug
  1814. (9, _("darwin_read_write_inferior: "
  1815. "mach_vm_region_recurse addr=%s, start=%s, len=%s\n"),
  1816. core_addr_to_string (region_address),
  1817. core_addr_to_string (region_start),
  1818. core_addr_to_string (region_length));
  1819. /* Check for holes in memory. */
  1820. if (region_start > region_address)
  1821. {
  1822. warning (_("No memory at %s (vs %s+0x%x). Nothing written"),
  1823. core_addr_to_string (region_address),
  1824. core_addr_to_string (region_start),
  1825. (unsigned)region_length);
  1826. return res_length;
  1827. }
  1828. /* Adjust the length. */
  1829. region_length -= (region_address - region_start);
  1830. if (region_length > aligned_length)
  1831. region_length = aligned_length;
  1832. /* Make the pages RW. */
  1833. if (!(info.protection & VM_PROT_WRITE))
  1834. {
  1835. vm_prot_t prot = VM_PROT_READ | VM_PROT_WRITE;
  1836. kret = mach_vm_protect (task, region_address, region_length,
  1837. FALSE, prot);
  1838. if (kret != KERN_SUCCESS)
  1839. {
  1840. prot |= VM_PROT_COPY;
  1841. kret = mach_vm_protect (task, region_address, region_length,
  1842. FALSE, prot);
  1843. }
  1844. if (kret != KERN_SUCCESS)
  1845. {
  1846. warning (_("darwin_read_write_inferior: "
  1847. "mach_vm_protect failed at %s "
  1848. "(len=0x%lx, prot=0x%x): %s"),
  1849. core_addr_to_string (region_address),
  1850. (unsigned long) region_length, (unsigned) prot,
  1851. mach_error_string (kret));
  1852. return res_length;
  1853. }
  1854. }
  1855. if (offset + length > region_length)
  1856. write_length = region_length - offset;
  1857. else
  1858. write_length = length;
  1859. /* Write. */
  1860. kret = mach_vm_write (task, addr, (vm_offset_t) wraddr, write_length);
  1861. if (kret != KERN_SUCCESS)
  1862. {
  1863. warning (_("darwin_read_write_inferior: mach_vm_write failed: %s"),
  1864. mach_error_string (kret));
  1865. return res_length;
  1866. }
  1867. /* Restore page rights. */
  1868. if (!(info.protection & VM_PROT_WRITE))
  1869. {
  1870. kret = mach_vm_protect (task, region_address, region_length,
  1871. FALSE, info.protection);
  1872. if (kret != KERN_SUCCESS)
  1873. {
  1874. warning (_("darwin_read_write_inferior: "
  1875. "mach_vm_protect restore failed at %s "
  1876. "(len=0x%lx): %s"),
  1877. core_addr_to_string (region_address),
  1878. (unsigned long) region_length,
  1879. mach_error_string (kret));
  1880. }
  1881. }
  1882. addr += write_length;
  1883. wraddr += write_length;
  1884. res_length += write_length;
  1885. length -= write_length;
  1886. }
  1887. return res_length;
  1888. }
  1889. /* Read LENGTH bytes at offset ADDR of task_dyld_info for TASK, and copy them
  1890. to RDADDR (in big endian).
  1891. Return 0 on failure; number of bytes read / written otherwise. */
  1892. #ifdef TASK_DYLD_INFO_COUNT
  1893. /* This is not available in Darwin 9. */
  1894. static enum target_xfer_status
  1895. darwin_read_dyld_info (task_t task, CORE_ADDR addr, gdb_byte *rdaddr,
  1896. ULONGEST length, ULONGEST *xfered_len)
  1897. {
  1898. struct task_dyld_info task_dyld_info;
  1899. mach_msg_type_number_t count = TASK_DYLD_INFO_COUNT;
  1900. kern_return_t kret;
  1901. if (addr != 0 || length > sizeof (mach_vm_address_t))
  1902. return TARGET_XFER_EOF;
  1903. kret = task_info (task, TASK_DYLD_INFO,
  1904. (task_info_t) &task_dyld_info, &count);
  1905. MACH_CHECK_ERROR (kret);
  1906. if (kret != KERN_SUCCESS)
  1907. return TARGET_XFER_E_IO;
  1908. store_unsigned_integer (rdaddr, length, BFD_ENDIAN_BIG,
  1909. task_dyld_info.all_image_info_addr);
  1910. *xfered_len = (ULONGEST) length;
  1911. return TARGET_XFER_OK;
  1912. }
  1913. #endif
  1914. enum target_xfer_status
  1915. darwin_nat_target::xfer_partial (enum target_object object, const char *annex,
  1916. gdb_byte *readbuf, const gdb_byte *writebuf,
  1917. ULONGEST offset, ULONGEST len,
  1918. ULONGEST *xfered_len)
  1919. {
  1920. struct inferior *inf = current_inferior ();
  1921. darwin_inferior *priv = get_darwin_inferior (inf);
  1922. inferior_debug
  1923. (8, _("darwin_xfer_partial(%s, %s, rbuf=%s, wbuf=%s) pid=%u\n"),
  1924. core_addr_to_string (offset), pulongest (len),
  1925. host_address_to_string (readbuf), host_address_to_string (writebuf),
  1926. inf->pid);
  1927. switch (object)
  1928. {
  1929. case TARGET_OBJECT_MEMORY:
  1930. {
  1931. int l = darwin_read_write_inferior (priv->task, offset,
  1932. readbuf, writebuf, len);
  1933. if (l == 0)
  1934. return TARGET_XFER_EOF;
  1935. else
  1936. {
  1937. gdb_assert (l > 0);
  1938. *xfered_len = (ULONGEST) l;
  1939. return TARGET_XFER_OK;
  1940. }
  1941. }
  1942. #ifdef TASK_DYLD_INFO_COUNT
  1943. case TARGET_OBJECT_DARWIN_DYLD_INFO:
  1944. if (writebuf != NULL || readbuf == NULL)
  1945. {
  1946. /* Support only read. */
  1947. return TARGET_XFER_E_IO;
  1948. }
  1949. return darwin_read_dyld_info (priv->task, offset, readbuf, len,
  1950. xfered_len);
  1951. #endif
  1952. default:
  1953. return TARGET_XFER_E_IO;
  1954. }
  1955. }
  1956. static void
  1957. set_enable_mach_exceptions (const char *args, int from_tty,
  1958. struct cmd_list_element *c)
  1959. {
  1960. if (inferior_ptid != null_ptid)
  1961. {
  1962. struct inferior *inf = current_inferior ();
  1963. darwin_inferior *priv = get_darwin_inferior (inf);
  1964. exception_mask_t mask;
  1965. kern_return_t kret;
  1966. if (enable_mach_exceptions)
  1967. mask = EXC_MASK_ALL;
  1968. else
  1969. {
  1970. darwin_restore_exception_ports (priv);
  1971. mask = EXC_MASK_SOFTWARE | EXC_MASK_BREAKPOINT;
  1972. }
  1973. kret = task_set_exception_ports (priv->task, mask, darwin_ex_port,
  1974. EXCEPTION_DEFAULT, THREAD_STATE_NONE);
  1975. MACH_CHECK_ERROR (kret);
  1976. }
  1977. }
  1978. char *
  1979. darwin_nat_target::pid_to_exec_file (int pid)
  1980. {
  1981. static char path[PATH_MAX];
  1982. int res;
  1983. res = proc_pidinfo (pid, PROC_PIDPATHINFO, 0, path, PATH_MAX);
  1984. if (res >= 0)
  1985. return path;
  1986. else
  1987. return NULL;
  1988. }
  1989. ptid_t
  1990. darwin_nat_target::get_ada_task_ptid (long lwp, ULONGEST thread)
  1991. {
  1992. struct inferior *inf = current_inferior ();
  1993. darwin_inferior *priv = get_darwin_inferior (inf);
  1994. kern_return_t kret;
  1995. mach_port_name_array_t names;
  1996. mach_msg_type_number_t names_count;
  1997. mach_port_type_array_t types;
  1998. mach_msg_type_number_t types_count;
  1999. long res = 0;
  2000. /* First linear search. */
  2001. for (darwin_thread_t *t : priv->threads)
  2002. {
  2003. if (t->inf_port == lwp)
  2004. return ptid_t (inferior_ptid.pid (), 0, t->gdb_port);
  2005. }
  2006. /* Maybe the port was never extract. Do it now. */
  2007. /* First get inferior port names. */
  2008. kret = mach_port_names (priv->task, &names, &names_count, &types,
  2009. &types_count);
  2010. MACH_CHECK_ERROR (kret);
  2011. if (kret != KERN_SUCCESS)
  2012. return null_ptid;
  2013. /* For each name, copy the right in the gdb space and then compare with
  2014. our view of the inferior threads. We don't forget to deallocate the
  2015. right. */
  2016. for (int i = 0; i < names_count; i++)
  2017. {
  2018. mach_port_t local_name;
  2019. mach_msg_type_name_t local_type;
  2020. /* We just need to know the corresponding name in gdb name space.
  2021. So extract and deallocate the right. */
  2022. kret = mach_port_extract_right (priv->task, names[i],
  2023. MACH_MSG_TYPE_COPY_SEND,
  2024. &local_name, &local_type);
  2025. if (kret != KERN_SUCCESS)
  2026. continue;
  2027. mach_port_deallocate (gdb_task, local_name);
  2028. for (darwin_thread_t *t : priv->threads)
  2029. {
  2030. if (t->gdb_port == local_name)
  2031. {
  2032. t->inf_port = names[i];
  2033. if (names[i] == lwp)
  2034. res = t->gdb_port;
  2035. }
  2036. }
  2037. }
  2038. vm_deallocate (gdb_task, (vm_address_t) names,
  2039. names_count * sizeof (mach_port_t));
  2040. if (res)
  2041. return ptid_t (current_inferior ()->pid, 0, res);
  2042. else
  2043. return null_ptid;
  2044. }
  2045. bool
  2046. darwin_nat_target::supports_multi_process ()
  2047. {
  2048. return true;
  2049. }
  2050. void _initialize_darwin_nat ();
  2051. void
  2052. _initialize_darwin_nat ()
  2053. {
  2054. kern_return_t kret;
  2055. gdb_task = mach_task_self ();
  2056. darwin_host_self = mach_host_self ();
  2057. /* Read page size. */
  2058. kret = host_page_size (darwin_host_self, &mach_page_size);
  2059. if (kret != KERN_SUCCESS)
  2060. {
  2061. mach_page_size = 0x1000;
  2062. MACH_CHECK_ERROR (kret);
  2063. }
  2064. inferior_debug (2, _("GDB task: 0x%lx, pid: %d\n"),
  2065. (unsigned long) mach_task_self (), getpid ());
  2066. add_setshow_zuinteger_cmd ("darwin", class_obscure,
  2067. &darwin_debug_flag, _("\
  2068. Set if printing inferior communication debugging statements."), _("\
  2069. Show if printing inferior communication debugging statements."), NULL,
  2070. NULL, NULL,
  2071. &setdebuglist, &showdebuglist);
  2072. add_setshow_boolean_cmd ("mach-exceptions", class_support,
  2073. &enable_mach_exceptions, _("\
  2074. Set if mach exceptions are caught."), _("\
  2075. Show if mach exceptions are caught."), _("\
  2076. When this mode is on, all low level exceptions are reported before being\n\
  2077. reported by the kernel."),
  2078. &set_enable_mach_exceptions, NULL,
  2079. &setlist, &showlist);
  2080. }