summaryrefslogtreecommitdiff
path: root/src/VBox/VMM/PATM/PATMPatch.cpp
blob: b1b20dcef6d51b72b9c85287eeb9675801b41bb7 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
/* $Id: PATMPatch.cpp 28800 2010-04-27 08:22:32Z vboxsync $ */
/** @file
 * PATMPatch - Dynamic Guest OS Instruction patches
 *
 * NOTE: CSAM assumes patch memory is never reused!!
 */

/*
 * Copyright (C) 2006-2007 Oracle Corporation
 *
 * This file is part of VirtualBox Open Source Edition (OSE), as
 * available from http://www.virtualbox.org. This file is free software;
 * you can redistribute it and/or modify it under the terms of the GNU
 * General Public License (GPL) as published by the Free Software
 * Foundation, in version 2 as it comes in the "COPYING" file of the
 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
 */

/*******************************************************************************
*   Header Files                                                               *
*******************************************************************************/
#define LOG_GROUP LOG_GROUP_PATM
#include <VBox/patm.h>
#include <VBox/stam.h>
#include <VBox/pgm.h>
#include <VBox/cpum.h>
#include <VBox/mm.h>
#include <VBox/trpm.h>
#include <VBox/param.h>
#include <iprt/avl.h>
#include "PATMInternal.h"
#include <VBox/vm.h>
#include <VBox/csam.h>

#include <VBox/dbg.h>
#include <VBox/err.h>
#include <VBox/log.h>
#include <iprt/assert.h>
#include <iprt/asm.h>
#include <iprt/string.h>
#include <VBox/dis.h>
#include <VBox/disopcode.h>

#include <stdlib.h>
#include <stdio.h>
#include "PATMA.h"
#include "PATMPatch.h"

/* internal structure for passing more information about call fixups to patmPatchGenCode */
typedef struct
{
    RTRCPTR   pTargetGC;
    RTRCPTR   pCurInstrGC;
    RTRCPTR   pNextInstrGC;
    RTRCPTR   pReturnGC;
} PATMCALLINFO, *PPATMCALLINFO;

int patmPatchAddReloc32(PVM pVM, PPATCHINFO pPatch, uint8_t *pRelocHC, uint32_t uType, RTRCPTR pSource, RTRCPTR pDest)
{
    PRELOCREC pRec;

    Assert(uType == FIXUP_ABSOLUTE || ((uType == FIXUP_REL_JMPTOPATCH || uType == FIXUP_REL_JMPTOGUEST) && pSource && pDest));

    LogFlow(("patmPatchAddReloc32 type=%d pRelocGC=%RRv source=%RRv dest=%RRv\n", uType, pRelocHC - pVM->patm.s.pPatchMemGC + pVM->patm.s.pPatchMemGC , pSource, pDest));

    pRec = (PRELOCREC)MMR3HeapAllocZ(pVM, MM_TAG_PATM_PATCH, sizeof(*pRec));
    Assert(pRec);
    pRec->Core.Key  = (AVLPVKEY)pRelocHC;
    pRec->pRelocPos = pRelocHC; /* @todo redundant. */
    pRec->pSource   = pSource;
    pRec->pDest     = pDest;
    pRec->uType     = uType;

    bool ret = RTAvlPVInsert(&pPatch->FixupTree, &pRec->Core);
    Assert(ret); NOREF(ret);
    pPatch->nrFixups++;

    return VINF_SUCCESS;
}

int patmPatchAddJump(PVM pVM, PPATCHINFO pPatch, uint8_t *pJumpHC, uint32_t offset, RTRCPTR pTargetGC, uint32_t opcode)
{
    PJUMPREC pRec;

    pRec = (PJUMPREC)MMR3HeapAllocZ(pVM, MM_TAG_PATM_PATCH, sizeof(*pRec));
    Assert(pRec);

    pRec->Core.Key  = (AVLPVKEY)pJumpHC;
    pRec->pJumpHC   = pJumpHC; /* @todo redundant. */
    pRec->offDispl  = offset;
    pRec->pTargetGC = pTargetGC;
    pRec->opcode    = opcode;

    bool ret = RTAvlPVInsert(&pPatch->JumpTree, &pRec->Core);
    Assert(ret); NOREF(ret);
    pPatch->nrJumpRecs++;

    return VINF_SUCCESS;
}

#define PATCHGEN_PROLOG_NODEF(pVM, pPatch)                                      \
    pPB = PATCHCODE_PTR_HC(pPatch) + pPatch->uCurPatchOffset;            \
                                                                               \
    if (pPB + 256 >= pVM->patm.s.pPatchMemHC + pVM->patm.s.cbPatchMem)          \
    {                                                                          \
        pVM->patm.s.fOutOfMemory = true; \
        Assert(pPB + 256 >= pVM->patm.s.pPatchMemHC + pVM->patm.s.cbPatchMem); \
        return VERR_NO_MEMORY; \
    }

#define PATCHGEN_PROLOG(pVM, pPatch)                                      \
    uint8_t *pPB;                                                         \
    PATCHGEN_PROLOG_NODEF(pVM, pPatch);


#define PATCHGEN_EPILOG(pPatch, size) \
    Assert(size <= 640);              \
    pPatch->uCurPatchOffset += size;


static uint32_t patmPatchGenCode(PVM pVM, PPATCHINFO pPatch, uint8_t *pPB, PPATCHASMRECORD pAsmRecord, RCPTRTYPE(uint8_t *) pReturnAddrGC, bool fGenJump,
                                 PPATMCALLINFO pCallInfo = 0)
{
    uint32_t i, j;

    Assert(fGenJump == false || pReturnAddrGC);
    Assert(fGenJump == false || pAsmRecord->offJump);
    Assert(pAsmRecord && pAsmRecord->size > sizeof(pAsmRecord->uReloc[0]));

    // Copy the code block
    memcpy(pPB, pAsmRecord->pFunction, pAsmRecord->size);

    // Process all fixups
    for (j=0,i=0;i<pAsmRecord->nrRelocs*2; i+=2)
    {
        for (;j<pAsmRecord->size;j++)
        {
            if (*(uint32_t*)&pPB[j] == pAsmRecord->uReloc[i])
            {
                RCPTRTYPE(uint32_t *) dest;

#ifdef VBOX_STRICT
                if (pAsmRecord->uReloc[i] == PATM_FIXUP)
                    Assert(pAsmRecord->uReloc[i+1] != 0);
                else
                    Assert(pAsmRecord->uReloc[i+1] == 0);
#endif

                /**
                 * BE VERY CAREFUL WITH THESE FIXUPS. TAKE INTO ACCOUNT THAT PROBLEMS MAY ARISE WHEN RESTORING A SAVED STATE WITH
                 * A DIFFERENT HYPERVISOR LAYOUT.
                 */
                switch (pAsmRecord->uReloc[i])
                {
                case PATM_VMFLAGS:
                    dest = pVM->patm.s.pGCStateGC + RT_OFFSETOF(PATMGCSTATE, uVMFlags);
                    break;

                case PATM_PENDINGACTION:
                    dest = pVM->patm.s.pGCStateGC + RT_OFFSETOF(PATMGCSTATE, uPendingAction);
                    break;

                case PATM_FIXUP:
                    /* Offset in uReloc[i+1] is from the base of the function. */
                    dest = (RTGCUINTPTR32)pVM->patm.s.pPatchMemGC + pAsmRecord->uReloc[i+1] + (RTGCUINTPTR32)(pPB - pVM->patm.s.pPatchMemHC);
                    break;
#ifdef VBOX_WITH_STATISTICS
                case PATM_ALLPATCHCALLS:
                    dest = pVM->patm.s.pGCStateGC + RT_OFFSETOF(PATMGCSTATE, uPatchCalls);
                    break;

                case PATM_IRETEFLAGS:
                    dest = pVM->patm.s.pGCStateGC + RT_OFFSETOF(PATMGCSTATE, uIretEFlags);
                    break;

                case PATM_IRETCS:
                    dest = pVM->patm.s.pGCStateGC + RT_OFFSETOF(PATMGCSTATE, uIretCS);
                    break;

                case PATM_IRETEIP:
                    dest = pVM->patm.s.pGCStateGC + RT_OFFSETOF(PATMGCSTATE, uIretEIP);
                    break;

                case PATM_PERPATCHCALLS:
                    dest = patmPatchQueryStatAddress(pVM, pPatch);
                    break;
#endif
                case PATM_STACKPTR:
                    dest = pVM->patm.s.pGCStateGC + RT_OFFSETOF(PATMGCSTATE, Psp);
                    break;

                /* The first part of our PATM stack is used to store offsets of patch return addresses; the 2nd
                 * part to store the original return addresses.
                 */
                case PATM_STACKBASE:
                    dest = pVM->patm.s.pGCStackGC;
                    break;

                case PATM_STACKBASE_GUEST:
                    dest = pVM->patm.s.pGCStackGC + PATM_STACK_SIZE;
                    break;

                case PATM_RETURNADDR:   /* absolute guest address; no fixup required */
                    Assert(pCallInfo && pAsmRecord->uReloc[i] >= PATM_NO_FIXUP);
                    dest = pCallInfo->pReturnGC;
                    break;

                case PATM_PATCHNEXTBLOCK:  /* relative address of instruction following this block */
                    Assert(pCallInfo && pAsmRecord->uReloc[i] >= PATM_NO_FIXUP);

                    /** @note hardcoded assumption that we must return to the instruction following this block */
                    dest = (uintptr_t)pPB - (uintptr_t)pVM->patm.s.pPatchMemHC + pAsmRecord->size;
                    break;

                case PATM_CALLTARGET:   /* relative to patch address; no fixup requird */
                    Assert(pCallInfo && pAsmRecord->uReloc[i] >= PATM_NO_FIXUP);

                    /* Address must be filled in later. (see patmr3SetBranchTargets)  */
                    patmPatchAddJump(pVM, pPatch, &pPB[j-1], 1, pCallInfo->pTargetGC, OP_CALL);
                    dest = PATM_ILLEGAL_DESTINATION;
                    break;

                case PATM_PATCHBASE:    /* Patch GC base address */
                    dest = pVM->patm.s.pPatchMemGC;
                    break;

                case PATM_CPUID_STD_PTR:
                    /* @todo dirty hack when correcting this fixup (state restore) */
                    dest = CPUMR3GetGuestCpuIdStdRCPtr(pVM);
                    break;

                case PATM_CPUID_EXT_PTR:
                    /* @todo dirty hack when correcting this fixup (state restore) */
                    dest = CPUMR3GetGuestCpuIdExtRCPtr(pVM);
                    break;

                case PATM_CPUID_CENTAUR_PTR:
                    /* @todo dirty hack when correcting this fixup (state restore) */
                    dest = CPUMR3GetGuestCpuIdCentaurRCPtr(pVM);
                    break;

                case PATM_CPUID_DEF_PTR:
                    /* @todo dirty hack when correcting this fixup (state restore) */
                    dest = CPUMR3GetGuestCpuIdDefRCPtr(pVM);
                    break;

                case PATM_CPUID_STD_MAX:
                    dest = CPUMGetGuestCpuIdStdMax(pVM);
                    break;

                case PATM_CPUID_EXT_MAX:
                    dest = CPUMGetGuestCpuIdExtMax(pVM);
                    break;

                case PATM_CPUID_CENTAUR_MAX:
                    dest = CPUMGetGuestCpuIdCentaurMax(pVM);
                    break;

                case PATM_INTERRUPTFLAG:
                    dest = pVM->patm.s.pGCStateGC + RT_OFFSETOF(PATMGCSTATE, fPIF);
                    break;

                case PATM_INHIBITIRQADDR:
                    dest = pVM->patm.s.pGCStateGC + RT_OFFSETOF(PATMGCSTATE, GCPtrInhibitInterrupts);
                    break;

                case PATM_NEXTINSTRADDR:
                    Assert(pCallInfo);
                    /* pNextInstrGC can be 0 if several instructions, that inhibit irqs, follow each other */
                    dest = pCallInfo->pNextInstrGC;
                    break;

                case PATM_CURINSTRADDR:
                    Assert(pCallInfo);
                    dest = pCallInfo->pCurInstrGC;
                    break;

                case PATM_VM_FORCEDACTIONS:
                    /* @todo dirty assumptions when correcting this fixup during saved state loading. */
                    dest = pVM->pVMRC + RT_OFFSETOF(VM, aCpus[0].fLocalForcedActions);
                    break;

                case PATM_TEMP_EAX:
                    dest = pVM->patm.s.pGCStateGC + RT_OFFSETOF(PATMGCSTATE, Restore.uEAX);
                    break;
                case PATM_TEMP_ECX:
                    dest = pVM->patm.s.pGCStateGC + RT_OFFSETOF(PATMGCSTATE, Restore.uECX);
                    break;
                case PATM_TEMP_EDI:
                    dest = pVM->patm.s.pGCStateGC + RT_OFFSETOF(PATMGCSTATE, Restore.uEDI);
                    break;
                case PATM_TEMP_EFLAGS:
                    dest = pVM->patm.s.pGCStateGC + RT_OFFSETOF(PATMGCSTATE, Restore.eFlags);
                    break;
                case PATM_TEMP_RESTORE_FLAGS:
                    dest = pVM->patm.s.pGCStateGC + RT_OFFSETOF(PATMGCSTATE, Restore.uFlags);
                    break;
                case PATM_CALL_PATCH_TARGET_ADDR:
                    dest = pVM->patm.s.pGCStateGC + RT_OFFSETOF(PATMGCSTATE, GCCallPatchTargetAddr);
                    break;
                case PATM_CALL_RETURN_ADDR:
                    dest = pVM->patm.s.pGCStateGC + RT_OFFSETOF(PATMGCSTATE, GCCallReturnAddr);
                    break;

                /* Relative address of global patm lookup and call function. */
                case PATM_LOOKUP_AND_CALL_FUNCTION:
                {
                    RTRCPTR pInstrAfterCall = pVM->patm.s.pPatchMemGC + (RTGCUINTPTR32)(&pPB[j] + sizeof(RTRCPTR) - pVM->patm.s.pPatchMemHC);
                    Assert(pVM->patm.s.pfnHelperCallGC);
                    Assert(sizeof(uint32_t) == sizeof(RTRCPTR));

                    /* Relative value is target minus address of instruction after the actual call instruction. */
                    dest = pVM->patm.s.pfnHelperCallGC - pInstrAfterCall;
                    break;
                }

                case PATM_RETURN_FUNCTION:
                {
                    RTRCPTR pInstrAfterCall = pVM->patm.s.pPatchMemGC + (RTGCUINTPTR32)(&pPB[j] + sizeof(RTRCPTR) - pVM->patm.s.pPatchMemHC);
                    Assert(pVM->patm.s.pfnHelperRetGC);
                    Assert(sizeof(uint32_t) == sizeof(RTRCPTR));

                    /* Relative value is target minus address of instruction after the actual call instruction. */
                    dest = pVM->patm.s.pfnHelperRetGC - pInstrAfterCall;
                    break;
                }

                case PATM_IRET_FUNCTION:
                {
                    RTRCPTR pInstrAfterCall = pVM->patm.s.pPatchMemGC + (RTGCUINTPTR32)(&pPB[j] + sizeof(RTRCPTR) - pVM->patm.s.pPatchMemHC);
                    Assert(pVM->patm.s.pfnHelperIretGC);
                    Assert(sizeof(uint32_t) == sizeof(RTRCPTR));

                    /* Relative value is target minus address of instruction after the actual call instruction. */
                    dest = pVM->patm.s.pfnHelperIretGC - pInstrAfterCall;
                    break;
                }

                case PATM_LOOKUP_AND_JUMP_FUNCTION:
                {
                    RTRCPTR pInstrAfterCall = pVM->patm.s.pPatchMemGC + (RTGCUINTPTR32)(&pPB[j] + sizeof(RTRCPTR) - pVM->patm.s.pPatchMemHC);
                    Assert(pVM->patm.s.pfnHelperJumpGC);
                    Assert(sizeof(uint32_t) == sizeof(RTRCPTR));

                    /* Relative value is target minus address of instruction after the actual call instruction. */
                    dest = pVM->patm.s.pfnHelperJumpGC - pInstrAfterCall;
                    break;
                }

                default:
                    dest = PATM_ILLEGAL_DESTINATION;
                    AssertRelease(0);
                    break;
                }

                *(RTRCPTR *)&pPB[j] = dest;
                if (pAsmRecord->uReloc[i] < PATM_NO_FIXUP)
                {
                    patmPatchAddReloc32(pVM, pPatch, &pPB[j], FIXUP_ABSOLUTE);
                }
                break;
            }
        }
        Assert(j < pAsmRecord->size);
    }
    Assert(pAsmRecord->uReloc[i] == 0xffffffff);

    /* Add the jump back to guest code (if required) */
    if (fGenJump)
    {
        int32_t displ = pReturnAddrGC - (PATCHCODE_PTR_GC(pPatch) + pPatch->uCurPatchOffset + pAsmRecord->offJump - 1 + SIZEOF_NEARJUMP32);

        /* Add lookup record for patch to guest address translation */
        Assert(pPB[pAsmRecord->offJump - 1] == 0xE9);
        patmr3AddP2GLookupRecord(pVM, pPatch, &pPB[pAsmRecord->offJump - 1], pReturnAddrGC, PATM_LOOKUP_PATCH2GUEST);

        *(uint32_t *)&pPB[pAsmRecord->offJump] = displ;
        patmPatchAddReloc32(pVM, pPatch, &pPB[pAsmRecord->offJump], FIXUP_REL_JMPTOGUEST,
                        PATCHCODE_PTR_GC(pPatch) + pPatch->uCurPatchOffset + pAsmRecord->offJump - 1 + SIZEOF_NEARJUMP32,
                        pReturnAddrGC);
    }

    // Calculate the right size of this patch block
    if ((fGenJump && pAsmRecord->offJump) || (!fGenJump && !pAsmRecord->offJump))
    {
        return pAsmRecord->size;
    }
    else {
        // if a jump instruction is present and we don't want one, then subtract SIZEOF_NEARJUMP32
        return pAsmRecord->size - SIZEOF_NEARJUMP32;
    }
}

/* Read bytes and check for overwritten instructions. */
static int patmPatchReadBytes(PVM pVM, uint8_t *pDest, RTRCPTR pSrc, uint32_t cb)
{
    int rc = PGMPhysSimpleReadGCPtr(&pVM->aCpus[0], pDest, pSrc, cb);
    AssertRCReturn(rc, rc);
    /*
     * Could be patched already; make sure this is checked!
     */
    for (uint32_t i=0;i<cb;i++)
    {
        uint8_t temp;

        int rc2 = PATMR3QueryOpcode(pVM, pSrc+i, &temp);
        if (RT_SUCCESS(rc2))
        {
            pDest[i] = temp;
        }
        else
            break;  /* no more */
    }
    return VINF_SUCCESS;
}

int patmPatchGenDuplicate(PVM pVM, PPATCHINFO pPatch, DISCPUSTATE *pCpu, RCPTRTYPE(uint8_t *) pCurInstrGC)
{
    int rc = VINF_SUCCESS;
    PATCHGEN_PROLOG(pVM, pPatch);

    rc = patmPatchReadBytes(pVM, pPB, pCurInstrGC, pCpu->opsize);
    AssertRC(rc);
    PATCHGEN_EPILOG(pPatch, pCpu->opsize);
    return rc;
}

int patmPatchGenIret(PVM pVM, PPATCHINFO pPatch, RTRCPTR pCurInstrGC, bool fSizeOverride)
{
    uint32_t size;
    PATMCALLINFO callInfo;

    PATCHGEN_PROLOG(pVM, pPatch);

    AssertMsg(fSizeOverride == false, ("operand size override!!\n"));

    callInfo.pCurInstrGC = pCurInstrGC;

    size = patmPatchGenCode(pVM, pPatch, pPB, &PATMIretRecord, 0, false, &callInfo);

    PATCHGEN_EPILOG(pPatch, size);
    return VINF_SUCCESS;
}

int patmPatchGenCli(PVM pVM, PPATCHINFO pPatch)
{
    uint32_t size;
    PATCHGEN_PROLOG(pVM, pPatch);

    size = patmPatchGenCode(pVM, pPatch, pPB, &PATMCliRecord, 0, false);

    PATCHGEN_EPILOG(pPatch, size);
    return VINF_SUCCESS;
}

/*
 * Generate an STI patch
 */
int patmPatchGenSti(PVM pVM, PPATCHINFO pPatch, RTRCPTR pCurInstrGC, RTRCPTR pNextInstrGC)
{
    PATMCALLINFO callInfo;
    uint32_t     size;

    Log(("patmPatchGenSti at %RRv; next %RRv\n", pCurInstrGC, pNextInstrGC));
    PATCHGEN_PROLOG(pVM, pPatch);
    callInfo.pNextInstrGC = pNextInstrGC;
    size = patmPatchGenCode(pVM, pPatch, pPB, &PATMStiRecord, 0, false, &callInfo);
    PATCHGEN_EPILOG(pPatch, size);

    return VINF_SUCCESS;
}


int patmPatchGenPopf(PVM pVM, PPATCHINFO pPatch, RCPTRTYPE(uint8_t *) pReturnAddrGC, bool fSizeOverride, bool fGenJumpBack)
{
    uint32_t        size;
    PATMCALLINFO    callInfo;

    PATCHGEN_PROLOG(pVM, pPatch);

    callInfo.pNextInstrGC = pReturnAddrGC;

    Log(("patmPatchGenPopf at %RRv\n", pReturnAddrGC));

    /* Note: keep IOPL in mind when changing any of this!! (see comments in PATMA.asm, PATMPopf32Replacement) */
    if (fSizeOverride == true)
    {
        Log(("operand size override!!\n"));
        size = patmPatchGenCode(pVM, pPatch, pPB, (fGenJumpBack) ? &PATMPopf16Record : &PATMPopf16Record_NoExit , pReturnAddrGC, fGenJumpBack, &callInfo);
    }
    else
    {
        size = patmPatchGenCode(pVM, pPatch, pPB, (fGenJumpBack) ? &PATMPopf32Record : &PATMPopf32Record_NoExit, pReturnAddrGC, fGenJumpBack, &callInfo);
    }

    PATCHGEN_EPILOG(pPatch, size);
    STAM_COUNTER_INC(&pVM->patm.s.StatGenPopf);
    return VINF_SUCCESS;
}

int patmPatchGenPushf(PVM pVM, PPATCHINFO pPatch, bool fSizeOverride)
{
    uint32_t size;
    PATCHGEN_PROLOG(pVM, pPatch);

    if (fSizeOverride == true)
    {
        Log(("operand size override!!\n"));
        size = patmPatchGenCode(pVM, pPatch, pPB, &PATMPushf16Record, 0, false);
    }
    else
    {
        size = patmPatchGenCode(pVM, pPatch, pPB, &PATMPushf32Record, 0, false);
    }

    PATCHGEN_EPILOG(pPatch, size);
    return VINF_SUCCESS;
}

int patmPatchGenPushCS(PVM pVM, PPATCHINFO pPatch)
{
    uint32_t size;
    PATCHGEN_PROLOG(pVM, pPatch);
    size = patmPatchGenCode(pVM, pPatch, pPB, &PATMPushCSRecord, 0, false);
    PATCHGEN_EPILOG(pPatch, size);
    return VINF_SUCCESS;
}

int patmPatchGenLoop(PVM pVM, PPATCHINFO pPatch, RCPTRTYPE(uint8_t *) pTargetGC, uint32_t opcode, bool fSizeOverride)
{
    uint32_t size = 0;
    PPATCHASMRECORD pPatchAsmRec;

    PATCHGEN_PROLOG(pVM, pPatch);

    switch (opcode)
    {
    case OP_LOOP:
        pPatchAsmRec = &PATMLoopRecord;
        break;
    case OP_LOOPNE:
        pPatchAsmRec = &PATMLoopNZRecord;
        break;
    case OP_LOOPE:
        pPatchAsmRec = &PATMLoopZRecord;
        break;
    case OP_JECXZ:
        pPatchAsmRec = &PATMJEcxRecord;
        break;
    default:
        AssertMsgFailed(("PatchGenLoop: invalid opcode %d\n", opcode));
        return VERR_INVALID_PARAMETER;
    }
    Assert(pPatchAsmRec->offSizeOverride && pPatchAsmRec->offRelJump);

    Log(("PatchGenLoop %d jump %d to %08x offrel=%d\n", opcode, pPatch->nrJumpRecs, pTargetGC, pPatchAsmRec->offRelJump));

    // Generate the patch code
    size = patmPatchGenCode(pVM, pPatch, pPB, pPatchAsmRec, 0, false);

    if (fSizeOverride)
    {
        pPB[pPatchAsmRec->offSizeOverride] = 0x66;  // ecx -> cx or vice versa
    }

    *(RTRCPTR *)&pPB[pPatchAsmRec->offRelJump] = 0xDEADBEEF;

    patmPatchAddJump(pVM, pPatch, &pPB[pPatchAsmRec->offRelJump - 1], 1, pTargetGC, opcode);

    PATCHGEN_EPILOG(pPatch, size);
    return VINF_SUCCESS;
}

int patmPatchGenRelJump(PVM pVM, PPATCHINFO pPatch, RCPTRTYPE(uint8_t *) pTargetGC, uint32_t opcode, bool fSizeOverride)
{
    uint32_t offset = 0;
    PATCHGEN_PROLOG(pVM, pPatch);

    // internal relative jumps from patch code to patch code; no relocation record required

    Assert(PATMIsPatchGCAddr(pVM, pTargetGC) == false);

    switch (opcode)
    {
    case OP_JO:
        pPB[1] = 0x80;
        break;
    case OP_JNO:
        pPB[1] = 0x81;
        break;
    case OP_JC:
        pPB[1] = 0x82;
        break;
    case OP_JNC:
        pPB[1] = 0x83;
        break;
    case OP_JE:
        pPB[1] = 0x84;
        break;
    case OP_JNE:
        pPB[1] = 0x85;
        break;
    case OP_JBE:
        pPB[1] = 0x86;
        break;
    case OP_JNBE:
        pPB[1] = 0x87;
        break;
    case OP_JS:
        pPB[1] = 0x88;
        break;
    case OP_JNS:
        pPB[1] = 0x89;
        break;
    case OP_JP:
        pPB[1] = 0x8A;
        break;
    case OP_JNP:
        pPB[1] = 0x8B;
        break;
    case OP_JL:
        pPB[1] = 0x8C;
        break;
    case OP_JNL:
        pPB[1] = 0x8D;
        break;
    case OP_JLE:
        pPB[1] = 0x8E;
        break;
    case OP_JNLE:
        pPB[1] = 0x8F;
        break;

    case OP_JMP:
        /* If interrupted here, then jump to the target instruction. Used by PATM.cpp for jumping to known instructions. */
        /* Add lookup record for patch to guest address translation */
        patmr3AddP2GLookupRecord(pVM, pPatch, pPB, pTargetGC, PATM_LOOKUP_PATCH2GUEST);

        pPB[0] = 0xE9;
        break;

    case OP_JECXZ:
    case OP_LOOP:
    case OP_LOOPNE:
    case OP_LOOPE:
        return patmPatchGenLoop(pVM, pPatch, pTargetGC, opcode, fSizeOverride);

    default:
        AssertMsg(0, ("Invalid jump opcode %d\n", opcode));
        return VERR_PATCHING_REFUSED;
    }
    if (opcode != OP_JMP)
    {
         pPB[0] = 0xF;
         offset += 2;
    }
    else offset++;

    *(RTRCPTR *)&pPB[offset] = 0xDEADBEEF;

    patmPatchAddJump(pVM, pPatch, pPB, offset, pTargetGC, opcode);

    offset += sizeof(RTRCPTR);

    PATCHGEN_EPILOG(pPatch, offset);
    return VINF_SUCCESS;
}

/*
 * Rewrite call to dynamic or currently unknown function (on-demand patching of function)
 */
int patmPatchGenCall(PVM pVM, PPATCHINFO pPatch, DISCPUSTATE *pCpu, RTRCPTR pCurInstrGC, RTRCPTR pTargetGC, bool fIndirect)
{
    PATMCALLINFO        callInfo;
    uint32_t            offset;
    uint32_t            i, size;
    int                 rc;

    /** @note Don't check for IF=1 here. The ret instruction will do this.  */
    /** @note It's dangerous to do this for 'normal' patches. the jump target might be inside the generated patch jump. (seen this!) */

    /* 1: Clear PATM interrupt flag on entry. */
    rc = patmPatchGenClearPIF(pVM, pPatch, pCurInstrGC);
    if (rc == VERR_NO_MEMORY)
        return rc;
    AssertRCReturn(rc, rc);

    PATCHGEN_PROLOG(pVM, pPatch);
    /* 2: We must push the target address onto the stack before appending the indirect call code. */

    if (fIndirect)
    {
        Log(("patmPatchGenIndirectCall\n"));
        Assert(pCpu->param1.size == 4);
        Assert(OP_PARM_VTYPE(pCpu->pCurInstr->param1) != OP_PARM_J);

        /* We push it onto the stack here, so the guest's context isn't ruined when this happens to cause
         * a page fault. The assembly code restores the stack afterwards.
         */
        offset = 0;
        /* include prefix byte to make sure we don't use the incorrect selector register. */
        if (pCpu->prefix & PREFIX_SEG)
            pPB[offset++] = DISQuerySegPrefixByte(pCpu);
        pPB[offset++] = 0xFF;              // push r/m32
        pPB[offset++] = MAKE_MODRM(pCpu->ModRM.Bits.Mod, 6 /* group 5 */, pCpu->ModRM.Bits.Rm);
        i = 2;  /* standard offset of modrm bytes */
        if (pCpu->prefix & PREFIX_OPSIZE)
            i++;    //skip operand prefix
        if (pCpu->prefix & PREFIX_SEG)
            i++;    //skip segment prefix

        rc = patmPatchReadBytes(pVM, &pPB[offset], (RTRCPTR)((RTGCUINTPTR32)pCurInstrGC + i), pCpu->opsize - i);
        AssertRCReturn(rc, rc);
        offset += (pCpu->opsize - i);
    }
    else
    {
        AssertMsg(PATMIsPatchGCAddr(pVM, pTargetGC) == false, ("Target is already a patch address (%RRv)?!?\n", pTargetGC));
        Assert(pTargetGC);
        Assert(OP_PARM_VTYPE(pCpu->pCurInstr->param1) == OP_PARM_J);

        /** @todo wasting memory as the complex search is overkill and we need only one lookup slot... */

        /* Relative call to patch code (patch to patch -> no fixup). */
        Log(("PatchGenCall from %RRv (next=%RRv) to %RRv\n", pCurInstrGC, pCurInstrGC + pCpu->opsize, pTargetGC));

        /* We push it onto the stack here, so the guest's context isn't ruined when this happens to cause
         * a page fault. The assembly code restores the stack afterwards.
         */
        offset = 0;
        pPB[offset++] = 0x68;              // push %Iv
        *(RTRCPTR *)&pPB[offset] = pTargetGC;
        offset += sizeof(RTRCPTR);
    }

    /* align this block properly to make sure the jump table will not be misaligned. */
    size = (RTHCUINTPTR)&pPB[offset] & 3;
    if (size)
        size = 4 - size;

    for (i=0;i<size;i++)
    {
        pPB[offset++] = 0x90;   /* nop */
    }
    PATCHGEN_EPILOG(pPatch, offset);

    /* 3: Generate code to lookup address in our local cache; call hypervisor PATM code if it can't be located. */
    PATCHGEN_PROLOG_NODEF(pVM, pPatch);
    callInfo.pReturnGC      = pCurInstrGC + pCpu->opsize;
    callInfo.pTargetGC      = (fIndirect) ? 0xDEADBEEF : pTargetGC;
    size = patmPatchGenCode(pVM, pPatch, pPB, (fIndirect) ? &PATMCallIndirectRecord : &PATMCallRecord, 0, false, &callInfo);
    PATCHGEN_EPILOG(pPatch, size);

    /* Need to set PATM_INTERRUPTFLAG after the patched ret returns here. */
    rc = patmPatchGenSetPIF(pVM, pPatch, pCurInstrGC);
    if (rc == VERR_NO_MEMORY)
        return rc;
    AssertRCReturn(rc, rc);

    STAM_COUNTER_INC(&pVM->patm.s.StatGenCall);
    return VINF_SUCCESS;
}

/**
 * Generate indirect jump to unknown destination
 *
 * @returns VBox status code.
 * @param   pVM         The VM to operate on.
 * @param   pPatch      Patch record
 * @param   pCpu        Disassembly state
 * @param   pCurInstrGC Current instruction address
 */
int patmPatchGenJump(PVM pVM, PPATCHINFO pPatch, DISCPUSTATE *pCpu, RTRCPTR pCurInstrGC)
{
    PATMCALLINFO        callInfo;
    uint32_t            offset;
    uint32_t            i, size;
    int                 rc;

    /* 1: Clear PATM interrupt flag on entry. */
    rc = patmPatchGenClearPIF(pVM, pPatch, pCurInstrGC);
    if (rc == VERR_NO_MEMORY)
        return rc;
    AssertRCReturn(rc, rc);

    PATCHGEN_PROLOG(pVM, pPatch);
    /* 2: We must push the target address onto the stack before appending the indirect call code. */

    Log(("patmPatchGenIndirectJump\n"));
    Assert(pCpu->param1.size == 4);
    Assert(OP_PARM_VTYPE(pCpu->pCurInstr->param1) != OP_PARM_J);

    /* We push it onto the stack here, so the guest's context isn't ruined when this happens to cause
     * a page fault. The assembly code restores the stack afterwards.
     */
    offset = 0;
    /* include prefix byte to make sure we don't use the incorrect selector register. */
    if (pCpu->prefix & PREFIX_SEG)
        pPB[offset++] = DISQuerySegPrefixByte(pCpu);

    pPB[offset++] = 0xFF;              // push r/m32
    pPB[offset++] = MAKE_MODRM(pCpu->ModRM.Bits.Mod, 6 /* group 5 */, pCpu->ModRM.Bits.Rm);
    i = 2;  /* standard offset of modrm bytes */
    if (pCpu->prefix & PREFIX_OPSIZE)
        i++;    //skip operand prefix
    if (pCpu->prefix & PREFIX_SEG)
        i++;    //skip segment prefix

    rc = patmPatchReadBytes(pVM, &pPB[offset], (RTRCPTR)((RTGCUINTPTR32)pCurInstrGC + i), pCpu->opsize - i);
    AssertRCReturn(rc, rc);
    offset += (pCpu->opsize - i);

    /* align this block properly to make sure the jump table will not be misaligned. */
    size = (RTHCUINTPTR)&pPB[offset] & 3;
    if (size)
        size = 4 - size;

    for (i=0;i<size;i++)
    {
        pPB[offset++] = 0x90;   /* nop */
    }
    PATCHGEN_EPILOG(pPatch, offset);

    /* 3: Generate code to lookup address in our local cache; call hypervisor PATM code if it can't be located. */
    PATCHGEN_PROLOG_NODEF(pVM, pPatch);
    callInfo.pReturnGC      = pCurInstrGC + pCpu->opsize;
    callInfo.pTargetGC      = 0xDEADBEEF;
    size = patmPatchGenCode(pVM, pPatch, pPB, &PATMJumpIndirectRecord, 0, false, &callInfo);
    PATCHGEN_EPILOG(pPatch, size);

    STAM_COUNTER_INC(&pVM->patm.s.StatGenJump);
    return VINF_SUCCESS;
}

/**
 * Generate return instruction
 *
 * @returns VBox status code.
 * @param   pVM         The VM to operate on.
 * @param   pPatch      Patch structure
 * @param   pCpu        Disassembly struct
 * @param   pCurInstrGC Current instruction pointer
 *
 */
int patmPatchGenRet(PVM pVM, PPATCHINFO pPatch, DISCPUSTATE *pCpu, RCPTRTYPE(uint8_t *) pCurInstrGC)
{
    int size = 0, rc;
    RTRCPTR pPatchRetInstrGC;

    /* Remember start of this patch for below. */
    pPatchRetInstrGC = PATCHCODE_PTR_GC(pPatch) + pPatch->uCurPatchOffset;

    Log(("patmPatchGenRet %RRv\n", pCurInstrGC));

    /** @note optimization: multiple identical ret instruction in a single patch can share a single patched ret. */
    if (    pPatch->pTempInfo->pPatchRetInstrGC
        &&  pPatch->pTempInfo->uPatchRetParam1 == (uint32_t)pCpu->param1.parval) /* nr of bytes popped off the stack should be identical of course! */
    {
        Assert(pCpu->pCurInstr->opcode == OP_RETN);
        STAM_COUNTER_INC(&pVM->patm.s.StatGenRetReused);

        return patmPatchGenPatchJump(pVM, pPatch, pCurInstrGC, pPatch->pTempInfo->pPatchRetInstrGC);
    }

    /* Jump back to the original instruction if IF is set again. */
    Assert(!PATMFindActivePatchByEntrypoint(pVM, pCurInstrGC));
    rc = patmPatchGenCheckIF(pVM, pPatch, pCurInstrGC);
    AssertRCReturn(rc, rc);

    /* align this block properly to make sure the jump table will not be misaligned. */
    PATCHGEN_PROLOG(pVM, pPatch);
    size = (RTHCUINTPTR)pPB & 3;
    if (size)
        size = 4 - size;

    for (int i=0;i<size;i++)
        pPB[i] = 0x90;   /* nop */
    PATCHGEN_EPILOG(pPatch, size);

    PATCHGEN_PROLOG_NODEF(pVM, pPatch);
    size = patmPatchGenCode(pVM, pPatch, pPB, &PATMRetRecord, 0, false);
    PATCHGEN_EPILOG(pPatch, size);

    STAM_COUNTER_INC(&pVM->patm.s.StatGenRet);
    /* Duplicate the ret or ret n instruction; it will use the PATM return address */
    rc = patmPatchGenDuplicate(pVM, pPatch, pCpu, pCurInstrGC);

    if (rc == VINF_SUCCESS)
    {
        pPatch->pTempInfo->pPatchRetInstrGC = pPatchRetInstrGC;
        pPatch->pTempInfo->uPatchRetParam1  = pCpu->param1.parval;
    }
    return rc;
}

/**
 * Generate all global patm functions
 *
 * @returns VBox status code.
 * @param   pVM         The VM to operate on.
 * @param   pPatch      Patch structure
 *
 */
int patmPatchGenGlobalFunctions(PVM pVM, PPATCHINFO pPatch)
{
    int size = 0;

    pVM->patm.s.pfnHelperCallGC = PATCHCODE_PTR_GC(pPatch) + pPatch->uCurPatchOffset;
    PATCHGEN_PROLOG(pVM, pPatch);
    size = patmPatchGenCode(pVM, pPatch, pPB, &PATMLookupAndCallRecord, 0, false);
    PATCHGEN_EPILOG(pPatch, size);

    /* Round to next 8 byte boundary. */
    pPatch->uCurPatchOffset = RT_ALIGN_32(pPatch->uCurPatchOffset, 8);

    pVM->patm.s.pfnHelperRetGC = PATCHCODE_PTR_GC(pPatch) + pPatch->uCurPatchOffset;
    PATCHGEN_PROLOG_NODEF(pVM, pPatch);
    size = patmPatchGenCode(pVM, pPatch, pPB, &PATMRetFunctionRecord, 0, false);
    PATCHGEN_EPILOG(pPatch, size);

    /* Round to next 8 byte boundary. */
    pPatch->uCurPatchOffset = RT_ALIGN_32(pPatch->uCurPatchOffset, 8);

    pVM->patm.s.pfnHelperJumpGC = PATCHCODE_PTR_GC(pPatch) + pPatch->uCurPatchOffset;
    PATCHGEN_PROLOG_NODEF(pVM, pPatch);
    size = patmPatchGenCode(pVM, pPatch, pPB, &PATMLookupAndJumpRecord, 0, false);
    PATCHGEN_EPILOG(pPatch, size);

    /* Round to next 8 byte boundary. */
    pPatch->uCurPatchOffset = RT_ALIGN_32(pPatch->uCurPatchOffset, 8);

    pVM->patm.s.pfnHelperIretGC = PATCHCODE_PTR_GC(pPatch) + pPatch->uCurPatchOffset;
    PATCHGEN_PROLOG_NODEF(pVM, pPatch);
    size = patmPatchGenCode(pVM, pPatch, pPB, &PATMIretFunctionRecord, 0, false);
    PATCHGEN_EPILOG(pPatch, size);

    Log(("pfnHelperCallGC %RRv\n", pVM->patm.s.pfnHelperCallGC));
    Log(("pfnHelperRetGC  %RRv\n", pVM->patm.s.pfnHelperRetGC));
    Log(("pfnHelperJumpGC %RRv\n", pVM->patm.s.pfnHelperJumpGC));
    Log(("pfnHelperIretGC %RRv\n", pVM->patm.s.pfnHelperIretGC));

    return VINF_SUCCESS;
}

/**
 * Generate illegal instruction (int 3)
 *
 * @returns VBox status code.
 * @param   pVM         The VM to operate on.
 * @param   pPatch      Patch structure
 *
 */
int patmPatchGenIllegalInstr(PVM pVM, PPATCHINFO pPatch)
{
    PATCHGEN_PROLOG(pVM, pPatch);

    pPB[0] = 0xCC;

    PATCHGEN_EPILOG(pPatch, 1);
    return VINF_SUCCESS;
}

/**
 * Check virtual IF flag and jump back to original guest code if set
 *
 * @returns VBox status code.
 * @param   pVM         The VM to operate on.
 * @param   pPatch      Patch structure
 * @param   pCurInstrGC Guest context pointer to the current instruction
 *
 */
int patmPatchGenCheckIF(PVM pVM, PPATCHINFO pPatch, RTRCPTR pCurInstrGC)
{
    uint32_t size;

    PATCHGEN_PROLOG(pVM, pPatch);

    /* Add lookup record for patch to guest address translation */
    patmr3AddP2GLookupRecord(pVM, pPatch, pPB, pCurInstrGC, PATM_LOOKUP_PATCH2GUEST);

    /* Generate code to check for IF=1 before executing the call to the duplicated function. */
    size = patmPatchGenCode(pVM, pPatch, pPB, &PATMCheckIFRecord, pCurInstrGC, true);

    PATCHGEN_EPILOG(pPatch, size);
    return VINF_SUCCESS;
}

/**
 * Set PATM interrupt flag
 *
 * @returns VBox status code.
 * @param   pVM         The VM to operate on.
 * @param   pPatch      Patch structure
 * @param   pInstrGC    Corresponding guest instruction
 *
 */
int patmPatchGenSetPIF(PVM pVM, PPATCHINFO pPatch, RTRCPTR pInstrGC)
{
    PATCHGEN_PROLOG(pVM, pPatch);

    /* Add lookup record for patch to guest address translation */
    patmr3AddP2GLookupRecord(pVM, pPatch, pPB, pInstrGC, PATM_LOOKUP_PATCH2GUEST);

    int size = patmPatchGenCode(pVM, pPatch, pPB, &PATMSetPIFRecord, 0, false);
    PATCHGEN_EPILOG(pPatch, size);
    return VINF_SUCCESS;
}

/**
 * Clear PATM interrupt flag
 *
 * @returns VBox status code.
 * @param   pVM         The VM to operate on.
 * @param   pPatch      Patch structure
 * @param   pInstrGC    Corresponding guest instruction
 *
 */
int patmPatchGenClearPIF(PVM pVM, PPATCHINFO pPatch, RTRCPTR pInstrGC)
{
    PATCHGEN_PROLOG(pVM, pPatch);

    /* Add lookup record for patch to guest address translation */
    patmr3AddP2GLookupRecord(pVM, pPatch, pPB, pInstrGC, PATM_LOOKUP_PATCH2GUEST);

    int size = patmPatchGenCode(pVM, pPatch, pPB, &PATMClearPIFRecord, 0, false);
    PATCHGEN_EPILOG(pPatch, size);
    return VINF_SUCCESS;
}


/**
 * Clear PATM inhibit irq flag
 *
 * @returns VBox status code.
 * @param   pVM             The VM to operate on.
 * @param   pPatch          Patch structure
 * @param   pNextInstrGC    Next guest instruction
 */
int patmPatchGenClearInhibitIRQ(PVM pVM, PPATCHINFO pPatch, RTRCPTR pNextInstrGC)
{
    int          size;
    PATMCALLINFO callInfo;

    PATCHGEN_PROLOG(pVM, pPatch);

    Assert((pPatch->flags & (PATMFL_GENERATE_JUMPTOGUEST|PATMFL_DUPLICATE_FUNCTION)) != (PATMFL_GENERATE_JUMPTOGUEST|PATMFL_DUPLICATE_FUNCTION));

    /* Add lookup record for patch to guest address translation */
    patmr3AddP2GLookupRecord(pVM, pPatch, pPB, pNextInstrGC, PATM_LOOKUP_PATCH2GUEST);

    callInfo.pNextInstrGC = pNextInstrGC;

    if (pPatch->flags & PATMFL_DUPLICATE_FUNCTION)
        size = patmPatchGenCode(pVM, pPatch, pPB, &PATMClearInhibitIRQContIF0Record, 0, false, &callInfo);
    else
        size = patmPatchGenCode(pVM, pPatch, pPB, &PATMClearInhibitIRQFaultIF0Record, 0, false, &callInfo);

    PATCHGEN_EPILOG(pPatch, size);
    return VINF_SUCCESS;
}

/**
 * Generate an interrupt handler entrypoint
 *
 * @returns VBox status code.
 * @param   pVM         The VM to operate on.
 * @param   pPatch      Patch record
 * @param   pIntHandlerGC IDT handler address
 *
 ** @todo must check if virtual IF is already cleared on entry!!!!!!!!!!!!!!!!!!!!!!!
 */
int patmPatchGenIntEntry(PVM pVM, PPATCHINFO pPatch, RTRCPTR pIntHandlerGC)
{
    uint32_t size;
    int rc = VINF_SUCCESS;

    PATCHGEN_PROLOG(pVM, pPatch);

    /* Add lookup record for patch to guest address translation */
    patmr3AddP2GLookupRecord(pVM, pPatch, pPB, pIntHandlerGC, PATM_LOOKUP_PATCH2GUEST);

    /* Generate entrypoint for the interrupt handler (correcting CS in the interrupt stack frame) */
    size = patmPatchGenCode(pVM, pPatch, pPB,
                            (pPatch->flags & PATMFL_INTHANDLER_WITH_ERRORCODE) ? &PATMIntEntryRecordErrorCode : &PATMIntEntryRecord,
                            0, false);

    PATCHGEN_EPILOG(pPatch, size);

    // Interrupt gates set IF to 0
    rc = patmPatchGenCli(pVM, pPatch);
    AssertRCReturn(rc, rc);

    return rc;
}

/**
 * Generate a trap handler entrypoint
 *
 * @returns VBox status code.
 * @param   pVM         The VM to operate on.
 * @param   pPatch      Patch record
 * @param   pTrapHandlerGC  IDT handler address
 */
int patmPatchGenTrapEntry(PVM pVM, PPATCHINFO pPatch, RTRCPTR pTrapHandlerGC)
{
    uint32_t size;

    PATCHGEN_PROLOG(pVM, pPatch);

    /* Add lookup record for patch to guest address translation */
    patmr3AddP2GLookupRecord(pVM, pPatch, pPB, pTrapHandlerGC, PATM_LOOKUP_PATCH2GUEST);

    /* Generate entrypoint for the trap handler (correcting CS in the interrupt stack frame) */
    size = patmPatchGenCode(pVM, pPatch, pPB,
                            (pPatch->flags & PATMFL_TRAPHANDLER_WITH_ERRORCODE) ? &PATMTrapEntryRecordErrorCode : &PATMTrapEntryRecord,
                            pTrapHandlerGC, true);
    PATCHGEN_EPILOG(pPatch, size);

    return VINF_SUCCESS;
}

#ifdef VBOX_WITH_STATISTICS
int patmPatchGenStats(PVM pVM, PPATCHINFO pPatch, RTRCPTR pInstrGC)
{
    uint32_t size;

    PATCHGEN_PROLOG(pVM, pPatch);

    /* Add lookup record for stats code -> guest handler. */
    patmr3AddP2GLookupRecord(pVM, pPatch, pPB, pInstrGC, PATM_LOOKUP_PATCH2GUEST);

    /* Generate code to keep calling statistics for this patch */
    size = patmPatchGenCode(pVM, pPatch, pPB, &PATMStatsRecord, pInstrGC, false);
    PATCHGEN_EPILOG(pPatch, size);

    return VINF_SUCCESS;
}
#endif

/**
 * Debug register moves to or from general purpose registers
 * mov GPR, DRx
 * mov DRx, GPR
 *
 * @todo: if we ever want to support hardware debug registers natively, then
 *        this will need to be changed!
 */
int patmPatchGenMovDebug(PVM pVM, PPATCHINFO pPatch, DISCPUSTATE *pCpu)
{
    int rc = VINF_SUCCESS;
    int reg, mod, rm, dbgreg;
    uint32_t offset;

    PATCHGEN_PROLOG(pVM, pPatch);

    mod = 0;            //effective address (only)
    rm  = 5;            //disp32
    if (pCpu->pCurInstr->param1 == OP_PARM_Dd)
    {
        Assert(0);  // You not come here. Illegal!

        // mov DRx, GPR
        pPB[0] = 0x89;      //mov disp32, GPR
        Assert(pCpu->param1.flags & USE_REG_DBG);
        Assert(pCpu->param2.flags & USE_REG_GEN32);

        dbgreg = pCpu->param1.base.reg_dbg;
        reg    = pCpu->param2.base.reg_gen;
    }
    else
    {
        // mov GPR, DRx
        Assert(pCpu->param1.flags & USE_REG_GEN32);
        Assert(pCpu->param2.flags & USE_REG_DBG);

        pPB[0] = 0x8B;      // mov GPR, disp32
        reg    = pCpu->param1.base.reg_gen;
        dbgreg = pCpu->param2.base.reg_dbg;
    }

    pPB[1] = MAKE_MODRM(mod, reg, rm);

    AssertReturn(dbgreg <= USE_REG_DR7, VERR_INVALID_PARAMETER);
    offset = RT_OFFSETOF(CPUMCTX, dr[dbgreg]);

    *(RTRCPTR *)&pPB[2] = pVM->patm.s.pCPUMCtxGC + offset;
    patmPatchAddReloc32(pVM, pPatch, &pPB[2], FIXUP_ABSOLUTE);

    PATCHGEN_EPILOG(pPatch, 2 + sizeof(RTRCPTR));
    return rc;
}

/*
 * Control register moves to or from general purpose registers
 * mov GPR, CRx
 * mov CRx, GPR
 */
int patmPatchGenMovControl(PVM pVM, PPATCHINFO pPatch, DISCPUSTATE *pCpu)
{
    int rc = VINF_SUCCESS;
    int reg, mod, rm, ctrlreg;
    uint32_t offset;

    PATCHGEN_PROLOG(pVM, pPatch);

    mod = 0;            //effective address (only)
    rm  = 5;            //disp32
    if (pCpu->pCurInstr->param1 == OP_PARM_Cd)
    {
        Assert(0);  // You not come here. Illegal!

        // mov CRx, GPR
        pPB[0] = 0x89;      //mov disp32, GPR
        ctrlreg = pCpu->param1.base.reg_ctrl;
        reg     = pCpu->param2.base.reg_gen;
        Assert(pCpu->param1.flags & USE_REG_CR);
        Assert(pCpu->param2.flags & USE_REG_GEN32);
    }
    else
    {
        // mov GPR, DRx
        Assert(pCpu->param1.flags & USE_REG_GEN32);
        Assert(pCpu->param2.flags & USE_REG_CR);

        pPB[0]  = 0x8B;      // mov GPR, disp32
        reg     = pCpu->param1.base.reg_gen;
        ctrlreg = pCpu->param2.base.reg_ctrl;
    }

    pPB[1] = MAKE_MODRM(mod, reg, rm);

    /// @todo: make this an array in the context structure
    switch (ctrlreg)
    {
    case USE_REG_CR0:
        offset = RT_OFFSETOF(CPUMCTX, cr0);
        break;
    case USE_REG_CR2:
        offset = RT_OFFSETOF(CPUMCTX, cr2);
        break;
    case USE_REG_CR3:
        offset = RT_OFFSETOF(CPUMCTX, cr3);
        break;
    case USE_REG_CR4:
        offset = RT_OFFSETOF(CPUMCTX, cr4);
        break;
    default: /* Shut up compiler warning. */
        AssertFailed();
        offset = 0;
        break;
    }
    *(RTRCPTR *)&pPB[2] = pVM->patm.s.pCPUMCtxGC + offset;
    patmPatchAddReloc32(pVM, pPatch, &pPB[2], FIXUP_ABSOLUTE);

    PATCHGEN_EPILOG(pPatch, 2 + sizeof(RTRCPTR));
    return rc;
}

/*
 * mov GPR, SS
 */
int patmPatchGenMovFromSS(PVM pVM, PPATCHINFO pPatch, DISCPUSTATE *pCpu, RTRCPTR pCurInstrGC)
{
    uint32_t size, offset;

    Log(("patmPatchGenMovFromSS %RRv\n", pCurInstrGC));

    Assert(pPatch->flags & PATMFL_CODE32);

    PATCHGEN_PROLOG(pVM, pPatch);
    size = patmPatchGenCode(pVM, pPatch, pPB, &PATMClearPIFRecord, 0, false);
    PATCHGEN_EPILOG(pPatch, size);

    /* push ss */
    PATCHGEN_PROLOG_NODEF(pVM, pPatch);
    offset = 0;
    if (pCpu->prefix & PREFIX_OPSIZE)
        pPB[offset++] = 0x66;       /* size override -> 16 bits push */
    pPB[offset++] = 0x16;
    PATCHGEN_EPILOG(pPatch, offset);

    /* checks and corrects RPL of pushed ss*/
    PATCHGEN_PROLOG_NODEF(pVM, pPatch);
    size = patmPatchGenCode(pVM, pPatch, pPB, &PATMMovFromSSRecord, 0, false);
    PATCHGEN_EPILOG(pPatch, size);

    /* pop general purpose register */
    PATCHGEN_PROLOG_NODEF(pVM, pPatch);
    offset = 0;
    if (pCpu->prefix & PREFIX_OPSIZE)
        pPB[offset++] = 0x66; /* size override -> 16 bits pop */
    pPB[offset++] = 0x58 + pCpu->param1.base.reg_gen;
    PATCHGEN_EPILOG(pPatch, offset);


    PATCHGEN_PROLOG_NODEF(pVM, pPatch);
    size = patmPatchGenCode(pVM, pPatch, pPB, &PATMSetPIFRecord, 0, false);
    PATCHGEN_EPILOG(pPatch, size);

    return VINF_SUCCESS;
}


/**
 * Generate an sldt or str patch instruction
 *
 * @returns VBox status code.
 * @param   pVM         The VM to operate on.
 * @param   pPatch      Patch record
 * @param   pCpu        Disassembly state
 * @param   pCurInstrGC Guest instruction address
 */
int patmPatchGenSldtStr(PVM pVM, PPATCHINFO pPatch, DISCPUSTATE *pCpu, RTRCPTR pCurInstrGC)
{
    // sldt %Ew
    int rc = VINF_SUCCESS;
    uint32_t offset = 0;
    uint32_t i;

    /** @todo segment prefix (untested) */
    Assert(pCpu->prefix == PREFIX_NONE || pCpu->prefix == PREFIX_OPSIZE);

    PATCHGEN_PROLOG(pVM, pPatch);

    if (pCpu->param1.flags == USE_REG_GEN32 || pCpu->param1.flags == USE_REG_GEN16)
    {
        /* Register operand */
        // 8B 15 [32 bits addr]   mov edx, CPUMCTX.tr/ldtr

        if (pCpu->prefix == PREFIX_OPSIZE)
            pPB[offset++] = 0x66;

        pPB[offset++] = 0x8B;              // mov       destreg, CPUMCTX.tr/ldtr
        /* Modify REG part according to destination of original instruction */
        pPB[offset++] = MAKE_MODRM(0, pCpu->param1.base.reg_gen, 5);
        if (pCpu->pCurInstr->opcode == OP_STR)
        {
            *(RTRCPTR *)&pPB[offset] = pVM->patm.s.pCPUMCtxGC + RT_OFFSETOF(CPUMCTX, tr);
        }
        else
        {
            *(RTRCPTR *)&pPB[offset] = pVM->patm.s.pCPUMCtxGC + RT_OFFSETOF(CPUMCTX, ldtr);
        }
        patmPatchAddReloc32(pVM, pPatch, &pPB[offset], FIXUP_ABSOLUTE);
        offset += sizeof(RTRCPTR);
    }
    else
    {
        /* Memory operand */
        //50                   push        eax
        //52                   push        edx
        //8D 15 48 7C 42 00    lea         edx, dword ptr [dest]
        //66 A1 48 7C 42 00    mov         ax, CPUMCTX.tr/ldtr
        //66 89 02             mov         word ptr [edx],ax
        //5A                   pop         edx
        //58                   pop         eax

        pPB[offset++] = 0x50;              // push      eax
        pPB[offset++] = 0x52;              // push      edx

        if (pCpu->prefix == PREFIX_SEG)
        {
            pPB[offset++] = DISQuerySegPrefixByte(pCpu);
        }
        pPB[offset++] = 0x8D;              // lea       edx, dword ptr [dest]
        // duplicate and modify modrm byte and additional bytes if present (e.g. direct address)
        pPB[offset++] = MAKE_MODRM(pCpu->ModRM.Bits.Mod, USE_REG_EDX, pCpu->ModRM.Bits.Rm);

        i = 3;  /* standard offset of modrm bytes */
        if (pCpu->prefix == PREFIX_OPSIZE)
            i++;    //skip operand prefix
        if (pCpu->prefix == PREFIX_SEG)
            i++;    //skip segment prefix

        rc = patmPatchReadBytes(pVM, &pPB[offset], (RTRCPTR)((RTGCUINTPTR32)pCurInstrGC + i), pCpu->opsize - i);
        AssertRCReturn(rc, rc);
        offset += (pCpu->opsize - i);

        pPB[offset++] = 0x66;              // mov       ax, CPUMCTX.tr/ldtr
        pPB[offset++] = 0xA1;
        if (pCpu->pCurInstr->opcode == OP_STR)
        {
            *(RTRCPTR *)&pPB[offset] = pVM->patm.s.pCPUMCtxGC + RT_OFFSETOF(CPUMCTX, tr);
        }
        else
        {
            *(RTRCPTR *)&pPB[offset] = pVM->patm.s.pCPUMCtxGC + RT_OFFSETOF(CPUMCTX, ldtr);
        }
        patmPatchAddReloc32(pVM, pPatch, &pPB[offset], FIXUP_ABSOLUTE);
        offset += sizeof(RTRCPTR);

        pPB[offset++] = 0x66;              // mov       word ptr [edx],ax
        pPB[offset++] = 0x89;
        pPB[offset++] = 0x02;

        pPB[offset++] = 0x5A;              // pop       edx
        pPB[offset++] = 0x58;              // pop       eax
    }

    PATCHGEN_EPILOG(pPatch, offset);

    return rc;
}

/**
 * Generate an sgdt or sidt patch instruction
 *
 * @returns VBox status code.
 * @param   pVM         The VM to operate on.
 * @param   pPatch      Patch record
 * @param   pCpu        Disassembly state
 * @param   pCurInstrGC Guest instruction address
 */
int patmPatchGenSxDT(PVM pVM, PPATCHINFO pPatch, DISCPUSTATE *pCpu, RTRCPTR pCurInstrGC)
{
    int rc = VINF_SUCCESS;
    uint32_t offset = 0, offset_base, offset_limit;
    uint32_t i;

    /* @todo segment prefix (untested) */
    Assert(pCpu->prefix == PREFIX_NONE);

    // sgdt %Ms
    // sidt %Ms

    switch (pCpu->pCurInstr->opcode)
    {
    case OP_SGDT:
        offset_base  = RT_OFFSETOF(CPUMCTX, gdtr.pGdt);
        offset_limit = RT_OFFSETOF(CPUMCTX, gdtr.cbGdt);
        break;

    case OP_SIDT:
        offset_base  = RT_OFFSETOF(CPUMCTX, idtr.pIdt);
        offset_limit = RT_OFFSETOF(CPUMCTX, idtr.cbIdt);
        break;

    default:
        return VERR_INVALID_PARAMETER;
    }

//50                   push        eax
//52                   push        edx
//8D 15 48 7C 42 00    lea         edx, dword ptr [dest]
//66 A1 48 7C 42 00    mov         ax, CPUMCTX.gdtr.limit
//66 89 02             mov         word ptr [edx],ax
//A1 48 7C 42 00       mov         eax, CPUMCTX.gdtr.base
//89 42 02             mov         dword ptr [edx+2],eax
//5A                   pop         edx
//58                   pop         eax

    PATCHGEN_PROLOG(pVM, pPatch);
    pPB[offset++] = 0x50;              // push      eax
    pPB[offset++] = 0x52;              // push      edx

    if (pCpu->prefix == PREFIX_SEG)
    {
        pPB[offset++] = DISQuerySegPrefixByte(pCpu);
    }
    pPB[offset++] = 0x8D;              // lea       edx, dword ptr [dest]
    // duplicate and modify modrm byte and additional bytes if present (e.g. direct address)
    pPB[offset++] = MAKE_MODRM(pCpu->ModRM.Bits.Mod, USE_REG_EDX, pCpu->ModRM.Bits.Rm);

    i = 3;  /* standard offset of modrm bytes */
    if (pCpu->prefix == PREFIX_OPSIZE)
        i++;    //skip operand prefix
    if (pCpu->prefix == PREFIX_SEG)
        i++;    //skip segment prefix
    rc = patmPatchReadBytes(pVM, &pPB[offset], (RTRCPTR)((RTGCUINTPTR32)pCurInstrGC + i), pCpu->opsize - i);
    AssertRCReturn(rc, rc);
    offset += (pCpu->opsize - i);

    pPB[offset++] = 0x66;              // mov       ax, CPUMCTX.gdtr.limit
    pPB[offset++] = 0xA1;
    *(RTRCPTR *)&pPB[offset] = pVM->patm.s.pCPUMCtxGC + offset_limit;
    patmPatchAddReloc32(pVM, pPatch, &pPB[offset], FIXUP_ABSOLUTE);
    offset += sizeof(RTRCPTR);

    pPB[offset++] = 0x66;              // mov       word ptr [edx],ax
    pPB[offset++] = 0x89;
    pPB[offset++] = 0x02;

    pPB[offset++] = 0xA1;              // mov       eax, CPUMCTX.gdtr.base
    *(RTRCPTR *)&pPB[offset] = pVM->patm.s.pCPUMCtxGC + offset_base;
    patmPatchAddReloc32(pVM, pPatch, &pPB[offset], FIXUP_ABSOLUTE);
    offset += sizeof(RTRCPTR);

    pPB[offset++] = 0x89;              // mov       dword ptr [edx+2],eax
    pPB[offset++] = 0x42;
    pPB[offset++] = 0x02;

    pPB[offset++] = 0x5A;              // pop       edx
    pPB[offset++] = 0x58;              // pop       eax

    PATCHGEN_EPILOG(pPatch, offset);

    return rc;
}

/**
 * Generate a cpuid patch instruction
 *
 * @returns VBox status code.
 * @param   pVM         The VM to operate on.
 * @param   pPatch      Patch record
 * @param   pCurInstrGC Guest instruction address
 */
int patmPatchGenCpuid(PVM pVM, PPATCHINFO pPatch, RTRCPTR pCurInstrGC)
{
    uint32_t size;
    PATCHGEN_PROLOG(pVM, pPatch);

    size = patmPatchGenCode(pVM, pPatch, pPB, &PATMCpuidRecord, 0, false);

    PATCHGEN_EPILOG(pPatch, size);
    return VINF_SUCCESS;
}

/**
 * Generate the jump from guest to patch code
 *
 * @returns VBox status code.
 * @param   pVM         The VM to operate on.
 * @param   pPatch      Patch record
 * @param   pTargetGC   Guest target jump
 * @param   fClearInhibitIRQs   Clear inhibit irq flag
 */
int patmPatchGenJumpToGuest(PVM pVM, PPATCHINFO pPatch, RCPTRTYPE(uint8_t *) pReturnAddrGC, bool fClearInhibitIRQs)
{
    int rc = VINF_SUCCESS;
    uint32_t size;

    if (fClearInhibitIRQs)
    {
        rc = patmPatchGenClearInhibitIRQ(pVM, pPatch, pReturnAddrGC);
        if (rc == VERR_NO_MEMORY)
            return rc;
        AssertRCReturn(rc, rc);
    }

    PATCHGEN_PROLOG(pVM, pPatch);

    /* Add lookup record for patch to guest address translation */
    patmr3AddP2GLookupRecord(pVM, pPatch, pPB, pReturnAddrGC, PATM_LOOKUP_PATCH2GUEST);

    /* Generate code to jump to guest code if IF=1, else fault. */
    size = patmPatchGenCode(pVM, pPatch, pPB, &PATMJumpToGuest_IF1Record, pReturnAddrGC, true);
    PATCHGEN_EPILOG(pPatch, size);

    return rc;
}

/*
 * Relative jump from patch code to patch code (no fixup required)
 */
int patmPatchGenPatchJump(PVM pVM, PPATCHINFO pPatch, RTRCPTR pCurInstrGC, RCPTRTYPE(uint8_t *) pPatchAddrGC, bool fAddLookupRecord)
{
    int32_t displ;
    int     rc = VINF_SUCCESS;

    Assert(PATMIsPatchGCAddr(pVM, pPatchAddrGC));
    PATCHGEN_PROLOG(pVM, pPatch);

    if (fAddLookupRecord)
    {
        /* Add lookup record for patch to guest address translation */
        patmr3AddP2GLookupRecord(pVM, pPatch, pPB, pCurInstrGC, PATM_LOOKUP_PATCH2GUEST);
    }

    pPB[0] = 0xE9;  //JMP

    displ = pPatchAddrGC - (PATCHCODE_PTR_GC(pPatch) + pPatch->uCurPatchOffset + SIZEOF_NEARJUMP32);

     *(uint32_t *)&pPB[1] = displ;

    PATCHGEN_EPILOG(pPatch, SIZEOF_NEARJUMP32);

    return rc;
}