-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Expand file tree
/
Copy pathmya.cpp
More file actions
1407 lines (1289 loc) · 51.4 KB
/
Copy pathmya.cpp
File metadata and controls
1407 lines (1289 loc) · 51.4 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
/*
* Copyright (C) 2026 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#if (OS(MACOS) || USE(APPLE_INTERNAL_SDK)) && !PLATFORM(MACCATALYST) && !PLATFORM(IOS_FAMILY_SIMULATOR)
#include <JavaScriptCore/CorpseAddress.h>
#include <JavaScriptCore/CorpseClient.h>
#include <JavaScriptCore/CorpseProcess.h>
#include <JavaScriptCore/CorpseRegion.h>
#include <JavaScriptCore/CorpseSnapshot.h>
#include <JavaScriptCore/CorpseThread.h>
#include <algorithm>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <memory>
#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <string_view>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <vector>
#include <wtf/ASCIICType.h>
#include <wtf/Assertions.h>
#include <wtf/CheckedArithmetic.h>
#include <wtf/DoublyLinkedList.h>
#include <wtf/HashMap.h>
#include <wtf/Ref.h>
#include <wtf/RefPtr.h>
#include <wtf/Vector.h>
#if HAVE(READLINE)
// readline/history.h has a Function typedef that conflicts with WTF::Function;
// rename it across these includes to avoid the clash.
#define Function ReadlineFunction
#include <readline/history.h>
#include <readline/readline.h>
#undef Function
#endif
WTF_ALLOW_UNSAFE_BUFFER_USAGE_BEGIN
using JSC::Corpse::Address;
using JSC::Corpse::Process;
using JSC::Corpse::Snapshot;
using JSC::Corpse::Thread;
namespace Mya {
// A lexer over a null-terminated string. Parsing methods skip leading
// whitespace and advance past whatever they consume; a failed parse leaves the
// position where it was. A Lexer is essentially made up of a position in the
// string. So copying one is how you look ahead without committing.
class Lexer {
public:
explicit Lexer(const char* text)
: m_at(text)
{
}
void skipWhitespace()
{
while (isTabOrSpace(*m_at))
++m_at;
}
// True if only whitespace remains.
bool atEnd()
{
skipWhitespace();
return !*m_at;
}
// The next non-whitespace character, or '\0' at end of input.
char peek()
{
skipWhitespace();
return *m_at;
}
// Consumes and returns the next whitespace-delimited token, which is empty
// at end of input.
std::string_view nextToken()
{
skipWhitespace();
const char* start = m_at;
while (*m_at && !isTabOrSpace(*m_at))
++m_at;
return std::string_view(start, static_cast<size_t>(m_at - start));
}
// Consumes the next token only if it matches word.
bool consumeToken(const char* word)
{
Lexer probe = *this;
if (probe.nextToken() != word)
return false;
*this = probe;
return true;
}
// Consumes the next non-whitespace character only if it matches c.
bool consumeChar(char c)
{
skipWhitespace();
if (*m_at != c)
return false;
++m_at;
return true;
}
// Consumes a positive number from the specified `minimum` upwards, but capped at INT_MAX.
template<long minimum = 0, typename T>
bool consumeUint32(T& out)
{
skipWhitespace();
if (!isASCIIDigit(*m_at))
return false; // Rejects cases like -0, -1, +3, which strtol allows.
errno = 0;
char* end = nullptr;
long value = strtol(m_at, &end, 10);
if (end == m_at || errno || value < minimum || value > INT_MAX)
return false;
m_at = end;
out = static_cast<T>(value);
return true;
}
bool consumePID(pid_t& pid) { return consumeUint32<1>(pid); }
private:
const char* m_at;
};
class Shell {
public:
~Shell()
{
cleanup();
}
int run(int argc, char** argv)
{
JSC::Corpse::Client::setName("mya"_s);
auto action = parseArguments(argc, argv);
switch (action) {
case ContinuationAction::Continue:
openHistory();
runInteractive();
return 0;
case ContinuationAction::Exit:
return 0;
case ContinuationAction::Error:
return 1;
}
RELEASE_ASSERT_NOT_REACHED();
return 1;
}
private:
static constexpr const char* prompt = ">>> ";
static constexpr const char* historyDirName = ".mya";
static constexpr const char* historyFileName = "history";
static constexpr unsigned defaultMaxHistoryEntries = 50;
static constexpr unsigned minHistorySize = 5;
// The history file records the target max history entries in its first line, followed by
// historical commands. To avoid re-writing the file on every new command, we allow the file
// to exceed the max entries by maxOverflowEntries, before we do a re-write to purge
// the extra entries. We will keep appending to the same file until the re-write is needed.
static constexpr const char* maxEntriesHeaderPrefix = "max entries ";
static constexpr unsigned maxOverflowEntries = 100;
static void printUsage(FILE* out)
{
fputs("Mya (MY-uh /ˈmaɪə/) - MemorY Analyzer\n", out);
fputs("Usage:\n", out);
fputs(" mya [--pid|-p <pid>]\n", out);
fputs(" mya [--help|-h [<command>]]\n", out);
fputs("Commands:\n", out);
fputs(" attach [--pid|-p] <pid> Set the target PID and attach\n", out);
fputs(" detach Detach from the current PID\n", out);
fputs(" status (st) Show whether mya is attached\n", out);
fputs(" snapshot (sn, snap) ... Capture and manage snapshots\n", out);
fputs(" thread (th) ... Inspect the threads in a snapshot\n", out);
fputs(" p[/x] &<symbol> Print a symbol's address, /x for hex\n", out);
fputs(" history (hi, hist) ... Show and manage the command history\n", out);
fputs(" help [<command>] Show this help, or help for <command>\n", out);
fputs(" quit (q, exit) Exit mya\n", out);
fputs("\n", out);
fputs(" Use `help snapshot`, `help thread` or `help history` for their subcommands.\n", out);
fputs("\n", out);
}
static void printThreadUsage(FILE* out)
{
fputs("thread - inspect the threads captured in a snapshot\n", out);
fputs(" thread list (li) List the threads in the snapshot in use\n", out);
fputs("\n", out);
fputs(" `thread` may be abbreviated as `th`, and lists by default.\n", out);
fputs(" Threads are read from the snapshot in use; see `help snapshot`.\n", out);
fputs("\n", out);
}
static void printSnapshotUsage(FILE* out)
{
fputs("snapshot - capture and manage snapshots of a process\n", out);
fputs(" snapshot Capture a snapshot of the current process\n", out);
fputs(" snapshot --pid|-p <pid> Attach to <pid> and capture a snapshot of it\n", out);
fputs(" snapshot <n> Switch to using snapshot <n>\n", out);
fputs(" snapshot list (li) List captured snapshots (* marks the one in use)\n", out);
fputs(" snapshot info (inf) <n> Show details of snapshot <n>\n", out);
fputs(" snapshot delete (del) <n> Delete snapshot <n>\n", out);
fputs(" snapshot diff <a> <b> Diff snapshot <a> against snapshot <b>\n", out);
fputs("\n", out);
fputs(" `snapshot` may be abbreviated as `sn` or `snap`.\n", out);
fputs(" Capturing a snapshot switches to using it.\n", out);
fputs("\n", out);
}
static void printHistoryUsage(FILE* out)
{
fputs("history - show and manage the command history\n", out);
fputs(" history List the command history\n", out);
fputs(" history clear [<n>] Clear the history, or its <n> oldest entries\n", out);
fputs(" history size [<n>] Show or set the max entries kept\n", out);
fputs(" !<n> Replay history entry <n>\n", out);
fputs(" !! Replay the previous command\n", out);
fputs("\n", out);
fputs(" `history` may be abbreviated as `hi` or `hist`.\n", out);
fprintf(out, " Command history is kept (defaults up to %u entries) in ~/%s/%s.\n",
defaultMaxHistoryEntries, historyDirName, historyFileName);
#if HAVE(READLINE)
fputs(" It is navigable with the Up/Down arrows and Ctrl-R reverse search.\n", out);
#endif
fputs("\n", out);
}
// Dispatches `help [<command>]`. `lex` is positioned after the "help" word.
static bool handleHelp(Lexer lex)
{
if (lex.atEnd()) {
printUsage(stdout);
return true;
}
std::string_view topic = lex.nextToken();
if (topic == "sn" || topic == "snap" || topic == "snapshot") {
printSnapshotUsage(stdout);
return true;
}
if (topic == "hi" || topic == "hist" || topic == "history") {
printHistoryUsage(stdout);
return true;
}
if (topic == "th" || topic == "thread") {
printThreadUsage(stdout);
return true;
}
fprintf(stderr, "mya: No help for '%.*s'\n", static_cast<int>(topic.length()), topic.data());
return false;
}
// Writes a byte count in the largest unit that keeps it readable, e.g. "512 KB" or "1.50 MB".
static void formatByteSize(size_t bytes, char* out, size_t outSize)
{
if (bytes >= 1024 * 1024)
snprintf(out, outSize, "%.2f MB", bytes / (1024.0 * 1024.0));
else if (bytes >= 1024)
snprintf(out, outSize, "%zu KB", bytes / 1024);
else
snprintf(out, outSize, "%zu B", bytes);
}
enum class ContinuationAction { Continue, Exit, Error };
ContinuationAction parseArguments(int argc, char** argv)
{
// Help is answered before anything else is acted on, so that asking for it
// never attaches to a process or takes a snapshot along the way.
for (int i = 1; i < argc; ++i) {
std::string_view arg = argv[i];
if (arg != "--help" && arg != "-h")
continue;
if (i + 1 >= argc) {
printUsage(stdout);
return ContinuationAction::Exit;
}
Lexer lex(argv[i + 1]);
return handleHelp(lex) ? ContinuationAction::Exit : ContinuationAction::Error;
}
for (int i = 1; i < argc; ++i) {
const char* argText = argv[i];
std::string_view arg = argText;
const char* pidText = nullptr;
if (arg == "--pid" || arg == "-p") {
if (i + 1 >= argc) {
fprintf(stderr, "mya: %s requires an argument\n", argText);
return ContinuationAction::Error;
}
pidText = argv[++i];
} else if (arg.starts_with("--pid="))
pidText = argText + 6;
else if (arg.starts_with("-p") && arg.size() > 2)
pidText = argText + 2; // "-p12345"
else {
fprintf(stderr, "mya: Unknown option '%s'\n", argText);
return ContinuationAction::Error;
}
pid_t pid = -1;
Lexer lex(pidText);
if (!lex.consumePID(pid) || !lex.atEnd()) {
fprintf(stderr, "mya: Invalid PID '%s'\n", pidText);
return ContinuationAction::Error;
}
attachAndSnapshot(pid);
}
return ContinuationAction::Continue;
}
void attach(pid_t pid)
{
RefPtr<Process> process;
auto existing = m_processes.find(pid);
if (existing != m_processes.end())
process = existing->value;
else {
process = Process::create(pid);
m_processes.add(pid, process);
}
if (!process->attach())
return;
if (m_currentProcess && m_currentProcess != process)
m_currentProcess->detach();
m_currentProcess = WTF::move(process);
printf("Attached to %d\n", static_cast<int>(m_currentProcess->pid()));
}
void detach()
{
if (!m_currentProcess) {
fputs("Not attached to any process.\n", stdout);
return;
}
pid_t pid = m_currentProcess->pid();
m_currentProcess->detach();
m_currentProcess = nullptr;
printf("Detached from %d\n", static_cast<int>(pid));
}
// `mya --pid <pid>` and `snapshot --pid <pid>` both attach then snapshot.
void attachAndSnapshot(pid_t pid)
{
attach(pid);
if (m_currentProcess && m_currentProcess->pid() == pid)
captureSnapshot();
}
void captureSnapshot()
{
if (!m_currentProcess) {
fputs("Unable to capture snapshot. Not attached to any process. Use `attach` command or specify `--pid` argument for the snapshot command.\n", stderr);
return;
}
auto snapshot = WTF::makeUnique<Snapshot>(m_currentProcess);
if (!snapshot->isValid())
return; // The Snapshot constructor already logged the failure.
unsigned id = snapshot->id();
// The map owns the Snapshot and the list only records capture order.
Snapshot* node = snapshot.get();
m_snapshotsById.add(id, WTF::move(snapshot));
m_snapshots.append(node);
printf("Captured Snapshot #%u of %d\n", id, static_cast<int>(m_currentProcess->pid()));
useSnapshot(id); // Capturing switches to the new snapshot.
}
// Sets the current snapshot used by subsequent commands.
void useSnapshot(unsigned id)
{
if (!snapshotById(id)) {
fprintf(stderr, "mya: No snapshot #%u\n", id);
return;
}
if (m_currentSnapshot) {
if (m_currentSnapshot == id)
printf("Already using snapshot %u\n", id);
else
printf("Switching to using snapshot %u\n", id);
}
m_currentSnapshot = id;
}
// Returns the snapshot with the given id, or nullptr if there is none.
Snapshot* snapshotById(unsigned id) const
{
auto entry = m_snapshotsById.find(id);
return entry != m_snapshotsById.end() ? entry->value.get() : nullptr;
}
void listSnapshots()
{
if (m_snapshots.isEmpty()) {
fputs("No snapshots.\n", stdout);
return;
}
for (Snapshot* snapshot = m_snapshots.head(); snapshot; snapshot = snapshot->next()) {
// Mark the snapshot currently in use.
const char* marker = snapshot->id() == m_currentSnapshot ? "*" : " ";
printf("%s #%u: pid %d\n", marker, snapshot->id(), static_cast<int>(snapshot->process()->pid()));
}
}
void snapshotInfo(unsigned id)
{
Snapshot* snapshot = snapshotById(id);
if (!snapshot) {
fprintf(stderr, "mya: No snapshot #%u\n", id);
return;
}
printf("Snapshot #%u: pid %d, corpse %s\n", id,
static_cast<int>(snapshot->process()->pid()), snapshot->isValid() ? "valid" : "invalid");
}
void snapshotDelete(unsigned id)
{
Snapshot* snapshot = snapshotById(id);
if (!snapshot) {
fprintf(stderr, "mya: No snapshot #%u\n", id);
return;
}
// Unlink before dropping the owning entry: the list does not own its
// nodes, so it must not be left pointing at a destroyed Snapshot.
m_snapshots.remove(snapshot);
m_snapshotsById.remove(id);
if (id == m_currentSnapshot)
m_currentSnapshot = 0;
printf("Deleted Snapshot #%u.\n", id);
}
void snapshotDiff(unsigned a, unsigned b)
{
if (!snapshotById(a)) {
fprintf(stderr, "mya: No snapshot #%u\n", a);
return;
}
if (!snapshotById(b)) {
fprintf(stderr, "mya: No snapshot #%u\n", b);
return;
}
printf("Snapshot diff #%u vs #%u is not implemented yet.\n", a, b);
}
// `lex` is positioned after the "snapshot" command word.
void handleSnapshot(Lexer lex)
{
if (lex.atEnd()) {
captureSnapshot();
return;
}
// A bare number switches to that snapshot e.g. "snapshot 3".
if (isASCIIDigit(static_cast<unsigned char>(lex.peek()))) {
unsigned number = 0;
if (!lex.consumeUint32(number) || !lex.atEnd()) {
fputs("Usage: snapshot <n>\n", stderr);
return;
}
useSnapshot(number);
return;
}
if (lex.consumeToken("--pid") || lex.consumeToken("-p")) {
pid_t pid = -1;
if (!lex.consumePID(pid) || !lex.atEnd()) {
fputs("Usage: snapshot [--pid|-p] <pid>\n", stderr);
return;
}
attachAndSnapshot(pid);
return;
}
if (lex.consumeToken("li") || lex.consumeToken("list")) {
listSnapshots();
return;
}
if (lex.consumeToken("inf") || lex.consumeToken("info")) {
unsigned number = 0;
if (!lex.consumeUint32(number) || !lex.atEnd()) {
fputs("Usage: snapshot info <n>\n", stderr);
return;
}
snapshotInfo(number);
return;
}
if (lex.consumeToken("del") || lex.consumeToken("delete")) {
unsigned number = 0;
if (!lex.consumeUint32(number) || !lex.atEnd()) {
fputs("Usage: snapshot delete <n>\n", stderr);
return;
}
snapshotDelete(number);
return;
}
if (lex.consumeToken("diff")) {
unsigned a = 0;
unsigned b = 0;
if (!lex.consumeUint32(a) || !lex.consumeUint32(b) || !lex.atEnd()) {
fputs("Usage: snapshot diff <a> <b>\n", stderr);
return;
}
snapshotDiff(a, b);
return;
}
std::string_view token = lex.nextToken();
fprintf(stderr, "mya: Unknown snapshot subcommand '%.*s'\n",
static_cast<int>(token.length()), token.data());
}
// Lists the threads captured in the snapshot currently in use.
void listThreads()
{
Snapshot* snapshot = snapshotById(m_currentSnapshot);
if (!snapshot) {
fputs("No snapshot in use. Capture one with `snapshot`, or select one with `snapshot <n>`.\n", stderr);
return;
}
const Vector<Thread>& threads = snapshot->threads();
if (threads.isEmpty()) {
fputs("No threads.\n", stdout);
return;
}
printf("Threads in snapshot #%u (pid %d):\n", snapshot->id(), static_cast<int>(snapshot->process()->pid()));
// Build the rows as text first so each column can be sized to its widest entry.
static constexpr size_t columnCount = 12;
static const char* const headings[columnCount] = {
"INDEX", "TID", "STATE", "USER(ms)", "SYS(ms)", "SP", "STACK", "SIZE",
"PAGES", "RESIDENT", "DIRTY", "NAME"
};
static const bool rightAligned[columnCount] = {
true, false, false, true, true, false, false, true, true, true, true, false
};
struct Row {
std::string cells[columnCount];
};
Vector<Row> rows;
rows.reserveCapacity(threads.size());
char buffer[64];
for (size_t i = 0; i < threads.size(); ++i) {
const Thread& thread = threads[i];
Row row;
snprintf(buffer, sizeof(buffer), "%zu", i + 1);
row.cells[0] = buffer;
snprintf(buffer, sizeof(buffer), "0x%llx", static_cast<unsigned long long>(thread.id()));
row.cells[1] = buffer;
row.cells[2] = thread.runStateDescription();
snprintf(buffer, sizeof(buffer), "%.3f", thread.userTimeUsec() / 1000.0);
row.cells[3] = buffer;
snprintf(buffer, sizeof(buffer), "%.3f", thread.systemTimeUsec() / 1000.0);
row.cells[4] = buffer;
if (thread.stackPointer()) {
snprintf(buffer, sizeof(buffer), "0x%llx",
thread.stackPointer().toMachVMAddress());
row.cells[5] = buffer;
} else
row.cells[5] = "-";
if (thread.hasStack()) {
const auto& stack = thread.stackRegion();
snprintf(buffer, sizeof(buffer), "0x%llx-0x%llx",
stack.base().toMachVMAddress(),
stack.end().toMachVMAddress());
row.cells[6] = buffer;
formatByteSize(stack.size(), buffer, sizeof(buffer));
row.cells[7] = buffer;
snprintf(buffer, sizeof(buffer), "%llu",
static_cast<unsigned long long>(stack.pageCount()));
row.cells[8] = buffer;
snprintf(buffer, sizeof(buffer), "%llu",
static_cast<unsigned long long>(stack.residentPageCount()));
row.cells[9] = buffer;
snprintf(buffer, sizeof(buffer), "%llu",
static_cast<unsigned long long>(stack.dirtyPageCount()));
row.cells[10] = buffer;
} else {
row.cells[6] = "-";
row.cells[7] = "-";
row.cells[8] = "-";
row.cells[9] = "-";
row.cells[10] = "-";
}
row.cells[11] = thread.name().empty() ? "-" : thread.name();
rows.append(WTF::move(row));
}
size_t widths[columnCount];
for (size_t column = 0; column < columnCount; ++column) {
widths[column] = strlen(headings[column]);
for (const Row& row : rows)
widths[column] = std::max(widths[column], row.cells[column].length());
}
auto printRow = [&](auto&& cellAt) {
fputs(" ", stdout);
for (size_t column = 0; column < columnCount; ++column) {
if (column)
fputs(" ", stdout);
const char* text = cellAt(column);
// The last column needs no padding, which also avoids trailing
// whitespace on every line.
if (column == columnCount - 1)
fputs(text, stdout);
else if (rightAligned[column])
printf("%*s", static_cast<int>(widths[column]), text);
else
printf("%-*s", static_cast<int>(widths[column]), text);
}
putchar('\n');
};
printRow([&](size_t column) { return headings[column]; });
for (const Row& row : rows)
printRow([&](size_t column) { return row.cells[column].c_str(); });
}
// Dispatches the `thread ...` subcommands. `lex` is positioned after the
// "thread" command word.
void handleThread(Lexer lex)
{
// Listing is the default, so a bare `thread` lists too.
if (lex.atEnd() || lex.consumeToken("li") || lex.consumeToken("list")) {
if (!lex.atEnd()) {
fputs("Usage: thread list\n", stderr);
return;
}
listThreads();
return;
}
std::string_view token = lex.nextToken();
fprintf(stderr, "mya: Unknown thread subcommand '%.*s'\n",
static_cast<int>(token.length()), token.data());
}
// Dispatches `p[/<format>] <expression>`. The only expression understood so
// far is `&<symbol>`, which resolves the symbol in the snapshot in use.
// `format` is the text after the '/', empty when none was given.
void handlePrint(std::string_view format, Lexer lex)
{
bool hex = false;
if (!format.empty()) {
if (format == "x")
hex = true;
else if (format != "d") {
fprintf(stderr, "mya: Unknown print format '%.*s'; use x or d\n",
static_cast<int>(format.length()), format.data());
return;
}
}
Snapshot* snapshot = snapshotById(m_currentSnapshot);
if (!snapshot) {
fputs("No snapshot in use. Capture one with `snapshot`, or select one with `snapshot <n>`.\n", stderr);
return;
}
// Taking a symbol's address is all we can do without type information.
if (!lex.consumeChar('&')) {
fputs("Usage: p[/x] &<symbol>\n", stderr);
return;
}
std::string_view token = lex.nextToken();
if (token.empty() || !lex.atEnd()) {
fputs("Usage: p[/x] &<symbol>\n", stderr);
return;
}
std::string name(token);
Address address = snapshot->symbol(name.c_str());
if (!address) {
fprintf(stderr, "mya: No symbol '%s' in snapshot #%u\n", name.c_str(), snapshot->id());
return;
}
if (hex)
printf("&%s = 0x%llx\n", name.c_str(), address.toMachVMAddress());
else
printf("&%s = %llu\n", name.c_str(), address.toMachVMAddress());
}
// Releases resources without extra output. Dropping the current selection
// and clearing the containers runs ~Process / ~Snapshot, which release the
// task and corpse ports. Idempotent: safe from the quit path and destructor.
void cleanup()
{
m_currentProcess = nullptr;
m_processes.clear();
// Unlink the non-owning list before destroying the Snapshots it points at.
m_snapshots.clear();
m_snapshotsById.clear();
if (m_historyFile) {
fclose(m_historyFile);
m_historyFile = nullptr;
}
if (m_historyDirDescriptor >= 0) {
close(m_historyDirDescriptor);
m_historyDirDescriptor = -1;
}
}
// Prompts for confirmation before quitting. Enter (empty) defaults to yes.
bool confirmQuit()
{
for (;;) {
std::string response;
#if HAVE(READLINE)
char* input = readline("Really quit? [Y/n] ");
if (!input) {
putchar('\n');
return true; // EOF: treat as yes.
}
response = input;
free(input);
#else
fputs("Really quit? [Y/n] ", stdout);
fflush(stdout);
char buffer[64];
if (!fgets(buffer, sizeof(buffer), stdin)) {
putchar('\n');
return true; // EOF: treat as yes.
}
// Without a newline the answer was longer than the buffer, and the rest
// would be read as the answer to the next prompt. Discard it.
if (!std::string_view(buffer).contains('\n')) {
int discarded = 0;
while ((discarded = getchar()) != '\n' && discarded != EOF) { }
}
response = buffer;
#endif
size_t start = 0;
while (start < response.size() && isASCIIWhitespace(static_cast<unsigned char>(response[start])))
++start;
size_t stop = response.size();
while (stop > start && isASCIIWhitespace(static_cast<unsigned char>(response[stop - 1])))
--stop;
response = response.substr(start, stop - start);
if (response.empty() || response[0] == 'y' || response[0] == 'Y')
return true;
if (response[0] == 'n' || response[0] == 'N')
return false;
fputs("Please answer 'y' or 'n'.\n", stdout);
}
}
void printStatus()
{
if (m_currentProcess)
printf("Attached to pid %d\n", static_cast<int>(m_currentProcess->pid()));
else
fputs("Not attached to any process.\n", stdout);
if (Snapshot* snapshot = snapshotById(m_currentSnapshot))
printf("Using snapshot %u of pid %d\n", snapshot->id(), static_cast<int>(snapshot->process()->pid()));
else
fputs("No snapshot in use.\n", stdout);
}
void printHistory()
{
if (!m_history.size()) {
printf("History is empty.\n");
return;
}
for (size_t i = 0; i < m_history.size(); ++i)
printf("%5zu %s\n", i + 1, m_history[i].c_str());
}
// Drops the `count` oldest entries.
void clearHistory(unsigned count)
{
if (!count) {
fputs("Nothing to do for clearing 0 history entries.\n", stdout);
return;
}
if (m_history.empty()) {
fputs("History is already empty.\n", stdout);
return;
}
unsigned removeCount = count >= m_history.size() ? safeCast<unsigned>(m_history.size()) : count;
m_history.erase(m_history.begin(), m_history.begin() + removeCount);
#if HAVE(READLINE)
// readline has no way to drop individual entries, so rebuild its history
// from the cache to keep the arrow keys in sync.
clear_history();
for (const std::string& command : m_history)
add_history(command.c_str());
#endif
if (m_historyFile && !rewriteHistoryFile()) {
fputs("mya: Failed to clear history file.\n", stderr);
return;
}
if (m_history.empty()) {
if (removeCount == 1)
printf("Cleared 1 history entry.\n");
else
printf("Cleared %u history entries.\n", removeCount);
} else if (removeCount == 1)
printf("Cleared the oldest history entry.\n");
else
printf("Cleared the %u oldest history entries.\n", removeCount);
}
void printHistorySize()
{
printf("History holds %zu of %u entries.\n", m_history.size(), m_maxHistoryEntries);
}
// Sets how many entries the history keeps, purging the oldest if the new
// capacity is smaller than what is currently stored.
void setMaxHistorySize(unsigned capacity)
{
if (capacity < minHistorySize) {
capacity = minHistorySize;
printf("Minimum history size is %u.\n", minHistorySize);
}
if (m_maxHistoryEntries == capacity) {
printf("Maximum history size is already %u.\n", m_maxHistoryEntries);
return;
}
m_maxHistoryEntries = capacity;
boundReadlineHistory();
if (m_history.size() > m_maxHistoryEntries) {
m_history.erase(m_history.begin(), m_history.end() - m_maxHistoryEntries);
#if HAVE(READLINE)
clear_history();
for (const std::string& command : m_history)
add_history(command.c_str());
#endif
}
if (!rewriteHistoryFile())
fputs("mya: The new size applies to this session only.\n", stderr);
printHistorySize();
}
// Dispatches the `history ...` subcommands. `lex` is positioned after the
// "history" command word.
void handleHistory(Lexer lex)
{
if (lex.atEnd()) {
printHistory();
return;
}
if (lex.consumeToken("clear")) {
unsigned count = UINT_MAX; // Default to "all".
if (!lex.atEnd()) {
unsigned parsed = 0;
if (!lex.consumeUint32(parsed) || !lex.atEnd()) {
fputs("Usage: history clear [<n>]\n", stderr);
return;
}
count = parsed;
}
clearHistory(count);
return;
}
if (lex.consumeToken("size")) {
if (lex.atEnd()) {
printHistorySize();
return;
}
unsigned capacity = 0;
if (!lex.consumeUint32(capacity) || !lex.atEnd()) {
fputs("Usage: history size [<n>]\n", stderr);
return;
}
setMaxHistorySize(capacity);
return;
}
std::string_view token = lex.nextToken();
fprintf(stderr, "mya: Unknown history subcommand '%.*s'\n",
static_cast<int>(token.length()), token.data());
}
// Resolves a history reference ("!!" or "!<n>") to a stored command and
// replays it. `lex` is positioned after the leading '!'; `line` is the whole
// input, used for error reporting.
void replayHistory(const char* line, Lexer lex)
{
std::string command;
if (lex.consumeChar('!') && lex.atEnd()) {
if (m_history.empty()) {
fputs("mya: No commands in history\n", stderr);
return;
}
command = m_history.back();
} else {
unsigned index = 0;
if (!lex.consumeUint32(index) || !lex.atEnd() || index > m_history.size()) {
fprintf(stderr, "mya: %s: event not found\n", line);
return;
}
if (!index) {
fprintf(stderr, "mya: %s: invalid history entry\n", line);
return;
}
command = m_history[index - 1];
}
// Echo the resolved command, then run it as if it had been typed. The
// replayed command records itself; the "!" reference is not recorded.
printf("%s\n", command.c_str());
handleLine(command.c_str());
}
static bool isRunningAsRoot() { return !geteuid(); }
// The directory that holds the history file, empty if the user has no home
// directory to put it in.
//
// We deliberately keep root (when run with sudo)'s history file distinct from
// the non-root user's. This is better for security (root is not dependent on
// non-root user data), and does not block the non-root user from accessing
// their history if the last mya run was via sudo and the history file was
// updated by root (and ownership changed).
static std::string historyDirectory()
{
const char* home = nullptr;
if (isRunningAsRoot()) {
if (const struct passwd* entry = getpwuid(0))
home = entry->pw_dir;
} else {
home = getenv("HOME");
if (!home || !*home) {
if (const struct passwd* entry = getpwuid(getuid()))
home = entry->pw_dir;
}
}
if (!home || !*home)
return { };
std::string directory = home;
if (directory.back() != '/')
directory += '/';
directory += historyDirName;
return directory;
}
void boundReadlineHistory()
{
#if HAVE(READLINE)
// libedit only applies the bound when an entry is added, so lowering it does
// not shorten the existing list: callers that shrink the cache must rebuild
// readline's list as well for the change to take effect immediately.
stifle_history(safeCast<int>(m_maxHistoryEntries));
#endif
}
// Opens the history file for read+write, creating it if absent, and loads any
// stored commands into the cache. If it cannot be opened, the cache stays in
// memory only for the session.
//
// The file lives under the user's home directory, not the working directory:
// mya carries a debugger entitlement and its own usage suggests running it as
// root, so it must not be steered into writing through a path controlled by
// whoever owns the directory it happens to be started in. Both path
// components are opened O_NOFOLLOW, so a symlink planted at either one is
// refused rather than followed, and the file is never opened with O_TRUNC.