-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy pathlib.rs
More file actions
2007 lines (1853 loc) · 72.9 KB
/
Copy pathlib.rs
File metadata and controls
2007 lines (1853 loc) · 72.9 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
#![deny(missing_docs)]
#![deny(rustdoc::missing_doc_code_examples)]
#![deny(missing_debug_implementations)]
//! **Warning:** *This crate is experimental. It relies on implementation
//! techniques that are hard to keep working for 100% of configurations. It may
//! work fine for you, or it may crash, hang, or otherwise do the wrong thing.
//! Its maintenance is not a high priority of the author. Support requests such
//! as issues and pull requests may receive slow responses, or no response at
//! all. Sorry!*
//!
//! This crate provides heap profiling and [ad hoc profiling] capabilities to
//! Rust programs, similar to those provided by [DHAT].
//!
//! [ad hoc profiling]: https://github.com/nnethercote/counts/#ad-hoc-profiling
//! [DHAT]: https://www.valgrind.org/docs/manual/dh-manual.html
//!
//! The heap profiling works by using a global allocator that wraps the system
//! allocator, tracks all heap allocations, and on program exit writes data to
//! file so it can be viewed with DHAT's viewer. This corresponds to DHAT's
//! `--mode=heap` mode.
//!
//! The ad hoc profiling is via a second mode of operation, where ad hoc events
//! can be manually inserted into a Rust program for aggregation and viewing.
//! This corresponds to DHAT's `--mode=ad-hoc` mode.
//!
//! `dhat` also supports *heap usage testing*, where you can write tests and
//! then check that they allocated as much heap memory as you expected. This
//! can be useful for performance-sensitive code.
//!
//! # Motivation
//!
//! DHAT is a powerful heap profiler that comes with Valgrind. This crate is a
//! related but alternative choice for heap profiling Rust programs. DHAT and
//! this crate have the following differences.
//! - This crate works on any platform, while DHAT only works on some platforms
//! (Linux, mostly). (Note that DHAT's viewer is just HTML+JS+CSS and should
//! work in any modern web browser on any platform.)
//! - This crate typically causes a smaller slowdown than DHAT.
//! - This crate requires some modifications to a program's source code and
//! recompilation, while DHAT does not.
//! - This crate cannot track memory accesses the way DHAT does, because it does
//! not instrument all memory loads and stores.
//! - This crate does not provide profiling of copy functions such as `memcpy`
//! and `strcpy`, unlike DHAT.
//! - The backtraces produced by this crate may be better than those produced
//! by DHAT.
//! - DHAT measures a program's entire execution, but this crate only measures
//! what happens within `main`. It will miss the small number of allocations
//! that occur before or after `main`, within the Rust runtime.
//! - This crate enables heap usage testing.
//!
//! # Configuration (profiling and testing)
//!
//! In your `Cargo.toml` file, as well as specifying `dhat` as a dependency,
//! you should (a) enable source line debug info, and (b) create a feature or
//! two that lets you easily switch profiling on and off:
//! ```toml
//! [profile.release]
//! debug = 1
//!
//! [features]
//! dhat-heap = [] # if you are doing heap profiling
//! dhat-ad-hoc = [] # if you are doing ad hoc profiling
//! ```
//! You should only use `dhat` in release builds. Debug builds are too slow to
//! be useful.
//!
//! # Setup (heap profiling)
//!
//! For heap profiling, enable the global allocator by adding this code to your
//! program:
//! ```
//! # // Tricky: comment out the `cfg` so it shows up in docs but the following
//! # // line is still tsted by `cargo test`.
//! # /*
//! #[cfg(feature = "dhat-heap")]
//! # */
//! #[global_allocator]
//! static ALLOC: dhat::Alloc = dhat::Alloc;
//! ```
//! Then add the following code to the very start of your `main` function:
//! ```
//! # // Tricky: comment out the `cfg` so it shows up in docs but the following
//! # // line is still tsted by `cargo test`.
//! # /*
//! #[cfg(feature = "dhat-heap")]
//! # */
//! let _profiler = dhat::Profiler::new_heap();
//! ```
//! Then run this command to enable heap profiling during the lifetime of the
//! [`Profiler`] instance:
//! ```text
//! cargo run --features dhat-heap
//! ```
//! [`dhat::Alloc`](Alloc) is slower than the normal allocator, so it should
//! only be enabled while profiling.
//!
//! # Setup (ad hoc profiling)
//!
//! [Ad hoc profiling] involves manually annotating hot code points and then
//! aggregating the executed annotations in some fashion.
//!
//! [Ad hoc profiling]: https://github.com/nnethercote/counts/#ad-hoc-profiling
//!
//! To do this, add the following code to the very start of your `main`
//! function:
//!```
//! # // Tricky: comment out the `cfg` so it shows up in docs but the following
//! # // line is still tsted by `cargo test`.
//! # /*
//! #[cfg(feature = "dhat-ad-hoc")]
//! # */
//! let _profiler = dhat::Profiler::new_ad_hoc();
//! ```
//! Then insert calls like this at points of interest:
//! ```
//! # // Tricky: comment out the `cfg` so it shows up in docs but the following
//! # // line is still tsted by `cargo test`.
//! # /*
//! #[cfg(feature = "dhat-ad-hoc")]
//! # */
//! dhat::ad_hoc_event(100);
//! ```
//! Then run this command to enable ad hoc profiling during the lifetime of the
//! [`Profiler`] instance:
//! ```text
//! cargo run --features dhat-ad-hoc
//! ```
//! For example, imagine you have a hot function that is called from many call
//! sites. You might want to know how often it is called and which other
//! functions called it the most. In that case, you would add an
//! [`ad_hoc_event`] call to that function, and the data collected by this
//! crate and viewed with DHAT's viewer would show you exactly what you want to
//! know.
//!
//! The meaning of the integer argument to `ad_hoc_event` will depend on
//! exactly what you are measuring. If there is no meaningful weight to give to
//! an event, you can just use `1`.
//!
//! # Running
//!
//! For both heap profiling and ad hoc profiling, the program will run more
//! slowly than normal. The exact slowdown is hard to predict because it
//! depends greatly on the program being profiled, but it can be large. (Even
//! more so on Windows, because backtrace gathering can be drastically slower
//! on Windows than on other platforms.)
//!
//! When the [`Profiler`] is dropped at the end of `main`, some basic
//! information will be printed to `stderr`. For heap profiling it will look
//! like the following.
//! ```text
//! dhat: Total: 1,256 bytes in 6 blocks
//! dhat: At t-gmax: 1,256 bytes in 6 blocks
//! dhat: At t-end: 1,256 bytes in 6 blocks
//! dhat: The data has been saved to dhat-heap.json, and is viewable with dhat/dh_view.html
//! ```
//! ("Blocks" is a synonym for "allocations".)
//!
//! For ad hoc profiling it will look like the following.
//! ```text
//! dhat: Total: 141 units in 11 events
//! dhat: The data has been saved to dhat-ad-hoc.json, and is viewable with dhat/dh_view.html
//! ```
//! A file called `dhat-heap.json` (for heap profiling) or `dhat-ad-hoc.json`
//! (for ad hoc profiling) will be written. It can be viewed in DHAT's viewer.
//!
//! If you don't see this output, it may be because your program called
//! [`std::process::exit`], which exits a program without running any
//! destructors. To work around this, explicitly call `drop` on the
//! [`Profiler`] value just before exiting.
//!
//! When doing heap profiling, if you unexpectedly see zero allocations in the
//! output it may be because you forgot to set [`dhat::Alloc`](Alloc) as the
//! global allocator.
//!
//! When doing heap profiling it is recommended that the lifetime of the
//! [`Profiler`] value cover all of `main`. But it is still possible for
//! allocations and deallocations to occur outside of its lifetime. Such cases
//! are handled in the following ways.
//! - Allocated before, untouched within: ignored.
//! - Allocated before, freed within: ignored.
//! - Allocated before, reallocated within: treated like a new allocation
//! within.
//! - Allocated after: ignored.
//!
//! These cases are not ideal, but it is impossible to do better. `dhat`
//! deliberately provides no way to reset the heap profiling state mid-run
//! precisely because it leaves open the possibility of many such occurrences.
//!
//! # Viewing
//!
//! Open a copy of DHAT's viewer, version 3.17 or later. There are two ways to
//! do this.
//! - Easier: Use the [online version].
//! - Harder: Clone the [Valgrind repository] with `git clone
//! git://sourceware.org/git/valgrind.git` and open `dhat/dh_view.html`.
//! There is no need to build any code in this repository.
//!
//! [online version]: https://nnethercote.github.io/dh_view/dh_view.html
//! [Valgrind repository]: https://www.valgrind.org/downloads/repository.html
//!
//! Then click on the "Load…" button to load `dhat-heap.json` or
//! `dhat-ad-hoc.json`.
//!
//! DHAT's viewer shows a tree with nodes that look like this.
//! ```text
//! PP 1.1/2 {
//! Total: 1,024 bytes (98.46%, 14,422,535.21/s) in 1 blocks (50%, 14,084.51/s), avg size 1,024 bytes, avg lifetime 35 µs (49.3% of program duration)
//! Max: 1,024 bytes in 1 blocks, avg size 1,024 bytes
//! At t-gmax: 1,024 bytes (98.46%) in 1 blocks (50%), avg size 1,024 bytes
//! At t-end: 1,024 bytes (100%) in 1 blocks (100%), avg size 1,024 bytes
//! Allocated at {
//! #1: 0x10ae8441b: <alloc::alloc::Global as core::alloc::Allocator>::allocate (alloc/src/alloc.rs:226:9)
//! #2: 0x10ae8441b: alloc::raw_vec::RawVec<T,A>::allocate_in (alloc/src/raw_vec.rs:207:45)
//! #3: 0x10ae8441b: alloc::raw_vec::RawVec<T,A>::with_capacity_in (alloc/src/raw_vec.rs:146:9)
//! #4: 0x10ae8441b: alloc::vec::Vec<T,A>::with_capacity_in (src/vec/mod.rs:609:20)
//! #5: 0x10ae8441b: alloc::vec::Vec<T>::with_capacity (src/vec/mod.rs:470:9)
//! #6: 0x10ae8441b: std::io::buffered::bufwriter::BufWriter<W>::with_capacity (io/buffered/bufwriter.rs:115:33)
//! #7: 0x10ae8441b: std::io::buffered::linewriter::LineWriter<W>::with_capacity (io/buffered/linewriter.rs:109:29)
//! #8: 0x10ae8441b: std::io::buffered::linewriter::LineWriter<W>::new (io/buffered/linewriter.rs:89:9)
//! #9: 0x10ae8441b: std::io::stdio::stdout::{{closure}} (src/io/stdio.rs:680:58)
//! #10: 0x10ae8441b: std::lazy::SyncOnceCell<T>::get_or_init_pin::{{closure}} (std/src/lazy.rs:375:25)
//! #11: 0x10ae8441b: std::sync::once::Once::call_once_force::{{closure}} (src/sync/once.rs:320:40)
//! #12: 0x10aea564c: std::sync::once::Once::call_inner (src/sync/once.rs:419:21)
//! #13: 0x10ae81b1b: std::sync::once::Once::call_once_force (src/sync/once.rs:320:9)
//! #14: 0x10ae81b1b: std::lazy::SyncOnceCell<T>::get_or_init_pin (std/src/lazy.rs:374:9)
//! #15: 0x10ae81b1b: std::io::stdio::stdout (src/io/stdio.rs:679:16)
//! #16: 0x10ae81b1b: std::io::stdio::print_to (src/io/stdio.rs:1196:21)
//! #17: 0x10ae81b1b: std::io::stdio::_print (src/io/stdio.rs:1209:5)
//! #18: 0x10ae2fe20: dhatter::main (dhatter/src/main.rs:8:5)
//! }
//! }
//! ```
//! Full details about the output are in the [DHAT documentation]. Note that
//! DHAT uses the word "block" as a synonym for "allocation".
//!
//! [DHAT documentation]: https://valgrind.org/docs/manual/dh-manual.html
//!
//! When heap profiling, this crate doesn't track memory accesses (unlike DHAT)
//! and so the "reads" and "writes" measurements are not shown within DHAT's
//! viewer, and "sort metric" views involving reads, writes, or accesses are
//! not available.
//!
//! The backtraces produced by this crate are trimmed to reduce output file
//! sizes and improve readability in DHAT's viewer, in the following ways.
//! - Only one allocation-related frame will be shown at the top of the
//! backtrace. That frame may be a function within `alloc::alloc`, a function
//! within this crate, or a global allocation function like `__rg_alloc`.
//! - Common frames at the bottom of all backtraces, below `main`, are omitted.
//!
//! Backtrace trimming is inexact and if the above heuristics fail more frames
//! will be shown. [`ProfilerBuilder::trim_backtraces`] allows (approximate)
//! control of how deep backtraces will be.
//!
//! # Heap usage testing
//!
//! `dhat` lets you write tests that check that a certain piece of code does a
//! certain amount of heap allocation when it runs. This is sometimes called
//! "high water mark" testing. Sometimes it is precise (e.g. "this code should
//! do exactly 96 allocations" or "this code should free all allocations before
//! finishing") and sometimes it is less precise (e.g. "the peak heap usage of
//! this code should be less than 10 MiB").
//!
//! These tests are somewhat fragile, because heap profiling involves global
//! state (allocation stats), which introduces complications.
//! - `dhat` will panic if more than one `Profiler` is running at a time, but
//! Rust tests run in parallel by default. So parallel running of heap usage
//! tests must be prevented.
//! - If you use something like the
//! [`serial_test`](https://docs.rs/serial_test/) crate to run heap usage
//! tests in serial, Rust's test runner code by default still runs in
//! parallel with those tests, and it allocates memory. These allocations
//! will be counted by the `Profiler` as if they are part of the test, which
//! will likely cause test failures.
//!
//! Therefore, the best approach is to put each heap usage test in its own
//! integration test file. Each integration test runs in its own process, and
//! so cannot interfere with any other test. Also, if there is only one test in
//! an integration test file, Rust's test runner code does not use any
//! parallelism, and so will not interfere with the test. If you do this, a
//! simple `cargo test` will work as expected.
//!
//! Alternatively, if you really want multiple heap usage tests in a single
//! integration test file you can write your own [custom test harness], which
//! is simpler than it sounds.
//!
//! [custom test harness]: https://www.infinyon.com/blog/2021/04/rust-custom-test-harness/
//!
//! But integration tests have some limits. For example, they only be used to
//! test items from libraries, not binaries. One way to get around this is to
//! restructure things so that most of the functionality is in a library, and
//! the binary is a thin wrapper around the library.
//!
//! Failing that, a blunt fallback is to run `cargo tests -- --test-threads=1`.
//! This disables all parallelism in tests, avoiding all the problems. This
//! allows the use of unit tests and multiples tests per integration test file,
//! at the cost of a non-standard invocation and slower test execution.
//!
//! With all that in mind, configuration of `Cargo.toml` is much the same as
//! for the profiling use case.
//!
//! Here is an example showing what is possible. This code would go in an
//! integration test within a crate's `tests/` directory:
//! ```
//! #[global_allocator]
//! static ALLOC: dhat::Alloc = dhat::Alloc;
//!
//! # // Tricky: comment out the `#[test]` because it's needed in an actual
//! # // test but messes up things here.
//! # /*
//! #[test]
//! # */
//! fn test() {
//! let _profiler = dhat::Profiler::builder().testing().build();
//!
//! let _v1 = vec![1, 2, 3, 4];
//! let v2 = vec![5, 6, 7, 8];
//! drop(v2);
//! let v3 = vec![9, 10, 11, 12];
//! drop(v3);
//!
//! let stats = dhat::HeapStats::get();
//!
//! // Three allocations were done in total.
//! dhat::assert_eq!(stats.total_blocks, 3);
//! dhat::assert_eq!(stats.total_bytes, 48);
//!
//! // At the point of peak heap size, two allocations totalling 32 bytes existed.
//! dhat::assert_eq!(stats.max_blocks, 2);
//! dhat::assert_eq!(stats.max_bytes, 32);
//!
//! // Now a single allocation remains alive.
//! dhat::assert_eq!(stats.curr_blocks, 1);
//! dhat::assert_eq!(stats.curr_bytes, 16);
//! }
//! # test()
//! ```
//! The [`testing`](ProfilerBuilder::testing) call puts the profiler into
//! testing mode, which allows the stats provided by [`HeapStats::get`] to be
//! checked with [`dhat::assert!`](assert) and similar assertions. These
//! assertions work much the same as normal assertions, except that if any of
//! them fail a heap profile will be saved.
//!
//! When viewing the heap profile after a test failure, the best choice of sort
//! metric in the viewer will depend on which stat was involved in the
//! assertion failure.
//! - `total_blocks`: "Total (blocks)"
//! - `total_bytes`: "Total (bytes)"
//! - `max_blocks` or `max_bytes`: "At t-gmax (bytes)"
//! - `curr_blocks` or `curr_bytes`: "At t-end (bytes)"
//!
//! This should give you a good understanding of why the assertion failed.
//!
//! Note: if you try this example test it may work in a debug build but fail in
//! a release build. This is because the compiler may optimize away some of the
//! allocations that are unused. This is a common problem for contrived
//! examples but less common for real tests. The unstable
//! [`std::hint::black_box`](std::hint::black_box) function may also be helpful
//! in this situation.
//!
//! # Ad hoc usage testing
//!
//! Ad hoc usage testing is also possible. It can be used to ensure certain
//! code points in your program are hit a particular number of times during
//! execution. It works in much the same way as heap usage testing, but
//! [`ProfilerBuilder::ad_hoc`] must be specified, [`AdHocStats::get`] is
//! used instead of [`HeapStats::get`], and there is no possibility of Rust's
//! test runner code interfering with the tests.
use backtrace::SymbolName;
use lazy_static::lazy_static;
// In normal Rust code, the allocator is on a lower level than the mutex
// implementation, which means the mutex implementation can use the allocator.
// But DHAT implements an allocator which requires a mutex. If we're not
// careful, this can easily result in deadlocks from circular sequences of
// operations, E.g. see #18 and #25 from when we used `parking_lot::Mutex`. We
// now use `mintex::Mutex`, which is guaranteed to not allocate, effectively
// making the mutex implementation on a lower level than the allocator,
// allowing the allocator to depend on it.
use mintex::Mutex;
use rustc_hash::FxHashMap;
use serde::Serialize;
use std::alloc::{GlobalAlloc, Layout, System};
use std::cell::Cell;
use std::fs::File;
use std::hash::{Hash, Hasher};
use std::io::BufWriter;
use std::ops::AddAssign;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
use thousands::Separable;
lazy_static! {
static ref TRI_GLOBALS: Mutex<Phase<Globals>> = Mutex::new(Phase::Ready);
}
// State transition diagram:
//
// +---------------> Ready
// | |
// | Profiler:: | ProfilerBuilder::
// | drop_inner() | build()
// | v
// +---------------- Running
// | |
// | | check_assert_condition()
// | | [if the check fails]
// | v
// +---------------- PostAssert
//
// Note: the use of `std::process::exit` or `std::mem::forget` (on the
// `Profiler`) can result in termination while the profiler is still running,
// i.e. it won't produce output.
#[derive(PartialEq)]
enum Phase<T> {
// We are ready to start running a `Profiler`.
Ready,
// A `Profiler` is running.
Running(T),
// The current `Profiler` has stopped due to as assertion failure, but
// hasn't been dropped yet.
PostAssert,
}
// Type used in frame trimming.
#[derive(PartialEq)]
enum TB {
Top,
Bottom,
}
// Global state that can be accessed from any thread and is therefore protected
// by a `Mutex`.
struct Globals {
// The file name for the saved data.
file_name: PathBuf,
// Are we in testing mode?
testing: bool,
// How should we trim backtraces?
trim_backtraces: Option<usize>,
// Print the JSON to stderr when saving it?
eprint_json: bool,
// The backtrace at startup. Used for backtrace trimmming.
start_bt: Backtrace,
// Frames to trim at the top and bottom of backtraces. Computed once the
// first backtrace is obtained during profiling; that backtrace is then
// compared to `start_bt`.
//
// Each element is the address of a frame, and thus actually a `*mut
// c_void`, but we store it as a `usize` because (a) we never dereference
// it, and (b) using `*mut c_void` leads to compile errors because raw
// pointers don't implement `Send`.
frames_to_trim: Option<FxHashMap<usize, TB>>,
// When `Globals` is created, which is when the `Profiler` is created.
start_instant: Instant,
// All the `PpInfos` gathered during execution. Elements are never deleted.
// Each element is referred to by exactly one `Backtrace` from
// `backtraces`, and referred to by any number of live blocks from
// `live_blocks`. Storing all the `PpInfos` in a `Vec` is a bit clumsy, but
// allows multiple references from `backtraces` and `live_blocks` without
// requiring any unsafety, because the references are just indices rather
// than `Rc`s or raw pointers or whatever.
pp_infos: Vec<PpInfo>,
// Each `Backtrace` is associated with a `PpInfo`. The `usize` is an index
// into `pp_infos`. Entries are not deleted during execution.
backtraces: FxHashMap<Backtrace, usize>,
// Counts for the entire run.
total_blocks: u64, // For ad hoc profiling it's actually `total_events`.
total_bytes: u64, // For ad hoc profiling it's actually `total_units`.
// Extra things kept when heap profiling.
heap: Option<HeapGlobals>,
}
struct HeapGlobals {
// Each live block is associated with a `PpInfo`. An element is deleted
// when the corresponding allocation is freed.
//
// Each key is the address of a live block, and thus actually a `*mut u8`,
// but we store it as a `usize` because (a) we never dereference it, and
// (b) using `*mut u8` leads to compile errors because raw pointers don't
// implement `Send`.
live_blocks: FxHashMap<usize, LiveBlock>,
// Current counts.
curr_blocks: usize,
curr_bytes: usize,
// Counts at the global max, i.e. when `curr_bytes` peaks.
max_blocks: usize,
max_bytes: usize,
// Time of the global max.
tgmax_instant: Instant,
}
impl Globals {
fn new(
testing: bool,
file_name: PathBuf,
trim_backtraces: Option<usize>,
eprint_json: bool,
heap: Option<HeapGlobals>,
) -> Self {
Self {
testing,
file_name,
trim_backtraces,
eprint_json,
// `None` here because we don't want any frame trimming for this
// backtrace.
start_bt: new_backtrace_inner(None, &FxHashMap::default()),
frames_to_trim: None,
start_instant: Instant::now(),
pp_infos: Vec::default(),
backtraces: FxHashMap::default(),
total_blocks: 0,
total_bytes: 0,
heap,
}
}
// Get the PpInfo for this backtrace, creating it if necessary.
fn get_pp_info<F: FnOnce() -> PpInfo>(&mut self, bt: Backtrace, new: F) -> usize {
let pp_infos = &mut self.pp_infos;
*self.backtraces.entry(bt).or_insert_with(|| {
let pp_info_idx = pp_infos.len();
pp_infos.push(new());
pp_info_idx
})
}
fn record_block(&mut self, ptr: *mut u8, pp_info_idx: usize, now: Instant) {
let h = self.heap.as_mut().unwrap();
let old = h.live_blocks.insert(
ptr as usize,
LiveBlock {
pp_info_idx,
allocation_instant: now,
},
);
std::assert!(matches!(old, None));
}
fn update_counts_for_alloc(
&mut self,
pp_info_idx: usize,
size: usize,
delta: Option<Delta>,
now: Instant,
) {
self.total_blocks += 1;
self.total_bytes += size as u64;
let h = self.heap.as_mut().unwrap();
if let Some(delta) = delta {
// realloc
h.curr_blocks += 0; // unchanged
h.curr_bytes += delta;
} else {
// alloc
h.curr_blocks += 1;
h.curr_bytes += size;
}
// The use of `>=` not `>` means that if there are multiple equal peaks
// we record the latest one, like `check_for_global_peak` does.
if h.curr_bytes >= h.max_bytes {
h.max_blocks = h.curr_blocks;
h.max_bytes = h.curr_bytes;
h.tgmax_instant = now;
}
self.pp_infos[pp_info_idx].update_counts_for_alloc(size, delta);
}
fn update_counts_for_dealloc(
&mut self,
pp_info_idx: usize,
size: usize,
alloc_duration: Duration,
) {
let h = self.heap.as_mut().unwrap();
h.curr_blocks -= 1;
h.curr_bytes -= size;
self.pp_infos[pp_info_idx].update_counts_for_dealloc(size, alloc_duration);
}
fn update_counts_for_ad_hoc_event(&mut self, pp_info_idx: usize, weight: usize) {
std::assert!(self.heap.is_none());
self.total_blocks += 1;
self.total_bytes += weight as u64;
self.pp_infos[pp_info_idx].update_counts_for_ad_hoc_event(weight);
}
// If we are at peak memory, update `at_tgmax_{blocks,bytes}` in all
// `PpInfo`s. This is somewhat expensive so we avoid calling it on every
// allocation; instead we call it upon a deallocation (when we might be
// coming down from a global peak) and at termination (when we might be at
// a global peak).
fn check_for_global_peak(&mut self) {
let h = self.heap.as_mut().unwrap();
if h.curr_bytes == h.max_bytes {
// It's a peak. (If there are multiple equal peaks we record the
// latest one.) Record it in every PpInfo.
for pp_info in self.pp_infos.iter_mut() {
let h = pp_info.heap.as_mut().unwrap();
h.at_tgmax_blocks = h.curr_blocks;
h.at_tgmax_bytes = h.curr_bytes;
}
}
}
fn get_heap_stats(&self) -> HeapStats {
match &self.heap {
Some(heap) => HeapStats {
total_blocks: self.total_blocks,
total_bytes: self.total_bytes,
curr_blocks: heap.curr_blocks,
curr_bytes: heap.curr_bytes,
max_blocks: heap.max_blocks,
max_bytes: heap.max_bytes,
},
None => panic!("dhat: getting heap stats while doing ad hoc profiling"),
}
}
fn get_ad_hoc_stats(&self) -> AdHocStats {
match self.heap {
None => AdHocStats {
total_events: self.total_blocks,
total_units: self.total_bytes,
},
Some(_) => panic!("dhat: getting ad hoc stats while doing heap profiling"),
}
}
// Finish tracking allocations and deallocations, print a summary message
// to `stderr` and save the profile to file/memory if requested.
fn finish(mut self, memory_output: Option<&mut String>) {
let now = Instant::now();
if self.heap.is_some() {
// Total bytes is at a possible peak.
self.check_for_global_peak();
let h = self.heap.as_ref().unwrap();
// Account for the lifetimes of all remaining live blocks.
for &LiveBlock {
pp_info_idx,
allocation_instant,
} in h.live_blocks.values()
{
self.pp_infos[pp_info_idx]
.heap
.as_mut()
.unwrap()
.total_lifetimes_duration += now.duration_since(allocation_instant);
}
}
// We give each unique frame an index into `ftbl`, starting with 0
// for the special frame "[root]".
let mut ftbl_indices: FxHashMap<String, usize> = FxHashMap::default();
ftbl_indices.insert("[root]".to_string(), 0);
let mut next_ftbl_idx = 1;
// Because `self` is being consumed, we can consume `self.backtraces`
// and replace it with an empty `FxHashMap`. (This is necessary because
// we modify the *keys* here with `resolve`, which isn't allowed with a
// non-consuming iterator.)
let pps: Vec<_> = std::mem::take(&mut self.backtraces)
.into_iter()
.map(|(mut bt, pp_info_idx)| {
// Do the potentially expensive debug info lookups to get
// symbol names, line numbers, etc.
bt.0.resolve();
// Trim boring frames at the top and bottom of the backtrace.
let first_symbol_to_show = if self.trim_backtraces.is_some() {
if self.heap.is_some() {
bt.first_heap_symbol_to_show()
} else {
bt.first_ad_hoc_symbol_to_show()
}
} else {
0
};
// Determine the frame indices for this backtrace. This
// involves getting the string for each frame and adding a
// new entry to `ftbl_indices` if it hasn't been seen
// before.
let mut fs = vec![];
let mut i = 0;
for frame in bt.0.frames().iter() {
for symbol in frame.symbols().iter() {
i += 1;
if (i - 1) < first_symbol_to_show {
continue;
}
let s = Backtrace::frame_to_string(frame, symbol);
let &mut ftbl_idx = ftbl_indices.entry(s).or_insert_with(|| {
next_ftbl_idx += 1;
next_ftbl_idx - 1
});
fs.push(ftbl_idx);
}
}
PpInfoJson::new(&self.pp_infos[pp_info_idx], fs)
})
.collect();
// We pre-allocate `ftbl` with empty strings, and then fill it in.
let mut ftbl = vec![String::new(); ftbl_indices.len()];
for (frame, ftbl_idx) in ftbl_indices.into_iter() {
ftbl[ftbl_idx] = frame;
}
let h = self.heap.as_ref();
let is_heap = h.is_some();
let json = DhatJson {
dhatFileVersion: 2,
mode: if is_heap { "rust-heap" } else { "rust-ad-hoc" },
verb: "Allocated",
bklt: is_heap,
bkacc: false,
bu: if is_heap { None } else { Some("unit") },
bsu: if is_heap { None } else { Some("units") },
bksu: if is_heap { None } else { Some("events") },
tu: "µs",
Mtu: "s",
tuth: if is_heap { Some(10) } else { None },
cmd: std::env::args().collect::<Vec<_>>().join(" "),
pid: std::process::id(),
tg: h.map(|h| {
h.tgmax_instant
.saturating_duration_since(self.start_instant)
.as_micros()
}),
te: now.duration_since(self.start_instant).as_micros(),
pps,
ftbl,
};
eprintln!(
"dhat: Total: {} {} in {} {}",
self.total_bytes.separate_with_commas(),
json.bsu.unwrap_or("bytes"),
self.total_blocks.separate_with_commas(),
json.bksu.unwrap_or("blocks"),
);
if let Some(h) = &self.heap {
eprintln!(
"dhat: At t-gmax: {} bytes in {} blocks",
h.max_bytes.separate_with_commas(),
h.max_blocks.separate_with_commas(),
);
eprintln!(
"dhat: At t-end: {} bytes in {} blocks",
h.curr_bytes.separate_with_commas(),
h.curr_blocks.separate_with_commas(),
);
}
if let Some(memory_output) = memory_output {
// Default pretty printing is fine here, it's only used for small
// tests.
*memory_output = serde_json::to_string_pretty(&json).unwrap();
eprintln!("dhat: The data has been saved to the memory buffer");
} else {
let write = || -> std::io::Result<()> {
let buffered_file = BufWriter::new(File::create(&self.file_name)?);
// `to_writer` produces JSON that is compact.
// `to_writer_pretty` produces JSON that is readable. This code
// gives us JSON that is fairly compact and fairly readable.
// Ideally it would be more like what DHAT produces, e.g. one
// space indents, no spaces after `:` and `,`, and `fs` arrays
// on a single line, but this is as good as we can easily
// achieve.
let formatter = serde_json::ser::PrettyFormatter::with_indent(b"");
let mut ser = serde_json::Serializer::with_formatter(buffered_file, formatter);
json.serialize(&mut ser)?;
Ok(())
};
match write() {
Ok(()) => eprintln!(
"dhat: The data has been saved to {}, and is viewable with dhat/dh_view.html",
self.file_name.to_string_lossy()
),
Err(e) => eprintln!(
"dhat: error: Writing to {} failed: {}",
self.file_name.to_string_lossy(),
e
),
}
}
if self.eprint_json {
eprintln!(
"dhat: json = `{}`",
serde_json::to_string_pretty(&json).unwrap()
);
}
}
}
impl HeapGlobals {
fn new() -> Self {
Self {
live_blocks: FxHashMap::default(),
curr_blocks: 0,
curr_bytes: 0,
max_blocks: 0,
max_bytes: 0,
tgmax_instant: Instant::now(),
}
}
}
struct PpInfo {
// The total number of blocks and bytes allocated by this PP.
total_blocks: u64,
total_bytes: u64,
heap: Option<HeapPpInfo>,
}
#[derive(Default)]
struct HeapPpInfo {
// The current number of blocks and bytes allocated by this PP.
curr_blocks: usize,
curr_bytes: usize,
// The number of blocks and bytes at the PP max, i.e. when this PP's
// `curr_bytes` peaks.
max_blocks: usize,
max_bytes: usize,
// The number of blocks and bytes at the global max, i.e. when
// `Globals::curr_bytes` peaks.
at_tgmax_blocks: usize,
at_tgmax_bytes: usize,
// Total lifetimes of all blocks allocated by this PP. Includes blocks
// explicitly freed and blocks implicitly freed at termination.
total_lifetimes_duration: Duration,
}
impl PpInfo {
fn new_heap() -> Self {
Self {
total_blocks: 0,
total_bytes: 0,
heap: Some(HeapPpInfo::default()),
}
}
fn new_ad_hoc() -> Self {
Self {
total_blocks: 0,
total_bytes: 0,
heap: None,
}
}
fn update_counts_for_alloc(&mut self, size: usize, delta: Option<Delta>) {
self.total_blocks += 1;
self.total_bytes += size as u64;
let h = self.heap.as_mut().unwrap();
if let Some(delta) = delta {
// realloc
h.curr_blocks += 0; // unchanged
h.curr_bytes += delta;
} else {
// alloc
h.curr_blocks += 1;
h.curr_bytes += size;
}
// The use of `>=` not `>` means that if there are multiple equal peaks
// we record the latest one, like `check_for_global_peak` does.
if h.curr_bytes >= h.max_bytes {
h.max_blocks = h.curr_blocks;
h.max_bytes = h.curr_bytes;
}
}
fn update_counts_for_dealloc(&mut self, size: usize, alloc_duration: Duration) {
let h = self.heap.as_mut().unwrap();
h.curr_blocks -= 1;
h.curr_bytes -= size;
h.total_lifetimes_duration += alloc_duration;
}
fn update_counts_for_ad_hoc_event(&mut self, weight: usize) {
std::assert!(self.heap.is_none());
self.total_blocks += 1;
self.total_bytes += weight as u64;
}
}
struct LiveBlock {
// The index of the PpInfo for this block.
pp_info_idx: usize,
// When the block was allocated.
allocation_instant: Instant,
}
// We record info about allocations and deallocations. A wrinkle: the recording
// done may trigger additional allocations. We must ignore these because (a)
// they're part of `dhat`'s execution, not the original program's execution,
// and (b) they would be intercepted and trigger additional allocations, which
// would be intercepted and trigger additional allocations, and so on, leading
// to infinite loops.
//
// With this type we can run one code path if we are already ignoring
// allocations. Otherwise, we can a second code path while ignoring
// allocations. In practice, the first code path is unreachable except within
// the `GlobalAlloc` methods.
//
// WARNING: This type must be used for any code within this crate that can
// trigger allocations.
struct IgnoreAllocs {
was_already_ignoring_allocs: bool,
}
thread_local!(static IGNORE_ALLOCS: Cell<bool> = Cell::new(false));
impl IgnoreAllocs {
fn new() -> Self {
Self {
was_already_ignoring_allocs: IGNORE_ALLOCS.with(|b| b.replace(true)),
}
}
}
/// If code panics while `IgnoreAllocs` is live, this will still reset
/// `IGNORE_ALLOCS` so that it can be used again.
impl Drop for IgnoreAllocs {
fn drop(&mut self) {
if !self.was_already_ignoring_allocs {
IGNORE_ALLOCS.with(|b| b.set(false));
}
}
}
/// A type whose lifetime dictates the start and end of profiling.
///
/// Profiling starts when the first value of this type is created. Profiling
/// stops when (a) this value is dropped or (b) a `dhat` assertion fails,
/// whichever comes first. When that happens, profiling data may be written to
/// file, depending on how the `Profiler` has been configured. Only one
/// `Profiler` can be running at any point in time.
//
// The actual profiler state is stored in `Globals`, so it can be accessed from
// places like `Alloc::alloc` and `ad_hoc_event()` when the `Profiler`
// instance isn't within reach.
#[derive(Debug)]
pub struct Profiler;
impl Profiler {
/// Initiates allocation profiling.
///
/// Typically the first thing in `main`. Its result should be assigned to a
/// variable whose lifetime ends at the end of `main`.
///
/// # Panics
///
/// Panics if another `Profiler` is running.
///
/// # Examples
/// ```
/// let _profiler = dhat::Profiler::new_heap();
/// ```
pub fn new_heap() -> Self {
Self::builder().build()
}
/// Initiates ad hoc profiling.
///
/// Typically the first thing in `main`. Its result should be assigned to a
/// variable whose lifetime ends at the end of `main`.