-
Notifications
You must be signed in to change notification settings - Fork 392
Expand file tree
/
Copy pathruby.go
More file actions
1891 lines (1622 loc) · 65.2 KB
/
ruby.go
File metadata and controls
1891 lines (1622 loc) · 65.2 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 The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package ruby // import "go.opentelemetry.io/ebpf-profiler/interpreter/ruby"
import (
"encoding/binary"
"errors"
"fmt"
"math/bits"
"regexp"
"runtime"
"strconv"
"strings"
"sync"
"sync/atomic"
"unsafe"
"go.opentelemetry.io/ebpf-profiler/internal/log"
"github.com/elastic/go-freelru"
"go.opentelemetry.io/ebpf-profiler/interpreter"
"go.opentelemetry.io/ebpf-profiler/libc"
"go.opentelemetry.io/ebpf-profiler/libpf"
"go.opentelemetry.io/ebpf-profiler/libpf/pfelf"
"go.opentelemetry.io/ebpf-profiler/libpf/pfunsafe"
"go.opentelemetry.io/ebpf-profiler/lpm"
"go.opentelemetry.io/ebpf-profiler/metrics"
npsr "go.opentelemetry.io/ebpf-profiler/nopanicslicereader"
"go.opentelemetry.io/ebpf-profiler/process"
"go.opentelemetry.io/ebpf-profiler/remotememory"
"go.opentelemetry.io/ebpf-profiler/reporter"
"go.opentelemetry.io/ebpf-profiler/successfailurecounter"
"go.opentelemetry.io/ebpf-profiler/support"
"go.opentelemetry.io/ebpf-profiler/util"
)
const (
// addrToStringSize is the LRU size for caching Ruby VM addresses to Ruby strings.
addrToStringSize = 1024
// rubyInsnInfoSizeLimit defines the limit up to which we will allocate memory for the
// binary search algorithm to get the line number.
rubyInsnInfoSizeLimit = 1 * 1024 * 1024
)
//nolint:lll
const (
// RUBY_T_ICLASS
// https://github.com/ruby/ruby/blob/c149708018135595b2c19c5f74baf9475674f394/include/ruby/internal/value_type.h#L138
rubyTIClass = 0x1c
// RUBY_T_STRING
// https://github.com/ruby/ruby/blob/c149708018135595b2c19c5f74baf9475674f394/include/ruby/internal/value_type.h#L117
rubyTString = 0x5
// RUBY_T_ARRAY
// https://github.com/ruby/ruby/blob/c149708018135595b2c19c5f74baf9475674f394/include/ruby/internal/value_type.h#L119
rubyTArray = 0x7
// RUBY_T_MASK
// https://github.com/ruby/ruby/blob/c149708018135595b2c19c5f74baf9475674f394/include/ruby/internal/value_type.h#L142
rubyTMask = 0x1f
// RSTRING_NOEMBED
// https://github.com/ruby/ruby/blob/5445e0435260b449decf2ac16f9d09bae3cafe72/include/ruby/ruby.h#L978
// https://github.com/ruby/ruby/blob/5445e0435260b449decf2ac16f9d09bae3cafe72/include/ruby/ruby.h#L855
// 1 << 13
rstringNoEmbed = RUBY_FL_USER1
// RARRAY_EMBED_FLAG
rarrayEmbed = RUBY_FL_USER1
// PATHOBJ_REALPATH
// https://github.com/ruby/ruby/blob/3185786874315ab4f1cfcc73c3d1b14613452905/vm_core.h#L343
pathObjRealPathIdx = 1
// ISEQ_TYPE_METHOD
// https://github.com/ruby/ruby/blob/v3_4_5/vm_core.h#L380
iseqTypeMethod = 1
// RUBY_ID_SCOPE_SHIFT = 4
// https://github.com/ruby/ruby/blob/797a4115bbb249c4f5f11e1b4bacba7781c68cee/template/id.h.tmpl#L30
rubyIdScopeShift = 4
// ID_ENTRY_UNIT
// https://github.com/ruby/ruby/blob/v3_4_5/symbol.c#L77
idEntryUnit = uint64(512)
// ID_ENTRY_SIZE
// https://github.com/ruby/ruby/blob/980e18496e1aafc642b199d24c81ab4a8afb3abb/symbol.c#L93
idEntrySize = uint64(2)
// https://github.com/ruby/ruby/blob/20cda200d3ce092571d0b5d342dadca69636cb0f/gc/default/default.c#L438-L443
rubyGcModeNone = 0
rubyGcModeMarking = 1
rubyGcModeSweeping = 2
rubyGcModeCompacting = 3
)
var (
// regex to identify the Ruby interpreter shared library
libRubyRegex = regexp.MustCompile(`^(?:.*/)?libruby(?:-.*)?\.so\.(\d+)\.(\d+)\.(\d+)$`)
// regex to identify a statically-linked Ruby binary
binRubyRegex = regexp.MustCompile(`^(?:.*/)?(?:bin/)?ruby$`)
// regex to extract a version from a string
rubyVersionRegex = regexp.MustCompile(`^(\d+)\.(\d+)\.(\d+)$`)
unknownCfunc = libpf.Intern("<unknown cfunc>")
cfuncDummyFile = libpf.Intern("<cfunc>")
rubyGcFrame = libpf.Intern("(garbage collection)")
rubyGcRunning = libpf.Intern("(running)")
rubyGcMarking = libpf.Intern("(marking)")
rubyGcSweeping = libpf.Intern("(sweeping)")
rubyGcCompacting = libpf.Intern("(compacting)")
rubyGcDummyFile = libpf.Intern("<gc>")
rubyJitDummyFrame = libpf.Intern("<unknown jit code>")
rubyJitDummyFile = libpf.Intern("<jitted code>")
// compiler check to make sure the needed interfaces are satisfied
_ interpreter.Data = &rubyData{}
_ interpreter.Instance = &rubyInstance{}
)
//nolint:lll
type rubyData struct {
// currentCtxPtr is the `ruby_current_execution_context_ptr` symbol value which is needed by the
// eBPF program to build ruby backtraces.
currentCtxPtr libpf.Address
// Address to the ruby_current_ec variable in TLS, as an offset from tpbase
currentEcTpBaseTlsOffset libpf.Address
// For statically-linked ruby, the direct TP-relative offset to ruby_current_ec
// extracted from disassembly of rb_current_ec_noinline
staticTLSOffset int64
// For DTV-based TLS access: offset of ruby_current_ec within its TLS block
currentEcTlsOffset libpf.Address
// For DTV-based TLS access: ELF offset where the TLS module ID is stored
// (from DTPMOD64 relocation, the actual module ID is written by the linker at load time)
tlsModuleIdOffset libpf.Address
// Address to global symbols, for id to string mappings
globalSymbolsAddr libpf.Address
// version of the currently used Ruby interpreter.
// major*0x10000 + minor*0x100 + release (e.g. 3.0.1 -> 0x30001)
version uint32
// this is compiled into ruby (id.h.tmpl) as a template and needed for symbolizing
// c function frames
lastOpId uint64
// Flag for detecting singletons, can vary by version
rubyFlSingleton libpf.Address
// Is it possible to read the classpath
hasClassPath bool
// Is it possible to read objspace information
hasObjspace bool
// Is it possible to read the global symbol table (to symbolize cfuncs)
hasGlobalSymbols bool
// vmStructs reflects the Ruby internal names and offsets of named fields.
vmStructs struct {
// rb_execution_context_struct
// https://github.com/ruby/ruby/blob/5445e0435260b449decf2ac16f9d09bae3cafe72/vm_core.h#L843
execution_context_struct struct {
vm_stack, vm_stack_size, cfp, thread_ptr uint8
}
// https://github.com/ruby/ruby/blob/v3_4_5/vm_core.h#L1108
thread_struct struct {
vm uint8
}
// https://github.com/ruby/ruby/blob/v3_4_5/vm_core.h#L666
vm_struct struct {
gc_objspace uint16
}
// https://github.com/ruby/ruby/blob/v3_4_5/gc/default/default.c#L445
objspace struct {
flags uint8
size_of_flags uint8
}
// rb_control_frame_struct
// https://github.com/ruby/ruby/blob/5445e0435260b449decf2ac16f9d09bae3cafe72/vm_core.h#L760
control_frame_struct struct {
pc, iseq, ep uint8
size_of_control_frame_struct uint8
}
// rb_iseq_struct
// https://github.com/ruby/ruby/blob/5445e0435260b449decf2ac16f9d09bae3cafe72/vm_core.h#L456
iseq_struct struct {
body uint8
}
// rb_iseq_constant_body
// https://github.com/ruby/ruby/blob/5445e0435260b449decf2ac16f9d09bae3cafe72/vm_core.h#L311
iseq_constant_body struct {
iseq_type, encoded, size, location, insn_info_body, insn_info_size, succ_index_table uint8
local_iseq, size_of_iseq_constant_body uint16
}
// rb_iseq_location_struct
// https://github.com/ruby/ruby/blob/5445e0435260b449decf2ac16f9d09bae3cafe72/vm_core.h#L272
iseq_location_struct struct {
pathobj, base_label, label uint8
size_of_iseq_location_struct uint8
}
// succ_index_table_struct
// https://github.com/ruby/ruby/blob/5445e0435260b449decf2ac16f9d09bae3cafe72/iseq.c#L3420
succ_index_table_struct struct {
small_block_ranks, block_bits, succ_part, succ_dict_block uint8
size_of_succ_dict_block uint8
}
// iseq_insn_info_entry
// https://github.com/ruby/ruby/blob/4e0a512972cdcbfcd5279f1a2a81ba342ed75b6e/iseq.h#L212
iseq_insn_info_entry struct {
position, line_no uint8
size_of_position, size_of_line_no, size_of_iseq_insn_info_entry uint8
}
// RBasic
// https://github.com/ruby/ruby/blob/d5c05585923bca11f07ff19edccd1f8e67620610/include/ruby/internal/core/rbasic.h#L110
rbasic_struct struct {
flags, klass uint8
}
// RString
// https://github.com/ruby/ruby/blob/5445e0435260b449decf2ac16f9d09bae3cafe72/include/ruby/ruby.h#L988
// https://github.com/ruby/ruby/blob/86ac17efde6cf98903513cac2538b15fc4ac80b2/include/ruby/internal/core/rstring.h#L196
rstring_struct struct {
// NOTE: starting with Ruby 3.1 the `as.ary` field is now `as.embed.ary`
as_heap_ptr, as_ary uint8
}
// RArray
// https://github.com/ruby/ruby/blob/5445e0435260b449decf2ac16f9d09bae3cafe72/include/ruby/ruby.h#L1048
rarray_struct struct {
as_heap_ptr, as_ary uint8
size_of_rarray uint8
}
// size_of_immediate_table holds the size of the macro IMMEDIATE_TABLE_SIZE as defined in
// https://github.com/ruby/ruby/blob/5445e0435260b449decf2ac16f9d09bae3cafe72/iseq.c#L3418
size_of_immediate_table uint8
// size_of_value holds the size of the macro VALUE as defined in
// https://github.com/ruby/ruby/blob/5445e0435260b449decf2ac16f9d09bae3cafe72/vm_core.h#L1136
size_of_value uint8
// rb_ractor_struct
// https://github.com/ruby/ruby/blob/5ce0d2aa354eb996cb3ca9bb944f880ff6acfd57/ractor_core.h#L82
rb_ractor_struct struct {
running_ec uint16
}
// rb_callable_method_entry_struct
// https://github.com/ruby/ruby/blob/fd59ac6410d0cc93a8baaa42df77491abdb2e9b6/method.h#L63-L69
rb_method_entry_struct struct {
flags, defined_class, def, owner uint8
}
// rb_method_definition_struct
// https://github.com/ruby/ruby/blob/fd59ac6410d0cc93a8baaa42df77491abdb2e9b6/method.h#L180
rb_method_definition_struct struct {
method_type, body, original_id uint8
}
// rb_method_iseq_struct
// https://github.com/ruby/ruby/blob/fd59ac6410d0cc93a8baaa42df77491abdb2e9b6/method.h#L135
rb_method_iseq_struct struct {
iseqptr uint8
}
// RClass_and_rb_classext_t
// https://github.com/ruby/ruby/blob/fd59ac6410d0cc93a8baaa42df77491abdb2e9b6/internal/class.h#L146
rclass_and_rb_classext_t struct {
classext uint8
}
// rb_classext_struct
// https://github.com/ruby/ruby/blob/fd59ac6410d0cc93a8baaa42df77491abdb2e9b6/internal/class.h#L79
rb_classext_struct struct {
classpath, as_singleton_class_attached_object uint8
}
// rb_symbols_t
// https://github.com/ruby/ruby/blob/v3_4_7/symbol.h#L61-L66
rb_symbols_t struct {
ids uint8
}
}
}
func rubyVersion(major, minor, release uint32) uint32 {
return major*0x10000 + minor*0x100 + release
}
func (r *rubyData) String() string {
ver := r.version
return fmt.Sprintf("Ruby %d.%d.%d", (ver>>16)&0xff, (ver>>8)&0xff, ver&0xff)
}
func (r *rubyData) Attach(ebpf interpreter.EbpfHandler, pid libpf.PID, bias libpf.Address,
rm remotememory.RemoteMemory,
) (interpreter.Instance, error) {
var tlsOffset int64
if r.staticTLSOffset != 0 {
// For statically-linked ruby, use the direct TP-relative offset
// extracted from disassembly of rb_current_ec_noinline.
tlsOffset = r.staticTLSOffset
} else if r.currentEcTpBaseTlsOffset != 0 {
// Read TLS offset from the TLS descriptor.
tlsOffset = int64(rm.Uint64(bias + r.currentEcTpBaseTlsOffset + 8))
}
// For DTV-based access: read the actual module ID from process memory.
// The linker writes the module ID at the relocation offset at load time.
var modID uint32
if r.tlsModuleIdOffset != 0 {
modID = uint32(rm.Uint64(bias + r.tlsModuleIdOffset))
log.Debugf("Ruby TLS module ID: %d", modID)
}
cdata := support.RubyProcInfo{
Version: r.version,
Current_ctx_ptr: uint64(r.currentCtxPtr + bias),
Current_ec_tpbase_tls_offset: tlsOffset,
Current_ec_tls_offset: uint64(r.currentEcTlsOffset),
Tls_module_id: modID,
Vm_stack: r.vmStructs.execution_context_struct.vm_stack,
Vm_stack_size: r.vmStructs.execution_context_struct.vm_stack_size,
Cfp: r.vmStructs.execution_context_struct.cfp,
Pc: r.vmStructs.control_frame_struct.pc,
Iseq: r.vmStructs.control_frame_struct.iseq,
Ep: r.vmStructs.control_frame_struct.ep,
Size_of_control_frame_struct: r.vmStructs.control_frame_struct.size_of_control_frame_struct,
Thread_ptr: r.vmStructs.execution_context_struct.thread_ptr,
Thread_vm: r.vmStructs.thread_struct.vm,
Has_objspace: r.hasObjspace,
Vm_objspace: r.vmStructs.vm_struct.gc_objspace,
Objspace_flags: r.vmStructs.objspace.flags,
Objspace_size_of_flags: r.vmStructs.objspace.size_of_flags,
Body: r.vmStructs.iseq_struct.body,
Cme_method_def: r.vmStructs.rb_method_entry_struct.def,
Size_of_value: r.vmStructs.size_of_value,
Running_ec: r.vmStructs.rb_ractor_struct.running_ec,
}
if err := ebpf.UpdateProcData(libpf.Ruby, pid, unsafe.Pointer(&cdata)); err != nil {
return nil, err
}
addrToString, err := freelru.New[libpf.Address, libpf.String](addrToStringSize,
libpf.Address.Hash32)
if err != nil {
return nil, err
}
return &rubyInstance{
r: r,
rm: rm,
procInfo: &cdata,
globalSymbolsAddr: r.globalSymbolsAddr + bias,
addrToString: addrToString,
mappings: make(map[process.RawMapping]uint32),
prefixes: make(map[lpm.Prefix]uint32),
memPool: sync.Pool{
New: func() any {
buf := make([]byte, 512)
return &buf
},
},
}, nil
}
func (r *rubyData) Unload(_ interpreter.EbpfHandler) {
}
// rubyIseq stores information extracted from a iseq_constant_body struct.
type rubyIseq struct {
// sourceFileName is the extracted filename field
sourceFileName libpf.String
// label
label libpf.String
// base_label
baseLabel libpf.String
// methodName is the optional method name for this iseq
// only present on CME-based iseq
methodName libpf.String
// line of code in source file for this instruction sequence
line libpf.SourceLineno
}
type rubyInstance struct {
interpreter.InstanceStubs
// procInfo stores the eBPF proc data for re-insertion when UpdateLibcInfo provides DTVInfo
procInfo *support.RubyProcInfo
// dtvInfoInserted tracks whether we have already updated procInfo with DTVInfo
dtvInfoInserted bool
// Ruby symbolization metrics
successCount atomic.Uint64
failCount atomic.Uint64
r *rubyData
rm remotememory.RemoteMemory
// lastId is a cached copy index of the final entry in the global symbol table
lastId uint32
// globalSymbolsAddr is the offset of the global symbol table, for looking up ruby symbolic ids
globalSymbolsAddr libpf.Address
// addrToString maps an address to an extracted Ruby String from this address.
addrToString *freelru.LRU[libpf.Address, libpf.String]
// memPool provides pointers to byte arrays for efficient memory reuse.
memPool sync.Pool
// maxSize is the largest number we did see in the last reporting interval for size
// in getRubyLineNo.
maxSize atomic.Uint32
// mappings is indexed by the Mapping to its generation.
// Entries are pruned each SynchronizeMappings call; the map size is bounded
// by the number of executable anonymous mappings for this process (typically
// a handful for JIT code pages plus any native gems with anonymous exec pages).
mappings map[process.RawMapping]uint32
// prefixes is indexed by the prefix added to ebpf maps (to be cleaned up) to its generation
prefixes map[lpm.Prefix]uint32
// mappingGeneration is the current generation (so old entries can be pruned)
mappingGeneration uint32
}
func (r *rubyInstance) Detach(ebpf interpreter.EbpfHandler, pid libpf.PID) error {
var err error
err = ebpf.DeleteProcData(libpf.Ruby, pid)
for prefix := range r.prefixes {
if err2 := ebpf.DeletePidInterpreterMapping(pid, prefix); err2 != nil {
err = errors.Join(err,
fmt.Errorf("failed to remove ruby prefix 0x%x/%d: %v",
prefix.Key, prefix.Length, err2))
}
}
return err
}
// UpdateLibcInfo is called when libc introspection data becomes available.
// Ruby uses this to receive DTVInfo for DTV-based TLS access to ruby_current_ec
// when TLSDESC relocations are unavailable.
func (r *rubyInstance) UpdateLibcInfo(ebpf interpreter.EbpfHandler, pid libpf.PID,
libcInfo libc.LibcInfo) error {
// Only need DTVInfo if we're using DTV-based access (have a module ID but no TLSDESC offset)
if r.procInfo.Tls_module_id == 0 {
return nil
}
if !libcInfo.HasDTVInfo() {
// DTV info not available yet (may arrive from a different DSO)
return nil
}
if r.dtvInfoInserted {
return nil
}
r.procInfo.Dtv_info = libcInfo.DTVInfo
if err := ebpf.UpdateProcData(libpf.Ruby, pid, unsafe.Pointer(r.procInfo)); err != nil {
return err
}
r.dtvInfoInserted = true
log.Debugf("Ruby: updated proc data with DTVInfo (offset=%d, multiplier=%d)",
libcInfo.DTVInfo.Offset, libcInfo.DTVInfo.Multiplier)
return nil
}
// readRubyArrayDataPtr obtains the data pointer of a Ruby array (RArray).
//
// https://github.com/ruby/ruby/blob/95aff2146/include/ruby/internal/core/rarray.h#L87
func (r *rubyInstance) readRubyArrayDataPtr(addr libpf.Address) (libpf.Address, error) {
flags := r.rm.Ptr(addr)
if flags&rubyTMask != rubyTArray {
return 0, fmt.Errorf("object at 0x%08X is not an array", addr)
}
vms := &r.r.vmStructs
if flags&rarrayEmbed == rarrayEmbed {
return addr + libpf.Address(vms.rarray_struct.as_ary), nil
}
p := r.rm.Ptr(addr + libpf.Address(vms.rarray_struct.as_heap_ptr))
if p != 0 {
return 0, fmt.Errorf("heap pointer of array at 0x%08X is 0", addr)
}
return addr, nil
}
// readPathObjRealPath reads the realpath field from a Ruby iseq pathobj.
//
// Path objects are represented as either a Ruby string (RString) or a
// Ruby arrays (RArray) with 2 entries. The first field contains a relative
// path, the second one an absolute one. All Ruby types start with an RBasic
// object that contains a type tag that we can use to determine what variant
// we're dealing with.
//
// https://github.com/ruby/ruby/blob/4e0a51297/iseq.c#L217
// https://github.com/ruby/ruby/blob/95aff2146/vm_core.h#L267
// https://github.com/ruby/ruby/blob/95aff2146/vm_core.h#L283
// https://github.com/ruby/ruby/blob/7127f39ba/vm_core.h#L321-L321
func (r *rubyInstance) readPathObjRealPath(addr libpf.Address) (string, error) {
flags := r.rm.Ptr(addr)
switch flags & rubyTMask {
case rubyTString:
return r.readRubyString(addr)
case rubyTArray:
vms := &r.r.vmStructs
arrData, e := r.readRubyArrayDataPtr(addr)
if e != nil {
return "", e
}
// Read contiguous pointer values into a buffer to be more efficient
dataBytes := make([]byte, 2*vms.size_of_value)
if err := r.rm.Read(arrData, dataBytes); err != nil {
return "", fmt.Errorf("failed to read array data bytes: %v", err)
}
var relTag, absTag uint64
relVal := npsr.Ptr(dataBytes, 0)
absVal := npsr.Ptr(dataBytes, uint(vms.size_of_value))
if absVal != 0 {
absTag = uint64(r.rm.Ptr(absVal)) & uint64(rubyTMask)
}
var candidate libpf.Address
if absVal != 0 && absTag == uint64(rubyTString) {
candidate = absVal
} else if relVal != 0 {
relTag = uint64(r.rm.Ptr(relVal)) & uint64(rubyTMask)
if relTag == uint64(rubyTString) {
candidate = relVal
}
} else {
return "", fmt.Errorf("pathobj array has no string entries: relTag=0x%x absTag=0x%x", relTag, absTag)
}
return r.readRubyString(candidate)
default:
return "", fmt.Errorf("unexpected pathobj type tag: 0x%X", flags&rubyTMask)
}
}
// readRubyString extracts a Ruby string from the given addr.
//
// 2.5.0: https://github.com/ruby/ruby/blob/4e0a51297/include/ruby/ruby.h#L1004
// 3.0.0: https://github.com/ruby/ruby/blob/48b94b791/include/ruby/internal/core/rstring.h#L73
func (r *rubyInstance) readRubyString(addr libpf.Address) (string, error) {
flags := r.rm.Ptr(addr)
if flags&rubyTMask != rubyTString {
return "", fmt.Errorf("object at 0x%08X is not a string", addr)
}
var str string
vms := &r.r.vmStructs
if flags&rstringNoEmbed == rstringNoEmbed {
str = r.rm.StringPtr(addr + libpf.Address(vms.rstring_struct.as_heap_ptr))
} else {
str = r.rm.String(addr + libpf.Address(vms.rstring_struct.as_ary))
}
r.addrToString.Add(addr, libpf.Intern(str))
return str, nil
}
type StringReader = func(address libpf.Address) (string, error)
// getStringCached retrieves a string from cache or reads and inserts it if it's missing.
func (r *rubyInstance) getStringCached(addr libpf.Address, reader StringReader) (
libpf.String, error,
) {
if value, ok := r.addrToString.Get(addr); ok {
return value, nil
}
str, err := reader(addr)
if err != nil {
return libpf.NullString, err
}
if !util.IsValidString(str) {
log.Debugf("Extracted invalid string from Ruby at 0x%x '%v'[len=%d]",
addr, unsafe.Slice(unsafe.StringData(str), min(len(str), 128)), len(str))
return libpf.NullString, fmt.Errorf("extracted invalid Ruby string from address 0x%x", addr)
}
val := libpf.Intern(str)
r.addrToString.Add(addr, val)
return val, err
}
// rubyPopcount64 is a helper macro.
// Ruby makes use of __builtin_popcount intrinsics. These builtin intrinsics are not available
// here so we use the equivalent function of the Go standard library.
// https://github.com/ruby/ruby/blob/48b94b791997881929c739c64f95ac30f3fd0bb9/internal/bits.h#L408
func rubyPopcount64(in uint64) uint32 {
return uint32(bits.OnesCount64(in))
}
// smallBlockRankGet is a helper macro.
// https://github.com/ruby/ruby/blob/5445e0435260b449decf2ac16f9d09bae3cafe72/iseq.c#L3432
func smallBlockRankGet(v uint64, i uint32) uint32 {
if i == 0 {
return 0
}
return uint32((v >> ((i - 1) * 9))) & 0x1ff
}
// immBlockRankGet is a helper macro.
// https://github.com/ruby/ruby/blob/5445e0435260b449decf2ac16f9d09bae3cafe72/iseq.c#L3430
func immBlockRankGet(v uint64, i uint32) uint32 {
tmp := v >> (i * 7)
return uint32(tmp) & 0x7f
}
// getObsoleteRubyLineNo implements a binary search algorithm to get the line number for a position.
//
// Implementation according to Ruby:
// https://github.com/ruby/ruby/blob/4e0a512972cdcbfcd5279f1a2a81ba342ed75b6e/iseq.c#L1254-L1295
func (r *rubyInstance) getObsoleteRubyLineNo(iseqBody libpf.Address,
pos, size uint32,
) (uint32, error) {
vms := &r.r.vmStructs
sizeOfEntry := uint32(vms.iseq_insn_info_entry.size_of_iseq_insn_info_entry)
ptr := r.rm.Ptr(iseqBody + libpf.Address(vms.iseq_constant_body.insn_info_body))
syncPoolData := r.memPool.Get().(*[]byte)
if syncPoolData == nil {
return 0, errors.New("failed to get memory from sync pool")
}
if uint32(len(*syncPoolData)) < size*sizeOfEntry {
// make sure the data we want to write into blob fits in
*syncPoolData = make([]byte, size*sizeOfEntry)
}
defer func() {
// Reset memory and return it for reuse.
for i := uint32(0); i < size*sizeOfEntry; i++ {
(*syncPoolData)[i] = 0x0
}
r.memPool.Put(syncPoolData)
}()
blob := (*syncPoolData)[:size*sizeOfEntry]
// Read the table with multiple iseq_insn_info_entry entries only once for the binary search.
if err := r.rm.Read(ptr, blob); err != nil {
return 0, fmt.Errorf("failed to read line table for binary search: %v", err)
}
var blobPos uint32
var entryPos, entryLine uint32
right := size - 1
left := uint32(1)
posOffset := uint32(vms.iseq_insn_info_entry.position)
posSize := uint32(vms.iseq_insn_info_entry.size_of_position)
lineNoOffset := uint32(vms.iseq_insn_info_entry.line_no)
lineNoSize := uint32(vms.iseq_insn_info_entry.size_of_line_no)
for left <= right {
index := left + (right-left)/2
blobPos = index * sizeOfEntry
entryPos = binary.LittleEndian.Uint32(
blob[blobPos+posOffset : blobPos+posOffset+posSize])
entryLine = binary.LittleEndian.Uint32(
blob[blobPos+lineNoOffset : blobPos+lineNoOffset+lineNoSize])
if entryPos == pos {
return entryLine, nil
}
if entryPos < pos {
left = index + 1
continue
}
right = index - 1
}
if left >= size {
blobPos = (size - 1) * sizeOfEntry
return binary.LittleEndian.Uint32(
blob[blobPos+lineNoOffset : blobPos+lineNoOffset+lineNoSize]), nil
}
blobPos = left * sizeOfEntry
entryPos = binary.LittleEndian.Uint32(blob[blobPos+posOffset : blobPos+posOffset+posSize])
if entryPos > pos {
blobPos = (left - 1) * sizeOfEntry
return binary.LittleEndian.Uint32(
blob[blobPos+lineNoOffset : blobPos+lineNoOffset+lineNoSize]), nil
}
return binary.LittleEndian.Uint32(
blob[blobPos+lineNoOffset : blobPos+lineNoOffset+lineNoSize]), nil
}
// getRubyLineNo extracts the line number information from the given instruction sequence body and
// Ruby VM program counter.
// Starting with Ruby version 2.6.0 [0] Ruby no longer stores the information about the line number
// in a struct field but encodes them in a succinct data structure [1].
// For the lookup of the line number in this data structure getRubyLineNo follows the naming and
// implementation of the Ruby internal function succ_index_lookup [2].
//
// [0] https://github.com/ruby/ruby/commit/83262f24896abeaf1977c8837cbefb1b27040bef
// [1] https://en.wikipedia.org/wiki/Succinct_data_structure
// [2] https://github.com/ruby/ruby/blob/5445e0435260b449decf2ac16f9d09bae3cafe72/iseq.c#L3500-L3517
func (r *rubyInstance) getRubyLineNo(iseqBody libpf.Address, pc uint64) (uint32, error) {
vms := &r.r.vmStructs
// Read the struct iseq_constant_body only once.
blob := make([]byte, vms.iseq_constant_body.size_of_iseq_constant_body)
if err := r.rm.Read(iseqBody, blob); err != nil {
return 0, fmt.Errorf("failed to read iseq_constant_body: %v", err)
}
offsetEncoded := vms.iseq_constant_body.encoded
iseqEncoded := binary.LittleEndian.Uint64(blob[offsetEncoded : offsetEncoded+8])
offsetSize := vms.iseq_constant_body.insn_info_size
size := binary.LittleEndian.Uint32(blob[offsetSize : offsetSize+4])
// For our better understanding and future improvement we track the maximum value we get for
// size and report it.
util.AtomicUpdateMaxUint32(&r.maxSize, size)
// https://github.com/ruby/ruby/blob/5445e0435260b449decf2ac16f9d09bae3cafe72/iseq.c#L1678
if size == 0 {
return 0, errors.New("failed to read size")
}
if size == 1 {
offsetBody := vms.iseq_constant_body.insn_info_body
lineNo := binary.LittleEndian.Uint32(blob[offsetBody : offsetBody+4])
return lineNo, nil
}
if size > rubyInsnInfoSizeLimit {
// When reading the value for size we don't have a way to validate this returned
// value. To make sure we don't accept any arbitrary number we set here a limit of
// 1MB.
// Returning 0 here is not the correct line number at this point. But we let the
// rest of the symbolization process unwind the frame and get the file name. This
// way we can provide partial results.
return 0, nil
}
// To get the line number iseq_encoded is subtracted from pc. This result also represents the
// size of the current instruction sequence. If the calculated size of the instruction sequence
// is greater than the value in iseq_encoded we don't report this pc to user space.
//
//nolint:lll
// https://github.com/ruby/ruby/blob/5445e0435260b449decf2ac16f9d09bae3cafe72/vm_backtrace.c#L47-L48
pos := (pc - iseqEncoded) / uint64(vms.size_of_value)
if pos != 0 {
pos--
}
// Ruby 2.6 changed the way of storing line numbers with [0]. As we still want to get
// the line number information for older Ruby versions, we have this special
// handling here.
//
// [0] https://github.com/ruby/ruby/commit/83262f24896abeaf1977c8837cbefb1b27040bef
if r.r.version < 0x20600 {
return r.getObsoleteRubyLineNo(iseqBody, uint32(pos), size)
}
offsetSuccTable := vms.iseq_constant_body.succ_index_table
succIndexTable := binary.LittleEndian.Uint64(blob[offsetSuccTable : offsetSuccTable+8])
if succIndexTable == 0 {
// https://github.com/ruby/ruby/blob/5445e0435260b449decf2ac16f9d09bae3cafe72/iseq.c#L1686
return 0, errors.New("failed to get table with line information")
}
// https://github.com/ruby/ruby/blob/5445e0435260b449decf2ac16f9d09bae3cafe72/iseq.c#L3500-L3517
var tableIndex uint32
if pos < uint64(vms.size_of_immediate_table) {
i := int(pos / 9)
j := int(pos % 9)
immPart := r.rm.Uint64(libpf.Address(succIndexTable) +
libpf.Address(i*int(vms.size_of_value)))
if immPart == 0 {
return 0, errors.New("failed to read immPart")
}
tableIndex = immBlockRankGet(immPart, uint32(j))
} else {
blockIndex := uint32((pos - uint64(vms.size_of_immediate_table)) / 512)
blockOffset := libpf.Address(blockIndex *
uint32(vms.succ_index_table_struct.size_of_succ_dict_block))
rank := r.rm.Uint32(libpf.Address(succIndexTable) +
libpf.Address(vms.succ_index_table_struct.succ_part) + blockOffset)
if rank == 0 {
return 0, errors.New("failed to read rank")
}
blockBitIndex := uint32((pos - uint64(vms.size_of_immediate_table)) % 512)
smallBlockIndex := blockBitIndex / 64
smallBlockOffset := libpf.Address(smallBlockIndex * uint32(vms.size_of_value))
smallBlockRanks := r.rm.Uint64(libpf.Address(succIndexTable) + blockOffset +
libpf.Address(vms.succ_index_table_struct.succ_part+
vms.succ_index_table_struct.small_block_ranks))
if smallBlockRanks == 0 {
return 0, errors.New("failed to read smallBlockRanks")
}
smallBlockPopcount := smallBlockRankGet(smallBlockRanks, smallBlockIndex)
blockBits := r.rm.Uint64(libpf.Address(succIndexTable) + blockOffset +
libpf.Address(vms.succ_index_table_struct.succ_part+
vms.succ_index_table_struct.block_bits) + smallBlockOffset)
if blockBits == 0 {
return 0, errors.New("failed to read blockBits")
}
popCnt := rubyPopcount64((blockBits << (63 - blockBitIndex%64)))
tableIndex = rank + smallBlockPopcount + popCnt
}
tableIndex--
offsetBody := vms.iseq_constant_body.insn_info_body
lineNoAddr := binary.LittleEndian.Uint64(blob[offsetBody : offsetBody+8])
if lineNoAddr == 0 {
return 0, errors.New("failed to read lineNoAddr")
}
lineNo := r.rm.Uint32(libpf.Address(lineNoAddr) +
libpf.Address(tableIndex*uint32(vms.iseq_insn_info_entry.size_of_iseq_insn_info_entry)))
if lineNo == 0 {
return 0, errors.New("failed to read lineNo")
}
return lineNo, nil
}
// Aims to implement the same logic as rb_profile_frame_classpath
// https://github.com/ruby/ruby/blob/v3_4_7/vm_backtrace.c#L1906
func (r *rubyInstance) readClassName(classAddr libpf.Address) (libpf.String, bool, error) {
var classPath libpf.String
var classpathPtr libpf.Address
var singleton bool
var err error
// Read the rbasic + rclass_ext + classpath + value to buffer entire object + classpath pointer
// do one large, buffered read rather than many small reads.
dataBytes := make([]byte, r.r.vmStructs.rclass_and_rb_classext_t.classext+r.r.vmStructs.rb_classext_struct.classpath+r.r.vmStructs.size_of_value)
if err := r.rm.Read(classAddr, dataBytes); err != nil {
return classPath, singleton, err
}
classFlags := npsr.Ptr(dataBytes, 0)
classMask := classFlags & rubyTMask
classpathPtr = npsr.Ptr(dataBytes, uint(r.r.vmStructs.rclass_and_rb_classext_t.classext+r.r.vmStructs.rb_classext_struct.classpath))
if classMask == rubyTIClass {
//https://github.com/ruby/ruby/blob/b627532/vm_backtrace.c#L1931-L1933
if klassAddr := npsr.Ptr(dataBytes, uint(r.r.vmStructs.rbasic_struct.klass)); klassAddr != 0 {
classpathPtr = r.rm.Ptr(klassAddr + libpf.Address(r.r.vmStructs.rclass_and_rb_classext_t.classext+r.r.vmStructs.rb_classext_struct.classpath))
}
} else if classFlags&r.r.rubyFlSingleton != 0 {
// https://github.com/ruby/ruby/blob/b62753246eba4940f82a81736fc09b6517fa3965/internal/class.h#L528
// https://github.com/ruby/ruby/blob/b62753246eba4940f82a81736fc09b6517fa3965/vm_backtrace.c#L1934-L1937
singleton = true
// From these ruby macros:
// #define RCLASS_ATTACHED_OBJECT(c) (RCLASS_EXT_PRIME(c)->as.singleton_class.attached_object)
// #define RCLASS_EXT_PRIME(c) (&((struct RClass_and_rb_classext_t*)(c))->classext)
singletonObject := npsr.Ptr(dataBytes, uint(r.r.vmStructs.rclass_and_rb_classext_t.classext+r.r.vmStructs.rb_classext_struct.as_singleton_class_attached_object))
classpathPtr = r.rm.Ptr(singletonObject + libpf.Address(r.r.vmStructs.rclass_and_rb_classext_t.classext+r.r.vmStructs.rb_classext_struct.classpath))
// TODO (dalehamel) in future PR handle anonymous classes and modules
// If it is neither a class nor a module, we need to follow more complex logic
// https://github.com/ruby/ruby/blob/b627532/vm_backtrace.c#L1936-L1937 (see rb_class2name)
}
// NB we currently only doing the "happy path" where there is a classpath, and not
// handling the anonymous case or weird module cases yet.
// https://github.com/ruby/ruby/blob/v3_4_7/variable.c#L373 (rb_class_path)
// only this "happy path" is supported, the fallback and checking for real_object
// is not yet implemented
// https://github.com/ruby/ruby/blob/v3_4_7/variable.c#L352-L356 (rb_tmp_class_path)
if classpathPtr != 0 {
classPath, err = r.getStringCached(classpathPtr, r.readRubyString)
if err != nil {
return libpf.NullString, singleton, fmt.Errorf("unable to read classpath string %x %v", classpathPtr, err)
}
}
return classPath, singleton, nil
}
// Aims to mimic the logic of id2str, which ultimately calls this
// https://github.com/ruby/ruby/blob/v3_4_5/symbol.c#L450-L499
func (r *rubyInstance) id2str(originalId uint64) (libpf.String, error) {
var symbolName libpf.String
var err error
vms := &r.r.vmStructs
serial := originalId
if originalId > r.r.lastOpId {
serial = originalId >> rubyIdScopeShift
}
if serial > uint64(r.lastId) {
// First try synchronizing the value in case it is uninitialized or was updated, then check again
r.lastId = r.rm.Uint32(r.globalSymbolsAddr)
if serial > uint64(r.lastId) {
return libpf.NullString, fmt.Errorf("invalid serial %d, greater than last id %d", serial, r.lastId)
}
}
ids := r.rm.Ptr(r.globalSymbolsAddr + libpf.Address(vms.rb_symbols_t.ids))
idx := serial / idEntryUnit
flags := r.rm.Uint64(ids)
var idsPtr libpf.Address
var idsLen uint64
// Handle embedded arrays
// https://github.com/ruby/ruby/blob/8836f26efa7a6deb0ef8b3f253d8d53d04d43152/include/ruby/internal/core/rarray.h#L297-L307
if (flags & RARRAY_EMBED_FLAG) > 0 {
log.Debugf("Handling embedded array with shift")
// It is embedded, so just get the offset of as.ary
idsPtr = r.rm.Ptr(ids + libpf.Address(vms.rarray_struct.as_ary))
// Get the length from the flags
// https://github.com/ruby/ruby/blob/8836f26efa7a6deb0ef8b3f253d8d53d04d43152/include/ruby/internal/core/rarray.h#L240-L242
idsLen = uint64((flags & RARRAY_EMBED_LEN_MASK) >> RARRAY_EMBED_LEN_SHIFT)
} else {
dataBytes := make([]byte, vms.rarray_struct.size_of_rarray)
if err := r.rm.Read(ids, dataBytes); err != nil {
return libpf.NullString, fmt.Errorf("failed to id table heap rarray data, %v", err)
}
idsPtr = npsr.Ptr(dataBytes, uint(vms.rarray_struct.as_heap_ptr))
idsLen = npsr.Uint64(dataBytes, uint(vms.rarray_struct.as_ary))
}
if idx > idsLen {
return libpf.NullString, fmt.Errorf("invalid idx %d, number of ids %d", idx, idsLen)
}
array := r.rm.Ptr(idsPtr + libpf.Address(idx*uint64(vms.size_of_value)))
arrayPtr := r.rm.Ptr(array + libpf.Address(vms.rarray_struct.as_heap_ptr))
flags = r.rm.Uint64(array + +libpf.Address(vms.rbasic_struct.flags))
if (flags & RARRAY_EMBED_FLAG) > 0 {
log.Debugf("Handling embedded array (2 levels) with shift")
arrayPtr = r.rm.Ptr(array + libpf.Address(vms.rarray_struct.as_ary))
}
offset := (serial % idEntryUnit) * idEntrySize
stringPtr := r.rm.Ptr(arrayPtr + libpf.Address(offset*uint64(vms.size_of_value)))
symbolName, err = r.getStringCached(stringPtr, r.readRubyString)
if err != nil {
log.Errorf("Unable to read string %v", err)
}
return symbolName, err
}
func (r *rubyInstance) readIseqBody(iseqBody, pc libpf.Address, frameAddrType uint8) (*rubyIseq, error) {
vms := &r.r.vmStructs
// Read contiguous pointer values into a buffer to be more efficient
dataBytes := make([]byte, vms.iseq_location_struct.size_of_iseq_location_struct)