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