This repository was archived by the owner on Oct 12, 2022. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 420
/
Copy pathdwarf.d
1099 lines (949 loc) · 34.7 KB
/
dwarf.d
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
/**
* Generates a human-readable stack-trace on POSIX targets using DWARF
*
* The common use case for printing a stack trace is when `toString` is called
* on a `Throwable` (see `object.d`). It will iterate on what is likely to be
* the default trace handler (see `core.runtime : defaultTraceHandler`).
* The class returned by `defaultTraceHandler` is what ends up calling into
* this module, through the use of `core.internal.traits : externDFunc`.
*
* The entry point of this module is `traceHandlerOpApplyImpl`,
* and the only really "public" symbol (since all `rt` symbols are private).
* In the future, this implementation should probably be made idiomatic,
* so that it can for example work with attributes.
*
* Resilience:
* As this module is used for diagnostic, it should handle failures
* as gracefully as possible. Having the runtime error out on printing
* the stack trace one is trying to debug would be quite a terrible UX.
* For this reason, this module works on a "best effort" basis and will
* sometimes print mangled symbols, or "???" when it cannot do anything
* more useful.
*
* Source_of_data:
* This module uses two main sources for generating human-readable data.
* First, it uses `backtrace_symbols` to obtain the name of the symbols
* (functions or methods) associated with the addresses.
* Since the names are mangled, it will also call into `core.demangle`,
* and doesn't need to use any DWARF information for this,
* however a future extension could make use of the call frame information
* (See DWARF4 "6.4 Call Frame Information", PDF page 126).
*
* The other piece of data used is the DWARF `.debug_line` section,
* which contains the line informations of a program, necessary to associate
* the instruction address with its (file, line) information.
*
* Since debug lines informations are quite large, they are encoded using a
* program that is to be fed to a finite state machine.
* See `runStateMachine` and `readLineNumberProgram` for more details.
*
* DWARF_Version:
* This module only supports DWARF 3, 4 and 5.
*
* Reference: http://www.dwarfstd.org/
* Copyright: Copyright Digital Mars 2015 - 2015.
* License: $(HTTP www.boost.org/LICENSE_1_0.txt, Boost License 1.0).
* Authors: Yazan Dabain, Sean Kelly
* Source: $(DRUNTIMESRC rt/backtrace/dwarf.d)
*/
module core.internal.backtrace.dwarf;
import core.internal.execinfo;
import core.internal.string;
version (Posix):
version (OSX)
version = Darwin;
else version (iOS)
version = Darwin;
else version (TVOS)
version = Darwin;
else version (WatchOS)
version = Darwin;
version (Darwin)
import core.internal.backtrace.macho;
else
import core.internal.backtrace.elf;
import core.internal.container.array;
import core.stdc.string : strlen, memcpy;
//debug = DwarfDebugMachine;
debug(DwarfDebugMachine) import core.stdc.stdio : printf;
struct Location
{
/**
* Address of the instruction for which this location is for.
*/
const(void)* address;
/**
* The name of the procedure, or function, this address is in.
*/
const(char)[] procedure;
/**
* Path to the file this location references, relative to `directory`
*
* Note that depending on implementation, this could be just a name,
* a relative path, or an absolute path.
*
* If no debug info is present, this may be `null`.
*/
const(char)[] file;
/**
* Directory where `file` resides
*
* This may be `null`, either if there is no debug info,
* or if the compiler implementation doesn't use this feature (e.g. DMD).
*/
const(char)[] directory;
/**
* Line within the file that correspond to this `location`.
*
* Note that in addition to a positive value, the values `0` and `-1`
* are to be expected by consumers. A value of `0` means that the code
* is not attributable to a specific line in the file, e.g. module-specific
* generated code, and `-1` means that no debug info could be found.
*/
int line = -1;
/// Format this location into a human-readable string
void toString (scope void delegate(scope const char[]) sink) const
{
import core.demangle;
// If there's no file information, there shouldn't be any directory
// information. If there is we will simply ignore it.
if (this.file.length)
{
// Note: Sink needs to handle empty data
sink(this.directory);
// Only POSIX path because this module is not used on Windows
if (this.directory.length && this.directory[$ - 1] != '/')
sink("/");
sink(this.file);
}
else
// Most likely, no debug information
sink("??");
// Also no debug infos
if (this.line < 0)
sink(":?");
// Line can be 0, e.g. if the frame is in generated code
else if (this.line)
{
sink(":");
sink(signedToTempString(this.line));
}
char[1024] symbolBuffer = void;
// When execinfo style is used, procedure can be null if the format
// of the line cannot be read, but it generally should not happen
if (this.procedure.length)
{
sink(" ");
sink(demangle(this.procedure, symbolBuffer));
}
sink(" [0x");
sink(unsignedToTempString!16(cast(size_t) this.address));
sink("]");
}
}
int traceHandlerOpApplyImpl(size_t numFrames,
scope const(void)* delegate(size_t) getNthAddress,
scope const(char)[] delegate(size_t) getNthFuncName,
scope int delegate(ref size_t, ref const(char[])) dg)
{
auto image = Image.openSelf();
Array!Location locations;
locations.length = numFrames;
size_t startIdx;
foreach (idx; 0 .. numFrames)
{
locations[idx].address = getNthAddress(idx);
locations[idx].procedure = getNthFuncName(idx);
// NOTE: The first few frames with the current implementation are
// inside core.runtime and the object code, so eliminate
// these for readability.
// They also might depend on build parameters, which would make
// using a fixed number of frames otherwise brittle.
version (LDC) enum BaseExceptionFunctionName = "_d_throw_exception";
else enum BaseExceptionFunctionName = "_d_throwdwarf";
if (!startIdx && locations[idx].procedure == BaseExceptionFunctionName)
startIdx = idx + 1;
}
if (!image.isValid())
return locations[startIdx .. $].processCallstack(null, image.baseAddress, dg);
// find address -> file, line mapping using dwarf debug_line
return image.processDebugLineSectionData(
(line) => locations[startIdx .. $].processCallstack(line, image.baseAddress, dg));
}
struct TraceInfoBuffer
{
private char[1536] buf = void;
private size_t position;
// BUG: https://issues.dlang.org/show_bug.cgi?id=21285
@safe pure nothrow @nogc
{
///
inout(char)[] opSlice() inout return
{
return this.buf[0 .. this.position > $ ? $ : this.position];
}
///
void reset()
{
this.position = 0;
}
}
/// Used as `sink` argument to `Location.toString`
void put(scope const char[] data)
{
// We cannot write anymore
if (this.position > this.buf.length)
return;
if (this.position + data.length > this.buf.length)
{
this.buf[this.position .. $] = data[0 .. this.buf.length - this.position];
this.buf[$ - 3 .. $] = "...";
// +1 is a marker for the '...', otherwise if the symbol
// name was to exactly fill the buffer,
// we'd discard anything else without printing the '...'.
this.position = this.buf.length + 1;
return;
}
this.buf[this.position .. this.position + data.length] = data;
this.position += data.length;
}
}
private:
int processCallstack(Location[] locations, const(ubyte)[] debugLineSectionData,
size_t baseAddress, scope int delegate(ref size_t, ref const(char[])) dg)
{
if (debugLineSectionData)
resolveAddresses(debugLineSectionData, locations, baseAddress);
TraceInfoBuffer buffer;
foreach (idx, const ref loc; locations)
{
buffer.reset();
loc.toString(&buffer.put);
auto lvalue = buffer[];
if (auto ret = dg(idx, lvalue))
return ret;
if (loc.procedure == "_Dmain")
break;
}
return 0;
}
/**
* Resolve the addresses of `locations` using `debugLineSectionData`
*
* Runs the DWARF state machine on `debugLineSectionData`,
* assuming it represents a debugging program describing the addresses
* in a continous and increasing manner.
*
* After this function successfully completes, `locations` will contains
* file / lines informations.
*
* Note that the lifetime of the `Location` data is bound to the lifetime
* of `debugLineSectionData`.
*
* Params:
* debugLineSectionData = A DWARF program to feed the state machine
* locations = The locations to resolve
* baseAddress = The offset to apply to every address
*/
void resolveAddresses(const(ubyte)[] debugLineSectionData, Location[] locations, size_t baseAddress) @nogc nothrow
{
debug(DwarfDebugMachine) import core.stdc.stdio;
size_t numberOfLocationsFound = 0;
const(ubyte)[] dbg = debugLineSectionData;
while (dbg.length > 0)
{
debug(DwarfDebugMachine) printf("new debug program\n");
const lp = readLineNumberProgram(dbg);
LocationInfo lastLoc = LocationInfo(-1, -1);
const(void)* lastAddress;
debug(DwarfDebugMachine) printf("program:\n");
runStateMachine(lp,
(const(void)* address, LocationInfo locInfo, bool isEndSequence)
{
// adjust to ASLR offset
address += baseAddress;
debug (DwarfDebugMachine)
printf("-- offsetting %p to %p\n", address - baseAddress, address);
foreach (ref loc; locations)
{
// If loc.line != -1, then it has been set previously.
// Some implementations (eg. dmd) write an address to
// the debug data multiple times, but so far I have found
// that the first occurrence to be the correct one.
if (loc.line != -1)
continue;
// Can be called with either `locInfo` or `lastLoc`
void update(const ref LocationInfo match)
{
const sourceFile = lp.sourceFiles[match.file - 1];
debug (DwarfDebugMachine)
{
printf("-- found for [%p]:\n", loc.address);
printf("-- file: %.*s\n",
cast(int) sourceFile.file.length, sourceFile.file.ptr);
printf("-- line: %d\n", match.line);
}
// DMD emits entries with FQN, but other implmentations
// (e.g. LDC) make use of directories
// See https://github.com/dlang/druntime/pull/2945
if (sourceFile.dirIndex != 0)
loc.directory = lp.includeDirectories[sourceFile.dirIndex - 1];
loc.file = sourceFile.file;
loc.line = match.line;
numberOfLocationsFound++;
}
// The state machine will not contain an entry for each
// address, as consecutive addresses with the same file/line
// are merged together to save on space, so we need to
// check if our address is within two addresses we get
// called with.
//
// Specs (DWARF v4, Section 6.2, PDF p.109) says:
// "We shrink it with two techniques. First, we delete from
// the matrix each row whose file, line, source column and
// discriminator information is identical with that of its
// predecessors.
if (loc.address == address)
update(locInfo);
else if (lastAddress &&
loc.address > lastAddress && loc.address < address)
update(lastLoc);
}
if (isEndSequence)
{
lastAddress = null;
}
else
{
lastAddress = address;
lastLoc = locInfo;
}
return numberOfLocationsFound < locations.length;
}
);
if (numberOfLocationsFound == locations.length) return;
}
}
/**
* A callback type for `runStateMachine`
*
* The callback is called when certain specific opcode are encountered
* (a.k.a when a complete `LocationInfo` is encountered).
* See `runStateMachine` implementation and the DWARF specs for more detail.
*
* Params:
* address = The address that the `LocationInfo` describes
* info = The `LocationInfo` itself, describing `address`
* isEndSequence = Whether the end of a sequence has been reached
*/
alias RunStateMachineCallback =
bool delegate(const(void)* address, LocationInfo info, bool isEndSequence)
@nogc nothrow;
/**
* Run the state machine to generate line number matrix
*
* Line number informations generated by the compiler are stored in the
* `.debug_line` section. Conceptually, they can be seen as a large matrix,
* with row such as "file", "line", "column", "is_statement", etc...
* However such a matrix would be too big to store in an object file,
* so DWARF instead generate this matrix using bytecode fed to a state machine.
*
* Note:
* Each compilation unit can have its own line number program.
*
* See_Also:
* - DWARF v4, Section 6.2: Line Number Information
*
* Params:
* lp = Program to execute
* callback = Delegate to call whenever a LocationInfo is completed
*
* Returns:
* `false` if an error happened (e.g. unknown opcode)
*/
bool runStateMachine(ref const(LineNumberProgram) lp, scope RunStateMachineCallback callback) @nogc nothrow
{
StateMachine machine;
machine.isStatement = lp.defaultIsStatement;
const(ubyte)[] program = lp.program;
while (program.length > 0)
{
size_t advanceAddressAndOpIndex(size_t operationAdvance)
{
const addressIncrement = lp.minimumInstructionLength * ((machine.operationIndex + operationAdvance) / lp.maximumOperationsPerInstruction);
machine.address += addressIncrement;
machine.operationIndex = (machine.operationIndex + operationAdvance) % lp.maximumOperationsPerInstruction;
return addressIncrement;
}
ubyte opcode = program.read!ubyte();
if (opcode < lp.opcodeBase)
{
switch (opcode) with (StandardOpcode)
{
case extendedOp:
size_t len = cast(size_t) program.readULEB128();
ubyte eopcode = program.read!ubyte();
switch (eopcode) with (ExtendedOpcode)
{
case endSequence:
machine.isEndSequence = true;
debug(DwarfDebugMachine) printf("endSequence %p\n", machine.address);
if (!callback(machine.address, LocationInfo(machine.fileIndex, machine.line), true)) return true;
machine = StateMachine.init;
machine.isStatement = lp.defaultIsStatement;
break;
case setAddress:
const address = program.read!(void*)();
debug(DwarfDebugMachine) printf("setAddress %p\n", address);
machine.address = address;
machine.operationIndex = 0;
break;
case defineFile: // TODO: add proper implementation
debug(DwarfDebugMachine) printf("defineFile\n");
program = program[len - 1 .. $];
break;
case setDiscriminator:
const discriminator = cast(uint) program.readULEB128();
debug(DwarfDebugMachine) printf("setDiscriminator %d\n", discriminator);
machine.discriminator = discriminator;
break;
default:
// unknown opcode
debug(DwarfDebugMachine) printf("unknown extended opcode %d\n", cast(int) eopcode);
program = program[len - 1 .. $];
break;
}
break;
case copy:
debug(DwarfDebugMachine) printf("copy %p\n", machine.address);
if (!callback(machine.address, LocationInfo(machine.fileIndex, machine.line), false)) return true;
machine.isBasicBlock = false;
machine.isPrologueEnd = false;
machine.isEpilogueBegin = false;
machine.discriminator = 0;
break;
case advancePC:
const operationAdvance = cast(size_t) readULEB128(program);
advanceAddressAndOpIndex(operationAdvance);
debug(DwarfDebugMachine) printf("advancePC %d to %p\n", cast(int) operationAdvance, machine.address);
break;
case advanceLine:
long ad = readSLEB128(program);
machine.line += ad;
debug(DwarfDebugMachine) printf("advanceLine %d to %d\n", cast(int) ad, cast(int) machine.line);
break;
case setFile:
uint index = cast(uint) readULEB128(program);
debug(DwarfDebugMachine) printf("setFile to %d\n", cast(int) index);
machine.fileIndex = index;
break;
case setColumn:
uint col = cast(uint) readULEB128(program);
debug(DwarfDebugMachine) printf("setColumn %d\n", cast(int) col);
machine.column = col;
break;
case negateStatement:
debug(DwarfDebugMachine) printf("negateStatement\n");
machine.isStatement = !machine.isStatement;
break;
case setBasicBlock:
debug(DwarfDebugMachine) printf("setBasicBlock\n");
machine.isBasicBlock = true;
break;
case constAddPC:
const operationAdvance = (255 - lp.opcodeBase) / lp.lineRange;
advanceAddressAndOpIndex(operationAdvance);
debug(DwarfDebugMachine) printf("constAddPC %p\n", machine.address);
break;
case fixedAdvancePC:
const add = program.read!ushort();
machine.address += add;
machine.operationIndex = 0;
debug(DwarfDebugMachine) printf("fixedAdvancePC %d to %p\n", cast(int) add, machine.address);
break;
case setPrologueEnd:
machine.isPrologueEnd = true;
debug(DwarfDebugMachine) printf("setPrologueEnd\n");
break;
case setEpilogueBegin:
machine.isEpilogueBegin = true;
debug(DwarfDebugMachine) printf("setEpilogueBegin\n");
break;
case setISA:
machine.isa = cast(uint) readULEB128(program);
debug(DwarfDebugMachine) printf("setISA %d\n", cast(int) machine.isa);
break;
default:
debug(DwarfDebugMachine) printf("unknown opcode %d\n", cast(int) opcode);
return false;
}
}
else
{
opcode -= lp.opcodeBase;
const operationAdvance = opcode / lp.lineRange;
const addressIncrement = advanceAddressAndOpIndex(operationAdvance);
const lineIncrement = lp.lineBase + (opcode % lp.lineRange);
machine.line += lineIncrement;
debug (DwarfDebugMachine)
printf("special %d %d to %p line %d\n", cast(int) addressIncrement,
cast(int) lineIncrement, machine.address, machine.line);
if (!callback(machine.address, LocationInfo(machine.fileIndex, machine.line), false)) return true;
machine.isBasicBlock = false;
machine.isPrologueEnd = false;
machine.isEpilogueBegin = false;
machine.discriminator = 0;
}
}
return true;
}
T read(T)(ref const(ubyte)[] buffer) @nogc nothrow
{
version (X86) enum hasUnalignedLoads = true;
else version (X86_64) enum hasUnalignedLoads = true;
else enum hasUnalignedLoads = false;
static if (hasUnalignedLoads || T.alignof == 1)
{
T result = *(cast(T*) buffer.ptr);
}
else
{
T result = void;
memcpy(&result, buffer.ptr, T.sizeof);
}
buffer = buffer[T.sizeof .. $];
return result;
}
/**
* Reads an ULEB128 length and then reads the followings bytes specified by the
* length.
*
* Params:
* buffer = buffer where the data is read from
* Returns:
* Value contained in the block.
*/
ulong readBlock(ref const(ubyte)[] buffer) @nogc nothrow
{
ulong length = buffer.readULEB128();
assert(length <= ulong.sizeof);
ulong block;
foreach (i; 0 .. length)
{
ubyte b = buffer.read!ubyte;
block <<= 8 * i;
block |= b;
}
return block;
}
/**
* Reads a MD5 hash from the `buffer`.
*
* Params:
* buffer = buffer where the data is read from
* Returns:
* A MD5 hash
*/
char[16] readMD5(ref const(ubyte)[] buffer) @nogc nothrow
{
assert(buffer.length >= 16);
ubyte[16] bytes;
foreach (h; 0 .. 16)
bytes[h] = buffer.read!ubyte;
return cast(char[16])bytes;
}
/**
* Reads a null-terminated string from `buffer`.
* The string is not removed from buffer and doesn't contain the last null byte.
*
* Params:
* buffer = buffer where the data is read from
*
* Returns:
* A string
*/
const(char)[] readString(ref const(ubyte)[] buffer) @nogc nothrow
{
import core.sys.posix.string : strnlen;
return cast(const(char)[])buffer[0 .. strnlen(cast(char*)buffer.ptr, buffer.length)];
}
unittest
{
const(ubyte)[] data = [0x48, 0x61, 0x76, 0x65, 0x20, 0x61, 0x20, 0x67, 0x6f,
0x6f, 0x64, 0x20, 0x64, 0x61, 0x79, 0x20, 0x21, 0x00];
const(char)[] result = data.readString();
assert(result == "Have a good day !");
data = [0x00];
assert(data.readString == null);
}
ulong readULEB128(ref const(ubyte)[] buffer) @nogc nothrow
{
ulong val = 0;
uint shift = 0;
while (true)
{
ubyte b = buffer.read!ubyte();
val |= (b & 0x7f) << shift;
if ((b & 0x80) == 0) break;
shift += 7;
}
return val;
}
unittest
{
const(ubyte)[] data = [0xe5, 0x8e, 0x26, 0xDE, 0xAD, 0xBE, 0xEF];
assert(readULEB128(data) == 624_485);
assert(data[] == [0xDE, 0xAD, 0xBE, 0xEF]);
}
long readSLEB128(ref const(ubyte)[] buffer) @nogc nothrow
{
long val = 0;
uint shift = 0;
int size = 8 << 3;
ubyte b;
while (true)
{
b = buffer.read!ubyte();
val |= (b & 0x7f) << shift;
shift += 7;
if ((b & 0x80) == 0)
break;
}
if (shift < size && (b & 0x40) != 0)
val |= -(1 << shift);
return val;
}
Array!EntryFormatData readEntryFormat(ref const(ubyte)[] buffer, ref Array!ulong entryFormat) @nogc nothrow
{
// The count needs to be pair, as the specification says
assert(entryFormat.length % 2 == 0);
Array!EntryFormatData result;
for (uint i = 0; i < entryFormat.length; i += 2)
{
EntryFormatData efdata;
ulong form = entryFormat[i + 1];
switch (entryFormat[i])
{
case StandardContentDescription.path:
if (form == FormEncoding._string)
efdata.path = buffer.readString();
else
{
size_t offset = buffer.read!size_t;
// TODO: set filename.path to the string at offset
static if (0)
{
if (form == FormEncoding.line_strp) // Offset in debug_line_str
{
}
else if (form == FormEncoding.strp) // Offset in debug_str
{
}
else if (form == FormEncoding.strp_sup) // Offset of debug_str in debug_info
{
}
else
assert(0);
}
else
assert(0);
}
break;
case StandardContentDescription.directoryIndex:
if (form == FormEncoding.data1)
efdata.directoryIndex = cast(ulong)buffer.read!ubyte;
else if (form == FormEncoding.data2)
efdata.directoryIndex = cast(ulong)buffer.read!ushort;
else if (form == FormEncoding.udata)
efdata.directoryIndex = buffer.readULEB128();
else
assert(0);
break;
case StandardContentDescription.timeStamp:
if (form == FormEncoding.udata)
efdata.timeStamp = buffer.readULEB128();
else if (form == FormEncoding.data4)
efdata.timeStamp = cast(ulong)buffer.read!uint;
else if (form == FormEncoding.data8)
efdata.timeStamp = buffer.read!ulong;
else if (form == FormEncoding.block)
efdata.timeStamp = buffer.readBlock();
else
assert(0);
break;
case StandardContentDescription.size:
if (form == FormEncoding.data1)
efdata.size = cast(ulong)buffer.read!ubyte;
else if (form == FormEncoding.data2)
efdata.size = cast(ulong)buffer.read!ushort;
else if (form == FormEncoding.data4)
efdata.size = cast(ulong)buffer.read!uint;
else if (form == FormEncoding.data8)
efdata.size = buffer.read!ulong;
else
assert(0);
break;
case StandardContentDescription.md5:
if (form == FormEncoding.data16)
efdata.md5 = buffer.readMD5();
else
assert(0);
break;
default:
assert(0);
}
result.insertBack(efdata);
}
return result;
}
enum FormEncoding : ubyte
{
addr = 1,
block2 = 3,
block4 = 4,
data2 = 5,
data4 = 6,
data8 = 7,
_string = 8,
block = 9,
block1 = 10,
data1 = 11,
flag = 12,
sdata = 13,
strp = 14,
udata = 15,
ref_addr = 16,
ref1 = 17,
ref2 = 18,
ref4 = 19,
ref8 = 20,
ref_udata = 21,
indirect = 22,
sec_offset = 23,
exprloc = 24,
flag_present = 25,
strx = 26,
addrx = 27,
ref_sup4 = 28,
strp_sup = 29,
data16 = 30,
line_strp = 31,
ref_sig8 = 32,
implicit_const = 33,
loclistx = 34,
rnglistx = 35,
ref_sup8 = 36,
strx1 = 37,
strx2 = 38,
strx3 = 39,
strx4 = 40,
addrx1 = 41,
addrx2 = 42,
addrx3 = 43,
addrx4 = 44,
}
enum StandardOpcode : ubyte
{
extendedOp = 0,
copy = 1,
advancePC = 2,
advanceLine = 3,
setFile = 4,
setColumn = 5,
negateStatement = 6,
setBasicBlock = 7,
constAddPC = 8,
fixedAdvancePC = 9,
setPrologueEnd = 10,
setEpilogueBegin = 11,
setISA = 12,
}
enum ExtendedOpcode : ubyte
{
endSequence = 1,
setAddress = 2,
defineFile = 3,
setDiscriminator = 4,
}
enum StandardContentDescription : ubyte
{
path = 1,
directoryIndex = 2,
timeStamp = 3,
size = 4,
md5 = 5,
}
struct EntryFormatData
{
const(char)[] path;
ulong directoryIndex;
ulong timeStamp;
ulong size;
char[16] md5;
}
struct StateMachine
{
const(void)* address;
uint operationIndex = 0;
uint fileIndex = 1;
uint line = 1;
uint column = 0;
uint isa = 0;
uint discriminator = 0;
bool isStatement;
bool isBasicBlock = false;
bool isEndSequence = false;
bool isPrologueEnd = false;
bool isEpilogueBegin = false;
}
struct LocationInfo
{
int file;
int line;
}
struct LineNumberProgram
{
ulong unitLength;
ushort dwarfVersion;
ubyte addressSize;
ubyte segmentSelectorSize;
ulong headerLength;
ubyte minimumInstructionLength;
ubyte maximumOperationsPerInstruction;
bool defaultIsStatement;
byte lineBase;
ubyte lineRange;
ubyte opcodeBase;
const(ubyte)[] standardOpcodeLengths;
ubyte directoryEntryFormatCount;
Array!ulong directoryEntryFormat;
ulong directoriesCount;
Array!EntryFormatData directories;
ubyte fileNameEntryFormatCount;
Array!ulong fileNameEntryFormat;
ulong fileNamesCount;
Array!EntryFormatData fileNames;
Array!(const(char)[]) includeDirectories;
Array!SourceFile sourceFiles;
const(ubyte)[] program;
}
struct SourceFile
{
const(char)[] file;
size_t dirIndex;
}
LineNumberProgram readLineNumberProgram(ref const(ubyte)[] data) @nogc nothrow
{
const originalData = data;
LineNumberProgram lp;
bool is64bitDwarf = false;
lp.unitLength = data.read!uint();
if (lp.unitLength == uint.max)
{
is64bitDwarf = true;
lp.unitLength = data.read!ulong();
}
const dwarfVersionFieldOffset = cast(size_t) (data.ptr - originalData.ptr);
lp.dwarfVersion = data.read!ushort();
assert(lp.dwarfVersion < 6, "DWARF v6+ not supported yet");
if (lp.dwarfVersion >= 5)
{
lp.addressSize = data.read!ubyte();
lp.segmentSelectorSize = data.read!ubyte();
}
lp.headerLength = (is64bitDwarf ? data.read!ulong() : data.read!uint());
const minimumInstructionLengthFieldOffset = cast(size_t) (data.ptr - originalData.ptr);
lp.minimumInstructionLength = data.read!ubyte();
lp.maximumOperationsPerInstruction = (lp.dwarfVersion >= 4 ? data.read!ubyte() : 1);
lp.defaultIsStatement = (data.read!ubyte() != 0);
lp.lineBase = data.read!byte();
lp.lineRange = data.read!ubyte();
lp.opcodeBase = data.read!ubyte();
lp.standardOpcodeLengths = data[0 .. lp.opcodeBase - 1];
data = data[lp.opcodeBase - 1 .. $];
if (lp.dwarfVersion >= 5)
{
lp.directoryEntryFormatCount = data.read!ubyte();
foreach (c; 0 .. lp.directoryEntryFormatCount)
lp.directoryEntryFormat.insertBack(data.readULEB128());
lp.directoriesCount = data.readULEB128();