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