-
-
Notifications
You must be signed in to change notification settings - Fork 101
Expand file tree
/
Copy pathllscan.cc
More file actions
1726 lines (1411 loc) · 53.7 KB
/
llscan.cc
File metadata and controls
1726 lines (1411 loc) · 53.7 KB
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
#include <errno.h>
#include <getopt.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
#include <cinttypes>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <lldb/API/SBExpressionOptions.h>
#include "deps/rang/include/rang.hpp"
#include "src/error.h"
#include "src/llscan.h"
#include "src/llv8-inl.h"
#include "src/settings.h"
namespace llnode {
using lldb::ByteOrder;
using lldb::SBCommandReturnObject;
using lldb::SBDebugger;
using lldb::SBError;
using lldb::SBExpressionOptions;
using lldb::SBStream;
using lldb::SBTarget;
using lldb::SBValue;
using lldb::eReturnStatusFailed;
using lldb::eReturnStatusSuccessFinishResult;
char** ParsePrinterOptions(char** cmd, Printer::PrinterOptions* options) {
static struct option opts[] = {
{"full-string", no_argument, nullptr, 'F'},
{"string-length", required_argument, nullptr, 'l'},
{"array-length", required_argument, nullptr, 'l'},
{"length", required_argument, nullptr, 'l'},
{"print-map", no_argument, nullptr, 'm'},
{"print-source", no_argument, nullptr, 's'},
{"verbose", no_argument, nullptr, 'v'},
{"detailed", no_argument, nullptr, 'd'},
{"output-limit", required_argument, nullptr, 'n'},
{nullptr, 0, nullptr, 0}};
int argc = 1;
for (char** p = cmd; p != nullptr && *p != nullptr; p++) argc++;
char* args[argc];
// Make this look like a command line, we need a valid element at index 0
// for getopt_long to use in its error messages.
char name[] = "llnode";
args[0] = name;
for (int i = 0; i < argc - 1; i++) args[i + 1] = cmd[i];
// Reset getopts.
optind = 0;
opterr = 1;
do {
int arg = getopt_long(argc, args, "Fmsdvln:", opts, nullptr);
if (arg == -1) break;
switch (arg) {
case 'F':
options->length = 0;
break;
case 'm':
options->print_map = true;
break;
case 'l':
options->length = strtol(optarg, nullptr, 10);
break;
case 's':
options->print_source = true;
break;
case 'd':
case 'v':
options->detailed = true;
break;
case 'n': {
int limit = strtol(optarg, nullptr, 10);
options->output_limit = limit && limit > 0 ? limit : 0;
} break;
default:
continue;
}
} while (true);
// Use the original cmd array for our return value.
return &cmd[optind - 1];
}
bool FindObjectsCmd::DoExecute(SBDebugger d, char** cmd,
SBCommandReturnObject& result) {
SBTarget target = d.GetSelectedTarget();
if (!target.IsValid()) {
result.SetError("No valid process, please start something\n");
return false;
}
// Load V8 constants from postmortem data
llscan_->v8()->Load(target);
/* Ensure we have a map of objects. */
if (!llscan_->ScanHeapForObjects(target, result)) {
result.SetStatus(eReturnStatusFailed);
return false;
}
Printer::PrinterOptions printer_options;
ParsePrinterOptions(cmd, &printer_options);
if (printer_options.detailed) {
DetailedOutput(result);
} else {
SimpleOutput(result);
}
result.SetStatus(eReturnStatusSuccessFinishResult);
return true;
}
void FindObjectsCmd::SimpleOutput(SBCommandReturnObject& result) {
/* Create a vector to hold the entries sorted by instance count
* TODO(hhellyer) - Make sort type an option (by count, size or name)
*/
std::vector<TypeRecord*> sorted_by_count;
TypeRecordMap::iterator end = llscan_->GetMapsToInstances().end();
for (TypeRecordMap::iterator it = llscan_->GetMapsToInstances().begin();
it != end; ++it) {
sorted_by_count.push_back(it->second);
}
std::sort(sorted_by_count.begin(), sorted_by_count.end(),
TypeRecord::CompareInstanceCounts);
uint64_t total_objects = 0;
uint64_t total_size = 0;
result.Printf(" Instances Total Size Name\n");
result.Printf(" ---------- ---------- ----\n");
for (std::vector<TypeRecord*>::iterator it = sorted_by_count.begin();
it != sorted_by_count.end(); ++it) {
TypeRecord* t = *it;
result.Printf(" %10" PRId64 " %10" PRId64 " %s\n", t->GetInstanceCount(),
t->GetTotalInstanceSize(), t->GetTypeName().c_str());
total_objects += t->GetInstanceCount();
total_size += t->GetTotalInstanceSize();
}
result.Printf(" ---------- ---------- \n");
result.Printf(" %10" PRId64 " %10" PRId64 " \n", total_objects, total_size);
}
void FindObjectsCmd::DetailedOutput(SBCommandReturnObject& result) {
std::vector<DetailedTypeRecord*> sorted_by_count;
for (auto kv : llscan_->GetDetailedMapsToInstances()) {
sorted_by_count.push_back(kv.second);
}
std::sort(sorted_by_count.begin(), sorted_by_count.end(),
TypeRecord::CompareInstanceCounts);
uint64_t total_objects = 0;
uint64_t total_size = 0;
result.Printf(
" Sample Obj. Instances Total Size Properties Elements Name\n");
result.Printf(
" ------------- ---------- ----------- ----------- --------- -----\n");
for (auto t : sorted_by_count) {
result.Printf(" %13" PRIx64 " %10" PRId64 " %11" PRId64 " %11" PRId64
" %9" PRId64 " %s\n",
*(t->GetInstances().begin()), t->GetInstanceCount(),
t->GetTotalInstanceSize(), t->GetOwnDescriptorsCount(),
t->GetIndexedPropertiesCount(), t->GetTypeName().c_str());
total_objects += t->GetInstanceCount();
total_size += t->GetTotalInstanceSize();
}
result.Printf(
" ------------ ---------- ----------- ----------- ----------- ----\n");
result.Printf(" %11" PRId64 " %11" PRId64 " \n", total_objects,
total_size);
}
bool FindInstancesCmd::DoExecute(SBDebugger d, char** cmd,
SBCommandReturnObject& result) {
if (cmd == nullptr || *cmd == nullptr) {
result.SetError("USAGE: v8 findjsinstances [flags] instance_name\n");
return false;
}
SBTarget target = d.GetSelectedTarget();
if (!target.IsValid()) {
result.SetError("No valid process, please start something\n");
return false;
}
// Load V8 constants from postmortem data
llscan_->v8()->Load(target);
/* Ensure we have a map of objects. */
if (!llscan_->ScanHeapForObjects(target, result)) {
result.SetStatus(eReturnStatusFailed);
return false;
}
Printer::PrinterOptions printer_options;
printer_options.detailed = detailed_;
// Use same options as inspect?
char** start = ParsePrinterOptions(cmd, &printer_options);
std::string full_cmd;
for (; start != nullptr && *start != nullptr; start++) full_cmd += *start;
std::string type_name = full_cmd;
TypeRecordMap::iterator instance_it =
llscan_->GetMapsToInstances().find(type_name);
if (instance_it != llscan_->GetMapsToInstances().end()) {
TypeRecord* t = instance_it->second;
// Update pagination options
if (full_cmd != pagination_.command ||
printer_options.output_limit != pagination_.output_limit) {
pagination_.total_entries = t->GetInstanceCount();
pagination_.command = full_cmd;
pagination_.current_page = 0;
pagination_.output_limit = printer_options.output_limit;
} else {
if (pagination_.output_limit <= 0 ||
(pagination_.current_page + 1) * pagination_.output_limit >
pagination_.total_entries) {
pagination_.current_page = 0;
} else {
pagination_.current_page++;
}
}
int initial_p_offset =
(pagination_.current_page * printer_options.output_limit);
int final_p_offset =
initial_p_offset +
std::min(pagination_.output_limit,
pagination_.total_entries -
pagination_.current_page * pagination_.output_limit);
if (final_p_offset <= 0) {
final_p_offset = pagination_.total_entries;
}
auto it =
pagination_.current_page == 0
? t->GetInstances().begin()
: std::next(t->GetInstances().begin(), initial_p_offset);
for (; it != t->GetInstances().end() &&
it != (std::next(t->GetInstances().begin(), final_p_offset));
++it) {
Error err;
v8::Value v8_value(llscan_->v8(), *it);
Printer printer(llscan_->v8(), printer_options);
std::string res = printer.Stringify(v8_value, err);
result.Printf("%s\n", res.c_str());
}
if (it != t->GetInstances().end()) {
result.Printf("..........\n");
}
result.Printf("(Showing %d to %d of %d instances)\n", initial_p_offset + 1,
final_p_offset, pagination_.total_entries);
} else {
// "No objects found with type name %s", type_name
std::stringstream ss;
ss << rang::style::bold << rang::fg::red
<< "No objects found with type name " << type_name << rang::fg::reset
<< rang::style::reset << std::endl;
std::string str(ss.str());
result.Printf("%s", str.c_str());
result.SetStatus(eReturnStatusFailed);
return false;
}
result.SetStatus(eReturnStatusSuccessFinishResult);
return true;
}
bool NodeInfoCmd::DoExecute(SBDebugger d, char** cmd,
SBCommandReturnObject& result) {
SBTarget target = d.GetSelectedTarget();
if (!target.IsValid()) {
result.SetError("No valid process, please start something\n");
return false;
}
// Load V8 constants from postmortem data
llscan_->v8()->Load(target);
/* Ensure we have a map of objects. */
if (!llscan_->ScanHeapForObjects(target, result)) {
return false;
}
std::string process_type_name("process");
TypeRecordMap::iterator instance_it =
llscan_->GetMapsToInstances().find(process_type_name);
if (instance_it != llscan_->GetMapsToInstances().end()) {
TypeRecord* t = instance_it->second;
for (auto it : t->GetInstances()) {
Error err;
// The properties object should be a JSObject
v8::JSObject process_obj(llscan_->v8(), it);
v8::Value pid_val = process_obj.GetProperty("pid", err);
if (pid_val.v8() != nullptr) {
v8::Smi pid_smi(pid_val);
result.Printf("Information for process id %" PRId64
" (process=0x%" PRIx64 ")\n",
pid_smi.GetValue(), process_obj.raw());
} else {
// This isn't the process object we are looking for.
continue;
}
v8::Value platform_val = process_obj.GetProperty("platform", err);
if (platform_val.v8() != nullptr) {
v8::String platform_str(platform_val);
result.Printf("Platform = %s, ", platform_str.ToString(err).c_str());
}
v8::Value arch_val = process_obj.GetProperty("arch", err);
if (arch_val.v8() != nullptr) {
v8::String arch_str(arch_val);
result.Printf("Architecture = %s, ", arch_str.ToString(err).c_str());
}
v8::Value ver_val = process_obj.GetProperty("version", err);
if (ver_val.v8() != nullptr) {
v8::String ver_str(ver_val);
result.Printf("Node Version = %s\n", ver_str.ToString(err).c_str());
}
// Note the extra s on versions!
v8::Value versions_val = process_obj.GetProperty("versions", err);
if (versions_val.v8() != nullptr) {
v8::JSObject versions_obj(versions_val);
std::vector<std::string> version_keys;
// Get the list of keys on an object as strings.
versions_obj.Keys(version_keys, err);
std::sort(version_keys.begin(), version_keys.end());
result.Printf("Component versions (process.versions=0x%" PRIx64 "):\n",
versions_val.raw());
for (std::vector<std::string>::iterator key = version_keys.begin();
key != version_keys.end(); ++key) {
v8::Value ver_val = versions_obj.GetProperty(*key, err);
if (ver_val.v8() != nullptr) {
v8::String ver_str(ver_val);
result.Printf(" %s = %s\n", key->c_str(),
ver_str.ToString(err).c_str());
}
}
}
v8::Value release_val = process_obj.GetProperty("release", err);
if (release_val.v8() != nullptr) {
v8::JSObject release_obj(release_val);
std::vector<std::string> release_keys;
// Get the list of keys on an object as strings.
release_obj.Keys(release_keys, err);
result.Printf("Release Info (process.release=0x%" PRIx64 "):\n",
release_val.raw());
for (std::vector<std::string>::iterator key = release_keys.begin();
key != release_keys.end(); ++key) {
v8::Value ver_val = release_obj.GetProperty(*key, err);
if (ver_val.v8() != nullptr) {
v8::String ver_str(ver_val);
result.Printf(" %s = %s\n", key->c_str(),
ver_str.ToString(err).c_str());
}
}
}
v8::Value execPath_val = process_obj.GetProperty("execPath", err);
if (execPath_val.v8() != nullptr) {
v8::String execPath_str(execPath_val);
result.Printf("Executable Path = %s\n",
execPath_str.ToString(err).c_str());
}
v8::Value argv_val = process_obj.GetProperty("argv", err);
if (argv_val.v8() != nullptr) {
v8::JSArray argv_arr(argv_val);
result.Printf("Command line arguments (process.argv=0x%" PRIx64 "):\n",
argv_val.raw());
// argv is an array, which we can treat as a subtype of object.
int64_t length = argv_arr.GetArrayLength(err);
for (int64_t i = 0; i < length; ++i) {
v8::Value element_val = argv_arr.GetArrayElement(i, err);
if (element_val.v8() != nullptr) {
v8::String element_str(element_val);
result.Printf(" [%" PRId64 "] = '%s'\n", i,
element_str.ToString(err).c_str());
}
}
}
/* The docs for process.execArgv say "These options are useful in order
* to spawn child processes with the same execution environment
* as the parent." so being able to check these have been passed in
* seems like a good idea.
*/
v8::Value execArgv_val = process_obj.GetProperty("execArgv", err);
if (argv_val.v8() != nullptr) {
// Should possibly just treat this as an object in case anyone has
// attached a property.
v8::JSArray execArgv_arr(execArgv_val);
result.Printf(
"Node.js Comamnd line arguments (process.execArgv=0x%" PRIx64
"):\n",
execArgv_val.raw());
// execArgv is an array, which we can treat as a subtype of object.
int64_t length = execArgv_arr.GetArrayLength(err);
for (int64_t i = 0; i < length; ++i) {
v8::Value element_val = execArgv_arr.GetArrayElement(i, err);
if (element_val.v8() != nullptr) {
v8::String element_str(element_val);
result.Printf(" [%" PRId64 "] = '%s'\n", i,
element_str.ToString(err).c_str());
}
}
}
}
} else {
result.Printf("No process objects found.\n");
}
return true;
}
bool FindReferencesCmd::DoExecute(SBDebugger d, char** cmd,
SBCommandReturnObject& result) {
if (cmd == nullptr || *cmd == nullptr) {
result.SetError("USAGE: v8 findrefs expr\n");
return false;
}
SBTarget target = d.GetSelectedTarget();
if (!target.IsValid()) {
result.SetError("No valid process, please start something\n");
return false;
}
// Load V8 constants from postmortem data
llscan_->v8()->Load(target);
// Default scan type.
ScanType type = ScanType::kFieldValue;
char** start = ParseScanOptions(cmd, &type);
if (*start == nullptr) {
result.SetError("Missing search parameter");
result.SetStatus(eReturnStatusFailed);
return false;
}
ObjectScanner* scanner;
switch (type) {
case ScanType::kFieldValue: {
std::string full_cmd;
for (; start != nullptr && *start != nullptr; start++) full_cmd += *start;
SBExpressionOptions options;
SBValue value = target.EvaluateExpression(full_cmd.c_str(), options);
if (value.GetError().Fail()) {
SBStream desc;
if (value.GetError().GetDescription(desc)) {
result.SetError(desc.GetData());
}
result.SetStatus(eReturnStatusFailed);
return false;
}
// Check the address we've been given at least looks like a valid object.
v8::Value search_value(llscan_->v8(), value.GetValueAsSigned());
v8::Smi smi(search_value);
if (smi.Check()) {
result.SetError("Search value is an SMI.");
result.SetStatus(eReturnStatusFailed);
return false;
}
scanner = new ReferenceScanner(llscan_, search_value);
break;
}
case ScanType::kPropertyName: {
// Check for extra parameters or parameters that needed quoting.
if (start[1] != nullptr) {
result.SetError("Extra search parameter or unquoted string specified.");
result.SetStatus(eReturnStatusFailed);
return false;
}
std::string property_name = start[0];
scanner = new PropertyScanner(llscan_, property_name);
break;
}
case ScanType::kStringValue: {
// Check for extra parameters or parameters that needed quoting.
if (start[1] != nullptr) {
result.SetError("Extra search parameter or unquoted string specified.");
result.SetStatus(eReturnStatusFailed);
return false;
}
std::string string_value = start[0];
scanner = new StringScanner(llscan_, string_value);
break;
}
/* We can add options to the command and further sub-classes of
* object scanner to do other searches, e.g.:
* - Objects that refer to a particular string literal.
* (lldb) findreferences -s "Hello World!"
*/
case ScanType::kBadOption:
default: {
result.SetError("Invalid search type");
result.SetStatus(eReturnStatusFailed);
return false;
}
}
/* Ensure we have a map of objects.
* (Do this after we've checked the options to avoid
* a long pause before reporting an error.)
*/
if (!llscan_->ScanHeapForObjects(target, result)) {
delete scanner;
result.SetStatus(eReturnStatusFailed);
return false;
}
if (!scanner->AreReferencesLoaded()) {
ScanForReferences(scanner);
}
ReferencesVector* references = scanner->GetReferences();
PrintReferences(result, references, scanner);
delete scanner;
result.SetStatus(eReturnStatusSuccessFinishResult);
return true;
}
void FindReferencesCmd::ScanForReferences(ObjectScanner* scanner) {
// Walk all the object instances and handle them according to their type.
TypeRecordMap mapstoinstances = llscan_->GetMapsToInstances();
for (auto const entry : mapstoinstances) {
TypeRecord* typerecord = entry.second;
for (uint64_t addr : typerecord->GetInstances()) {
Error err;
v8::Value obj_value(llscan_->v8(), addr);
v8::HeapObject heap_object(obj_value);
int64_t type = heap_object.GetType(err);
v8::LLV8* v8 = heap_object.v8();
// We only need to handle the types that are in
// FindJSObjectsVisitor::IsAHistogramType
// as those are the only objects that end up in GetMapsToInstances
if (v8::JSObject::IsObjectType(v8, type) ||
type == v8->types()->kJSArrayType) {
// Objects can have elements and arrays can have named properties.
// Basically we need to access objects and arrays as both objects and
// arrays.
v8::JSObject js_obj(heap_object);
scanner->ScanRefs(js_obj, err);
} else if (type < v8->types()->kFirstNonstringType) {
v8::String str(heap_object);
scanner->ScanRefs(str, err);
} else if (type == v8->types()->kJSTypedArrayType) {
// These should only point to off heap memory,
// this case should be a no-op.
} else {
// result.Printf("Unhandled type: %" PRId64 " for addr %" PRIx64
// "\n", type, addr);
}
}
}
}
void FindReferencesCmd::PrintReferences(SBCommandReturnObject& result,
ReferencesVector* references,
ObjectScanner* scanner) {
// Walk all the object instances and handle them according to their type.
TypeRecordMap mapstoinstances = llscan_->GetMapsToInstances();
for (uint64_t addr : *references) {
Error err;
v8::Value obj_value(llscan_->v8(), addr);
v8::HeapObject heap_object(obj_value);
int64_t type = heap_object.GetType(err);
v8::LLV8* v8 = heap_object.v8();
// We only need to handle the types that are in
// FindJSObjectsVisitor::IsAHistogramType
// as those are the only objects that end up in GetMapsToInstances
if (v8::JSObject::IsObjectType(v8, type) ||
type == v8->types()->kJSArrayType) {
// Objects can have elements and arrays can have named properties.
// Basically we need to access objects and arrays as both objects and
// arrays.
v8::JSObject js_obj(heap_object);
scanner->PrintRefs(result, js_obj, err);
} else if (type < v8->types()->kFirstNonstringType) {
v8::String str(heap_object);
scanner->PrintRefs(result, str, err);
} else if (type == v8->types()->kJSTypedArrayType) {
// These should only point to off heap memory,
// this case should be a no-op.
} else {
// result.Printf("Unhandled type: %" PRId64 " for addr %" PRIx64
// "\n", type, addr);
}
}
// Print references found directly inside Context objects
Error err;
scanner->PrintContextRefs(result, err);
}
char** FindReferencesCmd::ParseScanOptions(char** cmd, ScanType* type) {
static struct option opts[] = {{"value", no_argument, nullptr, 'v'},
{"name", no_argument, nullptr, 'n'},
{"string", no_argument, nullptr, 's'},
{nullptr, 0, nullptr, 0}};
int argc = 1;
for (char** p = cmd; p != nullptr && *p != nullptr; p++) argc++;
char* args[argc];
// Make this look like a command line, we need a valid element at index 0
// for getopt_long to use in its error messages.
char name[] = "llscan";
args[0] = name;
for (int i = 0; i < argc - 1; i++) args[i + 1] = cmd[i];
bool found_scan_type = false;
// Reset getopts.
optind = 0;
opterr = 1;
do {
int arg = getopt_long(argc, args, "vns", opts, nullptr);
if (arg == -1) break;
if (found_scan_type) {
*type = ScanType::kBadOption;
break;
}
switch (arg) {
case 'v':
*type = ScanType::kFieldValue;
found_scan_type = true;
break;
case 'n':
*type = ScanType::kPropertyName;
found_scan_type = true;
break;
case 's':
*type = ScanType::kStringValue;
found_scan_type = true;
break;
default:
*type = ScanType::kBadOption;
break;
}
} while (true);
return &cmd[optind - 1];
}
// Walk all contexts previously stored and print search_value_
// reference if it exists. Not all values are associated with
// a context object. It seems that Function-Local variables are
// stored in the stack, and when some nested closure references
// it is allocated in a Context object.
void FindReferencesCmd::ReferenceScanner::PrintContextRefs(
SBCommandReturnObject& result, Error& err) {
ContextVector* contexts = llscan_->GetContexts();
v8::LLV8* v8 = llscan_->v8();
for (auto ctx : *contexts) {
Error err;
v8::HeapObject context_obj(v8, ctx);
v8::Context c(context_obj);
v8::Context::Locals locals(&c, err);
if (err.Fail()) return;
for (v8::Context::Locals::Iterator it = locals.begin(); it != locals.end();
it++) {
if ((*it).raw() == search_value_.raw()) {
v8::String _name = it.LocalName(err);
if (err.Fail()) return;
std::string name = _name.ToString(err);
if (err.Fail()) return;
result.Printf("0x%" PRIx64 ": Context.%s=0x%" PRIx64 "\n", c.raw(),
name.c_str(), search_value_.raw());
}
}
}
}
std::string FindReferencesCmd::ObjectScanner::GetPropertyReferenceString() {
std::stringstream ss;
ss << rang::fg::cyan << "0x%" PRIx64 << rang::fg::reset << ": "
<< rang::fg::magenta << "%s" << rang::style::bold << rang::fg::yellow
<< ".%s" << rang::fg::reset << rang::style::reset << "=" << rang::fg::cyan
<< "0x%" PRIx64 << rang::fg::reset << "\n";
return ss.str();
}
std::string FindReferencesCmd::ObjectScanner::GetArrayReferenceString() {
std::stringstream ss;
ss << rang::fg::cyan << "0x%" PRIx64 << rang::fg::reset << ": "
<< rang::fg::magenta << "%s" << rang::style::bold << rang::fg::yellow
<< "[%" PRId64 "]" << rang::fg::reset << rang::style::reset << "="
<< rang::fg::cyan << "0x%" PRIx64 << rang::fg::reset << "\n";
return ss.str();
}
void FindReferencesCmd::ReferenceScanner::PrintRefs(
SBCommandReturnObject& result, v8::JSObject& js_obj, Error& err) {
int64_t length = js_obj.GetArrayLength(err);
for (int64_t i = 0; i < length; ++i) {
v8::Value v = js_obj.GetArrayElement(i, err);
// Array is borked, or not array at all - skip it
if (!err.Success()) break;
if (v.raw() != search_value_.raw()) continue;
std::string type_name = js_obj.GetTypeName(err);
std::string reference_template(GetArrayReferenceString());
result.Printf(reference_template.c_str(), js_obj.raw(), type_name.c_str(),
i, search_value_.raw());
}
// Walk all the properties in this object.
// We only create strings for the field names that match the search
// value.
std::vector<std::pair<v8::Value, v8::Value>> entries = js_obj.Entries(err);
if (err.Fail()) {
return;
}
for (auto entry : entries) {
v8::Value v = entry.second;
if (v.raw() == search_value_.raw()) {
std::string key = entry.first.ToString(err);
std::string type_name = js_obj.GetTypeName(err);
std::string reference_template(GetPropertyReferenceString());
result.Printf(reference_template.c_str(), js_obj.raw(), type_name.c_str(),
key.c_str(), search_value_.raw());
}
}
}
void FindReferencesCmd::ReferenceScanner::PrintRefs(
SBCommandReturnObject& result, v8::String& str, Error& err) {
v8::LLV8* v8 = str.v8();
int64_t repr = str.Representation(err);
// Concatenated and sliced strings refer to other strings so
// we need to check their references.
if (repr == v8->string()->kSlicedStringTag) {
v8::SlicedString sliced_str(str);
v8::String parent = sliced_str.Parent(err);
if (err.Success() && parent.raw() == search_value_.raw()) {
std::string type_name = sliced_str.GetTypeName(err);
std::string reference_template(GetPropertyReferenceString());
result.Printf(reference_template.c_str(), str.raw(), type_name.c_str(),
"<Parent>", search_value_.raw());
}
} else if (repr == v8->string()->kConsStringTag) {
v8::ConsString cons_str(str);
v8::String first = cons_str.First(err);
if (err.Success() && first.raw() == search_value_.raw()) {
std::string type_name = cons_str.GetTypeName(err);
std::string reference_template(GetPropertyReferenceString());
result.Printf(reference_template.c_str(), str.raw(), type_name.c_str(),
"<First>", search_value_.raw());
}
v8::String second = cons_str.Second(err);
if (err.Success() && second.raw() == search_value_.raw()) {
std::string type_name = cons_str.GetTypeName(err);
std::string reference_template(GetPropertyReferenceString());
result.Printf(reference_template.c_str(), str.raw(), type_name.c_str(),
"<Second>", search_value_.raw());
}
} else if (repr == v8->string()->kThinStringTag) {
v8::ThinString thin_str(str);
v8::String actual = thin_str.Actual(err);
if (err.Success() && actual.raw() == search_value_.raw()) {
std::string type_name = thin_str.GetTypeName(err);
std::string reference_template(GetPropertyReferenceString());
result.Printf(reference_template.c_str(), str.raw(), type_name.c_str(),
"<Actual>", search_value_.raw());
}
}
// Nothing to do for other kinds of string.
}
void FindReferencesCmd::ReferenceScanner::ScanRefs(v8::JSObject& js_obj,
Error& err) {
ReferencesVector* references;
std::set<uint64_t> already_saved;
int64_t length = js_obj.GetArrayLength(err);
for (int64_t i = 0; i < length; ++i) {
v8::Value v = js_obj.GetArrayElement(i, err);
// Array is borked, or not array at all - skip it
if (!err.Success()) break;
if (already_saved.count(v.raw())) continue;
references = llscan_->GetReferencesByValue(v.raw());
references->push_back(js_obj.raw());
already_saved.insert(v.raw());
}
// Walk all the properties in this object.
// We only create strings for the field names that match the search
// value.
std::vector<std::pair<v8::Value, v8::Value>> entries = js_obj.Entries(err);
if (err.Fail()) {
return;
}
for (auto entry : entries) {
v8::Value v = entry.second;
if (already_saved.count(v.raw())) continue;
references = llscan_->GetReferencesByValue(v.raw());
references->push_back(js_obj.raw());
already_saved.insert(v.raw());
}
}
void FindReferencesCmd::ReferenceScanner::ScanRefs(v8::String& str,
Error& err) {
ReferencesVector* references;
std::set<uint64_t> already_saved;
v8::LLV8* v8 = str.v8();
int64_t repr = str.Representation(err);
// Concatenated and sliced strings refer to other strings so
// we need to check their references.
if (repr == v8->string()->kSlicedStringTag) {
v8::SlicedString sliced_str(str);
v8::String parent = sliced_str.Parent(err);
if (err.Success()) {
references = llscan_->GetReferencesByValue(parent.raw());
references->push_back(str.raw());
}
} else if (repr == v8->string()->kConsStringTag) {
v8::ConsString cons_str(str);
v8::String first = cons_str.First(err);
if (err.Success()) {
references = llscan_->GetReferencesByValue(first.raw());
references->push_back(str.raw());
}
v8::String second = cons_str.Second(err);
if (err.Success() && first.raw() != second.raw()) {
references = llscan_->GetReferencesByValue(second.raw());
references->push_back(str.raw());
}
} else if (repr == v8->string()->kThinStringTag) {
v8::ThinString thin_str(str);
v8::String actual = thin_str.Actual(err);
if (err.Success()) {
references = llscan_->GetReferencesByValue(actual.raw());
references->push_back(str.raw());
}
}
// Nothing to do for other kinds of string.
}
bool FindReferencesCmd::ReferenceScanner::AreReferencesLoaded() {
return llscan_->AreReferencesByValueLoaded();
}
ReferencesVector* FindReferencesCmd::ReferenceScanner::GetReferences() {
return llscan_->GetReferencesByValue(search_value_.raw());
}
void FindReferencesCmd::PropertyScanner::PrintRefs(
SBCommandReturnObject& result, v8::JSObject& js_obj, Error& err) {
// (Note: We skip array elements as they don't have names.)
// Walk all the properties in this object.
// We only create strings for the field names that match the search
// value.
std::vector<std::pair<v8::Value, v8::Value>> entries = js_obj.Entries(err);
if (err.Fail()) {
return;
}
for (auto entry : entries) {
v8::HeapObject nameObj(entry.first);
std::string key = entry.first.ToString(err);
if (err.Fail()) {
continue;
}
if (key == search_value_) {
std::string type_name = js_obj.GetTypeName(err);
std::string reference_template(GetPropertyReferenceString());
result.Printf(reference_template.c_str(), js_obj.raw(), type_name.c_str(),
key.c_str(), entry.second.raw());
}
}
}
void FindReferencesCmd::PropertyScanner::ScanRefs(v8::JSObject& js_obj,
Error& err) {
// (Note: We skip array elements as they don't have names.)
// Walk all the properties in this object.
// We only create strings for the field names that match the search
// value.
ReferencesVector* references;
std::vector<std::pair<v8::Value, v8::Value>> entries = js_obj.Entries(err);
if (err.Fail()) {
return;
}