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
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// \file sleigh.hh
/// \brief Classes and utilities for the main SLEIGH engine
;
/// \brief Class for describing a relative p-code branch destination
///
/// An intra-instruction p-code branch takes a \e relative operand.
/// The actual value produced during p-code generation is calculated at
/// the last second using \b this. It stores the index of the BRANCH
/// instruction and a reference to its destination operand. This initially
/// holds a reference to a destination \e label symbol, but is later updated
/// with the final relative value.
;
/// \brief Data for building one p-code instruction
///
/// Raw data used by the emitter to produce a single PcodeOp
;
/// \brief Class for caching a chunk of p-code, prior to emitting
///
/// The engine accumulates PcodeData and VarnodeData objects for
/// a single instruction. Once the full instruction is constructed,
/// the objects are passed to the emitter (PcodeEmit) via the emit() method.
/// The class acts as a pool of memory for PcodeData and VarnodeData objects
/// that can be reused repeatedly to emit multiple instructions.
;
/// \brief A container for disassembly context used by the SLEIGH engine
///
/// This acts as a factor for the ParserContext objects which are used to disassemble
/// a single instruction. These all share a ContextCache which is a front end for
/// accessing the ContextDatabase and resolving context variables from the SLEIGH spec.
/// ParserContext objects are stored in a hash-table keyed by the address of the instruction.
;
/// \brief Build p-code from a pre-parsed instruction
///
/// Through the build() method, \b this walks the parse tree and prepares data
/// for final emission as p-code. (The final emitting is done separately through the
/// PcodeCacher.emit() method). Generally, only p-code for one instruction is prepared.
/// But, through the \b delay-slot mechanism, build() may recursively visit
/// additional instructions.
;
/// \brief A full SLEIGH engine
///
/// Its provided with a LoadImage of the bytes to be disassembled and
/// a ContextDatabase.
///
/// Assembly is produced via the printAssembly() method, provided with an
/// AssemblyEmit object and an Address.
///
/// P-code is produced via the oneInstruction() method, provided with a PcodeEmit
/// object and an Address.
;
/** \page sleigh SLEIGH
\section sleightoc Table of Contents
- \ref sleighoverview
- \ref sleighbuild
- \ref sleighuse
- \subpage sleighAPIbasic
- \subpage sleighAPIemulate
\b Key \b Classes
- \ref Translate
- \ref AssemblyEmit
- \ref PcodeEmit
- \ref LoadImage
- \ref ContextDatabase
\section sleighoverview Overview
Welcome to \b SLEIGH, a machine language translation and
dissassembly engine. SLEIGH is both a processor
specification language and the associated library and
tools for using such a specification to generate assembly
and to generate \b pcode, a reverse engineering Register
Transfer Language (RTL), from binary machine instructions.
SLEIGH was originally based on \b SLED, a
\e Specification \e Language \e for \e Encoding \e and
\e Decoding, designed by Norman Ramsey and Mary F. Fernandez,
which performed disassembly (and assembly). SLEIGH
extends SLED by providing semantic descriptions (via the
RTL) of machine instructions and other practical enhancements
for doing real world reverse engineering.
SLEIGH is part of Project \b GHIDRA. It provides the core
of the GHIDRA disassembler and the data-flow and
decompilation analysis. However, SLEIGH can serve as a
standalone library for use in other applications for
providing a generic disassembly and RTL translation interface.
\section sleighbuild Building SLEIGH
There are a couple of \e make targets for building the SLEIGH
library from source. These are:
\code
make libsla.a # Build the main library
make libsla_dbg.a # Build the library with debug symbols
\endcode
The source code file \e sleighexample.cc has a complete example
of initializing the Translate engine and using it to generate
assembly and pcode. The source has a hard-coded file name,
\e x86testcode, as the example binary executable it attempts
to decode, but this can easily be changed. It also needs
a SLEIGH specification file (\e .sla) to be present.
Building the example application can be done with something
similar to the following makefile fragment.
\code
# The C compiler
CXX=g++
# Debug flags
DBG_CXXFLAGS=-g -Wall -Wno-sign-compare
OPT_CXXFLAGS=-O2 -Wall -Wno-sign-compare
# libraries
INCLUDES=-I./src
LNK=src/libsla_dbg.a
sleighexample.o: sleighexample.cc
$(CXX) -c $(DBG_CXXFLAGS) -o sleighexample sleighexample.o $(LNK)
clean:
rm -rf *.o sleighexample
\endcode
\section sleighuse Using SLEIGH
SLEIGH is a generic reverse engineering tool in the sense
that the API is designed to be completely processor
independent. In order to process binary executables for a
specific processor, The library reads in a \e
specification \e file, which describes how instructions
are encoded and how they are interpreted by the processor.
An application which needs to do disassembly or generate
\b pcode can design to the SLEIGH API once, and then the
application will automatically support any processor for
which there is a specification.
For working with a single processor, the SLEIGH library
needs to load a single \e compiled form of the processor
specification, which is traditionally given a ".sla" suffix.
Most common processors already have a ".sla" file available.
So to use SLEIGH with these processors, the library merely
needs to be made aware of the desired file. This documentation
covers the use of the SLEIGH API, assuming that this
specification file is available.
The ".sla" files themselves are created by running
the \e compiler on a file written in the formal SLEIGH
language. These files traditionally have the suffix ".slaspec"
For those who want to design such a specification for a new
processor, please refer to the document, "SLEIGH: A Language
for Rapid Processor Specification."
*/
/**
\page sleighAPIbasic The Basic SLEIGH Interface
To use SLEIGH as a library within an application, there
are basically five classes that you need to be aware of.
- \ref sleightranslate
- \ref sleighassememit
- \ref sleighpcodeemit
- \ref sleighloadimage
- \ref sleighcontext
\section sleightranslate Translate (or Sleigh)
The core SLEIGH class is Sleigh, which is derived from the
interface, Translate. In order to instantiate it in your code,
you need a LoadImage object, and a ContextDatabase object.
The load image is responsible for retrieving instruction
bytes, based on address, from a binary executable. The context
database provides the library extra mode information that may
be necessary to do the disassembly or translation. This can
be used, for instance, to specify that an x86 binary is running
in 32-bit mode, or to specify that an ARM processor is running
in THUMB mode. Once these objects are built, the Sleigh
object can be immediately instantiated.
\code
LoadImageBfd *loader;
ContextDatabase *context;
Translate *trans;
// Set up the loadimage
// Providing an executable name and architecture
string loadimagename = "x86testcode";
string bfdtarget= "default";
loader = new LoadImageBfd(loadimagename,bfdtarget);
loader->open(); // Load the executable from file
context = new ContextInternal(); // Create a processor context
trans = new Sleigh(loader,context); // Instantiate the translator
\endcode
Once the Sleigh object is in hand, the only required
initialization step left is to inform it of the ".sla" file.
The file is in XML format and needs to be read in using
SLEIGH's built-in XML parser. The following code accomplishes
this.
\code
string sleighfilename = "specfiles/x86.sla";
DocumentStorage docstorage;
Element *sleighroot = docstorage.openDocument(sleighfilename)->getRoot();
docstorage.registerTag(sleighroot);
trans->initialize(docstorage); // Initialize the translator
\endcode
\section sleighassememit AssemblyEmit
In order to do disassembly, you need to derive a class from
AssemblyEmit, and implement the method \e dump. The library
will call this method exactly once, for each instruction
disassembled.
This routine simply needs to decide how (and where) to print
the corresponding portion of the disassembly. For instance,
\code
class AssemblyRaw : public AssemblyEmit {
public:
virtual void dump(const Address &addr,const string &mnem,const string &body) {
addr.printRaw(cout);
cout << ": " << mnem << ' ' << body << endl;
}
};
\endcode
This is a minimal implementation that simply dumps the
disassembly straight to standard out. Once this object is
instantiated, the Sleigh object can use it to write out
assembly via the Translate::printAssembly() method.
\code
AssemblyEmit *assememit = new AssemblyRaw();
Address addr(trans->getDefaultCodeSpace(),0x80484c0);
int4 length; // Length of instruction in bytes
length = trans->printAssembly(*assememit,addr);
addr = addr + length; // Advance to next instruction
length = trans->printAssembly(*assememit,addr);
addr = addr + length;
length = trans->printAssembly(*assememit,addr);
\endcode
\section sleighpcodeemit PcodeEmit
In order to generate a \b pcode translation of a machine
instruction, you need to derive a class from PcodeEmit and
implement the virtual method \e dump. This method will be
invoked once for each \b pcode operation in the translation
of a machine instruction. There will likely be multiple calls
per instruction. Each call passes in a single \b pcode
operation, complete with its possible varnode output, and
all of its varnode inputs. Here is an example of a PcodeEmit
object that simply prints out the \b pcode.
\code
class PcodeRawOut : public PcodeEmit {
public:
virtual void dump(const Address &addr,OpCode opc,VarnodeData *outvar,VarnodeData *vars,int4 isize);
};
static void print_vardata(ostream &s,VarnodeData &data)
{
s << '(' << data.space->getName() << ',';
data.space->printOffset(s,data.offset);
s << ',' << dec << data.size << ')';
}
void PcodeRawOut::dump(const Address &addr,OpCode opc,VarnodeData *outvar,VarnodeData *vars,int4 isize)
{
if (outvar != (VarnodeData *)0) { // The output is optional
print_vardata(cout,*outvar);
cout << " = ";
}
cout << get_opname(opc);
// Possibly check for a code reference or a space reference
for(int4 i=0;i<isize;++i) {
cout << ' ';
print_vardata(cout,vars[i]);
}
cout << endl;
}
\endcode
Notice that the \e dump routine uses the built-in function
\e get_opname to find a string version of the opcode. Each
varnode is defined in terms of the VarnodeData object, which
is defined simply:
\code
struct VarnodeData {
AddrSpace *space; // The address space
uintb offset; // The offset within the space
uint4 size; // The number of bytes at that location
};
\endcode
Once the PcodeEmit object is instantiated, the Sleigh object can
use it to generate pcode, one instruction at a time, using the
Translate::oneInstruction() const method.
\code
PcodeEmit *pcodeemit = new PcodeRawOut();
Address addr(trans->getDefaultCodeSpace(),0x80484c0);
int4 length; // Length of instruction in bytes
length = trans->oneInstruction(*pcodeemit,addr);
addr = addr + length; // Advance to next instruction
length = trans->oneInstruction(*pcodeemit,addr);
addr = addr + length;
length = trans->oneInstruction(*pcodeemit,addr);
\endcode
For an application to properly \e follow \e flow, while translating
machine instructions into pcode, the emitted pcode must be
inspected for the various branch operations.
\section sleighloadimage LoadImage
A LoadImage holds all the binary data from an executable file
in the format similar to how it would exist when being executed
by a real processor. The interface to this from SLEIGH is
actually very simple, although it can hide a complicated
structure. One method does most of the work, LoadImage::loadFill().
It takes a byte pointer, a size, and an Address. The method
is expected to fill in the \e ptr array with \e size bytes
taken from the load image, corresponding to the address \e addr.
There are two more virtual methods that are required for a
complete implementation of LoadImage, \e getArchType and
\e adjustVma, but these do not need to be implemented fully.
\code
class MyLoadImage : public LoadImage {
public:
MyLoadImage(const string &nm) : Loadimage(nm) {}
virtual void loadFill(uint1 *ptr,int4 size,const Address &addr);
virtual string getArchType(void) const { return "mytype"; }
virtual void adjustVma(long adjust) {}
};
\endcode
\section sleighcontext ContextDatabase
The ContextDatabase needs to keep track of any possible
context variable and its value, over different address ranges.
In most cases, you probably don't need to override the class
yourself, but can use the built-in class, ContextInternal.
This provides the basic functionality required and will work
for different architectures. What you may need to do is
set values for certain variables, depending on the processor
and the environment it is running in. For instance, for
the x86 platform, you need to set the \e addrsize and \e opsize
bits, to indicate the processor would be running in 32-bit
mode. The context variables specific to a particular processor
are established by the SLEIGH spec. So the variables can
only be set \e after the spec has been loaded.
\code
...
context = new ContextInternal();
trans = new Sleigh(loader,context);
DocumentStorage docstorage;
Element *root = docstorage.openDocument("specfiles/x86.sla")->getRoot();
docstorage.registerTag(root);
trans->initialize(docstorage);
context->setVariableDefault("addrsize",1); // Address size is 32-bits
context->setVariableDefault("opsize",1); // Operand size is 32-bits
\endcode
*/