Repository navigation
Expand file tree
/
Copy pathASMInline.pas
More file actions
586 lines (505 loc) · 15.8 KB
/
Copy pathASMInline.pas
File metadata and controls
586 lines (505 loc) · 15.8 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
unit ASMInline;
interface
{ASM Inliner
Nicholas Sherlock
This is incomplete, I've only implemented enough to support InnoCallback.
Instructions are stored in a TMemoryStream internally
Instructions usually accept some combination of Registers, Immediates and
Memory References. Memory References can either be of the simple form [EAX]
(Where [EAX] is really a Delphi set), or the user can build the address with
the TASMInline.addr() function. It'd be nice to have a function which builds
the address from a string, too, allowing the more intuitive '[EAX+EBX*4+1000]'
style.
The generation of instruction-relative addresses generates Relocations, using
SaveToMemory() automatically rebases using the relocations to make these correct
in the final block of memory.
!!!! Not all special cases have been implemented in WriteRegRef().
Further reduced to just what's needed for Inno Setup by Martijn Laan
Added x64 support by Martijn Laan
}
{$IFNDEF CPUX86}
{$IFNDEF CPUX64}
{$MESSAGE ERROR 'This needs updating for non-x86/x64 builds'}
{ From an Embarcadero presentation about Arm64EC:
VirtualAlloc will return pages for x64 instructions
- Calls should be moved to VirtualAlloc2 with MEM_EXTENDED_PARAMETER_EC_CODE
HeapCreate/HeapAlloc cannot be used for runtime code injection
- The resulting pages can only be used to execute x64 instructions }
{$ENDIF}
{$ENDIF}
{$IFDEF CPUX86}
{$WARN IMPLICIT_INTEGER_CAST_LOSS OFF}
{$WARN IMPLICIT_CONVERSION_LOSS OFF}
{$ENDIF}
uses Sysutils, Windows, Classes, Contnrs;
type
{$IFDEF CPUX86}
TModMode = (mmNaked, mmDeref, mmDisp8, mmDisp32);
TRegister32 = (EAX, EBX, ECX, EDX, ESP, EBP, ESI, EDI);
TMemSize = (ms8, ms16, ms32, ms64);
TMemoryAddress = record
Size: TMemSize;
Base, Index: TRegister32;
Offset: Integer;
Scale: Byte;
end;
EOperandSizeMismatch = class(Exception)
public
constructor Create;
end;
TRelocType = (rt32Bit);
TReloc = class
public
Position: Cardinal;
RelocType: TRelocType;
end;
{$ELSE}
TRegister64 = (RAX, RCX, RDX, RBX, RSP, RBP, RSI, RDI, R8, R9, R10, R11, R12, R13, R14, R15);
TXmmRegister64 = 0..15;
{$ENDIF}
TASMInline = class
strict private
class var
[volatile] FSharedCodeBlock: Pointer;
[volatile] FSharedCodeBlockBytesUsed: Integer;
class destructor Destroy;
private
FBuffer: TMemoryStream;
{$IFDEF CPUX86}
FRelocs: TObjectList;
FBase: Cardinal;
procedure AddRelocation(position: Cardinal; relocType: TRelocType);
function GetReloc(index: Integer): TReloc;
function RelocCount: Integer;
property Relocs[index: Integer]: TReloc read GetReloc;
procedure WriteRegRef(reg: byte; base: TRegister32; index: TRegister32; Offset: Integer; Scale: byte); overload;
procedure WriteRegRef(mem: TMemoryAddress; reg: TRegister32); overload;
procedure WriteRegRef(reg: TRegister32; base: TRegister32; index: TRegister32 = EAX; Offset: Integer = 0; Scale: byte = 0); overload;
procedure Relocate(base: pointer);
{$ELSE}
function RegCode(const R: TRegister64): Byte;
procedure WriteREX(const W, R, X, B: Boolean);
{$ENDIF}
procedure WriteByte(const B: Byte);
procedure WriteInteger(const I: Integer);
{$IFNDEF CPUX86}
procedure WriteUInt64(const U: UInt64);
{$ENDIF}
public
constructor Create;
destructor Destroy; override;
function SaveAsMemory: Pointer;
{$IFDEF CPUX86}
function Addr(base: TRegister32; offset: Integer; size: TMemSize = ms32): TMemoryAddress; overload;
procedure Push(reg: TRegister32); overload;
procedure Pop(reg: TRegister32);
procedure Jmp(target: pointer); overload;
procedure Mov(reg: TRegister32; b: longword); overload;
procedure Mov(mem: TMemoryAddress; reg: TRegister32); overload;
procedure Mov(reg: TRegister32; mem: TMemoryAddress); overload;
{$ELSE}
procedure MovRegReg(const Dest, Src: TRegister64);
procedure MovRegImm64(const Dest: TRegister64; const Value: UInt64);
procedure MovRegMemRSP(const Dest: TRegister64; const Disp: Integer);
procedure LeaRegMemRSP(const Dest: TRegister64; const Disp: Integer);
procedure MovMemRSPReg(const Disp: Integer; const Src: TRegister64);
procedure SubRsp(const Amount: Integer);
procedure AddRsp(const Amount: Integer);
procedure MovXmmXmm(const Dest, Src: TXmmRegister64);
procedure MovqRegXmm(const Dest: TRegister64; const Src: TXmmRegister64);
procedure CallReg(const Reg: TRegister64);
procedure Ret;
{$ENDIF}
end;
implementation
{$IFDEF CPUX86}
constructor EOperandSizeMismatch.create;
begin
inherited Create('Operand size mismatch');
end;
{Throw an exception if test<>match. Poor man's assert().
Could overload to add other sorts of tests}
procedure require(test: TMemSize; match: TMemSize);
begin
if test <> match then
raise EOperandSizeMismatch.Create;
end;
function regnum(reg: TRegister32): byte; overload;
begin
case reg of
EAX: result := 0;
EBX: result := 3;
ECX: result := 1;
EDX: result := 2;
ESP: result := 4;
EBP: result := 5;
ESI: result := 6;
EDI: result := 7;
else
raise Exception.create('Unknown register...');
end;
end;
function ModModeNum(m: TModMode): byte;
begin
case m of
mmDeref: result := 0;
mmDisp8: result := 1;
mmDisp32: result := 2;
mmNaked: result := 3;
else
raise Exception.create('Invalid mod mode: ' + inttostr(ord(m)));
end;
end;
function EncodeSIB(scale, index, base: byte): byte;
begin
result := byte(base or (index shl 3) or (scale shl 6));
end;
function EncodeModRM(aMod, aReg, aRM: byte): byte; overload;
begin
result := byte((aMod shl 6) or (areg shl 3) or aRM);
end;
{$ENDIF}
{ TASMInline }
class destructor TASMInline.Destroy;
begin
const P = AtomicExchange(FSharedCodeBlock, nil);
if Assigned(P) then
VirtualFree(P, 0, MEM_RELEASE);
end;
constructor TASMInline.Create;
begin
FBuffer := TMemoryStream.Create;
{$IFDEF CPUX86}
FRelocs := TobjectList.Create;
{$ENDIF}
end;
destructor TASMInline.Destroy;
begin
{$IFDEF CPUX86}
FRelocs.Free;
{$ENDIF}
FBuffer.Free;
inherited;
end;
{$IFDEF CPUX86}
{$UNDEF RESTORER}
{$UNDEF RESTOREQ}
{$IFOPT R+}
{$DEFINE RESTORER}
{$R-}
{$ENDIF}
{$IFOPT Q+}
{$DEFINE RESTOREQ}
{$Q-}
{$ENDIF}
procedure TASMInline.Relocate(base: pointer);
var diff, orig: integer;
i: integer;
reloc: TReloc;
begin
const oldpos = fbuffer.Position;
try
diff := -(longword(base) - fbase);
for i := 0 to RelocCount - 1 do begin
reloc := Relocs[i];
case reloc.relocType of
rt32Bit: begin
fbuffer.Seek(reloc.position, soBeginning);
fbuffer.ReadBuffer(orig, sizeof(orig));
fbuffer.seek(-sizeof(orig), soCurrent);
orig := LongWord(orig + diff);
fbuffer.WriteBuffer(orig, sizeof(orig));
end;
end;
end;
fbase := longword(base);
finally
fbuffer.position := oldpos;
end;
end;
{$IFDEF RESTORER}
{$R+}
{$UNDEF RESTORER}
{$ENDIF}
{$IFDEF RESTOREQ}
{$Q+}
{$UNDEF RESTOREQ}
{$ENDIF}
function TASMInline.GetReloc(index: integer): TReloc;
begin
Result := TReloc(frelocs[index]);
end;
function TASMInline.RelocCount: integer;
begin
Result := frelocs.Count;
end;
procedure TASMInline.AddRelocation(position: longword; relocType: TRelocType);
var reloc: TReloc;
begin
reloc := TReloc.Create;
reloc.position := position;
reloc.relocType := relocType;
frelocs.add(reloc);
end;
function TASMInline.Addr(base: TRegister32; offset: Integer; size: TMemSize = ms32): TMemoryAddress;
begin
result.base := base;
result.scale := 0; //don't use Index
result.offset := offset;
result.size := size;
end;
procedure TASMInline.Pop(reg: TRegister32);
begin
writebyte($58 + regnum(reg));
end;
procedure TASMInline.Jmp(target: pointer);
begin
writebyte($E9);
AddRelocation(fbuffer.position, rt32bit);
WriteInteger(integer(target) - (integer(fBase) + fbuffer.Position + 4));
end;
procedure TASMInline.Push(reg: TRegister32);
begin
writebyte($50 + regnum(reg));
end;
procedure TASMInline.WriteRegRef(mem: TMemoryAddress; reg: TRegister32);
begin
writeregref(reg, mem.base, mem.index, mem.offset, mem.scale);
end;
//Write the MODR/M and SIB byte for the given register or memory reference
procedure TASMInline.WriteRegRef(reg: TRegister32; base: TRegister32; index: TRegister32 = EAX; Offset: integer = 0; Scale: byte = 0);
begin
WriteRegRef(regnum(reg), base, index, Offset, scale);
end;
procedure TASMInline.WriteRegRef(reg: byte; base: TRegister32; index: TRegister32; Offset: integer; Scale: byte);
type TOffSize = (osNone, os8, os32);
var mode: TModMode;
offsize: TOffSize;
useSIB: boolean;
areg, arm: Byte;
begin
if Offset = 0 then begin
mode := mmDeref;
offsize := osNone;
end else
if (offset >= -128) and (offset < 128) then begin //signed byte
mode := mmDisp8;
offsize := os8;
end else begin
mode := mmDisp32;
offsize := os32;
end;
if (mode <> mmnaked) then begin
usesib := (Scale > 0) or (base = ESP);
end else usesib := false;
if useSIB then begin //calculate scale, easiest just to use a case statement..
case scale of
0: begin //dont want an index value
index := ESP; //"none" value
end;
1: scale := 0;
2: scale := 1;
4: scale := 2;
8: scale := 3;
else raise exception.create('Invalid scale, valid values are 1,2,4,8.');
end;
end;
if (not useSIB) and (mode = mmDeref) and (base = EBP) then begin
//not available, use [EBP+0] instead
mode := mmDisp8;
offsize := os8;
Offset := 0;
end;
arm := regnum(base);
areg := reg;
if usesib then
WriteByte(EncodeModRM(ModModeNum(mode), areg, 4)) else
WriteByte(EncodeModRM(ModModeNum(mode), areg, arm));
if usesib then begin
WriteByte(EncodeSIB(Scale, regnum(index), regnum(base)));
end;
//Do we have to append an offset?
case offsize of
os8: WriteByte(byte(offset)); //ignore sign..
os32: WriteInteger(offset);
end;
end;
procedure TASMInline.Mov(mem: TMemoryAddress; reg: TRegister32);
begin
require(mem.size, ms32);
WriteByte($89);
WriteRegRef(mem, reg);
end;
procedure TASMInline.Mov(reg: TRegister32; mem: TMemoryAddress);
begin
require(mem.size, ms32);
WriteByte($8B);
WriteRegRef(mem, reg);
end;
procedure TASMInline.Mov(reg: TRegister32; b: longword);
begin
writebyte($B8 + regnum(reg));
writeInteger(Integer(b));
end;
{$ELSE}
function TASMInline.RegCode(const R: TRegister64): Byte;
begin
Result := Byte(R);
end;
procedure TASMInline.WriteREX(const W, R, X, B: Boolean);
begin
var Prefix: Byte := $40;
if W then
Inc(Prefix, $08);
if R then
Inc(Prefix, $04);
if X then
Inc(Prefix, $02);
if B then
Inc(Prefix, $01);
WriteByte(Prefix);
end;
procedure TASMInline.MovRegReg(const Dest, Src: TRegister64);
begin
const DestCode = RegCode(Dest);
const SrcCode = RegCode(Src);
WriteREX(True, SrcCode >= 8, False, DestCode >= 8);
WriteByte($89);
WriteByte(Byte($C0 or ((SrcCode and 7) shl 3) or (DestCode and 7)));
end;
procedure TASMInline.MovRegImm64(const Dest: TRegister64; const Value: UInt64);
begin
const DestCode = RegCode(Dest);
WriteREX(True, False, False, DestCode >= 8);
WriteByte(Byte($B8 + (DestCode and 7)));
WriteUInt64(Value);
end;
procedure TASMInline.MovRegMemRSP(const Dest: TRegister64; const Disp: Integer);
begin
const DestCode = RegCode(Dest);
WriteREX(True, DestCode >= 8, False, False);
WriteByte($8B);
WriteByte(Byte($84 or ((DestCode and 7) shl 3)));
WriteByte($24);
WriteInteger(Disp);
end;
procedure TASMInline.LeaRegMemRSP(const Dest: TRegister64; const Disp: Integer);
begin
const DestCode = RegCode(Dest);
WriteREX(True, DestCode >= 8, False, False);
WriteByte($8D);
WriteByte(Byte($84 or ((DestCode and 7) shl 3)));
WriteByte($24);
WriteInteger(Disp);
end;
procedure TASMInline.MovMemRSPReg(const Disp: Integer; const Src: TRegister64);
begin
const SrcCode = RegCode(Src);
WriteREX(True, SrcCode >= 8, False, False);
WriteByte($89);
WriteByte(Byte($84 or ((SrcCode and 7) shl 3)));
WriteByte($24);
WriteInteger(Disp);
end;
procedure TASMInline.SubRsp(const Amount: Integer);
begin
WriteByte($48);
WriteByte($81);
WriteByte($EC);
WriteInteger(Amount);
end;
procedure TASMInline.AddRsp(const Amount: Integer);
begin
WriteByte($48);
WriteByte($81);
WriteByte($C4);
WriteInteger(Amount);
end;
procedure TASMInline.MovXmmXmm(const Dest, Src: TXmmRegister64);
begin
if (Dest >= 8) or (Src >= 8) then
WriteREX(False, Dest >= 8, False, Src >= 8);
WriteByte($0F);
WriteByte($28);
WriteByte(Byte($C0 or ((Dest and 7) shl 3) or (Src and 7)));
end;
procedure TASMInline.MovqRegXmm(const Dest: TRegister64; const Src: TXmmRegister64);
begin
const DestCode = RegCode(Dest);
WriteByte($66);
WriteREX(True, Src >= 8, False, DestCode >= 8);
WriteByte($0F);
WriteByte($7E);
WriteByte(Byte($C0 or ((Src and 7) shl 3) or (DestCode and 7)));
end;
procedure TASMInline.CallReg(const Reg: TRegister64);
begin
const RegValue = RegCode(Reg);
WriteREX(False, False, False, RegValue >= 8);
WriteByte($FF);
WriteByte(Byte($D0 + (RegValue and 7)));
end;
procedure TASMInline.Ret;
begin
WriteByte($C3);
end;
{$ENDIF}
function TASMInline.SaveAsMemory: Pointer;
const
SharedCodeBlockSize = $4000; { 16 KB -- far more than anyone should need }
begin
{ Allocate code block if not already done so (thread-safe) }
if FSharedCodeBlock = nil then begin
const NewBlock = VirtualAlloc(nil, SharedCodeBlockSize, MEM_COMMIT,
PAGE_EXECUTE_READWRITE);
if NewBlock = nil then
OutOfMemoryError;
{ Initialize with INT 3 (breakpoint) opcodes }
FillChar(NewBlock^, SharedCodeBlockSize, $CC);
FlushInstructionCache(GetCurrentProcess, NewBlock, SharedCodeBlockSize);
MemoryBarrier;
if AtomicCmpExchange(FSharedCodeBlock, NewBlock, nil) <> nil then
VirtualFree(NewBlock, 0, MEM_RELEASE); { another thread beat us to it }
end;
const CodeSize = FBuffer.Size;
if (CodeSize <= 0) or (CodeSize > 1024) then
raise Exception.Create('TASMInline: Invalid code size');
{ Pad to next multiple of 16 bytes. Do this even if the code size currently
is a multiple of 16 bytes so that there's always at least one INT 3
between code sequences -- it's added safety in case a terminating RET or
JMP is missing. }
const SuballocSize = (Integer(CodeSize) or $F) + 1;
{ Suballocate SuballocSize bytes from the code block (thread-safe) }
var SuballocOffset: Integer;
repeat
SuballocOffset := FSharedCodeBlockBytesUsed;
if SuballocSize > SharedCodeBlockSize - SuballocOffset then
raise Exception.Create('TASMInline: No room left in code block');
until AtomicCmpExchange(FSharedCodeBlockBytesUsed,
SuballocOffset + SuballocSize, SuballocOffset) = SuballocOffset;
MemoryBarrier;
{ We now exclusively own SuballocSize bytes at SuballocOffset }
const DestPtr = PByte(FSharedCodeBlock) + SuballocOffset;
{$IFDEF CPUX86}
Relocate(DestPtr);
{$ENDIF}
Move(FBuffer.Memory^, DestPtr^, NativeInt(CodeSize));
FlushInstructionCache(GetCurrentProcess, DestPtr, SIZE_T(CodeSize));
MemoryBarrier;
Result := DestPtr;
end;
procedure TASMInline.WriteByte(const B: Byte);
begin
FBuffer.WriteBuffer(B, SizeOf(B));
end;
procedure TASMInline.WriteInteger(const I: Integer);
begin
FBuffer.WriteBuffer(I, SizeOf(I));
end;
{$IFNDEF CPUX86}
procedure TASMInline.WriteUInt64(const U: UInt64);
begin
FBuffer.WriteBuffer(U, SizeOf(U));
end;
{$ENDIF}
end.