/
RNBRemote.cpp
6265 lines (5594 loc) · 214 KB
/
RNBRemote.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===-- RNBRemote.cpp -------------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Created by Greg Clayton on 12/12/07.
//
//===----------------------------------------------------------------------===//
#include "RNBRemote.h"
#include <errno.h>
#include <mach-o/loader.h>
#include <mach/exception_types.h>
#include <signal.h>
#include <sys/stat.h>
#include <sys/sysctl.h>
#include <unistd.h>
#if defined(__APPLE__)
#include <pthread.h>
#include <sched.h>
#endif
#include "DNB.h"
#include "DNBDataRef.h"
#include "DNBLog.h"
#include "DNBThreadResumeActions.h"
#include "DarwinLogCollector.h"
#include "DarwinLogEvent.h"
#include "JSON.h"
#include "JSONGenerator.h"
#include "JSONGenerator.h"
#include "MacOSX/Genealogy.h"
#include "OsLogger.h"
#include "RNBContext.h"
#include "RNBServices.h"
#include "RNBSocket.h"
#include "StdStringExtractor.h"
#if defined(HAVE_LIBCOMPRESSION)
#include <compression.h>
#endif
#if defined(HAVE_LIBZ)
#include <zlib.h>
#endif
#include <TargetConditionals.h> // for endianness predefines
#include <iomanip>
#include <sstream>
#include <unordered_set>
//----------------------------------------------------------------------
// constants
//----------------------------------------------------------------------
static const std::string OS_LOG_EVENTS_KEY_NAME("events");
static const std::string JSON_ASYNC_TYPE_KEY_NAME("type");
static const DarwinLogEventVector::size_type DARWIN_LOG_MAX_EVENTS_PER_PACKET =
10;
//----------------------------------------------------------------------
// std::iostream formatting macros
//----------------------------------------------------------------------
#define RAW_HEXBASE std::setfill('0') << std::hex << std::right
#define HEXBASE '0' << 'x' << RAW_HEXBASE
#define RAWHEX8(x) RAW_HEXBASE << std::setw(2) << ((uint32_t)((uint8_t)x))
#define RAWHEX16 RAW_HEXBASE << std::setw(4)
#define RAWHEX32 RAW_HEXBASE << std::setw(8)
#define RAWHEX64 RAW_HEXBASE << std::setw(16)
#define HEX8(x) HEXBASE << std::setw(2) << ((uint32_t)(x))
#define HEX16 HEXBASE << std::setw(4)
#define HEX32 HEXBASE << std::setw(8)
#define HEX64 HEXBASE << std::setw(16)
#define RAW_HEX(x) RAW_HEXBASE << std::setw(sizeof(x) * 2) << (x)
#define HEX(x) HEXBASE << std::setw(sizeof(x) * 2) << (x)
#define RAWHEX_SIZE(x, sz) RAW_HEXBASE << std::setw((sz)) << (x)
#define HEX_SIZE(x, sz) HEXBASE << std::setw((sz)) << (x)
#define STRING_WIDTH(w) std::setfill(' ') << std::setw(w)
#define LEFT_STRING_WIDTH(s, w) \
std::left << std::setfill(' ') << std::setw(w) << (s) << std::right
#define DECIMAL std::dec << std::setfill(' ')
#define DECIMAL_WIDTH(w) DECIMAL << std::setw(w)
#define FLOAT(n, d) \
std::setfill(' ') << std::setw((n) + (d) + 1) << std::setprecision(d) \
<< std::showpoint << std::fixed
#define INDENT_WITH_SPACES(iword_idx) \
std::setfill(' ') << std::setw((iword_idx)) << ""
#define INDENT_WITH_TABS(iword_idx) \
std::setfill('\t') << std::setw((iword_idx)) << ""
// Class to handle communications via gdb remote protocol.
//----------------------------------------------------------------------
// Prototypes
//----------------------------------------------------------------------
static std::string binary_encode_string(const std::string &s);
//----------------------------------------------------------------------
// Decode a single hex character and return the hex value as a number or
// -1 if "ch" is not a hex character.
//----------------------------------------------------------------------
static inline int xdigit_to_sint(char ch) {
if (ch >= 'a' && ch <= 'f')
return 10 + ch - 'a';
if (ch >= 'A' && ch <= 'F')
return 10 + ch - 'A';
if (ch >= '0' && ch <= '9')
return ch - '0';
return -1;
}
//----------------------------------------------------------------------
// Decode a single hex ASCII byte. Return -1 on failure, a value 0-255
// on success.
//----------------------------------------------------------------------
static inline int decoded_hex_ascii_char(const char *p) {
const int hi_nibble = xdigit_to_sint(p[0]);
if (hi_nibble == -1)
return -1;
const int lo_nibble = xdigit_to_sint(p[1]);
if (lo_nibble == -1)
return -1;
return (uint8_t)((hi_nibble << 4) + lo_nibble);
}
//----------------------------------------------------------------------
// Decode a hex ASCII string back into a string
//----------------------------------------------------------------------
static std::string decode_hex_ascii_string(const char *p,
uint32_t max_length = UINT32_MAX) {
std::string arg;
if (p) {
for (const char *c = p; ((c - p) / 2) < max_length; c += 2) {
int ch = decoded_hex_ascii_char(c);
if (ch == -1)
break;
else
arg.push_back(ch);
}
}
return arg;
}
uint64_t decode_uint64(const char *p, int base, char **end = nullptr,
uint64_t fail_value = 0) {
nub_addr_t addr = strtoull(p, end, 16);
if (addr == 0 && errno != 0)
return fail_value;
return addr;
}
extern void ASLLogCallback(void *baton, uint32_t flags, const char *format,
va_list args);
#if defined(__APPLE__) && \
(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ >= 101000)
// from System.framework/Versions/B/PrivateHeaders/sys/codesign.h
extern "C" {
#define CS_OPS_STATUS 0 /* return status */
#define CS_RESTRICT 0x0000800 /* tell dyld to treat restricted */
int csops(pid_t pid, unsigned int ops, void *useraddr, size_t usersize);
// from rootless.h
bool rootless_allows_task_for_pid(pid_t pid);
// from sys/csr.h
typedef uint32_t csr_config_t;
#define CSR_ALLOW_TASK_FOR_PID (1 << 2)
int csr_check(csr_config_t mask);
}
#endif
RNBRemote::RNBRemote()
: m_ctx(), m_comm(), m_arch(), m_continue_thread(-1), m_thread(-1),
m_mutex(), m_dispatch_queue_offsets(),
m_dispatch_queue_offsets_addr(INVALID_NUB_ADDRESS),
m_qSymbol_index(UINT32_MAX), m_packets_recvd(0), m_packets(),
m_rx_packets(), m_rx_partial_data(), m_rx_pthread(0),
m_max_payload_size(DEFAULT_GDB_REMOTE_PROTOCOL_BUFSIZE - 4),
m_extended_mode(false), m_noack_mode(false),
m_thread_suffix_supported(false), m_list_threads_in_stop_reply(false),
m_compression_minsize(384), m_enable_compression_next_send_packet(false),
m_compression_mode(compression_types::none) {
DNBLogThreadedIf(LOG_RNB_REMOTE, "%s", __PRETTY_FUNCTION__);
CreatePacketTable();
}
RNBRemote::~RNBRemote() {
DNBLogThreadedIf(LOG_RNB_REMOTE, "%s", __PRETTY_FUNCTION__);
StopReadRemoteDataThread();
}
void RNBRemote::CreatePacketTable() {
// Step required to add new packets:
// 1 - Add new enumeration to RNBRemote::PacketEnum
// 2 - Create the RNBRemote::HandlePacket_ function if a new function is
// needed
// 3 - Register the Packet definition with any needed callbacks in this
// function
// - If no response is needed for a command, then use NULL for the
// normal callback
// - If the packet is not supported while the target is running, use
// NULL for the async callback
// 4 - If the packet is a standard packet (starts with a '$' character
// followed by the payload and then '#' and checksum, then you are done
// else go on to step 5
// 5 - if the packet is a fixed length packet:
// - modify the switch statement for the first character in the payload
// in RNBRemote::CommDataReceived so it doesn't reject the new packet
// type as invalid
// - modify the switch statement for the first character in the payload
// in RNBRemote::GetPacketPayload and make sure the payload of the
// packet
// is returned correctly
std::vector<Packet> &t = m_packets;
t.push_back(Packet(ack, NULL, NULL, "+", "ACK"));
t.push_back(Packet(nack, NULL, NULL, "-", "!ACK"));
t.push_back(Packet(read_memory, &RNBRemote::HandlePacket_m, NULL, "m",
"Read memory"));
t.push_back(Packet(read_register, &RNBRemote::HandlePacket_p, NULL, "p",
"Read one register"));
t.push_back(Packet(read_general_regs, &RNBRemote::HandlePacket_g, NULL, "g",
"Read registers"));
t.push_back(Packet(write_memory, &RNBRemote::HandlePacket_M, NULL, "M",
"Write memory"));
t.push_back(Packet(write_register, &RNBRemote::HandlePacket_P, NULL, "P",
"Write one register"));
t.push_back(Packet(write_general_regs, &RNBRemote::HandlePacket_G, NULL, "G",
"Write registers"));
t.push_back(Packet(insert_mem_bp, &RNBRemote::HandlePacket_z, NULL, "Z0",
"Insert memory breakpoint"));
t.push_back(Packet(remove_mem_bp, &RNBRemote::HandlePacket_z, NULL, "z0",
"Remove memory breakpoint"));
t.push_back(Packet(single_step, &RNBRemote::HandlePacket_s, NULL, "s",
"Single step"));
t.push_back(Packet(cont, &RNBRemote::HandlePacket_c, NULL, "c", "continue"));
t.push_back(Packet(single_step_with_sig, &RNBRemote::HandlePacket_S, NULL,
"S", "Single step with signal"));
t.push_back(
Packet(set_thread, &RNBRemote::HandlePacket_H, NULL, "H", "Set thread"));
t.push_back(Packet(halt, &RNBRemote::HandlePacket_last_signal,
&RNBRemote::HandlePacket_stop_process, "\x03", "^C"));
// t.push_back (Packet (use_extended_mode,
// &RNBRemote::HandlePacket_UNIMPLEMENTED, NULL, "!", "Use extended mode"));
t.push_back(Packet(why_halted, &RNBRemote::HandlePacket_last_signal, NULL,
"?", "Why did target halt"));
t.push_back(
Packet(set_argv, &RNBRemote::HandlePacket_A, NULL, "A", "Set argv"));
// t.push_back (Packet (set_bp,
// &RNBRemote::HandlePacket_UNIMPLEMENTED, NULL, "B", "Set/clear
// breakpoint"));
t.push_back(Packet(continue_with_sig, &RNBRemote::HandlePacket_C, NULL, "C",
"Continue with signal"));
t.push_back(Packet(detach, &RNBRemote::HandlePacket_D, NULL, "D",
"Detach gdb from remote system"));
// t.push_back (Packet (step_inferior_one_cycle,
// &RNBRemote::HandlePacket_UNIMPLEMENTED, NULL, "i", "Step inferior by one
// clock cycle"));
// t.push_back (Packet (signal_and_step_inf_one_cycle,
// &RNBRemote::HandlePacket_UNIMPLEMENTED, NULL, "I", "Signal inferior, then
// step one clock cycle"));
t.push_back(Packet(kill, &RNBRemote::HandlePacket_k, NULL, "k", "Kill"));
// t.push_back (Packet (restart,
// &RNBRemote::HandlePacket_UNIMPLEMENTED, NULL, "R", "Restart inferior"));
// t.push_back (Packet (search_mem_backwards,
// &RNBRemote::HandlePacket_UNIMPLEMENTED, NULL, "t", "Search memory
// backwards"));
t.push_back(Packet(thread_alive_p, &RNBRemote::HandlePacket_T, NULL, "T",
"Is thread alive"));
t.push_back(Packet(query_supported_features,
&RNBRemote::HandlePacket_qSupported, NULL, "qSupported",
"Query about supported features"));
t.push_back(Packet(vattach, &RNBRemote::HandlePacket_v, NULL, "vAttach",
"Attach to a new process"));
t.push_back(Packet(vattachwait, &RNBRemote::HandlePacket_v, NULL,
"vAttachWait",
"Wait for a process to start up then attach to it"));
t.push_back(Packet(vattachorwait, &RNBRemote::HandlePacket_v, NULL,
"vAttachOrWait", "Attach to the process or if it doesn't "
"exist, wait for the process to start up "
"then attach to it"));
t.push_back(Packet(vattachname, &RNBRemote::HandlePacket_v, NULL,
"vAttachName", "Attach to an existing process by name"));
t.push_back(Packet(vcont_list_actions, &RNBRemote::HandlePacket_v, NULL,
"vCont;", "Verbose resume with thread actions"));
t.push_back(Packet(vcont_list_actions, &RNBRemote::HandlePacket_v, NULL,
"vCont?",
"List valid continue-with-thread-actions actions"));
t.push_back(Packet(read_data_from_memory, &RNBRemote::HandlePacket_x, NULL,
"x", "Read data from memory"));
t.push_back(Packet(write_data_to_memory, &RNBRemote::HandlePacket_X, NULL,
"X", "Write data to memory"));
// t.push_back (Packet (insert_hardware_bp,
// &RNBRemote::HandlePacket_UNIMPLEMENTED, NULL, "Z1", "Insert hardware
// breakpoint"));
// t.push_back (Packet (remove_hardware_bp,
// &RNBRemote::HandlePacket_UNIMPLEMENTED, NULL, "z1", "Remove hardware
// breakpoint"));
t.push_back(Packet(insert_write_watch_bp, &RNBRemote::HandlePacket_z, NULL,
"Z2", "Insert write watchpoint"));
t.push_back(Packet(remove_write_watch_bp, &RNBRemote::HandlePacket_z, NULL,
"z2", "Remove write watchpoint"));
t.push_back(Packet(insert_read_watch_bp, &RNBRemote::HandlePacket_z, NULL,
"Z3", "Insert read watchpoint"));
t.push_back(Packet(remove_read_watch_bp, &RNBRemote::HandlePacket_z, NULL,
"z3", "Remove read watchpoint"));
t.push_back(Packet(insert_access_watch_bp, &RNBRemote::HandlePacket_z, NULL,
"Z4", "Insert access watchpoint"));
t.push_back(Packet(remove_access_watch_bp, &RNBRemote::HandlePacket_z, NULL,
"z4", "Remove access watchpoint"));
t.push_back(Packet(query_monitor, &RNBRemote::HandlePacket_qRcmd, NULL,
"qRcmd", "Monitor command"));
t.push_back(Packet(query_current_thread_id, &RNBRemote::HandlePacket_qC, NULL,
"qC", "Query current thread ID"));
t.push_back(Packet(query_echo, &RNBRemote::HandlePacket_qEcho, NULL, "qEcho:",
"Echo the packet back to allow the debugger to sync up "
"with this server"));
t.push_back(Packet(query_get_pid, &RNBRemote::HandlePacket_qGetPid, NULL,
"qGetPid", "Query process id"));
t.push_back(Packet(query_thread_ids_first,
&RNBRemote::HandlePacket_qThreadInfo, NULL, "qfThreadInfo",
"Get list of active threads (first req)"));
t.push_back(Packet(query_thread_ids_subsequent,
&RNBRemote::HandlePacket_qThreadInfo, NULL, "qsThreadInfo",
"Get list of active threads (subsequent req)"));
// APPLE LOCAL: qThreadStopInfo
// syntax: qThreadStopInfoTTTT
// TTTT is hex thread ID
t.push_back(Packet(query_thread_stop_info,
&RNBRemote::HandlePacket_qThreadStopInfo, NULL,
"qThreadStopInfo",
"Get detailed info on why the specified thread stopped"));
t.push_back(Packet(query_thread_extra_info,
&RNBRemote::HandlePacket_qThreadExtraInfo, NULL,
"qThreadExtraInfo", "Get printable status of a thread"));
// t.push_back (Packet (query_image_offsets,
// &RNBRemote::HandlePacket_UNIMPLEMENTED, NULL, "qOffsets", "Report offset
// of loaded program"));
t.push_back(Packet(
query_launch_success, &RNBRemote::HandlePacket_qLaunchSuccess, NULL,
"qLaunchSuccess", "Report the success or failure of the launch attempt"));
t.push_back(
Packet(query_register_info, &RNBRemote::HandlePacket_qRegisterInfo, NULL,
"qRegisterInfo",
"Dynamically discover remote register context information."));
t.push_back(Packet(
query_shlib_notify_info_addr, &RNBRemote::HandlePacket_qShlibInfoAddr,
NULL, "qShlibInfoAddr", "Returns the address that contains info needed "
"for getting shared library notifications"));
t.push_back(Packet(query_step_packet_supported,
&RNBRemote::HandlePacket_qStepPacketSupported, NULL,
"qStepPacketSupported",
"Replys with OK if the 's' packet is supported."));
t.push_back(
Packet(query_vattachorwait_supported,
&RNBRemote::HandlePacket_qVAttachOrWaitSupported, NULL,
"qVAttachOrWaitSupported",
"Replys with OK if the 'vAttachOrWait' packet is supported."));
t.push_back(
Packet(query_sync_thread_state_supported,
&RNBRemote::HandlePacket_qSyncThreadStateSupported, NULL,
"qSyncThreadStateSupported",
"Replys with OK if the 'QSyncThreadState:' packet is supported."));
t.push_back(Packet(
query_host_info, &RNBRemote::HandlePacket_qHostInfo, NULL, "qHostInfo",
"Replies with multiple 'key:value;' tuples appended to each other."));
t.push_back(Packet(
query_gdb_server_version, &RNBRemote::HandlePacket_qGDBServerVersion,
NULL, "qGDBServerVersion",
"Replies with multiple 'key:value;' tuples appended to each other."));
t.push_back(Packet(
query_process_info, &RNBRemote::HandlePacket_qProcessInfo, NULL,
"qProcessInfo",
"Replies with multiple 'key:value;' tuples appended to each other."));
t.push_back(Packet(
query_symbol_lookup, &RNBRemote::HandlePacket_qSymbol, NULL, "qSymbol:",
"Notify that host debugger is ready to do symbol lookups"));
t.push_back(Packet(json_query_thread_extended_info,
&RNBRemote::HandlePacket_jThreadExtendedInfo, NULL,
"jThreadExtendedInfo",
"Replies with JSON data of thread extended information."));
t.push_back(Packet(json_query_get_loaded_dynamic_libraries_infos,
&RNBRemote::HandlePacket_jGetLoadedDynamicLibrariesInfos,
NULL, "jGetLoadedDynamicLibrariesInfos",
"Replies with JSON data of all the shared libraries "
"loaded in this process."));
t.push_back(
Packet(json_query_threads_info, &RNBRemote::HandlePacket_jThreadsInfo,
NULL, "jThreadsInfo",
"Replies with JSON data with information about all threads."));
t.push_back(Packet(json_query_get_shared_cache_info,
&RNBRemote::HandlePacket_jGetSharedCacheInfo, NULL,
"jGetSharedCacheInfo", "Replies with JSON data about the "
"location and uuid of the shared "
"cache in the inferior process."));
t.push_back(Packet(start_noack_mode, &RNBRemote::HandlePacket_QStartNoAckMode,
NULL, "QStartNoAckMode",
"Request that " DEBUGSERVER_PROGRAM_NAME
" stop acking remote protocol packets"));
t.push_back(Packet(prefix_reg_packets_with_tid,
&RNBRemote::HandlePacket_QThreadSuffixSupported, NULL,
"QThreadSuffixSupported",
"Check if thread specific packets (register packets 'g', "
"'G', 'p', and 'P') support having the thread ID appended "
"to the end of the command"));
t.push_back(Packet(set_logging_mode, &RNBRemote::HandlePacket_QSetLogging,
NULL, "QSetLogging:", "Check if register packets ('g', "
"'G', 'p', and 'P' support having "
"the thread ID prefix"));
t.push_back(Packet(
set_max_packet_size, &RNBRemote::HandlePacket_QSetMaxPacketSize, NULL,
"QSetMaxPacketSize:",
"Tell " DEBUGSERVER_PROGRAM_NAME " the max sized packet gdb can handle"));
t.push_back(Packet(
set_max_payload_size, &RNBRemote::HandlePacket_QSetMaxPayloadSize, NULL,
"QSetMaxPayloadSize:", "Tell " DEBUGSERVER_PROGRAM_NAME
" the max sized payload gdb can handle"));
t.push_back(
Packet(set_environment_variable, &RNBRemote::HandlePacket_QEnvironment,
NULL, "QEnvironment:",
"Add an environment variable to the inferior's environment"));
t.push_back(
Packet(set_environment_variable_hex,
&RNBRemote::HandlePacket_QEnvironmentHexEncoded, NULL,
"QEnvironmentHexEncoded:",
"Add an environment variable to the inferior's environment"));
t.push_back(Packet(set_launch_arch, &RNBRemote::HandlePacket_QLaunchArch,
NULL, "QLaunchArch:", "Set the architecture to use when "
"launching a process for hosts that "
"can run multiple architecture "
"slices from universal files."));
t.push_back(Packet(set_disable_aslr, &RNBRemote::HandlePacket_QSetDisableASLR,
NULL, "QSetDisableASLR:",
"Set whether to disable ASLR when launching the process "
"with the set argv ('A') packet"));
t.push_back(Packet(set_stdin, &RNBRemote::HandlePacket_QSetSTDIO, NULL,
"QSetSTDIN:", "Set the standard input for a process to be "
"launched with the 'A' packet"));
t.push_back(Packet(set_stdout, &RNBRemote::HandlePacket_QSetSTDIO, NULL,
"QSetSTDOUT:", "Set the standard output for a process to "
"be launched with the 'A' packet"));
t.push_back(Packet(set_stderr, &RNBRemote::HandlePacket_QSetSTDIO, NULL,
"QSetSTDERR:", "Set the standard error for a process to "
"be launched with the 'A' packet"));
t.push_back(Packet(set_working_dir, &RNBRemote::HandlePacket_QSetWorkingDir,
NULL, "QSetWorkingDir:", "Set the working directory for a "
"process to be launched with the "
"'A' packet"));
t.push_back(Packet(set_list_threads_in_stop_reply,
&RNBRemote::HandlePacket_QListThreadsInStopReply, NULL,
"QListThreadsInStopReply",
"Set if the 'threads' key should be added to the stop "
"reply packets with a list of all thread IDs."));
t.push_back(Packet(
sync_thread_state, &RNBRemote::HandlePacket_QSyncThreadState, NULL,
"QSyncThreadState:", "Do whatever is necessary to make sure 'thread' is "
"in a safe state to call functions on."));
// t.push_back (Packet (pass_signals_to_inferior,
// &RNBRemote::HandlePacket_UNIMPLEMENTED, NULL, "QPassSignals:", "Specify
// which signals are passed to the inferior"));
t.push_back(Packet(allocate_memory, &RNBRemote::HandlePacket_AllocateMemory,
NULL, "_M", "Allocate memory in the inferior process."));
t.push_back(Packet(deallocate_memory,
&RNBRemote::HandlePacket_DeallocateMemory, NULL, "_m",
"Deallocate memory in the inferior process."));
t.push_back(Packet(
save_register_state, &RNBRemote::HandlePacket_SaveRegisterState, NULL,
"QSaveRegisterState", "Save the register state for the current thread "
"and return a decimal save ID."));
t.push_back(Packet(restore_register_state,
&RNBRemote::HandlePacket_RestoreRegisterState, NULL,
"QRestoreRegisterState:",
"Restore the register state given a save ID previously "
"returned from a call to QSaveRegisterState."));
t.push_back(Packet(
memory_region_info, &RNBRemote::HandlePacket_MemoryRegionInfo, NULL,
"qMemoryRegionInfo", "Return size and attributes of a memory region that "
"contains the given address"));
t.push_back(Packet(get_profile_data, &RNBRemote::HandlePacket_GetProfileData,
NULL, "qGetProfileData",
"Return profiling data of the current target."));
t.push_back(Packet(set_enable_profiling,
&RNBRemote::HandlePacket_SetEnableAsyncProfiling, NULL,
"QSetEnableAsyncProfiling",
"Enable or disable the profiling of current target."));
t.push_back(Packet(enable_compression,
&RNBRemote::HandlePacket_QEnableCompression, NULL,
"QEnableCompression:",
"Enable compression for the remainder of the connection"));
t.push_back(Packet(watchpoint_support_info,
&RNBRemote::HandlePacket_WatchpointSupportInfo, NULL,
"qWatchpointSupportInfo",
"Return the number of supported hardware watchpoints"));
t.push_back(Packet(set_process_event,
&RNBRemote::HandlePacket_QSetProcessEvent, NULL,
"QSetProcessEvent:", "Set a process event, to be passed "
"to the process, can be set before "
"the process is started, or after."));
t.push_back(
Packet(set_detach_on_error, &RNBRemote::HandlePacket_QSetDetachOnError,
NULL, "QSetDetachOnError:",
"Set whether debugserver will detach (1) or kill (0) from the "
"process it is controlling if it loses connection to lldb."));
t.push_back(Packet(
speed_test, &RNBRemote::HandlePacket_qSpeedTest, NULL, "qSpeedTest:",
"Test the maximum speed at which packet can be sent/received."));
t.push_back(Packet(query_transfer, &RNBRemote::HandlePacket_qXfer, NULL,
"qXfer:", "Support the qXfer packet."));
t.push_back(
Packet(query_supported_async_json_packets,
&RNBRemote::HandlePacket_qStructuredDataPlugins, NULL,
"qStructuredDataPlugins",
"Query for the structured data plugins supported by the remote."));
t.push_back(
Packet(configure_darwin_log, &RNBRemote::HandlePacket_QConfigureDarwinLog,
NULL, "QConfigureDarwinLog:",
"Configure the DarwinLog structured data plugin support."));
}
void RNBRemote::FlushSTDIO() {
if (m_ctx.HasValidProcessID()) {
nub_process_t pid = m_ctx.ProcessID();
char buf[256];
nub_size_t count;
do {
count = DNBProcessGetAvailableSTDOUT(pid, buf, sizeof(buf));
if (count > 0) {
SendSTDOUTPacket(buf, count);
}
} while (count > 0);
do {
count = DNBProcessGetAvailableSTDERR(pid, buf, sizeof(buf));
if (count > 0) {
SendSTDERRPacket(buf, count);
}
} while (count > 0);
}
}
void RNBRemote::SendAsyncProfileData() {
if (m_ctx.HasValidProcessID()) {
nub_process_t pid = m_ctx.ProcessID();
char buf[1024];
nub_size_t count;
do {
count = DNBProcessGetAvailableProfileData(pid, buf, sizeof(buf));
if (count > 0) {
SendAsyncProfileDataPacket(buf, count);
}
} while (count > 0);
}
}
void RNBRemote::SendAsyncDarwinLogData() {
DNBLogThreadedIf(LOG_DARWIN_LOG, "RNBRemote::%s(): enter", __FUNCTION__);
if (!m_ctx.HasValidProcessID()) {
DNBLogThreadedIf(LOG_DARWIN_LOG, "RNBRemote::%s(): ignoring due to"
"invalid process id",
__FUNCTION__);
return;
}
nub_process_t pid = m_ctx.ProcessID();
DarwinLogEventVector::size_type entry_count = 0;
// NOTE: the current looping structure here does nothing
// to guarantee that we can send off async packets faster
// than we generate them. It will keep sending as long
// as there's data to send.
do {
DarwinLogEventVector events = DNBProcessGetAvailableDarwinLogEvents(pid);
entry_count = events.size();
DNBLogThreadedIf(LOG_DARWIN_LOG, "RNBRemote::%s(): outer loop enter",
__FUNCTION__);
for (DarwinLogEventVector::size_type base_entry = 0;
base_entry < entry_count;
base_entry += DARWIN_LOG_MAX_EVENTS_PER_PACKET) {
DNBLogThreadedIf(LOG_DARWIN_LOG, "RNBRemote::%s(): inner loop enter",
__FUNCTION__);
// We limit the total number of entries we pack
// into a single JSON async packet just so it
// doesn't get too large.
JSONGenerator::Dictionary async_dictionary;
// Specify the type of the JSON async data we're sending.
async_dictionary.AddStringItem(JSON_ASYNC_TYPE_KEY_NAME, "DarwinLog");
// Create an array entry in the dictionary to hold all
// the events going in this packet.
JSONGenerator::ArraySP events_array(new JSONGenerator::Array());
async_dictionary.AddItem(OS_LOG_EVENTS_KEY_NAME, events_array);
// We bundle up to DARWIN_LOG_MAX_EVENTS_PER_PACKET events in
// a single packet.
const auto inner_loop_bound =
std::min(base_entry + DARWIN_LOG_MAX_EVENTS_PER_PACKET, entry_count);
for (DarwinLogEventVector::size_type i = base_entry; i < inner_loop_bound;
++i) {
DNBLogThreadedIf(LOG_DARWIN_LOG, "RNBRemote::%s(): adding "
"entry index %lu to the JSON packet",
__FUNCTION__, i);
events_array->AddItem(events[i]);
}
// Send off the packet.
DNBLogThreadedIf(LOG_DARWIN_LOG, "RNBRemote::%s(): sending JSON "
"packet, %lu entries remain",
__FUNCTION__, entry_count - inner_loop_bound);
SendAsyncJSONPacket(async_dictionary);
}
DNBLogThreadedIf(LOG_DARWIN_LOG, "RNBRemote::%s(): outer loop exit",
__FUNCTION__);
} while (entry_count > 0);
DNBLogThreadedIf(LOG_DARWIN_LOG, "RNBRemote::%s(): exit",
__PRETTY_FUNCTION__);
}
rnb_err_t RNBRemote::SendHexEncodedBytePacket(const char *header,
const void *buf, size_t buf_len,
const char *footer) {
std::ostringstream packet_sstrm;
// Append the header cstr if there was one
if (header && header[0])
packet_sstrm << header;
nub_size_t i;
const uint8_t *ubuf8 = (const uint8_t *)buf;
for (i = 0; i < buf_len; i++) {
packet_sstrm << RAWHEX8(ubuf8[i]);
}
// Append the footer cstr if there was one
if (footer && footer[0])
packet_sstrm << footer;
return SendPacket(packet_sstrm.str());
}
rnb_err_t RNBRemote::SendSTDOUTPacket(char *buf, nub_size_t buf_size) {
if (buf_size == 0)
return rnb_success;
return SendHexEncodedBytePacket("O", buf, buf_size, NULL);
}
rnb_err_t RNBRemote::SendSTDERRPacket(char *buf, nub_size_t buf_size) {
if (buf_size == 0)
return rnb_success;
return SendHexEncodedBytePacket("O", buf, buf_size, NULL);
}
// This makes use of asynchronous bit 'A' in the gdb remote protocol.
rnb_err_t RNBRemote::SendAsyncProfileDataPacket(char *buf,
nub_size_t buf_size) {
if (buf_size == 0)
return rnb_success;
std::string packet("A");
packet.append(buf, buf_size);
return SendPacket(packet);
}
rnb_err_t
RNBRemote::SendAsyncJSONPacket(const JSONGenerator::Dictionary &dictionary) {
std::ostringstream stream;
// We're choosing something that is easy to spot if we somehow get one
// of these coming out at the wrong time (i.e. when the remote side
// is not waiting for a process control completion response).
stream << "JSON-async:";
dictionary.Dump(stream);
const std::string payload = binary_encode_string(stream.str());
return SendPacket(payload);
}
// Given a std::string packet contents to send, possibly encode/compress it.
// If compression is enabled, the returned std::string will be in one of two
// forms:
//
// N<original packet contents uncompressed>
// C<size of original decompressed packet>:<packet compressed with the
// requested compression scheme>
//
// If compression is not requested, the original packet contents are returned
std::string RNBRemote::CompressString(const std::string &orig) {
std::string compressed;
compression_types compression_type = GetCompressionType();
if (compression_type != compression_types::none) {
bool compress_this_packet = false;
if (orig.size() > m_compression_minsize) {
compress_this_packet = true;
}
if (compress_this_packet) {
const size_t encoded_data_buf_size = orig.size() + 128;
std::vector<uint8_t> encoded_data(encoded_data_buf_size);
size_t compressed_size = 0;
#if defined(HAVE_LIBCOMPRESSION)
if (compression_type == compression_types::lz4) {
compressed_size = compression_encode_buffer(
encoded_data.data(), encoded_data_buf_size,
(const uint8_t *)orig.c_str(), orig.size(), nullptr,
COMPRESSION_LZ4_RAW);
}
if (compression_type == compression_types::zlib_deflate) {
compressed_size = compression_encode_buffer(
encoded_data.data(), encoded_data_buf_size,
(const uint8_t *)orig.c_str(), orig.size(), nullptr,
COMPRESSION_ZLIB);
}
if (compression_type == compression_types::lzma) {
compressed_size = compression_encode_buffer(
encoded_data.data(), encoded_data_buf_size,
(const uint8_t *)orig.c_str(), orig.size(), nullptr,
COMPRESSION_LZMA);
}
if (compression_type == compression_types::lzfse) {
compressed_size = compression_encode_buffer(
encoded_data.data(), encoded_data_buf_size,
(const uint8_t *)orig.c_str(), orig.size(), nullptr,
COMPRESSION_LZFSE);
}
#endif
#if defined(HAVE_LIBZ)
if (compressed_size == 0 &&
compression_type == compression_types::zlib_deflate) {
z_stream stream;
memset(&stream, 0, sizeof(z_stream));
stream.next_in = (Bytef *)orig.c_str();
stream.avail_in = (uInt)orig.size();
stream.next_out = (Bytef *)encoded_data.data();
stream.avail_out = (uInt)encoded_data_buf_size;
stream.zalloc = Z_NULL;
stream.zfree = Z_NULL;
stream.opaque = Z_NULL;
deflateInit2(&stream, 5, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY);
int compress_status = deflate(&stream, Z_FINISH);
deflateEnd(&stream);
if (compress_status == Z_STREAM_END && stream.total_out > 0) {
compressed_size = stream.total_out;
}
}
#endif
if (compressed_size > 0) {
compressed.clear();
compressed.reserve(compressed_size);
compressed = "C";
char numbuf[16];
snprintf(numbuf, sizeof(numbuf), "%zu:", orig.size());
numbuf[sizeof(numbuf) - 1] = '\0';
compressed.append(numbuf);
for (size_t i = 0; i < compressed_size; i++) {
uint8_t byte = encoded_data[i];
if (byte == '#' || byte == '$' || byte == '}' || byte == '*' ||
byte == '\0') {
compressed.push_back(0x7d);
compressed.push_back(byte ^ 0x20);
} else {
compressed.push_back(byte);
}
}
} else {
compressed = "N" + orig;
}
} else {
compressed = "N" + orig;
}
} else {
compressed = orig;
}
return compressed;
}
rnb_err_t RNBRemote::SendPacket(const std::string &s) {
DNBLogThreadedIf(LOG_RNB_MAX, "%8d RNBRemote::%s (%s) called",
(uint32_t)m_comm.Timer().ElapsedMicroSeconds(true),
__FUNCTION__, s.c_str());
std::string s_compressed = CompressString(s);
std::string sendpacket = "$" + s_compressed + "#";
int cksum = 0;
char hexbuf[5];
if (m_noack_mode) {
sendpacket += "00";
} else {
for (size_t i = 0; i != s_compressed.size(); ++i)
cksum += s_compressed[i];
snprintf(hexbuf, sizeof hexbuf, "%02x", cksum & 0xff);
sendpacket += hexbuf;
}
rnb_err_t err = m_comm.Write(sendpacket.c_str(), sendpacket.size());
if (err != rnb_success)
return err;
if (m_noack_mode)
return rnb_success;
std::string reply;
RNBRemote::Packet packet;
err = GetPacket(reply, packet, true);
if (err != rnb_success) {
DNBLogThreadedIf(LOG_RNB_REMOTE,
"%8d RNBRemote::%s (%s) got error trying to get reply...",
(uint32_t)m_comm.Timer().ElapsedMicroSeconds(true),
__FUNCTION__, sendpacket.c_str());
return err;
}
DNBLogThreadedIf(LOG_RNB_MAX, "%8d RNBRemote::%s (%s) got reply: '%s'",
(uint32_t)m_comm.Timer().ElapsedMicroSeconds(true),
__FUNCTION__, sendpacket.c_str(), reply.c_str());
if (packet.type == ack)
return rnb_success;
// Should we try to resend the packet at this layer?
// if (packet.command == nack)
return rnb_err;
}
/* Get a packet via gdb remote protocol.
Strip off the prefix/suffix, verify the checksum to make sure
a valid packet was received, send an ACK if they match. */
rnb_err_t RNBRemote::GetPacketPayload(std::string &return_packet) {
// DNBLogThreadedIf (LOG_RNB_MAX, "%8u RNBRemote::%s called",
// (uint32_t)m_comm.Timer().ElapsedMicroSeconds(true), __FUNCTION__);
PThreadMutex::Locker locker(m_mutex);
if (m_rx_packets.empty()) {
// Only reset the remote command available event if we have no more packets
m_ctx.Events().ResetEvents(RNBContext::event_read_packet_available);
// DNBLogThreadedIf (LOG_RNB_MAX, "%8u RNBRemote::%s error: no packets
// available...", (uint32_t)m_comm.Timer().ElapsedMicroSeconds(true),
// __FUNCTION__);
return rnb_err;
}
// DNBLogThreadedIf (LOG_RNB_MAX, "%8u RNBRemote::%s has %u queued packets",
// (uint32_t)m_comm.Timer().ElapsedMicroSeconds(true), __FUNCTION__,
// m_rx_packets.size());
return_packet.swap(m_rx_packets.front());
m_rx_packets.pop_front();
locker.Reset(); // Release our lock on the mutex
if (m_rx_packets.empty()) {
// Reset the remote command available event if we have no more packets
m_ctx.Events().ResetEvents(RNBContext::event_read_packet_available);
}
// DNBLogThreadedIf (LOG_RNB_MEDIUM, "%8u RNBRemote::%s: '%s'",
// (uint32_t)m_comm.Timer().ElapsedMicroSeconds(true), __FUNCTION__,
// return_packet.c_str());
switch (return_packet[0]) {
case '+':
case '-':
case '\x03':
break;
case '$': {
long packet_checksum = 0;
if (!m_noack_mode) {
for (size_t i = return_packet.size() - 2; i < return_packet.size(); ++i) {
char checksum_char = tolower(return_packet[i]);
if (!isxdigit(checksum_char)) {
m_comm.Write("-", 1);
DNBLogThreadedIf(LOG_RNB_REMOTE, "%8u RNBRemote::%s error: packet "
"with invalid checksum characters: "
"%s",
(uint32_t)m_comm.Timer().ElapsedMicroSeconds(true),
__FUNCTION__, return_packet.c_str());
return rnb_err;
}
}
packet_checksum =
strtol(&return_packet[return_packet.size() - 2], NULL, 16);
}
return_packet.erase(0, 1); // Strip the leading '$'
return_packet.erase(return_packet.size() - 3); // Strip the #XX checksum
if (!m_noack_mode) {
// Compute the checksum
int computed_checksum = 0;
for (std::string::iterator it = return_packet.begin();
it != return_packet.end(); ++it) {
computed_checksum += *it;
}
if (packet_checksum == (computed_checksum & 0xff)) {
// DNBLogThreadedIf (LOG_RNB_MEDIUM, "%8u RNBRemote::%s sending ACK for
// '%s'", (uint32_t)m_comm.Timer().ElapsedMicroSeconds(true),
// __FUNCTION__, return_packet.c_str());
m_comm.Write("+", 1);
} else {
DNBLogThreadedIf(
LOG_RNB_MEDIUM, "%8u RNBRemote::%s sending ACK for '%s' (error: "
"packet checksum mismatch (0x%2.2lx != 0x%2.2x))",
(uint32_t)m_comm.Timer().ElapsedMicroSeconds(true), __FUNCTION__,
return_packet.c_str(), packet_checksum, computed_checksum);
m_comm.Write("-", 1);
return rnb_err;
}
}
} break;
default:
DNBLogThreadedIf(LOG_RNB_REMOTE,
"%8u RNBRemote::%s tossing unexpected packet???? %s",
(uint32_t)m_comm.Timer().ElapsedMicroSeconds(true),
__FUNCTION__, return_packet.c_str());
if (!m_noack_mode)
m_comm.Write("-", 1);
return rnb_err;
}
return rnb_success;
}
rnb_err_t RNBRemote::HandlePacket_UNIMPLEMENTED(const char *p) {
DNBLogThreadedIf(LOG_RNB_MAX, "%8u RNBRemote::%s(\"%s\")",
(uint32_t)m_comm.Timer().ElapsedMicroSeconds(true),
__FUNCTION__, p ? p : "NULL");
return SendPacket("");
}
rnb_err_t RNBRemote::HandlePacket_ILLFORMED(const char *file, int line,
const char *p,
const char *description) {
DNBLogThreadedIf(LOG_RNB_PACKETS, "%8u %s:%i ILLFORMED: '%s' (%s)",
(uint32_t)m_comm.Timer().ElapsedMicroSeconds(true), file,
line, __FUNCTION__, p);
return SendPacket("E03");
}
rnb_err_t RNBRemote::GetPacket(std::string &packet_payload,
RNBRemote::Packet &packet_info, bool wait) {
std::string payload;
rnb_err_t err = GetPacketPayload(payload);
if (err != rnb_success) {
PThreadEvent &events = m_ctx.Events();
nub_event_t set_events = events.GetEventBits();
// TODO: add timeout version of GetPacket?? We would then need to pass
// that timeout value along to DNBProcessTimedWaitForEvent.
if (!wait || ((set_events & RNBContext::event_read_thread_running) == 0))
return err;
const nub_event_t events_to_wait_for =
RNBContext::event_read_packet_available |
RNBContext::event_read_thread_exiting;
while ((set_events = events.WaitForSetEvents(events_to_wait_for)) != 0) {
if (set_events & RNBContext::event_read_packet_available) {
// Try the queue again now that we got an event
err = GetPacketPayload(payload);
if (err == rnb_success)
break;
}
if (set_events & RNBContext::event_read_thread_exiting)
err = rnb_not_connected;
if (err == rnb_not_connected)
return err;
}
while (err == rnb_err)
;
if (set_events == 0)
err = rnb_not_connected;
}
if (err == rnb_success) {
Packet::iterator it;
for (it = m_packets.begin(); it != m_packets.end(); ++it) {
if (payload.compare(0, it->abbrev.size(), it->abbrev) == 0)
break;