Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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

# Copyright (C) 2017 Free Software Foundation, Inc. 

 

# This program is free software; you can redistribute it and/or modify 

# it under the terms of the GNU General Public License as published by 

# the Free Software Foundation; either version 3 of the License, or 

# (at your option) any later version. 

# 

# This program is distributed in the hope that it will be useful, 

# but WITHOUT ANY WARRANTY; without even the implied warranty of 

# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

# GNU General Public License for more details. 

# 

# You should have received a copy of the GNU General Public License 

# along with GCC; see the file COPYING3. If not see 

# <http://www.gnu.org/licenses/>. 

 

# Data structures to represent DWARF compilation units, DIEs and attributes, 

# and helpers to perform various checks on them. 

 

from testutils import check 

 

 

class Abbrev(object): 

"""DWARF abbreviation entry.""" 

 

def __init__(self, number, tag, has_children, attributes=[]): 

""" 

:param int number: Abbreviation number, which is 1-based, as in the 

DWARF standard. 

:param str|int tag: Tag name or, if unknown, tag number. 

:param bool has_children: Whether DIEs will have children. 

:param list[(str|int, str)] attributes: List of attributes. 

""" 

self.number = number 

self.tag = tag 

self.has_children = has_children 

self.attributes = list(attributes) 

 

def add_attribute(self, name, form): 

""" 

:param str|int name: Attribute name or, if unknown, attribute number. 

:param str form: Form for this attribute. 

""" 

self.attributes.append((name, form)) 

 

def __repr__(self): 

return '<Abbrev #{0} {1}>'.format(self.number, self.tag) 

 

 

class CompilationUnit(object): 

"""DWARF compilation unit.""" 

 

def __init__(self, offset, length, is_32bit, version, abbrevs, 

pointer_size): 

""" 

:param int offset: Offset of this compilation unit in the .debug_info 

section. 

:param int length: Value of the length field for this compilation unit. 

:param bool is_32bit: Whether this compilation unit is encoded in the 

32-bit format. If not, it must be the 64-bit one. 

:param int version: DWARF version used by this compilation unit. 

:param list[Abbrev] abbrevs: List of abbreviations for this compilation 

unit. 

:param int pointer_size: Size of pointers for this architecture. 

""" 

self.offset = offset 

self.length = length 

self.is_32bit = is_32bit 

self.version = version 

self.abbrevs = abbrevs 

self.pointer_size = pointer_size 

 

self.root = None 

self.offset_to_die = {} 

 

def set_root(self, die): 

assert self.root is None, ('Trying to create the root DIE of a' 

' compilation unit that already has one') 

self.root = die 

 

def get(self, offset): 

""" 

Fetch the DIE that starts at the given offset. Raise a KeyError if not 

found. 

 

:param int offset: DIE offset in this compilation unit. 

:rtype: DIE 

""" 

return self.offset_to_die[offset] 

 

def find(self, *args, **kwargs): 

return self.root.find(*args, **kwargs) 

 

def __repr__(self): 

return '<CompilationUnit at {0:#0x}>'.format(self.offset) 

 

 

class DIE(object): 

"""DWARF information entry.""" 

 

def __init__(self, cu, level, offset, abbrev_number): 

""" 

:param CompilationUnit cu: Compilation unit this DIE belongs to. 

:param int level: Depth for this DIE. 

:param int offset: Offset of this DIE in the .debug_info section. 

:param int abbrev_number: Abbreviation number for this DIE. 

""" 

self.cu = cu 

self.cu.offset_to_die[offset] = self 

 

self.level = level 

self.offset = offset 

self.abbrev_number = abbrev_number 

 

self.parent = None 

self.attributes = [] 

self.children = [] 

 

@property 

def abbrev(self): 

"""Abbreviation for this DIE. 

 

:rtype: Abbrev 

""" 

# The abbreviation number is 1-based, but list indexes are 0-based 

return self.cu.abbrevs[self.abbrev_number - 1] 

 

@property 

def tag(self): 

"""Tag for this DIE. 

 

:rtype: str|int 

""" 

return self.abbrev.tag 

 

@property 

def has_children(self): 

return self.abbrev.has_children 

 

def get_attr(self, name, single=True, or_error=True): 

"""Look for an attribute in this DIE. 

 

:param str|int name: Attribute name, or number if name is unknown. 

:param bool single: If true, this will raise a KeyError for 

zero/multiple matches and return an Attribute instance when found. 

Otherwise, return a potentially empty list of attributes. 

:param bool or_error: When true, if `single` is true and no attribute 

is found, return None instead of raising a KeyError. 

:rtype: Attribute|list[Attribute] 

""" 

result = [a for a in self.attributes if a.name == name] 

 

if single: 

if not result: 

if or_error: 

raise KeyError('No {0} attribute in {1}'.format(name, 

self)) 

else: 

return None 

if len(result) > 1: 

raise KeyError('Multiple {0} attributes in {1}'.format(name, 

self)) 

return result[0] 

else: 

return result 

 

def check_attr(self, name, value): 

"""Check for the presence/value of an attribute. 

 

:param str|int name: Attribute name, or number if name is unknown. 

:param value: If None, check that the attribute is not present. 

Otherwise, check that the attribute exists and that its value 

matches `value`. 

""" 

m = MatchResult() 

Matcher._match_attr(self, name, value, m) 

check( 

m.succeeded, 

m.mismatch_reason or 'check attribute {0} of {1}'.format(name, 

self) 

) 

 

def get_child(self, child_index): 

"""Get a DIE child. 

 

:param int child_index: Index of the child to fetch (zero-based index). 

:rtype: DIE 

""" 

return self.children[child_index] 

 

@property 

def name(self): 

"""Return the name (DW_AT_name) for this DIE, if any. 

 

:rtype: str|None 

""" 

name = self.get_attr('DW_AT_name', or_error=False) 

return name.value if name is not None else None 

 

def __str__(self): 

tag = (self.tag if isinstance(self.tag, str) else 

'DIE {0}'.format(self.tag)) 

name = self.name 

fmt = '{tag} "{name}"' if name else '{tag}' 

return fmt.format(tag=tag, name=name) 

 

def __repr__(self): 

return '<{0} at {1:#x}>'.format(self, self.offset) 

 

def matches(self, tag=None, name=None): 

"""Return whether this DIE matches expectations. 

 

:rtype: bool 

""" 

return ((tag is None or self.tag == tag) and 

(name is None or self.name == name)) 

 

def tree_matches(self, matcher): 

"""Match this DIE against the given match object. 

 

:param Matcher matcher: Match object used to check the structure of 

this DIE. 

:rtype: MatchResult 

""" 

return matcher.matches(self) 

 

def tree_check(self, matcher): 

"""Like `tree_matches`, but also check that the DIE matches.""" 

m = self.tree_matches(matcher) 

check( 

m.succeeded, 

m.mismatch_reason or 'check structure of {0}'.format(self) 

) 

return m 

 

def find(self, predicate=None, tag=None, name=None, recursive=True, 

single=True): 

"""Look for a DIE that satisfies the given expectations. 

 

:param None|(DIE) -> bool predicate: If provided, function that filters 

out DIEs when it returns false. 

:param str|int|None tag: If provided, filter out DIEs whose tag does 

not match. 

:param str|None name: If provided, filter out DIEs whose name (see 

the `name` property) does not match. 

:param bool recursive: If true, perform the search recursively in 

self's children. 

:param bool single: If true, look for a single DIE and raise a 

ValueError if none or several DIEs are found. Otherwise, return a 

potentially empty list of DIEs. 

 

:rtype: DIE|list[DIE] 

""" 

def p(die): 

return (die.matches(tag, name) and 

(predicate is None or predicate(die))) 

result = self._find(p, recursive) 

 

if single: 

if not result: 

raise ValueError('No matching DIE found') 

if len(result) > 1: 

raise ValueError('Multiple matching DIEs found') 

return result[0] 

else: 

return result 

 

def _find(self, predicate, recursive): 

result = [] 

 

if predicate(self): 

result.append(self) 

 

for c in self.children: 

if not recursive: 

if predicate(c): 

result.append(c) 

else: 

result.extend(c._find(predicate, recursive)) 

 

return result 

 

def next_attribute_form(self, name): 

"""Return the form of the next attribute this DIE requires. 

 

Used during DIE tree construction. 

 

:param str name: Expected name for this attribute. The abbreviation 

will confirm it. 

:rtype: str 

""" 

assert len(self.attributes) < len(self.abbrev.attributes) 

expected_name, form = self.abbrev.attributes[len(self.attributes)] 

assert name == expected_name, ( 

'Attribute desynchronization in {0}'.format(self) 

) 

return form 

 

def add_attribute(self, name, form, offset, value): 

"""Add an attribute to this DIE. 

 

Used during DIE tree construction. See Attribute's constructor for the 

meaning of arguments. 

""" 

self.attributes.append(Attribute(self, name, form, offset, value)) 

 

def add_child(self, child): 

"""Add a DIE child to this DIE. 

 

Used during DIE tree construction. 

 

:param DIE child: DIE to append. 

""" 

assert self.has_children 

assert child.parent is None 

child.parent = self 

self.children.append(child) 

 

 

class Attribute(object): 

"""DIE attribute.""" 

 

def __init__(self, die, name, form, offset, value): 

""" 

:param DIE die: DIE that will own this attribute. 

:param str|int name: Attribute name, or attribute number if unknown. 

:param str form: Attribute form. 

:param int offset: Offset of this attribute in the .debug_info section. 

:param value: Decoded value for this attribute. If it's a Defer 

instance, decoding will happen the first time the "value" property 

is evaluated. 

""" 

self.die = die 

self.name = name 

self.form = form 

self.offset = offset 

 

if isinstance(value, Defer): 

self._value = None 

self._value_getter = value 

else: 

self._value = value 

self._value_getter = None 

self._refine_value() 

 

@property 

def value(self): 

if self._value_getter: 

self._value = self._value_getter.get() 

self._value_getter = None 

self._refine_value() 

return self._value 

 

def _refine_value(self): 

# If we hold a location expression, bind it to this attribute 

if isinstance(self._value, Exprloc): 

self._value.attribute = self 

 

def __repr__(self): 

label = (self.name if isinstance(self.name, str) else 

'Attribute {0}'.format(self.name)) 

return '<{0} at {1:#x}>'.format(label, self.offset) 

 

 

class Exprloc(object): 

"""DWARF location expression.""" 

 

def __init__(self, byte_list, operations): 

""" 

:param list[int] byte_list: List of bytes that encode this expression. 

:param list[(str, ...)] operations: List of operations this expression 

contains. Each expression is a tuple whose first element is the 

opcode name (DW_OP_...) and whose other elements are operands. 

""" 

self.attribute = None 

self.byte_list = byte_list 

self.operations = operations 

 

@property 

def die(self): 

return self.attribute.die 

 

@staticmethod 

def format_operation(operation): 

opcode = operation[0] 

operands = operation[1:] 

387 ↛ exitline 387 didn't run the generator expression on line 387 return ('{0}: {1}'.format(opcode, ' '.join(str(o) for o in operands)) 

if operands else opcode) 

 

def matches(self, operations): 

"""Match this list of operations to `operations`. 

 

:param list[(str, ...)] operations: List of operations to match. 

:rtype: bool 

""" 

return self.operations == operations 

 

def __repr__(self): 

return '{0} ({1})'.format( 

' '.join(hex(b) for b in self.byte_list), 

'; '.join(self.format_operation(op) for op in self.operations) 

) 

 

 

class Defer(object): 

"""Helper to defer a computation.""" 

 

def __init__(self, func): 

""" 

:param () -> T func: Callback to perform the computation. 

""" 

self.func = func 

 

def get(self): 

""" 

:rtype: T 

""" 

return self.func() 

 

 

class Matcher(object): 

"""Specification for DIE tree pattern matching.""" 

 

def __init__(self, tag=None, name=None, attrs=None, children=None, 

capture=None): 

""" 

:param None|str tag: If provided, name of the tag that DIEs must match. 

:param None|str name: If provided, name that DIEs must match (see the 

DIE.name property). 

:param attrs: If provided, dictionary that specifies attribute 

expectations. Keys are attribute names. Values can be: 

 

* None, so that attribute must be undefined in the DIE; 

* a value, so that attribute must be defined and the value must 

match; 

* a Capture instance, so that the attribute value (or None, if 

undefined) is captured. 

 

:param None | list[DIE|Capture] children: If provided, list of DIEs 

that children must match. Capture instances match any DIE and 

captures it. 

 

:param str|None capture: If provided, capture the DIE to match with the 

given name. 

""" 

self.tag = tag 

self.name = name 

self.attrs = attrs 

self.children = children 

self.capture_name = capture 

 

def matches(self, die): 

"""Pattern match the given DIE. 

 

:param DIE die: DIE to match. 

:rtype: MatchResult 

""" 

result = MatchResult() 

self._match_die(die, result) 

return result 

 

def _match_die(self, die, result): 

"""Helper for the "matches" method. 

 

Return whether DIE could be matched. If not, a message to describe why 

is recorded in `result`. 

 

:param DIE die: DIE to match. 

:param MatchResult result: Holder for the result of the match. 

:rtype: bool 

""" 

 

# If asked to, check the DIE tag 

if self.tag is not None and self.tag != die.tag: 

result.mismatch_reason = '{0} is expected to be a {1}'.format( 

die, self.tag 

) 

return False 

 

# If asked to, check the DIE name 

if self.name is not None and self.name != die.name: 

result.mismatch_reason = ( 

'{0} is expected to be called "{1}"'.format(die, self.name) 

) 

return False 

 

# Check attribute expectations 

if self.attrs: 

for n, v in self.attrs.items(): 

if not self._match_attr(die, n, v, result): 

return False 

 

# Check children expectations 

if self.children is not None: 

 

# The number of children must match 

if len(self.children) != len(die.children): 

result.mismatch_reason = ( 

'{0} has {1} children, {2} expected'.format( 

die, len(die.children), len(self.children) 

) 

) 

return False 

 

# Then each child must match the corresponding child matcher 

for matcher_child, die_child in zip(self.children, 

die.children): 

# Capture instances matches anything and captures it 

if isinstance(matcher_child, Capture): 

result.dict[matcher_child.name] = die_child 

 

elif not matcher_child._match_die(die_child, result): 

return False 

 

# Capture the input DIE if asked to 

if self.capture_name: 

result.dict[self.capture_name] = die 

 

# If no check failed, the DIE matches the pattern 

return True 

 

@staticmethod 

def _match_attr(die, attr_name, attr_value, result): 

"""Helper for the "matches" method. 

 

Return whether the `attr_name` attribute in DIE matches the 

`attr_value` expectation. If not, a message to describe why is recorded 

in `result`. 

 

:param DIE die: DIE that contain the attribute to match. 

:param str attr_name: Attribute name. 

:param attr_value: Attribute expectation. See attrs's description in 

Match.__init__ docstring for possible values. 

""" 

attr = die.get_attr(attr_name, or_error=False) 

 

if attr_value is None: 

# The attribute is expected not to be defined 

if attr is None: 

return True 

 

result.mismatch_reason = ( 

'{0} has a {1} attribute, none expected'.format( 

die, attr_name 

) 

) 

return False 

 

# Capture instances matches anything and capture it 

if isinstance(attr_value, Capture): 

result.dict[attr_value.name] = attr 

return True 

 

# If we reach this point, the attribute is supposed to be defined: 

# check it is. 

if attr is None: 

result.mismatch_reason = ( 

'{0} is missing a {1} attribute'.format(die, attr_name) 

) 

return False 

 

# Check the value of the attribute matches 

if isinstance(attr.value, Exprloc): 

is_matching = attr.value.matches(attr_value) 

else: 

is_matching = attr.value == attr_value 

if not is_matching: 

result.mismatch_reason = ( 

'{0}: {1} is {2}, expected to be {3}'.format( 

die, attr_name, attr.value, attr_value 

) 

) 

return False 

 

# If no check failed, the attribute matches the pattern 

return True 

 

 

class Capture(object): 

"""Placeholder in Matcher tree patterns. 

 

This is used to capture specific elements during pattern matching. 

""" 

def __init__(self, name): 

""" 

:param str name: Capture name. 

""" 

self.name = name 

 

 

class MatchResult(object): 

"""Holder for the result of a DIE tree pattern match.""" 

 

def __init__(self): 

self.dict = {} 

 

self.mismatch_reason = None 

""" 

If left to None, the match succeeded. Otherwise, must be set to a 

string that describes why the match failed. 

 

:type: None|str 

""" 

 

@property 

def succeeded(self): 

return self.mismatch_reason is None 

 

def capture(self, name): 

"""Return what has been captured by the `name` capture. 

 

This is valid iff the match succeeded. 

 

:param str name: Capture name: 

""" 

return self.dict[name]