1 /*
2 * Copyright (c) 2000-2019 Apple Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28
29 /*
30 * Copyright (c) 1982, 1986, 1993
31 * The Regents of the University of California. All rights reserved.
32 */
33
34 /*
35 * Kernel Debugging Protocol UDP implementation.
36 */
37
38 #include <mach/boolean.h>
39 #include <mach/mach_types.h>
40 #include <mach/exception_types.h>
41 #include <kern/cpu_data.h>
42 #include <kern/debug.h>
43 #include <kern/clock.h>
44
45 #include <kdp/kdp_core.h>
46 #include <kdp/kdp_internal.h>
47 #if (MACH_KDP && CONFIG_KDP_INTERACTIVE_DEBUGGING)
48 #include <kdp/kdp_en_debugger.h>
49 #endif
50 #include <kdp/kdp_callout.h>
51 #include <kdp/kdp_udp.h>
52 #include <kdp/kdp_core.h>
53 #if CONFIG_SERIAL_KDP
54 #include <kdp/kdp_serial.h>
55 #endif
56
57 #include <vm/vm_map.h>
58 #include <vm/vm_protos.h>
59 #include <vm/vm_kern.h> /* kernel_map */
60
61 #include <mach/memory_object_types.h>
62 #include <machine/pal_routines.h>
63
64 #include <sys/msgbuf.h>
65
66 /* we just want the link status flags, so undef KERNEL_PRIVATE for this
67 * header file. */
68 #undef KERNEL_PRIVATE
69 #include <net/if_media.h>
70 #define KERNEL_PRIVATE
71
72 #include <string.h>
73
74 #include <IOKit/IOPlatformExpert.h>
75 #include <libkern/version.h>
76
77 #include <sys/pgo.h>
78
79 extern unsigned int not_in_kdp;
80 extern int kdp_snapshot;
81
82 #ifdef CONFIG_KDP_INTERACTIVE_DEBUGGING
83
84 extern int inet_aton(const char *, struct kdp_in_addr *); /* in libkern */
85 extern char *inet_ntoa_r(struct kdp_in_addr ina, char *buf,
86 size_t buflen); /* in libkern */
87
88 #define DO_ALIGN 1 /* align all packet data accesses */
89 #define KDP_SERIAL_IPADDR 0xABADBABE /* IP address used for serial KDP */
90 #define LINK_UP_STATUS (IFM_AVALID | IFM_ACTIVE)
91
92 extern int kdp_getc(void);
93 extern int reattach_wait;
94
95 static u_short ip_id; /* ip packet ctr, for ids */
96
97 /* @(#)udp_usrreq.c 2.2 88/05/23 4.0NFSSRC SMI; from UCB 7.1 6/5/86 */
98
99 /*
100 * UDP protocol implementation.
101 * Per RFC 768, August, 1980.
102 */
103 #define UDP_TTL 60 /* default time to live for UDP packets */
104 static u_char udp_ttl = UDP_TTL;
105 static unsigned char exception_seq;
106
107 struct kdp_ipovly {
108 uint32_t ih_next, ih_prev; /* for protocol sequence q's */
109 u_char ih_x1; /* (unused) */
110 u_char ih_pr; /* protocol */
111 short ih_len; /* protocol length */
112 struct kdp_in_addr ih_src; /* source internet address */
113 struct kdp_in_addr ih_dst; /* destination internet address */
114 };
115
116 struct kdp_udphdr {
117 u_short uh_sport; /* source port */
118 u_short uh_dport; /* destination port */
119 short uh_ulen; /* udp length */
120 u_short uh_sum; /* udp checksum */
121 };
122
123 struct kdp_udpiphdr {
124 struct kdp_ipovly ui_i; /* overlaid ip structure */
125 struct kdp_udphdr ui_u; /* udp header */
126 };
127 #define ui_next ui_i.ih_next
128 #define ui_prev ui_i.ih_prev
129 #define ui_x1 ui_i.ih_x1
130 #define ui_pr ui_i.ih_pr
131 #define ui_len ui_i.ih_len
132 #define ui_src ui_i.ih_src
133 #define ui_dst ui_i.ih_dst
134 #define ui_sport ui_u.uh_sport
135 #define ui_dport ui_u.uh_dport
136 #define ui_ulen ui_u.uh_ulen
137 #define ui_sum ui_u.uh_sum
138
139 struct kdp_ip {
140 union {
141 uint32_t ip_w;
142 struct {
143 unsigned int
144 #ifdef __LITTLE_ENDIAN__
145 ip_xhl:4, /* header length */
146 ip_xv:4, /* version */
147 ip_xtos:8, /* type of service */
148 ip_xlen:16; /* total length */
149 #endif
150 #ifdef __BIG_ENDIAN__
151 ip_xv:4, /* version */
152 ip_xhl:4, /* header length */
153 ip_xtos:8, /* type of service */
154 ip_xlen:16; /* total length */
155 #endif
156 } ip_x;
157 } ip_vhltl;
158 u_short ip_id; /* identification */
159 short ip_off; /* fragment offset field */
160 #define IP_DF 0x4000 /* dont fragment flag */
161 #define IP_MF 0x2000 /* more fragments flag */
162 #define IP_OFFMASK 0x1fff /* mask for fragmenting bits */
163 u_char ip_ttl; /* time to live */
164 u_char ip_p; /* protocol */
165 u_short ip_sum; /* checksum */
166 struct kdp_in_addr ip_src, ip_dst; /* source and dest address */
167 };
168 #define ip_v ip_vhltl.ip_x.ip_xv
169 #define ip_hl ip_vhltl.ip_x.ip_xhl
170 #define ip_tos ip_vhltl.ip_x.ip_xtos
171 #define ip_len ip_vhltl.ip_x.ip_xlen
172
173 #define IPPROTO_UDP 17
174 #define IPVERSION 4
175
176 #define ETHERTYPE_IP 0x0800 /* IP protocol */
177
178 /*
179 * Ethernet Address Resolution Protocol.
180 *
181 * See RFC 826 for protocol description. Structure below is adapted
182 * to resolving internet addresses. Field names used correspond to
183 * RFC 826.
184 */
185
186 #define ETHERTYPE_ARP 0x0806 /* Addr. resolution protocol */
187
188 struct kdp_arphdr {
189 u_short ar_hrd; /* format of hardware address */
190 #define ARPHRD_ETHER 1 /* ethernet hardware format */
191 #define ARPHRD_FRELAY 15 /* frame relay hardware format */
192 u_short ar_pro; /* format of protocol address */
193 u_char ar_hln; /* length of hardware address */
194 u_char ar_pln; /* length of protocol address */
195 u_short ar_op; /* one of: */
196 #define ARPOP_REQUEST 1 /* request to resolve address */
197 #define ARPOP_REPLY 2 /* response to previous request */
198 #define ARPOP_REVREQUEST 3 /* request protocol address given hardware */
199 #define ARPOP_REVREPLY 4 /* response giving protocol address */
200 #define ARPOP_INVREQUEST 8 /* request to identify peer */
201 #define ARPOP_INVREPLY 9 /* response identifying peer */
202 };
203
204 struct kdp_ether_arp {
205 struct kdp_arphdr ea_hdr; /* fixed-size header */
206 u_char arp_sha[ETHER_ADDR_LEN]; /* sender hardware address */
207 u_char arp_spa[4]; /* sender protocol address */
208 u_char arp_tha[ETHER_ADDR_LEN]; /* target hardware address */
209 u_char arp_tpa[4]; /* target protocol address */
210 };
211 #define arp_hrd ea_hdr.ar_hrd
212 #define arp_pro ea_hdr.ar_pro
213 #define arp_hln ea_hdr.ar_hln
214 #define arp_pln ea_hdr.ar_pln
215 #define arp_op ea_hdr.ar_op
216
217 #define ETHERMTU 1500
218 #define ETHERHDRSIZE 14
219 #define ETHERCRC 4
220 #define KDP_MAXPACKET (ETHERHDRSIZE + ETHERMTU + ETHERCRC)
221
222 static struct {
223 unsigned char data[KDP_MAXPACKET];
224 unsigned int off, len;
225 boolean_t input;
226 } pkt, saved_reply;
227
228 struct kdp_manual_pkt manual_pkt;
229
230 struct {
231 struct {
232 struct kdp_in_addr in;
233 struct kdp_ether_addr ea;
234 } loc;
235 struct {
236 struct kdp_in_addr in;
237 struct kdp_ether_addr ea;
238 } rmt;
239 } adr;
240
241 static const char
242 *exception_message[] = {
243 "Unknown",
244 "Memory access", /* EXC_BAD_ACCESS */
245 "Failed instruction", /* EXC_BAD_INSTRUCTION */
246 "Arithmetic", /* EXC_ARITHMETIC */
247 "Emulation", /* EXC_EMULATION */
248 "Software", /* EXC_SOFTWARE */
249 "Breakpoint" /* EXC_BREAKPOINT */
250 };
251
252 volatile int kdp_flag = 0;
253 boolean_t kdp_corezip_disabled = 0;
254
255 kdp_send_t kdp_en_send_pkt;
256 static kdp_receive_t kdp_en_recv_pkt;
257 static kdp_link_t kdp_en_linkstatus;
258 static kdp_mode_t kdp_en_setmode;
259
260 #if CONFIG_SERIAL_KDP
261 static void kdp_serial_send(void *rpkt, unsigned int rpkt_len);
262 #define KDP_SERIAL_ENABLED() (kdp_en_send_pkt == kdp_serial_send)
263 #else
264 #define KDP_SERIAL_ENABLED() (0)
265 #endif
266
267 static uint32_t kdp_current_ip_address = 0;
268 static struct kdp_ether_addr kdp_current_mac_address = {.ether_addr_octet = {0, 0, 0, 0, 0, 0}};
269 static void *kdp_current_ifp;
270
271 static void kdp_handler( void *);
272
273 static uint32_t panic_server_ip = 0;
274 static uint32_t parsed_router_ip = 0;
275 static uint32_t router_ip = 0;
276 static uint32_t target_ip = 0;
277
278 static boolean_t save_ip_in_nvram = FALSE;
279
280 static volatile boolean_t panicd_specified = FALSE;
281 static boolean_t router_specified = FALSE;
282 static boolean_t corename_specified = FALSE;
283 static unsigned short panicd_port = CORE_REMOTE_PORT;
284
285 static struct kdp_ether_addr etherbroadcastaddr = {.ether_addr_octet = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}};
286
287 static struct kdp_ether_addr router_mac = {.ether_addr_octet = {0, 0, 0, 0, 0, 0}};
288 static struct kdp_ether_addr destination_mac = {.ether_addr_octet = {0, 0, 0, 0, 0, 0}};
289 static struct kdp_ether_addr temp_mac = {.ether_addr_octet = {0, 0, 0, 0, 0, 0}};
290 static struct kdp_ether_addr current_resolved_MAC = {.ether_addr_octet = {0, 0, 0, 0, 0, 0}};
291
292 static boolean_t flag_panic_dump_in_progress = FALSE;
293 static boolean_t flag_router_mac_initialized = FALSE;
294 static boolean_t flag_dont_abort_panic_dump = FALSE;
295
296 static boolean_t flag_arp_resolved = FALSE;
297
298 static unsigned int panic_timeout = 100000;
299 static unsigned short last_panic_port = CORE_REMOTE_PORT;
300
301 #define KDP_THROTTLE_VALUE (10ULL * NSEC_PER_SEC)
302
303 uint32_t kdp_crashdump_pkt_size = 512;
304 #define KDP_LARGE_CRASHDUMP_PKT_SIZE (1440 - 6 - sizeof(struct kdp_udpiphdr))
305 static char panicd_ip_str[20];
306 static char router_ip_str[20];
307 static char corename_str[100];
308
309 static unsigned int panic_block = 0;
310 volatile unsigned int kdp_trigger_core_dump = 0;
311 __private_extern__ volatile unsigned int flag_kdp_trigger_reboot = 0;
312
313
314 extern unsigned int disableConsoleOutput;
315
316 extern void kdp_call(void);
317
318 void * kdp_get_interface(void);
319 void kdp_set_gateway_mac(void *gatewaymac);
320 void kdp_set_ip_and_mac_addresses(struct kdp_in_addr *ipaddr, struct kdp_ether_addr *);
321 void kdp_set_interface(void *interface, const struct kdp_ether_addr *macaddr);
322
323 void kdp_disable_arp(void);
324 static void kdp_arp_reply(struct kdp_ether_arp *);
325 static void kdp_process_arp_reply(struct kdp_ether_arp *);
326 static boolean_t kdp_arp_resolve(uint32_t, struct kdp_ether_addr *);
327
328 static volatile unsigned kdp_reentry_deadline;
329
330 static uint32_t kdp_crashdump_feature_mask = KDP_FEATURE_LARGE_CRASHDUMPS | KDP_FEATURE_LARGE_PKT_SIZE;
331 uint32_t kdp_feature_large_crashdumps, kdp_feature_large_pkt_size;
332
333 char kdp_kernelversion_string[256];
334
335 static boolean_t gKDPDebug = FALSE;
336
337 #define KDP_DEBUG(...) if (gKDPDebug) printf(__VA_ARGS__);
338
339 #define SBLOCKSZ (2048)
340 uint64_t kdp_dump_start_time = 0;
341 uint64_t kdp_min_superblock_dump_time = ~1ULL;
342 uint64_t kdp_max_superblock_dump_time = 0;
343 uint64_t kdp_superblock_dump_time = 0;
344 uint64_t kdp_superblock_dump_start_time = 0;
345 static thread_call_t
346 kdp_timer_call;
347
348 static void
kdp_ml_enter_debugger_wrapper(__unused void * param0,__unused void * param1)349 kdp_ml_enter_debugger_wrapper(__unused void *param0, __unused void *param1)
350 {
351 kdp_ml_enter_debugger();
352 }
353
354 static void
kdp_timer_callout_init(void)355 kdp_timer_callout_init(void)
356 {
357 kdp_timer_call = thread_call_allocate(kdp_ml_enter_debugger_wrapper, NULL);
358 }
359
360
361 /* only send/receive data if the link is up */
362 inline static void
wait_for_link(void)363 wait_for_link(void)
364 {
365 static int first = 0;
366
367 if (!kdp_en_linkstatus) {
368 return;
369 }
370
371 while (((*kdp_en_linkstatus)() & LINK_UP_STATUS) != LINK_UP_STATUS) {
372 if (first) {
373 continue;
374 }
375
376 first = 1;
377 printf("Waiting for link to become available.\n");
378 kprintf("Waiting for link to become available.\n");
379 }
380 }
381
382
383 inline static void
kdp_send_data(void * packet,unsigned int len)384 kdp_send_data(void *packet, unsigned int len)
385 {
386 wait_for_link();
387 (*kdp_en_send_pkt)(packet, len);
388 }
389
390
391 inline static void
kdp_receive_data(void * packet,unsigned int * len,unsigned int timeout)392 kdp_receive_data(void *packet, unsigned int *len, unsigned int timeout)
393 {
394 wait_for_link();
395 (*kdp_en_recv_pkt)(packet, len, timeout);
396 }
397
398
399 void
kdp_register_link(kdp_link_t link,kdp_mode_t mode)400 kdp_register_link(kdp_link_t link, kdp_mode_t mode)
401 {
402 kdp_en_linkstatus = link;
403 kdp_en_setmode = mode;
404 }
405
406 void
kdp_unregister_link(__unused kdp_link_t link,__unused kdp_mode_t mode)407 kdp_unregister_link(__unused kdp_link_t link, __unused kdp_mode_t mode)
408 {
409 kdp_en_linkstatus = NULL;
410 kdp_en_setmode = NULL;
411 }
412
413 void
kdp_register_send_receive(kdp_send_t send,kdp_receive_t receive)414 kdp_register_send_receive(
415 kdp_send_t send,
416 kdp_receive_t receive)
417 {
418 unsigned int debug = debug_boot_arg;
419
420 if (kernel_debugging_restricted()) {
421 return;
422 }
423
424 if (!debug) {
425 return;
426 }
427
428 kdp_en_send_pkt = send;
429 kdp_en_recv_pkt = receive;
430
431 if (debug & DB_KDP_BP_DIS) {
432 kdp_flag |= KDP_BP_DIS;
433 }
434 if (debug & DB_KDP_GETC_ENA) {
435 kdp_flag |= KDP_GETC_ENA;
436 }
437 if (debug & DB_ARP) {
438 kdp_flag |= KDP_ARP;
439 }
440
441 if (debug & DB_KERN_DUMP_ON_PANIC) {
442 kdp_flag |= KDP_PANIC_DUMP_ENABLED;
443 }
444 if (debug & DB_KERN_DUMP_ON_NMI) {
445 kdp_flag |= PANIC_CORE_ON_NMI;
446 }
447
448 if (debug & DB_DBG_POST_CORE) {
449 kdp_flag |= DBG_POST_CORE;
450 }
451
452 if (debug & DB_PANICLOG_DUMP) {
453 kdp_flag |= PANIC_LOG_DUMP;
454 }
455
456 kdp_corezip_disabled = (0 != (debug & DB_DISABLE_GZIP_CORE));
457
458 if (PE_parse_boot_argn("_panicd_ip", panicd_ip_str, sizeof(panicd_ip_str))) {
459 panicd_specified = TRUE;
460 }
461
462 if ((debug & DB_REBOOT_POST_CORE) && (panicd_specified == TRUE)) {
463 kdp_flag |= REBOOT_POST_CORE;
464 }
465
466 if (PE_parse_boot_argn("_router_ip", router_ip_str, sizeof(router_ip_str))) {
467 router_specified = TRUE;
468 }
469
470 if (!PE_parse_boot_argn("panicd_port", &panicd_port, sizeof(panicd_port))) {
471 panicd_port = CORE_REMOTE_PORT;
472 }
473
474 if (PE_parse_boot_argn("_panicd_corename", &corename_str, sizeof(corename_str))) {
475 corename_specified = TRUE;
476 }
477
478 kdp_flag |= KDP_READY;
479
480 current_debugger = KDP_CUR_DB;
481 if ((kdp_current_ip_address != 0) && halt_in_debugger) {
482 kdp_call();
483 halt_in_debugger = 0;
484 }
485 }
486
487 void
kdp_unregister_send_receive(__unused kdp_send_t send,__unused kdp_receive_t receive)488 kdp_unregister_send_receive(
489 __unused kdp_send_t send,
490 __unused kdp_receive_t receive)
491 {
492 if (current_debugger == KDP_CUR_DB) {
493 current_debugger = NO_CUR_DB;
494 }
495 kdp_flag &= ~KDP_READY;
496 kdp_en_send_pkt = NULL;
497 kdp_en_recv_pkt = NULL;
498 }
499
500 static void
kdp_schedule_debugger_reentry(unsigned interval)501 kdp_schedule_debugger_reentry(unsigned interval)
502 {
503 uint64_t deadline;
504
505 clock_interval_to_deadline(interval, 1000 * 1000, &deadline);
506 thread_call_enter_delayed(kdp_timer_call, deadline);
507 }
508
509 static void
enaddr_copy(void * src,void * dst)510 enaddr_copy(
511 void *src,
512 void *dst
513 )
514 {
515 bcopy((char *)src, (char *)dst, sizeof(struct kdp_ether_addr));
516 }
517
518 static unsigned short
ip_sum(unsigned char * c,unsigned int hlen)519 ip_sum(
520 unsigned char *c,
521 unsigned int hlen
522 )
523 {
524 unsigned int high, low, sum;
525
526 high = low = 0;
527 while (hlen-- > 0) {
528 low += c[1] + c[3];
529 high += c[0] + c[2];
530
531 c += sizeof(int);
532 }
533
534 sum = (high << 8) + low;
535 sum = (sum >> 16) + (sum & USHRT_MAX);
536 sum = (sum > USHRT_MAX) ? sum - USHRT_MAX : sum;
537
538 return (unsigned short)sum;
539 }
540
541 static void
kdp_reply(unsigned short reply_port,const boolean_t sideband)542 kdp_reply(
543 unsigned short reply_port,
544 const boolean_t sideband
545 )
546 {
547 struct kdp_udpiphdr aligned_ui, *ui = &aligned_ui;
548 struct kdp_ip aligned_ip, *ip = &aligned_ip;
549 struct kdp_in_addr tmp_ipaddr;
550 struct kdp_ether_addr tmp_enaddr;
551 struct kdp_ether_header *eh = NULL;
552
553 if (!pkt.input) {
554 kdp_panic("kdp_reply: no input packet");
555 }
556
557 /* Packet size cannot be larger than the static space allocated for it. */
558 if (pkt.len > KDP_MAXPACKET) {
559 kdp_panic("kdp_send: packet too large (%d > %u)", pkt.len, KDP_MAXPACKET);
560 }
561
562 pkt.off -= (unsigned int)sizeof(struct kdp_udpiphdr);
563
564 #if DO_ALIGN
565 bcopy((char *)&pkt.data[pkt.off], (char *)ui, sizeof(*ui));
566 #else
567 ui = (struct kdp_udpiphdr *)&pkt.data[pkt.off];
568 #endif
569 ui->ui_next = ui->ui_prev = 0;
570 ui->ui_x1 = 0;
571 ui->ui_pr = IPPROTO_UDP;
572 ui->ui_len = htons((u_short)pkt.len + sizeof(struct kdp_udphdr));
573 tmp_ipaddr = ui->ui_src;
574 ui->ui_src = ui->ui_dst;
575 ui->ui_dst = tmp_ipaddr;
576 ui->ui_sport = htons(KDP_REMOTE_PORT);
577 ui->ui_dport = reply_port;
578 ui->ui_ulen = ui->ui_len;
579 ui->ui_sum = 0;
580 #if DO_ALIGN
581 bcopy((char *)ui, (char *)&pkt.data[pkt.off], sizeof(*ui));
582 bcopy((char *)&pkt.data[pkt.off], (char *)ip, sizeof(*ip));
583 #else
584 ip = (struct kdp_ip *)&pkt.data[pkt.off];
585 #endif
586 ip->ip_len = htons((ushort_t)(sizeof(struct kdp_udpiphdr) + pkt.len));
587 ip->ip_v = IPVERSION;
588 ip->ip_id = htons(ip_id++);
589 ip->ip_hl = sizeof(struct kdp_ip) >> 2;
590 ip->ip_ttl = udp_ttl;
591 ip->ip_sum = 0;
592 ip->ip_sum = htons(~ip_sum((unsigned char *)ip, ip->ip_hl));
593 #if DO_ALIGN
594 bcopy((char *)ip, (char *)&pkt.data[pkt.off], sizeof(*ip));
595 #endif
596
597 pkt.len += (unsigned int)sizeof(struct kdp_udpiphdr);
598
599 pkt.off -= (unsigned int)sizeof(struct kdp_ether_header);
600
601 eh = (struct kdp_ether_header *)&pkt.data[pkt.off];
602 enaddr_copy(eh->ether_shost, &tmp_enaddr);
603 enaddr_copy(eh->ether_dhost, eh->ether_shost);
604 enaddr_copy(&tmp_enaddr, eh->ether_dhost);
605 eh->ether_type = htons(ETHERTYPE_IP);
606
607 pkt.len += (unsigned int)sizeof(struct kdp_ether_header);
608
609 // save reply for possible retransmission
610 if (!sideband) {
611 bcopy((char *)&pkt, (char *)&saved_reply, sizeof(saved_reply));
612 }
613
614 kdp_send_data(&pkt.data[pkt.off], pkt.len);
615
616 // increment expected sequence number
617 if (!sideband) {
618 exception_seq++;
619 }
620 }
621
622 static void
kdp_send(unsigned short remote_port)623 kdp_send(
624 unsigned short remote_port
625 )
626 {
627 struct kdp_udpiphdr aligned_ui, *ui = &aligned_ui;
628 struct kdp_ip aligned_ip, *ip = &aligned_ip;
629 struct kdp_ether_header *eh;
630
631 if (pkt.input) {
632 kdp_panic("kdp_send: no input packet");
633 }
634
635 /* Packet size cannot be larger than the static space allocated for it. */
636 if (pkt.len > KDP_MAXPACKET) {
637 kdp_panic("kdp_send: packet too large (%d > %u)", pkt.len, KDP_MAXPACKET);
638 }
639
640 pkt.off -= (unsigned int)sizeof(struct kdp_udpiphdr);
641
642 #if DO_ALIGN
643 bcopy((char *)&pkt.data[pkt.off], (char *)ui, sizeof(*ui));
644 #else
645 ui = (struct kdp_udpiphdr *)&pkt.data[pkt.off];
646 #endif
647 ui->ui_next = ui->ui_prev = 0;
648 ui->ui_x1 = 0;
649 ui->ui_pr = IPPROTO_UDP;
650 ui->ui_len = htons((u_short)pkt.len + sizeof(struct kdp_udphdr));
651 ui->ui_src = adr.loc.in;
652 ui->ui_dst = adr.rmt.in;
653 ui->ui_sport = htons(KDP_REMOTE_PORT);
654 ui->ui_dport = remote_port;
655 ui->ui_ulen = ui->ui_len;
656 ui->ui_sum = 0;
657 #if DO_ALIGN
658 bcopy((char *)ui, (char *)&pkt.data[pkt.off], sizeof(*ui));
659 bcopy((char *)&pkt.data[pkt.off], (char *)ip, sizeof(*ip));
660 #else
661 ip = (struct kdp_ip *)&pkt.data[pkt.off];
662 #endif
663 ip->ip_len = htons((ushort_t)(sizeof(struct kdp_udpiphdr) + pkt.len));
664 ip->ip_v = IPVERSION;
665 ip->ip_id = htons(ip_id++);
666 ip->ip_hl = sizeof(struct kdp_ip) >> 2;
667 ip->ip_ttl = udp_ttl;
668 ip->ip_sum = 0;
669 ip->ip_sum = htons(~ip_sum((unsigned char *)ip, ip->ip_hl));
670 #if DO_ALIGN
671 bcopy((char *)ip, (char *)&pkt.data[pkt.off], sizeof(*ip));
672 #endif
673
674 pkt.len += (unsigned int)sizeof(struct kdp_udpiphdr);
675
676 pkt.off -= (unsigned int)sizeof(struct kdp_ether_header);
677
678 eh = (struct kdp_ether_header *)&pkt.data[pkt.off];
679 enaddr_copy(&adr.loc.ea, eh->ether_shost);
680 enaddr_copy(&adr.rmt.ea, eh->ether_dhost);
681 eh->ether_type = htons(ETHERTYPE_IP);
682
683 pkt.len += (unsigned int)sizeof(struct kdp_ether_header);
684 kdp_send_data(&pkt.data[pkt.off], pkt.len);
685 }
686
687
688 inline static void
debugger_if_necessary(void)689 debugger_if_necessary(void)
690 {
691 if ((current_debugger == KDP_CUR_DB) && halt_in_debugger) {
692 kdp_call();
693 halt_in_debugger = 0;
694 }
695 }
696
697
698 /* We don't interpret this pointer, we just give it to the bsd stack
699 * so it can decide when to set the MAC and IP info. We'll
700 * early initialize the MAC/IP info if we can so that we can use
701 * KDP early in boot. These values may subsequently get over-written
702 * when the interface gets initialized for real.
703 */
704 void
kdp_set_interface(void * ifp,const struct kdp_ether_addr * macaddr)705 kdp_set_interface(void *ifp, const struct kdp_ether_addr *macaddr)
706 {
707 char kdpstr[80];
708 struct kdp_in_addr addr = { .s_addr = 0 };
709 unsigned int len;
710
711 kdp_current_ifp = ifp;
712
713 if (PE_parse_boot_argn("kdp_ip_addr", kdpstr, sizeof(kdpstr))) {
714 /* look for a static ip address */
715 if (inet_aton(kdpstr, &addr) == FALSE) {
716 goto done;
717 }
718
719 goto config_network;
720 }
721
722 /* use saved ip address */
723 save_ip_in_nvram = TRUE;
724
725 len = sizeof(kdpstr);
726 if (PEReadNVRAMProperty("_kdp_ipstr", kdpstr, &len) == FALSE) {
727 goto done;
728 }
729
730 kdpstr[len < sizeof(kdpstr) ? len : sizeof(kdpstr) - 1] = '\0';
731 if (inet_aton(kdpstr, &addr) == FALSE) {
732 goto done;
733 }
734
735 config_network:
736 kdp_current_ip_address = addr.s_addr;
737 if (macaddr) {
738 kdp_current_mac_address = *macaddr;
739 }
740
741 /* we can't drop into the debugger at this point because the
742 * link will likely not be up. when getDebuggerLinkStatus() support gets
743 * added to the appropriate network drivers, adding the
744 * following will enable this capability:
745 * debugger_if_necessary();
746 */
747 done:
748 return;
749 }
750
751 void *
kdp_get_interface(void)752 kdp_get_interface(void)
753 {
754 return kdp_current_ifp;
755 }
756
757 void
kdp_set_ip_and_mac_addresses(struct kdp_in_addr * ipaddr,struct kdp_ether_addr * macaddr)758 kdp_set_ip_and_mac_addresses(
759 struct kdp_in_addr *ipaddr,
760 struct kdp_ether_addr *macaddr)
761 {
762 static uint64_t last_time = (uint64_t) -1;
763 static uint64_t throttle_val = 0;
764 uint64_t cur_time;
765 char addr[16];
766
767 if (kdp_current_ip_address == ipaddr->s_addr) {
768 goto done;
769 }
770
771 /* don't replace if serial debugging is configured */
772 if (!KDP_SERIAL_ENABLED() ||
773 (kdp_current_ip_address != KDP_SERIAL_IPADDR)) {
774 kdp_current_mac_address = *macaddr;
775 kdp_current_ip_address = ipaddr->s_addr;
776 }
777
778 if (save_ip_in_nvram == FALSE) {
779 goto done;
780 }
781
782 if (inet_ntoa_r(*ipaddr, addr, sizeof(addr)) == NULL) {
783 goto done;
784 }
785
786 /* throttle writes if needed */
787 if (!throttle_val) {
788 nanoseconds_to_absolutetime(KDP_THROTTLE_VALUE, &throttle_val);
789 }
790
791 cur_time = mach_absolute_time();
792 if (last_time == (uint64_t) -1 ||
793 ((cur_time - last_time) > throttle_val)) {
794 PEWriteNVRAMProperty("_kdp_ipstr", addr,
795 (const unsigned int) strlen(addr));
796 }
797 last_time = cur_time;
798
799 done:
800 debugger_if_necessary();
801 }
802
803 void
kdp_set_gateway_mac(void * gatewaymac)804 kdp_set_gateway_mac(void *gatewaymac)
805 {
806 router_mac = *(struct kdp_ether_addr *)gatewaymac;
807 flag_router_mac_initialized = TRUE;
808 }
809
810 struct kdp_ether_addr
kdp_get_mac_addr(void)811 kdp_get_mac_addr(void)
812 {
813 return kdp_current_mac_address;
814 }
815
816 unsigned int
kdp_get_ip_address(void)817 kdp_get_ip_address(void)
818 {
819 return (unsigned int)kdp_current_ip_address;
820 }
821
822 void
kdp_disable_arp(void)823 kdp_disable_arp(void)
824 {
825 kdp_flag &= ~(DB_ARP);
826 }
827
828 static void
kdp_arp_dispatch(void)829 kdp_arp_dispatch(void)
830 {
831 struct kdp_ether_arp aligned_ea, *ea = &aligned_ea;
832 unsigned arp_header_offset;
833
834 arp_header_offset = (unsigned)sizeof(struct kdp_ether_header) + pkt.off;
835 memcpy((void *)ea, (void *)&pkt.data[arp_header_offset], sizeof(*ea));
836
837 switch (ntohs(ea->arp_op)) {
838 case ARPOP_REQUEST:
839 kdp_arp_reply(ea);
840 break;
841 case ARPOP_REPLY:
842 kdp_process_arp_reply(ea);
843 break;
844 default:
845 return;
846 }
847 }
848
849 static void
kdp_process_arp_reply(struct kdp_ether_arp * ea)850 kdp_process_arp_reply(struct kdp_ether_arp *ea)
851 {
852 /* Are we interested in ARP replies? */
853 if (flag_arp_resolved == TRUE) {
854 return;
855 }
856
857 /* Did we receive a reply from the right source? */
858 if (((struct kdp_in_addr *)(ea->arp_spa))->s_addr != target_ip) {
859 return;
860 }
861
862 flag_arp_resolved = TRUE;
863 current_resolved_MAC = *(struct kdp_ether_addr *) (ea->arp_sha);
864
865 return;
866 }
867
868 /* ARP responses are enabled when the DB_ARP bit of the debug boot arg
869 * is set.
870 */
871
872 static void
kdp_arp_reply(struct kdp_ether_arp * ea)873 kdp_arp_reply(struct kdp_ether_arp *ea)
874 {
875 struct kdp_ether_header *eh;
876
877 struct kdp_in_addr isaddr, itaddr, myaddr;
878 struct kdp_ether_addr my_enaddr;
879
880 eh = (struct kdp_ether_header *)&pkt.data[pkt.off];
881 pkt.off += (unsigned int)sizeof(struct kdp_ether_header);
882
883 if (ntohs(ea->arp_op) != ARPOP_REQUEST) {
884 return;
885 }
886
887 myaddr.s_addr = kdp_get_ip_address();
888 my_enaddr = kdp_get_mac_addr();
889
890 if ((ntohl(myaddr.s_addr) == 0) ||
891 ((my_enaddr.ether_addr_octet[0] & 0xff) == 0
892 && (my_enaddr.ether_addr_octet[1] & 0xff) == 0
893 && (my_enaddr.ether_addr_octet[2] & 0xff) == 0
894 && (my_enaddr.ether_addr_octet[3] & 0xff) == 0
895 && (my_enaddr.ether_addr_octet[4] & 0xff) == 0
896 && (my_enaddr.ether_addr_octet[5] & 0xff) == 0
897 )) {
898 return;
899 }
900
901 (void)memcpy((void *)&isaddr, (void *)ea->arp_spa, sizeof(isaddr));
902 (void)memcpy((void *)&itaddr, (void *)ea->arp_tpa, sizeof(itaddr));
903
904 if (itaddr.s_addr == myaddr.s_addr) {
905 (void)memcpy((void *)ea->arp_tha, (void *)ea->arp_sha, sizeof(ea->arp_sha));
906 (void)memcpy((void *)ea->arp_sha, (void *)&my_enaddr, sizeof(ea->arp_sha));
907
908 (void)memcpy((void *)ea->arp_tpa, (void *) ea->arp_spa, sizeof(ea->arp_spa));
909 (void)memcpy((void *)ea->arp_spa, (void *) &itaddr, sizeof(ea->arp_spa));
910
911 ea->arp_op = htons(ARPOP_REPLY);
912 ea->arp_pro = htons(ETHERTYPE_IP);
913 (void)memcpy(eh->ether_dhost, ea->arp_tha, sizeof(eh->ether_dhost));
914 (void)memcpy(eh->ether_shost, &my_enaddr, sizeof(eh->ether_shost));
915 eh->ether_type = htons(ETHERTYPE_ARP);
916 (void)memcpy(&pkt.data[pkt.off], ea, sizeof(*ea));
917 pkt.off -= (unsigned int)sizeof(struct kdp_ether_header);
918 /* pkt.len is still the length we want, ether_header+ether_arp */
919 kdp_send_data(&pkt.data[pkt.off], pkt.len);
920 }
921 }
922
923 static void
kdp_poll(void)924 kdp_poll(void)
925 {
926 struct kdp_ether_header *eh = NULL;
927 struct kdp_udpiphdr aligned_ui, *ui = &aligned_ui;
928 struct kdp_ip aligned_ip, *ip = &aligned_ip;
929 static int msg_printed;
930
931 if (pkt.input) {
932 kdp_panic("kdp_poll");
933 }
934
935 if (!kdp_en_recv_pkt || !kdp_en_send_pkt) {
936 if (msg_printed == 0) {
937 msg_printed = 1;
938 printf("kdp_poll: no debugger device\n");
939 }
940 return;
941 }
942
943 pkt.off = pkt.len = 0;
944 kdp_receive_data(pkt.data, &pkt.len, 3 /* ms */);
945
946 if (pkt.len == 0) {
947 return;
948 }
949
950 if (pkt.len >= sizeof(struct kdp_ether_header)) {
951 eh = (struct kdp_ether_header *)&pkt.data[pkt.off];
952
953 if (kdp_flag & KDP_ARP) {
954 if (ntohs(eh->ether_type) == ETHERTYPE_ARP) {
955 kdp_arp_dispatch();
956 return;
957 }
958 }
959 }
960
961 if (pkt.len < (sizeof(struct kdp_ether_header) + sizeof(struct kdp_udpiphdr))) {
962 return;
963 }
964
965 pkt.off += (unsigned int)sizeof(struct kdp_ether_header);
966 if (ntohs(eh->ether_type) != ETHERTYPE_IP) {
967 return;
968 }
969
970 #if DO_ALIGN
971 bcopy((char *)&pkt.data[pkt.off], (char *)ui, sizeof(*ui));
972 bcopy((char *)&pkt.data[pkt.off], (char *)ip, sizeof(*ip));
973 #else
974 ui = (struct kdp_udpiphdr *)&pkt.data[pkt.off];
975 ip = (struct kdp_ip *)&pkt.data[pkt.off];
976 #endif
977
978 pkt.off += (unsigned int)sizeof(struct kdp_udpiphdr);
979 if (ui->ui_pr != IPPROTO_UDP) {
980 return;
981 }
982
983 if (ip->ip_hl > (sizeof(struct kdp_ip) >> 2)) {
984 return;
985 }
986
987 if (ntohs(ui->ui_dport) != KDP_REMOTE_PORT) {
988 if (panicd_port == (ntohs(ui->ui_dport)) &&
989 flag_panic_dump_in_progress) {
990 last_panic_port = ui->ui_sport;
991 } else {
992 return;
993 }
994 }
995 /* If we receive a kernel debugging packet whilst a
996 * core dump is in progress, abort the transfer and
997 * enter the debugger if not told otherwise.
998 */
999 else if (flag_panic_dump_in_progress) {
1000 if (!flag_dont_abort_panic_dump) {
1001 abort_panic_transfer();
1002 }
1003 return;
1004 }
1005
1006 if (!kdp.is_conn && !flag_panic_dump_in_progress) {
1007 enaddr_copy(eh->ether_dhost, &adr.loc.ea);
1008 adr.loc.in = ui->ui_dst;
1009
1010 enaddr_copy(eh->ether_shost, &adr.rmt.ea);
1011 adr.rmt.in = ui->ui_src;
1012 }
1013
1014 /*
1015 * Calculate kdp packet length.
1016 */
1017 pkt.len = ntohs((u_short)ui->ui_ulen) - (unsigned int)sizeof(struct kdp_udphdr);
1018 pkt.input = TRUE;
1019 }
1020
1021
1022 /* Create and transmit an ARP resolution request for the target IP address.
1023 * This is modeled on ether_inet_arp()/RFC 826.
1024 */
1025
1026 static void
transmit_ARP_request(uint32_t ip_addr)1027 transmit_ARP_request(uint32_t ip_addr)
1028 {
1029 struct kdp_ether_header *eh = (struct kdp_ether_header *) &pkt.data[0];
1030 struct kdp_ether_arp *ea = (struct kdp_ether_arp *) &pkt.data[sizeof(struct kdp_ether_header)];
1031
1032 KDP_DEBUG("Transmitting ARP request\n");
1033 /* Populate the ether_header */
1034 eh->ether_type = htons(ETHERTYPE_ARP);
1035 enaddr_copy(&kdp_current_mac_address, eh->ether_shost);
1036 enaddr_copy(ðerbroadcastaddr, eh->ether_dhost);
1037
1038 /* Populate the ARP header */
1039 ea->arp_pro = htons(ETHERTYPE_IP);
1040 ea->arp_hln = sizeof(ea->arp_sha);
1041 ea->arp_pln = sizeof(ea->arp_spa);
1042 ea->arp_hrd = htons(ARPHRD_ETHER);
1043 ea->arp_op = htons(ARPOP_REQUEST);
1044
1045 /* Target fields */
1046 enaddr_copy(ðerbroadcastaddr, ea->arp_tha);
1047 memcpy(ea->arp_tpa, (void *) &ip_addr, sizeof(ip_addr));
1048
1049 /* Source fields */
1050 enaddr_copy(&kdp_current_mac_address, ea->arp_sha);
1051 memcpy(ea->arp_spa, (void *) &kdp_current_ip_address, sizeof(kdp_current_ip_address));
1052
1053 pkt.off = 0;
1054 pkt.len = sizeof(struct kdp_ether_header) + sizeof(struct kdp_ether_arp);
1055 /* Transmit */
1056 kdp_send_data(&pkt.data[pkt.off], pkt.len);
1057 }
1058
1059 static boolean_t
kdp_arp_resolve(uint32_t arp_target_ip,struct kdp_ether_addr * resolved_MAC)1060 kdp_arp_resolve(uint32_t arp_target_ip, struct kdp_ether_addr *resolved_MAC)
1061 {
1062 int poll_count = 256; /* ~770 ms modulo broadcast/delayed traffic? */
1063 char tretries = 0;
1064
1065 #define NUM_ARP_TX_RETRIES 5
1066
1067 target_ip = arp_target_ip;
1068 flag_arp_resolved = FALSE;
1069
1070 TRANSMIT_RETRY:
1071 pkt.off = pkt.len = 0;
1072
1073 tretries++;
1074
1075 if (tretries >= NUM_ARP_TX_RETRIES) {
1076 return FALSE;
1077 }
1078
1079 KDP_DEBUG("ARP TX attempt #%d \n", tretries);
1080
1081 transmit_ARP_request(arp_target_ip);
1082
1083 while (!pkt.input && !flag_arp_resolved && flag_panic_dump_in_progress && --poll_count) {
1084 kdp_poll();
1085 }
1086
1087 if (flag_arp_resolved) {
1088 *resolved_MAC = current_resolved_MAC;
1089 return TRUE;
1090 }
1091
1092 if (!flag_panic_dump_in_progress || pkt.input) { /* we received a debugging packet, bail*/
1093 printf("Received a debugger packet,transferring control to debugger\n");
1094 /* Indicate that we should wait in the debugger when we return */
1095 kdp_flag |= DBG_POST_CORE;
1096 pkt.input = FALSE;
1097 return FALSE;
1098 } else { /* We timed out */
1099 if (0 == poll_count) {
1100 poll_count = 256;
1101 goto TRANSMIT_RETRY;
1102 }
1103 }
1104 return FALSE;
1105 }
1106
1107 static void
kdp_handler(void * saved_state)1108 kdp_handler(
1109 void *saved_state
1110 )
1111 {
1112 unsigned short reply_port;
1113 kdp_hdr_t aligned_hdr, *hdr = &aligned_hdr;
1114
1115 kdp.saved_state = saved_state; // see comment in kdp_raise_exception
1116
1117 do {
1118 while (!pkt.input) {
1119 kdp_poll();
1120 }
1121
1122 #if DO_ALIGN
1123 bcopy((char *)&pkt.data[pkt.off], (char *)hdr, sizeof(*hdr));
1124 #else
1125 hdr = (kdp_hdr_t *)&pkt.data[pkt.off];
1126 #endif
1127
1128 // ignore replies -- we're not expecting them anyway.
1129 if (hdr->is_reply) {
1130 goto again;
1131 }
1132
1133 if (hdr->request == KDP_REATTACH) {
1134 exception_seq = hdr->seq;
1135 }
1136
1137 // check for retransmitted request
1138 if (hdr->seq == (exception_seq - 1)) {
1139 /* retransmit last reply */
1140 kdp_send_data(&saved_reply.data[saved_reply.off],
1141 saved_reply.len);
1142 goto again;
1143 } else if ((hdr->seq != exception_seq) &&
1144 (hdr->request != KDP_CONNECT)) {
1145 printf("kdp: bad sequence %d (want %d)\n",
1146 hdr->seq, exception_seq);
1147 goto again;
1148 }
1149
1150 /* This is a manual side-channel to the main KDP protocol.
1151 * A client like GDB/kgmacros can manually construct
1152 * a request, set the input flag, issue a dummy KDP request,
1153 * and then manually collect the result
1154 */
1155 if (manual_pkt.input) {
1156 kdp_hdr_t *manual_hdr = (kdp_hdr_t *)&manual_pkt.data;
1157 unsigned short manual_port_unused = 0;
1158 if (!manual_hdr->is_reply) {
1159 /* process */
1160 int packet_length = manual_pkt.len;
1161 kdp_packet((unsigned char *)&manual_pkt.data,
1162 &packet_length,
1163 &manual_port_unused);
1164 manual_pkt.len = packet_length;
1165 }
1166 manual_pkt.input = 0;
1167 }
1168
1169 if (kdp_packet((unsigned char*)&pkt.data[pkt.off],
1170 (int *)&pkt.len,
1171 (unsigned short *)&reply_port)) {
1172 boolean_t sideband = FALSE;
1173
1174 /* if it's an already connected error message,
1175 * send a sideband reply for that. for successful connects,
1176 * make sure the sequence number is correct. */
1177 if (hdr->request == KDP_CONNECT) {
1178 kdp_connect_reply_t *rp =
1179 (kdp_connect_reply_t *) &pkt.data[pkt.off];
1180 kdp_error_t err = rp->error;
1181
1182 if (err == KDPERR_NO_ERROR) {
1183 exception_seq = hdr->seq;
1184 } else if (err == KDPERR_ALREADY_CONNECTED) {
1185 sideband = TRUE;
1186 }
1187 }
1188
1189 kdp_reply(reply_port, sideband);
1190 }
1191
1192 again:
1193 pkt.input = FALSE;
1194 } while (kdp.is_halted);
1195 }
1196
1197 static void
kdp_connection_wait(void)1198 kdp_connection_wait(void)
1199 {
1200 unsigned short reply_port;
1201 struct kdp_ether_addr kdp_mac_addr = kdp_get_mac_addr();
1202 unsigned int ip_addr = ntohl(kdp_get_ip_address());
1203
1204 /*
1205 * Do both a printf() and a kprintf() of the MAC and IP so that
1206 * they will print out on headless machines but not be added to
1207 * the panic.log
1208 */
1209
1210 if (KDP_SERIAL_ENABLED()) {
1211 printf("Using serial KDP.\n");
1212 kprintf("Using serial KDP.\n");
1213 } else {
1214 printf("ethernet MAC address: %02x:%02x:%02x:%02x:%02x:%02x\n",
1215 kdp_mac_addr.ether_addr_octet[0] & 0xff,
1216 kdp_mac_addr.ether_addr_octet[1] & 0xff,
1217 kdp_mac_addr.ether_addr_octet[2] & 0xff,
1218 kdp_mac_addr.ether_addr_octet[3] & 0xff,
1219 kdp_mac_addr.ether_addr_octet[4] & 0xff,
1220 kdp_mac_addr.ether_addr_octet[5] & 0xff);
1221
1222 kprintf("ethernet MAC address: %02x:%02x:%02x:%02x:%02x:%02x\n",
1223 kdp_mac_addr.ether_addr_octet[0] & 0xff,
1224 kdp_mac_addr.ether_addr_octet[1] & 0xff,
1225 kdp_mac_addr.ether_addr_octet[2] & 0xff,
1226 kdp_mac_addr.ether_addr_octet[3] & 0xff,
1227 kdp_mac_addr.ether_addr_octet[4] & 0xff,
1228 kdp_mac_addr.ether_addr_octet[5] & 0xff);
1229
1230 printf("ip address: %d.%d.%d.%d\n",
1231 (ip_addr & 0xff000000) >> 24,
1232 (ip_addr & 0xff0000) >> 16,
1233 (ip_addr & 0xff00) >> 8,
1234 (ip_addr & 0xff));
1235
1236 kprintf("ip address: %d.%d.%d.%d\n",
1237 (ip_addr & 0xff000000) >> 24,
1238 (ip_addr & 0xff0000) >> 16,
1239 (ip_addr & 0xff00) >> 8,
1240 (ip_addr & 0xff));
1241 }
1242
1243 printf("\nWaiting for remote debugger connection.\n");
1244 kprintf("\nWaiting for remote debugger connection.\n");
1245
1246 if (reattach_wait == 0) {
1247 if ((kdp_flag & KDP_GETC_ENA) && (0 != kdp_getc())) {
1248 printf("Options..... Type\n");
1249 printf("------------ ----\n");
1250 printf("continue.... 'c'\n");
1251 printf("reboot...... 'r'\n");
1252 }
1253 } else {
1254 reattach_wait = 0;
1255 }
1256
1257 exception_seq = 0;
1258
1259 do {
1260 kdp_hdr_t aligned_hdr, *hdr = &aligned_hdr;
1261
1262 while (!pkt.input) {
1263 if (kdp_flag & KDP_GETC_ENA) {
1264 switch (kdp_getc()) {
1265 case 'c':
1266 printf("Continuing...\n");
1267 return;
1268 case 'r':
1269 printf("Rebooting...\n");
1270 kdp_machine_reboot();
1271 break;
1272 default:
1273 break;
1274 }
1275 }
1276 kdp_poll();
1277 }
1278
1279 #if DO_ALIGN
1280 bcopy((char *)&pkt.data[pkt.off], (char *)hdr, sizeof(*hdr));
1281 #else
1282 hdr = (kdp_hdr_t *)&pkt.data[pkt.off];
1283 #endif
1284 if (hdr->request == KDP_HOSTREBOOT) {
1285 kdp_machine_reboot();
1286 /* should not return! */
1287 }
1288 if (((hdr->request == KDP_CONNECT) || (hdr->request == KDP_REATTACH)) &&
1289 !hdr->is_reply && (hdr->seq == exception_seq)) {
1290 if (kdp_packet((unsigned char *)&pkt.data[pkt.off],
1291 (int *)&pkt.len,
1292 (unsigned short *)&reply_port)) {
1293 kdp_reply(reply_port, FALSE);
1294 }
1295 if (hdr->request == KDP_REATTACH) {
1296 reattach_wait = 0;
1297 hdr->request = KDP_DISCONNECT;
1298 exception_seq = 0;
1299 }
1300 }
1301
1302 pkt.input = FALSE;
1303 } while (!kdp.is_conn);
1304
1305 if (current_debugger == KDP_CUR_DB) {
1306 active_debugger = 1;
1307 }
1308 printf("Connected to remote debugger.\n");
1309 kprintf("Connected to remote debugger.\n");
1310 }
1311
1312 static void
kdp_send_exception(unsigned int exception,unsigned int code,unsigned int subcode)1313 kdp_send_exception(
1314 unsigned int exception,
1315 unsigned int code,
1316 unsigned int subcode
1317 )
1318 {
1319 unsigned short remote_port;
1320 unsigned int timeout_count = 100;
1321 unsigned int poll_timeout;
1322
1323 do {
1324 pkt.off = sizeof(struct kdp_ether_header) + sizeof(struct kdp_udpiphdr);
1325 kdp_exception((unsigned char *)&pkt.data[pkt.off],
1326 (int *)&pkt.len,
1327 (unsigned short *)&remote_port,
1328 (unsigned int)exception,
1329 (unsigned int)code,
1330 (unsigned int)subcode);
1331
1332 kdp_send(remote_port);
1333
1334 poll_timeout = 50;
1335 while (!pkt.input && poll_timeout) {
1336 kdp_poll();
1337 poll_timeout--;
1338 }
1339
1340 if (pkt.input) {
1341 if (!kdp_exception_ack(&pkt.data[pkt.off], pkt.len)) {
1342 pkt.input = FALSE;
1343 }
1344 }
1345
1346 pkt.input = FALSE;
1347
1348 if (kdp.exception_ack_needed) {
1349 kdp_us_spin(250000);
1350 }
1351 } while (kdp.exception_ack_needed && timeout_count--);
1352
1353 if (kdp.exception_ack_needed) {
1354 // give up & disconnect
1355 printf("kdp: exception ack timeout\n");
1356 if (current_debugger == KDP_CUR_DB) {
1357 active_debugger = 0;
1358 }
1359 kdp_reset();
1360 }
1361 }
1362
1363 static void
kdp_debugger_loop(unsigned int exception,unsigned int code,unsigned int subcode,void * saved_state)1364 kdp_debugger_loop(
1365 unsigned int exception,
1366 unsigned int code,
1367 unsigned int subcode,
1368 void *saved_state)
1369 {
1370 int index;
1371
1372 if (saved_state == 0) {
1373 printf("kdp_raise_exception with NULL state\n");
1374 }
1375
1376 index = exception;
1377 if (exception != EXC_BREAKPOINT) {
1378 if (exception > EXC_BREAKPOINT || exception < EXC_BAD_ACCESS) {
1379 index = 0;
1380 }
1381 printf("%s exception (%x,%x,%x)\n",
1382 exception_message[index],
1383 exception, code, subcode);
1384 }
1385
1386 kdp_sync_cache();
1387
1388 /* XXX WMG it seems that sometimes it doesn't work to let kdp_handler
1389 * do this. I think the client and the host can get out of sync.
1390 */
1391 kdp.saved_state = saved_state;
1392 kdp.kdp_cpu = cpu_number();
1393 kdp.kdp_thread = current_thread();
1394
1395 if (kdp_en_setmode) {
1396 (*kdp_en_setmode)(TRUE); /* enabling link mode */
1397 }
1398 if (pkt.input) {
1399 kdp_panic("kdp_raise_exception");
1400 }
1401
1402 if (((kdp_flag & KDP_PANIC_DUMP_ENABLED)
1403 || (kdp_flag & PANIC_LOG_DUMP))
1404 && panic_active()) {
1405 kdp_panic_dump();
1406 if (kdp_flag & REBOOT_POST_CORE && dumped_kernel_core()) {
1407 kdp_machine_reboot();
1408 }
1409 } else {
1410 if ((kdp_flag & PANIC_CORE_ON_NMI) && !panic_active()
1411 && !kdp.is_conn) {
1412 disableConsoleOutput = FALSE;
1413 kdp_panic_dump();
1414 if (kdp_flag & REBOOT_POST_CORE && dumped_kernel_core()) {
1415 kdp_machine_reboot();
1416 }
1417
1418 if (!(kdp_flag & DBG_POST_CORE)) {
1419 goto exit_debugger_loop;
1420 }
1421 }
1422 }
1423
1424 again:
1425 if (!kdp.is_conn) {
1426 kdp_connection_wait();
1427 } else {
1428 kdp_send_exception(exception, code, subcode);
1429 if (kdp.exception_ack_needed) {
1430 kdp.exception_ack_needed = FALSE;
1431 kdp_remove_all_breakpoints();
1432 printf("Remote debugger disconnected.\n");
1433 }
1434 }
1435
1436 if (kdp.is_conn) {
1437 kdp.is_halted = TRUE; /* XXX */
1438 kdp_handler(saved_state);
1439 if (!kdp.is_conn) {
1440 kdp_remove_all_breakpoints();
1441 printf("Remote debugger disconnected.\n");
1442 }
1443 }
1444 /* Allow triggering a panic core dump when connected to the machine
1445 * Continuing after setting kdp_trigger_core_dump should do the
1446 * trick.
1447 */
1448
1449 if (1 == kdp_trigger_core_dump) {
1450 kdp_flag |= KDP_PANIC_DUMP_ENABLED;
1451 kdp_panic_dump();
1452 if (kdp_flag & REBOOT_POST_CORE && dumped_kernel_core()) {
1453 kdp_machine_reboot();
1454 }
1455 kdp_trigger_core_dump = 0;
1456 }
1457
1458 /* Trigger a reboot if the user has set this flag through the
1459 * debugger.Ideally, this would be done through the HOSTREBOOT packet
1460 * in the protocol,but that will need gdb support,and when it's
1461 * available, it should work automatically.
1462 */
1463 if (1 == flag_kdp_trigger_reboot) {
1464 kdp_machine_reboot();
1465 /* If we're still around, reset the flag */
1466 flag_kdp_trigger_reboot = 0;
1467 }
1468
1469 if (kdp_reentry_deadline) {
1470 kdp_schedule_debugger_reentry(kdp_reentry_deadline);
1471 printf("Debugger re-entry scheduled in %d milliseconds\n", kdp_reentry_deadline);
1472 kdp_reentry_deadline = 0;
1473 }
1474
1475 kdp_sync_cache();
1476
1477 #if defined(__x86_64__)
1478 /* We only support returning from KDP on x86 */
1479 if (reattach_wait == 1)
1480 #endif
1481 {
1482 goto again;
1483 }
1484
1485 exit_debugger_loop:
1486 if (kdp_en_setmode) {
1487 (*kdp_en_setmode)(FALSE); /* link cleanup */
1488 }
1489 }
1490
1491 void
kdp_reset(void)1492 kdp_reset(void)
1493 {
1494 kdp.reply_port = kdp.exception_port = 0;
1495 kdp.is_halted = kdp.is_conn = FALSE;
1496 kdp.exception_seq = kdp.conn_seq = 0;
1497 kdp.session_key = 0;
1498 pkt.input = manual_pkt.input = FALSE;
1499 pkt.len = pkt.off = manual_pkt.len = 0;
1500 }
1501
1502 static void
kdp_setup_packet_size(void)1503 kdp_setup_packet_size(void)
1504 {
1505 /* Override default packet size from boot arguments (if present). */
1506 kdp_crashdump_pkt_size = KDP_LARGE_CRASHDUMP_PKT_SIZE;
1507 if (PE_parse_boot_argn("kdp_crashdump_pkt_size", &kdp_crashdump_pkt_size, sizeof(kdp_crashdump_pkt_size)) &&
1508 (kdp_crashdump_pkt_size > KDP_LARGE_CRASHDUMP_PKT_SIZE)) {
1509 kdp_crashdump_pkt_size = KDP_LARGE_CRASHDUMP_PKT_SIZE;
1510 printf("kdp_crashdump_pkt_size is too large. Reverting to %d\n", kdp_crashdump_pkt_size);
1511 }
1512 }
1513
1514 struct corehdr *
create_panic_header(unsigned int request,const char * corename,unsigned length,unsigned int block)1515 create_panic_header(unsigned int request, const char *corename,
1516 unsigned length, unsigned int block)
1517 {
1518 struct kdp_udpiphdr aligned_ui, *ui = &aligned_ui;
1519 struct kdp_ip aligned_ip, *ip = &aligned_ip;
1520 struct kdp_ether_header *eh;
1521 struct corehdr *coreh;
1522 const char *mode = "octet";
1523 size_t modelen = strlen(mode) + 1;
1524
1525 size_t fmask_size = sizeof(KDP_FEATURE_MASK_STRING) + sizeof(kdp_crashdump_feature_mask);
1526
1527 pkt.off = sizeof(struct kdp_ether_header);
1528 pkt.len = (unsigned int)(length + ((request == KDP_WRQ) ? modelen + fmask_size : 0) +
1529 (corename ? (strlen(corename) + 1): 0) + sizeof(struct corehdr));
1530
1531 #if DO_ALIGN
1532 bcopy((char *)&pkt.data[pkt.off], (char *)ui, sizeof(*ui));
1533 #else
1534 ui = (struct kdp_udpiphdr *)&pkt.data[pkt.off];
1535 #endif
1536 ui->ui_next = ui->ui_prev = 0;
1537 ui->ui_x1 = 0;
1538 ui->ui_pr = IPPROTO_UDP;
1539 ui->ui_len = htons((u_short)pkt.len + sizeof(struct kdp_udphdr));
1540 ui->ui_src.s_addr = (uint32_t)kdp_current_ip_address;
1541 /* Already in network byte order via inet_aton() */
1542 ui->ui_dst.s_addr = panic_server_ip;
1543 ui->ui_sport = htons(panicd_port);
1544 ui->ui_dport = ((request == KDP_WRQ) ? htons(panicd_port) : last_panic_port);
1545 ui->ui_ulen = ui->ui_len;
1546 ui->ui_sum = 0;
1547 #if DO_ALIGN
1548 bcopy((char *)ui, (char *)&pkt.data[pkt.off], sizeof(*ui));
1549 bcopy((char *)&pkt.data[pkt.off], (char *)ip, sizeof(*ip));
1550 #else
1551 ip = (struct kdp_ip *)&pkt.data[pkt.off];
1552 #endif
1553 ip->ip_len = htons((ushort_t)(sizeof(struct kdp_udpiphdr) + pkt.len));
1554 ip->ip_v = IPVERSION;
1555 ip->ip_id = htons(ip_id++);
1556 ip->ip_hl = sizeof(struct kdp_ip) >> 2;
1557 ip->ip_ttl = udp_ttl;
1558 ip->ip_sum = 0;
1559 ip->ip_sum = htons(~ip_sum((unsigned char *)ip, ip->ip_hl));
1560 #if DO_ALIGN
1561 bcopy((char *)ip, (char *)&pkt.data[pkt.off], sizeof(*ip));
1562 #endif
1563
1564 pkt.len += (unsigned int)sizeof(struct kdp_udpiphdr);
1565
1566 pkt.off += (unsigned int)sizeof(struct kdp_udpiphdr);
1567
1568 coreh = (struct corehdr *) &pkt.data[pkt.off];
1569 coreh->th_opcode = htons((u_short)request);
1570
1571 if (request == KDP_WRQ) {
1572 char *cp = coreh->th_u.tu_rpl;
1573 /* Calculate available string space (remaining space after accounting for mandatory components). */
1574 size_t length_remaining = (sizeof(pkt.data) - pkt.off - offsetof(struct corehdr, th_u)
1575 - sizeof(kdp_crashdump_feature_mask) - sizeof(kdp_crashdump_pkt_size));
1576
1577 /* account for the extra NULL characters that have been added historically */
1578 int len = snprintf(cp, length_remaining, "%s%c%s%c%s%c", corename, '\0', mode, '\0', KDP_FEATURE_MASK_STRING, '\0');
1579 if (len < 0) {
1580 kdb_printf("Unable to create core header packet.\n");
1581 return NULL;
1582 } else if (len >= length_remaining) {
1583 kdb_printf("dumpinfo does not fit into KDP packet.\n");
1584 return NULL;
1585 }
1586 cp += len;
1587
1588 /* Append feature flags. The value is already converted with htonl in startup code. */
1589 bcopy(&kdp_crashdump_feature_mask, cp, sizeof(kdp_crashdump_feature_mask));
1590 cp += sizeof(kdp_crashdump_feature_mask);
1591
1592 // Make sure we advertise the maximum supported packet size
1593 kdp_setup_packet_size();
1594
1595 uint32_t pktsz = htonl(kdp_crashdump_pkt_size);
1596 bcopy(&pktsz, cp, sizeof(uint32_t));
1597 } else {
1598 coreh->th_block = htonl((unsigned int) block);
1599 }
1600
1601 pkt.off -= (unsigned int)sizeof(struct kdp_udpiphdr);
1602 pkt.off -= (unsigned int)sizeof(struct kdp_ether_header);
1603
1604 eh = (struct kdp_ether_header *)&pkt.data[pkt.off];
1605 enaddr_copy(&kdp_current_mac_address, eh->ether_shost);
1606 enaddr_copy(&destination_mac, eh->ether_dhost);
1607 eh->ether_type = htons(ETHERTYPE_IP);
1608
1609 pkt.len += (unsigned int)sizeof(struct kdp_ether_header);
1610 return coreh;
1611 }
1612
1613 static int
kdp_send_crashdump_seek(char * corename,uint64_t seek_off)1614 kdp_send_crashdump_seek(char *corename, uint64_t seek_off)
1615 {
1616 int panic_error;
1617
1618 if (kdp_feature_large_crashdumps) {
1619 panic_error = kdp_send_crashdump_pkt(KDP_SEEK, corename,
1620 sizeof(seek_off),
1621 &seek_off);
1622 } else {
1623 uint32_t off = (uint32_t) seek_off;
1624 panic_error = kdp_send_crashdump_pkt(KDP_SEEK, corename,
1625 sizeof(off), &off);
1626 }
1627
1628 if (panic_error < 0) {
1629 printf("kdp_send_crashdump_pkt failed with error %d\n",
1630 panic_error);
1631 return panic_error;
1632 }
1633
1634 return KERN_SUCCESS;
1635 }
1636
1637 int
kdp_send_crashdump_data(unsigned int request,char * corename,uint64_t length,void * txstart)1638 kdp_send_crashdump_data(unsigned int request, char *corename,
1639 uint64_t length, void * txstart)
1640 {
1641 int panic_error = 0;
1642
1643 while ((length > 0) || !txstart) {
1644 uint64_t chunk = MIN(kdp_crashdump_pkt_size, length);
1645
1646 panic_error = kdp_send_crashdump_pkt(request, corename, chunk,
1647 txstart);
1648 if (panic_error < 0) {
1649 printf("kdp_send_crashdump_pkt failed with error %d\n", panic_error);
1650 return panic_error;
1651 }
1652 if (!txstart) {
1653 break;
1654 }
1655 txstart = (void *)(((uintptr_t) txstart) + chunk);
1656 length -= chunk;
1657 }
1658 return KERN_SUCCESS;
1659 }
1660
1661 uint32_t kdp_crashdump_short_pkt;
1662
1663 int
kdp_send_crashdump_pkt(unsigned int request,char * corename,uint64_t length,void * panic_data)1664 kdp_send_crashdump_pkt(unsigned int request, char *corename,
1665 uint64_t length, void *panic_data)
1666 {
1667 int poll_count;
1668 struct corehdr *th = NULL;
1669 char rretries, tretries;
1670
1671 if (kdp_dump_start_time == 0) {
1672 kdp_dump_start_time = mach_absolute_time();
1673 kdp_superblock_dump_start_time = kdp_dump_start_time;
1674 }
1675
1676 tretries = rretries = 0;
1677 poll_count = KDP_CRASHDUMP_POLL_COUNT;
1678 pkt.off = pkt.len = 0;
1679 if (request == KDP_WRQ) { /* longer timeout for initial request */
1680 poll_count += 1000;
1681 }
1682
1683 TRANSMIT_RETRY:
1684 tretries++;
1685
1686 if (tretries >= 15) {
1687 /* The crashdump server is unreachable for some reason. This could be a network
1688 * issue or, if we've been especially unfortunate, we've hit Radar 2760413,
1689 * which is a long standing problem with the IOKit polled mode network driver
1690 * shim which can prevent transmits/receives completely.
1691 */
1692 printf("Cannot contact panic server, timing out.\n");
1693 return -3;
1694 }
1695
1696 if (tretries > 2) {
1697 printf("TX retry #%d ", tretries );
1698 }
1699
1700 th = create_panic_header(request, corename, (unsigned)length, panic_block);
1701 if (th == NULL) {
1702 printf("Unable to get panic header.\n");
1703 return -4;
1704 }
1705
1706 if (request == KDP_DATA) {
1707 /* as all packets are kdp_crashdump_pkt_size in length, the last packet
1708 * may end up with trailing bits. make sure that those
1709 * bits aren't confusing. */
1710 if (length < kdp_crashdump_pkt_size) {
1711 kdp_crashdump_short_pkt++;
1712 memset(th->th_data + length, 'Y',
1713 kdp_crashdump_pkt_size - (uint32_t) length);
1714 }
1715
1716 if (!kdp_machine_vm_read((mach_vm_address_t)(uintptr_t)panic_data, (caddr_t) th->th_data, length)) {
1717 uintptr_t next_page = round_page((uintptr_t)panic_data);
1718 memset((caddr_t) th->th_data, 'X', (size_t)length);
1719 if ((next_page - ((uintptr_t) panic_data)) < length) {
1720 uint64_t resid = length - (next_page - (intptr_t) panic_data);
1721 if (!kdp_machine_vm_read((mach_vm_address_t)(uintptr_t)next_page, (caddr_t) th->th_data + (length - resid), resid)) {
1722 memset((caddr_t) th->th_data + (length - resid), 'X', (size_t)resid);
1723 }
1724 }
1725 }
1726 } else if (request == KDP_SEEK) {
1727 if (kdp_feature_large_crashdumps) {
1728 *(uint64_t *) th->th_data = OSSwapHostToBigInt64((*(uint64_t *) panic_data));
1729 } else {
1730 *(unsigned int *) th->th_data = htonl(*(unsigned int *) panic_data);
1731 }
1732 }
1733
1734 kdp_send_data(&pkt.data[pkt.off], pkt.len);
1735
1736 /* Listen for the ACK */
1737 RECEIVE_RETRY:
1738 while (!pkt.input && flag_panic_dump_in_progress && poll_count) {
1739 kdp_poll();
1740 poll_count--;
1741 }
1742
1743 if (pkt.input) {
1744 pkt.input = FALSE;
1745
1746 th = (struct corehdr *) &pkt.data[pkt.off];
1747 if (request == KDP_WRQ) {
1748 uint16_t opcode64 = ntohs(th->th_opcode);
1749 uint16_t features64 = (opcode64 & 0xFF00) >> 8;
1750 if ((opcode64 & 0xFF) == KDP_ACK) {
1751 kdp_feature_large_crashdumps = features64 & KDP_FEATURE_LARGE_CRASHDUMPS;
1752 if (features64 & KDP_FEATURE_LARGE_PKT_SIZE) {
1753 kdp_feature_large_pkt_size = 1;
1754 } else {
1755 kdp_feature_large_pkt_size = 0;
1756 kdp_crashdump_pkt_size = 512;
1757 }
1758 printf("Protocol features: 0x%x\n", (uint32_t) features64);
1759 th->th_opcode = htons(KDP_ACK);
1760 }
1761 }
1762 if (ntohs(th->th_opcode) == KDP_ACK && ntohl(th->th_block) == panic_block) {
1763 } else {
1764 if (ntohs(th->th_opcode) == KDP_ERROR) {
1765 printf("Panic server returned error %d, retrying\n", ntohl(th->th_code));
1766 poll_count = 1000;
1767 goto TRANSMIT_RETRY;
1768 } else if (ntohl(th->th_block) == (panic_block - 1)) {
1769 printf("RX retry ");
1770 if (++rretries > 1) {
1771 goto TRANSMIT_RETRY;
1772 } else {
1773 goto RECEIVE_RETRY;
1774 }
1775 }
1776 }
1777 } else if (!flag_panic_dump_in_progress) { /* we received a debugging packet, bail*/
1778 printf("Received a debugger packet,transferring control to debugger\n");
1779 /* Configure that if not set ..*/
1780 kdp_flag |= DBG_POST_CORE;
1781 return -2;
1782 } else { /* We timed out */
1783 if (0 == poll_count) {
1784 poll_count = 1000;
1785 kdp_us_spin((tretries % 4) * panic_timeout); /* capped linear backoff */
1786 goto TRANSMIT_RETRY;
1787 }
1788 }
1789
1790 if (!(++panic_block % SBLOCKSZ)) {
1791 uint64_t ctime;
1792 kdb_printf_unbuffered(".");
1793 ctime = mach_absolute_time();
1794 kdp_superblock_dump_time = ctime - kdp_superblock_dump_start_time;
1795 kdp_superblock_dump_start_time = ctime;
1796 if (kdp_superblock_dump_time > kdp_max_superblock_dump_time) {
1797 kdp_max_superblock_dump_time = kdp_superblock_dump_time;
1798 }
1799 if (kdp_superblock_dump_time < kdp_min_superblock_dump_time) {
1800 kdp_min_superblock_dump_time = kdp_superblock_dump_time;
1801 }
1802 }
1803
1804 if (request == KDP_EOF) {
1805 printf("\nTotal number of packets transmitted: %d\n", panic_block);
1806 printf("Avg. superblock transfer abstime 0x%llx\n", ((mach_absolute_time() - kdp_dump_start_time) / panic_block) * SBLOCKSZ);
1807 printf("Minimum superblock transfer abstime: 0x%llx\n", kdp_min_superblock_dump_time);
1808 printf("Maximum superblock transfer abstime: 0x%llx\n", kdp_max_superblock_dump_time);
1809 }
1810 return KERN_SUCCESS;
1811 }
1812
1813 static int
isdigit(char c)1814 isdigit(char c)
1815 {
1816 return (c > 47) && (c < 58);
1817 }
1818
1819 /* Horrid hack to extract xnu version if possible - a much cleaner approach
1820 * would be to have the integrator run a script which would copy the
1821 * xnu version into a string or an int somewhere at project submission
1822 * time - makes assumptions about sizeof(version), but will not fail if
1823 * it changes, but may be incorrect.
1824 */
1825 /* 2006: Incorporated a change from Darwin user P. Lovell to extract
1826 * the minor kernel version numbers from the version string.
1827 */
1828 static int
kdp_get_xnu_version(char * versionbuf)1829 kdp_get_xnu_version(char *versionbuf)
1830 {
1831 const char *versionpos;
1832 char vstr[20];
1833 int retval = -1;
1834 char *vptr;
1835 size_t length_remaining = (sizeof(pkt.data) - pkt.off);
1836
1837 strlcpy(vstr, "custom", 10);
1838 if (kdp_machine_vm_read((mach_vm_address_t)(uintptr_t)version, versionbuf, 128)) {
1839 versionbuf[127] = '\0';
1840 versionpos = strnstr(versionbuf, "xnu-", 115);
1841 if (versionpos) {
1842 strncpy(vstr, versionpos, sizeof(vstr));
1843 vstr[sizeof(vstr) - 1] = '\0';
1844 vptr = vstr + 4; /* Begin after "xnu-" */
1845 while (*vptr && (isdigit(*vptr) || *vptr == '.')) {
1846 vptr++;
1847 }
1848 *vptr = '\0';
1849 /* Remove trailing period, if any */
1850 if (*(--vptr) == '.') {
1851 *vptr = '\0';
1852 }
1853 retval = 0;
1854 }
1855 }
1856 strlcpy(versionbuf, vstr, length_remaining);
1857 return retval;
1858 }
1859
1860 void
kdp_set_dump_info(const uint32_t flags,const char * filename,const char * destipstr,const char * routeripstr,const uint32_t port)1861 kdp_set_dump_info(const uint32_t flags, const char *filename,
1862 const char *destipstr, const char *routeripstr,
1863 const uint32_t port)
1864 {
1865 uint32_t cmd;
1866
1867 if (destipstr && (destipstr[0] != '\0')) {
1868 strlcpy(panicd_ip_str, destipstr, sizeof(panicd_ip_str));
1869 panicd_specified = 1;
1870 }
1871
1872 if (routeripstr && (routeripstr[0] != '\0')) {
1873 strlcpy(router_ip_str, routeripstr, sizeof(router_ip_str));
1874 router_specified = 1;
1875 }
1876
1877 if (filename && (filename[0] != '\0')) {
1878 strlcpy(corename_str, filename, sizeof(corename_str));
1879 corename_specified = TRUE;
1880 } else {
1881 corename_specified = FALSE;
1882 }
1883
1884 /* Accept only valid UDP port numbers. */
1885 if (port && port <= USHRT_MAX) {
1886 panicd_port = (unsigned short)port;
1887 } else {
1888 kdb_printf("kdp_set_dump_info: Skipping invalid panicd port %d (using %d)\n", port, panicd_port);
1889 }
1890
1891 /* on a disconnect, should we stay in KDP or not? */
1892 noresume_on_disconnect = (flags & KDP_DUMPINFO_NORESUME) ? 1 : 0;
1893
1894 if ((flags & KDP_DUMPINFO_DUMP) == 0) {
1895 return;
1896 }
1897
1898 /* the rest of the commands can modify kdp_flags */
1899 cmd = flags & KDP_DUMPINFO_MASK;
1900 if (cmd == KDP_DUMPINFO_DISABLE) {
1901 kdp_flag &= ~KDP_PANIC_DUMP_ENABLED;
1902 panicd_specified = 0;
1903 kdp_trigger_core_dump = 0;
1904 return;
1905 }
1906
1907 kdp_flag &= ~REBOOT_POST_CORE;
1908 if (flags & KDP_DUMPINFO_REBOOT) {
1909 kdp_flag |= REBOOT_POST_CORE;
1910 }
1911
1912 kdp_flag &= ~PANIC_LOG_DUMP;
1913 if (cmd == KDP_DUMPINFO_PANICLOG) {
1914 kdp_flag |= PANIC_LOG_DUMP;
1915 }
1916
1917 kdp_flag &= ~SYSTEM_LOG_DUMP;
1918 if (cmd == KDP_DUMPINFO_SYSTEMLOG) {
1919 kdp_flag |= SYSTEM_LOG_DUMP;
1920 }
1921
1922 /* trigger a dump */
1923 kdp_flag |= DBG_POST_CORE;
1924
1925 flag_dont_abort_panic_dump = (flags & KDP_DUMPINFO_NOINTR) ?
1926 TRUE : FALSE;
1927
1928 reattach_wait = 1;
1929 disableConsoleOutput = 0;
1930 kdp_trigger_core_dump = 1;
1931 }
1932
1933 void
kdp_get_dump_info(kdp_dumpinfo_reply_t * rp)1934 kdp_get_dump_info(kdp_dumpinfo_reply_t *rp)
1935 {
1936 if (panicd_specified) {
1937 strlcpy(rp->destip, panicd_ip_str,
1938 sizeof(rp->destip));
1939 } else {
1940 rp->destip[0] = '\0';
1941 }
1942
1943 if (router_specified) {
1944 strlcpy(rp->routerip, router_ip_str,
1945 sizeof(rp->routerip));
1946 } else {
1947 rp->routerip[0] = '\0';
1948 }
1949
1950 if (corename_specified) {
1951 strlcpy(rp->name, corename_str,
1952 sizeof(rp->name));
1953 } else {
1954 rp->name[0] = '\0';
1955 }
1956
1957 rp->port = panicd_port;
1958
1959 rp->type = 0;
1960 if (!panicd_specified) {
1961 rp->type |= KDP_DUMPINFO_DISABLE;
1962 } else if (kdp_flag & PANIC_LOG_DUMP) {
1963 rp->type |= KDP_DUMPINFO_PANICLOG;
1964 } else {
1965 rp->type |= KDP_DUMPINFO_CORE;
1966 }
1967
1968 if (noresume_on_disconnect) {
1969 rp->type |= KDP_DUMPINFO_NORESUME;
1970 }
1971 }
1972
1973
1974 /* Primary dispatch routine for the system dump */
1975 void
kdp_panic_dump(void)1976 kdp_panic_dump(void)
1977 {
1978 char coreprefix[10];
1979 char coresuffix[4];
1980 int panic_error;
1981
1982 uint64_t abstime;
1983 uint32_t current_ip = ntohl((uint32_t)kdp_current_ip_address);
1984
1985 if (flag_panic_dump_in_progress) {
1986 kdb_printf("System dump aborted.\n");
1987 goto panic_dump_exit;
1988 }
1989
1990 printf("Entering system dump routine\n");
1991
1992 if (!kdp_en_recv_pkt || !kdp_en_send_pkt) {
1993 kdb_printf("Error: No transport device registered for kernel crashdump\n");
1994 return;
1995 }
1996
1997 if (!panicd_specified) {
1998 kdb_printf("A dump server was not specified in the boot-args, terminating kernel core dump.\n");
1999 goto panic_dump_exit;
2000 }
2001
2002 flag_panic_dump_in_progress = TRUE;
2003
2004 if (pkt.input) {
2005 kdp_panic("kdp_panic_dump: unexpected pending input packet");
2006 }
2007
2008 kdp_get_xnu_version((char *) &pkt.data[0]);
2009
2010 if (!corename_specified) {
2011 coresuffix[0] = 0;
2012 /* Panic log bit takes precedence over core dump bit */
2013 if ((debugger_panic_str != (char *) 0) && (kdp_flag & PANIC_LOG_DUMP)) {
2014 strlcpy(coreprefix, "paniclog", sizeof(coreprefix));
2015 } else if (kdp_flag & SYSTEM_LOG_DUMP) {
2016 strlcpy(coreprefix, "systemlog", sizeof(coreprefix));
2017 } else {
2018 strlcpy(coreprefix, "core", sizeof(coreprefix));
2019 if (!kdp_corezip_disabled) {
2020 strlcpy(coresuffix, ".gz", sizeof(coresuffix));
2021 }
2022 }
2023
2024 abstime = mach_absolute_time();
2025 pkt.data[20] = '\0';
2026 snprintf(corename_str,
2027 sizeof(corename_str),
2028 "%s-%s-%d.%d.%d.%d-%x%s",
2029 coreprefix, &pkt.data[0],
2030 (current_ip & 0xff000000) >> 24,
2031 (current_ip & 0xff0000) >> 16,
2032 (current_ip & 0xff00) >> 8,
2033 (current_ip & 0xff),
2034 (unsigned int) (abstime & 0xffffffff),
2035 coresuffix);
2036 }
2037
2038 if (0 == inet_aton(panicd_ip_str, (struct kdp_in_addr *) &panic_server_ip)) {
2039 kdb_printf("inet_aton() failed interpreting %s as a panic server IP\n", panicd_ip_str);
2040 } else {
2041 kdb_printf("Attempting connection to panic server configured at IP %s, port %d\n", panicd_ip_str, panicd_port);
2042 }
2043
2044 destination_mac = router_mac;
2045
2046 if (kdp_arp_resolve(panic_server_ip, &temp_mac)) {
2047 kdb_printf("Resolved %s's (or proxy's) link level address\n", panicd_ip_str);
2048 destination_mac = temp_mac;
2049 } else {
2050 if (!flag_panic_dump_in_progress) {
2051 goto panic_dump_exit;
2052 }
2053 if (router_specified) {
2054 if (0 == inet_aton(router_ip_str, (struct kdp_in_addr *) &parsed_router_ip)) {
2055 kdb_printf("inet_aton() failed interpreting %s as an IP\n", router_ip_str);
2056 } else {
2057 router_ip = parsed_router_ip;
2058 if (kdp_arp_resolve(router_ip, &temp_mac)) {
2059 destination_mac = temp_mac;
2060 kdb_printf("Routing through specified router IP %s (%d)\n", router_ip_str, router_ip);
2061 }
2062 }
2063 }
2064 }
2065
2066 if (!flag_panic_dump_in_progress) {
2067 goto panic_dump_exit;
2068 }
2069
2070 kdb_printf("Transmitting packets to link level address: %02x:%02x:%02x:%02x:%02x:%02x\n",
2071 destination_mac.ether_addr_octet[0] & 0xff,
2072 destination_mac.ether_addr_octet[1] & 0xff,
2073 destination_mac.ether_addr_octet[2] & 0xff,
2074 destination_mac.ether_addr_octet[3] & 0xff,
2075 destination_mac.ether_addr_octet[4] & 0xff,
2076 destination_mac.ether_addr_octet[5] & 0xff);
2077
2078 kdb_printf("Kernel map size is %llu\n", (unsigned long long) get_vmmap_size(kernel_map));
2079 kdb_printf("Sending write request for %s\n", corename_str);
2080
2081 if ((panic_error = kdp_send_crashdump_pkt(KDP_WRQ, corename_str, 0, NULL)) < 0) {
2082 kdb_printf("kdp_send_crashdump_pkt failed with error %d\n", panic_error);
2083 goto panic_dump_exit;
2084 }
2085
2086 /* Just the panic log requested */
2087 if ((debugger_panic_str != (char *) 0) && (kdp_flag & PANIC_LOG_DUMP)) {
2088 kdb_printf_unbuffered("Transmitting panic log, please wait: ");
2089 kdp_send_crashdump_data(KDP_DATA, corename_str,
2090 debug_buf_ptr - debug_buf_base,
2091 debug_buf_base);
2092 kdp_send_crashdump_pkt(KDP_EOF, NULL, 0, ((void *) 0));
2093 printf("Please file a bug report on this panic, if possible.\n");
2094 goto panic_dump_exit;
2095 }
2096
2097 /* maybe we wanted the systemlog */
2098 if (kdp_flag & SYSTEM_LOG_DUMP) {
2099 long start_off = msgbufp->msg_bufx;
2100 long len;
2101
2102 kdb_printf_unbuffered("Transmitting system log, please wait: ");
2103 if (start_off >= msgbufp->msg_bufr) {
2104 len = msgbufp->msg_size - start_off;
2105 kdp_send_crashdump_data(KDP_DATA, corename_str, len,
2106 msgbufp->msg_bufc + start_off);
2107 /* seek to remove trailing bytes */
2108 kdp_send_crashdump_seek(corename_str, len);
2109 start_off = 0;
2110 }
2111
2112 if (start_off != msgbufp->msg_bufr) {
2113 len = msgbufp->msg_bufr - start_off;
2114 kdp_send_crashdump_data(KDP_DATA, corename_str, len,
2115 msgbufp->msg_bufc + start_off);
2116 }
2117
2118 kdp_send_crashdump_pkt(KDP_EOF, NULL, 0, ((void *) 0));
2119 goto panic_dump_exit;
2120 }
2121
2122 /* We want a core dump if we're here */
2123 kern_dump(KERN_DUMP_NET);
2124
2125 panic_dump_exit:
2126 abort_panic_transfer();
2127 kdp_reset();
2128 return;
2129 }
2130
2131 void
begin_panic_transfer(void)2132 begin_panic_transfer(void)
2133 {
2134 flag_panic_dump_in_progress = TRUE;
2135 }
2136
2137 void
abort_panic_transfer(void)2138 abort_panic_transfer(void)
2139 {
2140 flag_panic_dump_in_progress = FALSE;
2141 flag_dont_abort_panic_dump = FALSE;
2142 panic_block = 0;
2143 }
2144
2145 #if CONFIG_SERIAL_KDP
2146
2147 static boolean_t needs_serial_init = TRUE;
2148
2149 static void
kdp_serial_send(void * rpkt,unsigned int rpkt_len)2150 kdp_serial_send(void *rpkt, unsigned int rpkt_len)
2151 {
2152 // printf("tx\n");
2153 kdp_serialize_packet((unsigned char *)rpkt, rpkt_len, pal_serial_putc_nocr);
2154 }
2155
2156 static void
kdp_serial_receive(void * rpkt,unsigned int * rpkt_len,unsigned int timeout)2157 kdp_serial_receive(void *rpkt, unsigned int *rpkt_len, unsigned int timeout)
2158 {
2159 int readkar;
2160 uint64_t now, deadline;
2161
2162 clock_interval_to_deadline(timeout, 1000 * 1000 /* milliseconds */, &deadline);
2163
2164 // printf("rx\n");
2165 for (clock_get_uptime(&now); now < deadline; clock_get_uptime(&now)) {
2166 readkar = pal_serial_getc();
2167 if (readkar >= 0) {
2168 unsigned char *packet;
2169 // printf("got char %02x\n", readkar);
2170 if ((packet = kdp_unserialize_packet((unsigned char)readkar, rpkt_len))) {
2171 memcpy(rpkt, packet, *rpkt_len);
2172 return;
2173 }
2174 }
2175 }
2176 *rpkt_len = 0;
2177 }
2178
2179 static boolean_t
kdp_serial_setmode(boolean_t active)2180 kdp_serial_setmode(boolean_t active)
2181 {
2182 if (active == FALSE) { /* leaving KDP */
2183 return TRUE;
2184 }
2185
2186 if (!needs_serial_init) {
2187 return TRUE;
2188 }
2189
2190 pal_serial_init();
2191 needs_serial_init = FALSE;
2192 return TRUE;
2193 }
2194
2195
2196 static void
kdp_serial_callout(__unused void * arg,kdp_event_t event)2197 kdp_serial_callout(__unused void *arg, kdp_event_t event)
2198 {
2199 /*
2200 * When we stop KDP, set the bit to re-initialize the console serial
2201 * port the next time we send/receive a KDP packet. We don't do it on
2202 * KDP_EVENT_ENTER directly because it also gets called when we trap to
2203 * KDP for non-external debugging, i.e., stackshot or core dumps.
2204 *
2205 * Set needs_serial_init on exit (and initialization, see above) and not
2206 * enter because enter is sent multiple times and causes excess
2207 * reinitialization.
2208 */
2209
2210 switch (event) {
2211 case KDP_EVENT_PANICLOG:
2212 case KDP_EVENT_ENTER:
2213 break;
2214 case KDP_EVENT_EXIT:
2215 needs_serial_init = TRUE;
2216 break;
2217 }
2218 }
2219
2220 #endif /* CONFIG_SERIAL_KDP */
2221
2222 void
kdp_init(void)2223 kdp_init(void)
2224 {
2225 strlcpy(kdp_kernelversion_string, version, sizeof(kdp_kernelversion_string));
2226
2227 /* Relies on platform layer calling panic_init() before kdp_init() */
2228 assert(startup_phase >= STARTUP_SUB_TUNABLES);
2229 if (kernel_uuid_string[0] != '\0') {
2230 /*
2231 * Update kdp_kernelversion_string with our UUID
2232 * generated at link time.
2233 */
2234
2235 strlcat(kdp_kernelversion_string, "; UUID=", sizeof(kdp_kernelversion_string));
2236 strlcat(kdp_kernelversion_string, kernel_uuid_string, sizeof(kdp_kernelversion_string));
2237 }
2238
2239 debug_log_init();
2240
2241 #if defined(__x86_64__) || defined(__arm64__)
2242 if (vm_kernel_slide) {
2243 char KASLR_stext[19];
2244 strlcat(kdp_kernelversion_string, "; stext=", sizeof(kdp_kernelversion_string));
2245 snprintf(KASLR_stext, sizeof(KASLR_stext), "%p", (void *) vm_kernel_stext);
2246 strlcat(kdp_kernelversion_string, KASLR_stext, sizeof(kdp_kernelversion_string));
2247 }
2248 #endif
2249
2250 if (debug_boot_arg & DB_REBOOT_POST_CORE) {
2251 kdp_flag |= REBOOT_POST_CORE;
2252 }
2253 #if defined(__x86_64__)
2254 kdp_machine_init();
2255 #endif
2256
2257 kdp_timer_callout_init();
2258 kdp_crashdump_feature_mask = htonl(kdp_crashdump_feature_mask);
2259 // Figure out the initial packet size
2260 kdp_setup_packet_size();
2261 kdp_core_init();
2262
2263 #if CONFIG_SERIAL_KDP
2264 char kdpname[80];
2265 struct kdp_in_addr ipaddr;
2266 struct kdp_ether_addr macaddr;
2267
2268 boolean_t kdp_match_name_found = PE_parse_boot_argn("kdp_match_name", kdpname, sizeof(kdpname));
2269 boolean_t kdp_not_serial = kdp_match_name_found ? (strncmp(kdpname, "serial", sizeof(kdpname))) : TRUE;
2270
2271 #if defined(__arm64__)
2272 //respect any custom debugger boot-args
2273 if (kdp_match_name_found && kdp_not_serial) {
2274 return;
2275 }
2276 #else /* defined(__arm64__) */
2277 // serial must be explicitly requested
2278 if (!kdp_match_name_found || kdp_not_serial) {
2279 return;
2280 }
2281 #endif /* defined(__arm64__) */
2282
2283 #if defined(__arm64__)
2284 if (kdp_not_serial && PE_consistent_debug_enabled() && debug_boot_arg) {
2285 return;
2286 } else {
2287 printf("Serial requested, consistent debug disabled or debug boot arg not present, configuring debugging over serial\n");
2288 }
2289 #endif /* defined(__arm64__) */
2290
2291 kprintf("Initializing serial KDP\n");
2292
2293 kdp_register_callout(kdp_serial_callout, NULL);
2294 kdp_register_link(NULL, kdp_serial_setmode);
2295 kdp_register_send_receive(kdp_serial_send, kdp_serial_receive);
2296
2297 /* fake up an ip and mac for early serial debugging */
2298 macaddr.ether_addr_octet[0] = 's';
2299 macaddr.ether_addr_octet[1] = 'e';
2300 macaddr.ether_addr_octet[2] = 'r';
2301 macaddr.ether_addr_octet[3] = 'i';
2302 macaddr.ether_addr_octet[4] = 'a';
2303 macaddr.ether_addr_octet[5] = 'l';
2304 ipaddr.s_addr = KDP_SERIAL_IPADDR;
2305 kdp_set_ip_and_mac_addresses(&ipaddr, &macaddr);
2306
2307 #endif /* CONFIG_SERIAL_KDP */
2308 }
2309
2310 #else /* CONFIG_KDP_INTERACTIVE_DEBUGGING */
2311 void
kdp_init(void)2312 kdp_init(void)
2313 {
2314 }
2315 #endif /* CONFIG_KDP_INTERACTIVE_DEBUGGING */
2316
2317 #if !(MACH_KDP && CONFIG_KDP_INTERACTIVE_DEBUGGING)
2318 static struct kdp_ether_addr kdp_current_mac_address = {.ether_addr_octet = {0, 0, 0, 0, 0, 0}};
2319
2320 /* XXX ugly forward declares to stop warnings */
2321 void *kdp_get_interface(void);
2322 void kdp_set_ip_and_mac_addresses(struct kdp_in_addr *, struct kdp_ether_addr *);
2323 void kdp_set_gateway_mac(void *);
2324 void kdp_set_interface(void *);
2325 void kdp_register_send_receive(void *, void *);
2326 void kdp_unregister_send_receive(void *, void *);
2327
2328 uint32_t kdp_stack_snapshot_bytes_traced(void);
2329
2330 void
kdp_register_send_receive(__unused void * send,__unused void * receive)2331 kdp_register_send_receive(__unused void *send, __unused void *receive)
2332 {
2333 }
2334
2335 void
kdp_unregister_send_receive(__unused void * send,__unused void * receive)2336 kdp_unregister_send_receive(__unused void *send, __unused void *receive)
2337 {
2338 }
2339
2340 void *
kdp_get_interface(void)2341 kdp_get_interface( void)
2342 {
2343 return (void *)0;
2344 }
2345
2346 unsigned int
kdp_get_ip_address(void)2347 kdp_get_ip_address(void )
2348 {
2349 return 0;
2350 }
2351
2352 struct kdp_ether_addr
kdp_get_mac_addr(void)2353 kdp_get_mac_addr(void)
2354 {
2355 return kdp_current_mac_address;
2356 }
2357
2358 void
kdp_set_ip_and_mac_addresses(__unused struct kdp_in_addr * ipaddr,__unused struct kdp_ether_addr * macaddr)2359 kdp_set_ip_and_mac_addresses(
2360 __unused struct kdp_in_addr *ipaddr,
2361 __unused struct kdp_ether_addr *macaddr)
2362 {
2363 }
2364
2365 void
kdp_set_gateway_mac(__unused void * gatewaymac)2366 kdp_set_gateway_mac(__unused void *gatewaymac)
2367 {
2368 }
2369
2370 void
kdp_set_interface(__unused void * ifp)2371 kdp_set_interface(__unused void *ifp)
2372 {
2373 }
2374
2375 void
kdp_register_link(__unused kdp_link_t link,__unused kdp_mode_t mode)2376 kdp_register_link(__unused kdp_link_t link, __unused kdp_mode_t mode)
2377 {
2378 }
2379
2380 void
kdp_unregister_link(__unused kdp_link_t link,__unused kdp_mode_t mode)2381 kdp_unregister_link(__unused kdp_link_t link, __unused kdp_mode_t mode)
2382 {
2383 }
2384
2385 #endif /* !(MACH_KDP && CONFIG_KDP_INTERACTIVE_DEBUGGING) */
2386
2387 #if !CONFIG_KDP_INTERACTIVE_DEBUGGING
2388 extern __attribute__((noreturn)) void panic_spin_forever(void);
2389
2390 __attribute__((noreturn))
2391 void
kdp_raise_exception(__unused unsigned int exception,__unused unsigned int code,__unused unsigned int subcode,__unused void * saved_state)2392 kdp_raise_exception(
2393 __unused unsigned int exception,
2394 __unused unsigned int code,
2395 __unused unsigned int subcode,
2396 __unused void *saved_state
2397 )
2398 #else
2399 void
2400 kdp_raise_exception(
2401 unsigned int exception,
2402 unsigned int code,
2403 unsigned int subcode,
2404 void *saved_state
2405 )
2406 #endif
2407 {
2408 #if defined(__arm64__)
2409 assert(!kernel_debugging_restricted());
2410 #endif
2411
2412 #if CONFIG_KDP_INTERACTIVE_DEBUGGING
2413 kdp_debugger_loop(exception, code, subcode, saved_state);
2414 #else /* CONFIG_KDP_INTERACTIVE_DEBUGGING */
2415
2416 assert(current_debugger != KDP_CUR_DB);
2417 panic_spin_forever();
2418 #endif /* CONFIG_KDP_INTERACTIVE_DEBUGGING */
2419 }
2420