-
Notifications
You must be signed in to change notification settings - Fork 554
/
drreg.c
2136 lines (1990 loc) · 86.8 KB
/
drreg.c
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
/* **********************************************************
* Copyright (c) 2013-2021 Google, Inc. All rights reserved.
* **********************************************************/
/*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of Google, Inc. nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL GOOGLE, INC. OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
/* DynamoRIO Register Management Extension: a mediator for
* selecting, preserving, and using registers among multiple
* instrumentation components.
*/
/* XXX i#511: currently the whole interface is tied to drmgr.
* Should we also provide an interface that works on standalone instrlists?
* Distinguish by name, "drregi_*" or sthg.
*/
#include "dr_api.h"
#include "drmgr.h"
#include "drvector.h"
#include "drreg.h"
#include "../ext_utils.h"
#include <string.h>
#include <limits.h>
#include <stddef.h> /* offsetof */
#ifdef DEBUG
# define ASSERT(x, msg) DR_ASSERT_MSG(x, msg)
# define LOG(dc, mask, level, ...) dr_log(dc, mask, level, __VA_ARGS__)
#else
# define ASSERT(x, msg) /* nothing */
# define LOG(dc, mask, level, ...) /* nothing */
#endif
#ifdef WINDOWS
# define DISPLAY_ERROR(msg) dr_messagebox(msg)
#else
# define DISPLAY_ERROR(msg) dr_fprintf(STDERR, "%s\n", msg);
#endif
#define PRE instrlist_meta_preinsert
/* This should be pretty hard to exceed as there aren't this many GPRs */
#define MAX_SPILLS (SPILL_SLOT_MAX + 8)
/* We store data about spill slot usage in the data area of a label instr. */
#define SPILL_SLOT_ID_LABEL_INSTR_DATA_AREA_OFFSET 0
/* Arbitrary base to avoid conflict of default zero value in label data
* slot with the zero-numbered spill slot.
*/
#define SPILL_SLOT_ID_BASE 100
#define AFLAGS_SLOT 0 /* always */
/* We support using GPR registers only: [DR_REG_START_GPR..DR_REG_STOP_GPR] */
#define REG_DEAD ((void *)(ptr_uint_t)0)
#define REG_LIVE ((void *)(ptr_uint_t)1)
#define REG_UNKNOWN ((void *)(ptr_uint_t)2) /* only used outside drmgr insert phase */
typedef struct _reg_info_t {
/* XXX: better to flip around and store bitvector of registers per instr
* in a single drvector_t?
*/
/* The live vector holds one entry per app instr in the bb.
* For registers, each vector entry holds REG_{LIVE,DEAD}.
* For aflags, each vector entry holds a ptr_uint_t with the EFLAGS_READ_ARITH bits
* telling which arithmetic flags are live at that point.
*/
drvector_t live;
bool in_use;
uint app_uses; /* # of uses in this bb by app */
/* With lazy restore, and b/c we must set native to false, we need to record
* whether we spilled or not (we could instead record live_idx at time of
* reservation).
*/
bool ever_spilled;
/* Where is the app value for this reg? */
bool native; /* app value is in original app reg */
reg_id_t xchg; /* if !native && != REG_NULL, value was exchanged w/ this dead reg */
int slot; /* if !native && xchg==REG_NULL, value is in this TLS slot # */
} reg_info_t;
/* We use this in per_thread_t.slot_use[] and other places */
#define DR_REG_EFLAGS DR_REG_INVALID
#define GPR_IDX(reg) ((reg)-DR_REG_START_GPR)
typedef struct _per_thread_t {
instr_t *cur_instr;
int live_idx;
reg_info_t reg[DR_NUM_GPR_REGS];
reg_info_t aflags;
reg_id_t slot_use[MAX_SPILLS]; /* holds the reg_id_t of which reg is inside */
int pending_unreserved; /* count of to-be-lazily-restored unreserved regs */
/* We store the linear address of our TLS for access from another thread: */
byte *tls_seg_base;
/* bb-local values */
drreg_bb_properties_t bb_props;
bool bb_has_internal_flow;
} per_thread_t;
/* Enum describing the different types of notes in drreg. */
enum { DRREG_NOTE_SPILL_SLOT_ID, DRREG_NOTE_COUNT };
static drreg_options_t ops;
static int tls_idx = -1;
static uint tls_slot_offs;
static reg_id_t tls_seg;
#ifdef DEBUG
static uint stats_max_slot;
#endif
static per_thread_t *
get_tls_data(void *drcontext);
static drreg_status_t
drreg_restore_reg_now(void *drcontext, instrlist_t *ilist, instr_t *inst,
per_thread_t *pt, reg_id_t reg);
static void
drreg_move_aflags_from_reg(void *drcontext, instrlist_t *ilist, instr_t *where,
per_thread_t *pt, bool stateful);
static drreg_status_t
drreg_restore_aflags(void *drcontext, instrlist_t *ilist, instr_t *where,
per_thread_t *pt, bool release);
static drreg_status_t
drreg_spill_aflags(void *drcontext, instrlist_t *ilist, instr_t *where, per_thread_t *pt);
static void
drreg_report_error(drreg_status_t res, const char *msg)
{
if (ops.error_callback != NULL) {
if ((*ops.error_callback)(res))
return;
}
ASSERT(false, msg);
DISPLAY_ERROR(msg);
dr_abort();
}
#ifdef DEBUG
static inline app_pc
get_where_app_pc(instr_t *where)
{
if (where == NULL)
return NULL;
return instr_get_app_pc(where);
}
#endif
/***************************************************************************
* SPILLING AND RESTORING
*/
static ptr_uint_t drreg_note_base;
/* Get note value for a drreg instr note. */
static inline ptr_uint_t
get_drreg_note_val(uint val)
{
return (ptr_uint_t)(drreg_note_base + val);
}
/* Returns whether the given ilist has an existing usage of the given slot
* on or after `where`. Such a usage, if any, must have been added by a
* previous instrumentation pass, and tells us that it is not safe to reuse
* the slot in the current pass.
*/
static bool
has_pending_slot_usage_by_prior_pass(per_thread_t *pt, instrlist_t *ilist, instr_t *where,
uint slot)
{
if (!TEST(DRREG_HANDLE_MULTI_PHASE_SLOT_RESERVATIONS, pt->bb_props))
return false;
for (instr_t *in = where; in != NULL; in = instr_get_next(in)) {
/* We store data about spill slot usage in the data area of a label instr
* immediately following the usage.
*/
if (instr_is_label(in) &&
instr_get_note(in) == (void *)get_drreg_note_val(DRREG_NOTE_SPILL_SLOT_ID)) {
dr_instr_label_data_t *data = instr_get_label_data_area(in);
ASSERT(data != NULL, "failed to find label's data area");
/* Try to continue in release build. */
if (data != NULL &&
data->data[SPILL_SLOT_ID_LABEL_INSTR_DATA_AREA_OFFSET] ==
SPILL_SLOT_ID_BASE + slot) {
return true;
}
}
}
return false;
}
static uint
find_free_slot(per_thread_t *pt, instrlist_t *ilist, instr_t *where)
{
uint i;
/* 0 is always reserved for AFLAGS_SLOT */
ASSERT(AFLAGS_SLOT == 0, "AFLAGS_SLOT is not 0");
for (i = AFLAGS_SLOT + 1; i < MAX_SPILLS; i++) {
if (pt->slot_use[i] == DR_REG_NULL &&
!has_pending_slot_usage_by_prior_pass(pt, ilist, where, i)) {
return i;
}
}
return MAX_SPILLS;
}
/* Up to caller to update pt->reg, including .ever_spilled.
* This routine updates pt->slot_use.
*/
static void
spill_reg(void *drcontext, per_thread_t *pt, reg_id_t reg, uint slot, instrlist_t *ilist,
instr_t *where)
{
LOG(drcontext, DR_LOG_ALL, 3, "%s @%d." PFX " %s %d\n", __FUNCTION__, pt->live_idx,
get_where_app_pc(where), get_register_name(reg), slot);
ASSERT(pt->slot_use[slot] == DR_REG_NULL || pt->slot_use[slot] == reg ||
/* aflags can be saved and restored using different regs */
slot == AFLAGS_SLOT,
"internal tracking error");
if (slot == AFLAGS_SLOT)
pt->aflags.ever_spilled = true;
pt->slot_use[slot] = reg;
if (slot < ops.num_spill_slots) {
dr_insert_write_raw_tls(drcontext, ilist, where, tls_seg,
tls_slot_offs + slot * sizeof(reg_t), reg);
} else {
dr_spill_slot_t DR_slot = (dr_spill_slot_t)(slot - ops.num_spill_slots);
dr_save_reg(drcontext, ilist, where, reg, DR_slot);
}
instr_t *spill_slot_data_label = INSTR_CREATE_label(drcontext);
dr_instr_label_data_t *data = instr_get_label_data_area(spill_slot_data_label);
ASSERT(data != NULL, "failed to find label's data area");
/* Try to continue in release build. */
if (data != NULL) {
data->data[SPILL_SLOT_ID_LABEL_INSTR_DATA_AREA_OFFSET] =
(ptr_uint_t)slot + SPILL_SLOT_ID_BASE;
}
instr_set_note(spill_slot_data_label,
(void *)get_drreg_note_val(DRREG_NOTE_SPILL_SLOT_ID));
/* This must immediately follow the spill instrs inserted above. */
PRE(ilist, where, spill_slot_data_label);
#ifdef DEBUG
if (slot > stats_max_slot)
stats_max_slot = slot; /* racy but that's ok */
#endif
}
/* Up to caller to update pt->reg. This routine updates pt->slot_use if release==true. */
static void
restore_reg(void *drcontext, per_thread_t *pt, reg_id_t reg, uint slot,
instrlist_t *ilist, instr_t *where, bool release)
{
LOG(drcontext, DR_LOG_ALL, 3, "%s @%d." PFX " %s slot=%d release=%d\n", __FUNCTION__,
pt->live_idx, get_where_app_pc(where), get_register_name(reg), slot, release);
ASSERT(pt->slot_use[slot] == reg ||
/* aflags can be saved and restored using different regs */
(slot == AFLAGS_SLOT && pt->slot_use[slot] != DR_REG_NULL),
"internal tracking error");
if (release) {
pt->slot_use[slot] = DR_REG_NULL;
}
if (slot < ops.num_spill_slots) {
dr_insert_read_raw_tls(drcontext, ilist, where, tls_seg,
tls_slot_offs + slot * sizeof(reg_t), reg);
} else {
dr_spill_slot_t DR_slot = (dr_spill_slot_t)(slot - ops.num_spill_slots);
dr_restore_reg(drcontext, ilist, where, reg, DR_slot);
}
if (release) {
instr_t *spill_slot_data_label = INSTR_CREATE_label(drcontext);
dr_instr_label_data_t *data = instr_get_label_data_area(spill_slot_data_label);
ASSERT(data != NULL, "failed to find label's data area");
/* Try to continue in release build. */
if (data != NULL) {
data->data[SPILL_SLOT_ID_LABEL_INSTR_DATA_AREA_OFFSET] =
(ptr_uint_t)slot + SPILL_SLOT_ID_BASE;
}
instr_set_note(spill_slot_data_label,
(void *)get_drreg_note_val(DRREG_NOTE_SPILL_SLOT_ID));
/* This must immediately follow the restore instrs inserted above. */
PRE(ilist, where, spill_slot_data_label);
}
}
static reg_t
get_spilled_value(void *drcontext, uint slot)
{
if (slot < ops.num_spill_slots) {
per_thread_t *pt = get_tls_data(drcontext);
return *(reg_t *)(pt->tls_seg_base + tls_slot_offs + slot * sizeof(reg_t));
} else {
dr_spill_slot_t DR_slot = (dr_spill_slot_t)(slot - ops.num_spill_slots);
return dr_read_saved_reg(drcontext, DR_slot);
}
}
drreg_status_t
drreg_max_slots_used(OUT uint *max)
{
#ifdef DEBUG
if (max == NULL)
return DRREG_ERROR_INVALID_PARAMETER;
*max = stats_max_slot;
return DRREG_SUCCESS;
#else
return DRREG_ERROR_FEATURE_NOT_AVAILABLE;
#endif
}
/***************************************************************************
* ANALYSIS AND CROSS-APP-INSTR
*/
static void
count_app_uses(per_thread_t *pt, opnd_t opnd)
{
int i;
for (i = 0; i < opnd_num_regs_used(opnd); i++) {
reg_id_t reg = opnd_get_reg_used(opnd, i);
if (reg_is_gpr(reg)) {
reg = reg_to_pointer_sized(reg);
pt->reg[GPR_IDX(reg)].app_uses++;
/* Tools that instrument memory uses (memtrace, Dr. Memory, etc.)
* want to double-count memory opnd uses, as they need to restore
* the app value to get the memory address into a register there.
* We go ahead and do that for all tools.
*/
if (opnd_is_memory_reference(opnd))
pt->reg[GPR_IDX(reg)].app_uses++;
}
}
}
/* This event has to go last, to handle labels inserted by other components:
* else our indices get off, and we can't simply skip labels in the
* per-instr event b/c we need the liveness to advance at the label
* but not after the label.
*/
static dr_emit_flags_t
drreg_event_bb_analysis(void *drcontext, void *tag, instrlist_t *bb, bool for_trace,
bool translating, OUT void **user_data)
{
per_thread_t *pt = get_tls_data(drcontext);
instr_t *inst;
ptr_uint_t aflags_new, aflags_cur = 0;
uint index = 0;
reg_id_t reg;
for (reg = DR_REG_START_GPR; reg <= DR_REG_STOP_GPR; reg++)
pt->reg[GPR_IDX(reg)].app_uses = 0;
/* pt->bb_props is set to 0 at thread init and after each bb */
pt->bb_has_internal_flow = false;
/* Reverse scan is more efficient. This means our indices are also reversed. */
for (inst = instrlist_last(bb); inst != NULL; inst = instr_get_prev(inst)) {
/* We consider both meta and app instrs, to handle rare cases of meta instrs
* being inserted during app2app for corner cases. An example are app2app
* emulation functions like drx_expand_scatter_gather().
*/
bool xfer =
(instr_is_cti(inst) || instr_is_interrupt(inst) || instr_is_syscall(inst));
if (!pt->bb_has_internal_flow && (instr_is_ubr(inst) || instr_is_cbr(inst)) &&
opnd_is_instr(instr_get_target(inst))) {
/* i#1954: we disable some opts in the presence of control flow. */
pt->bb_has_internal_flow = true;
LOG(drcontext, DR_LOG_ALL, 2,
"%s @%d." PFX ": disabling lazy restores due to intra-bb control flow\n",
__FUNCTION__, index, get_where_app_pc(inst));
}
/* GPR liveness */
LOG(drcontext, DR_LOG_ALL, 3, "%s @%d." PFX ":", __FUNCTION__, index,
get_where_app_pc(inst));
for (reg = DR_REG_START_GPR; reg <= DR_REG_STOP_GPR; reg++) {
void *value = REG_LIVE;
/* DRi#1849: COND_SRCS here includes addressing regs in dsts */
if (instr_reads_from_reg(inst, reg, DR_QUERY_INCLUDE_COND_SRCS))
value = REG_LIVE;
/* make sure we don't consider writes to sub-regs */
else if (instr_writes_to_exact_reg(inst, reg, DR_QUERY_INCLUDE_COND_SRCS)
/* A write to a 32-bit reg zeroes the top 32 bits for x86_64 and
* aarch64.
*/
IF_X64(||
instr_writes_to_exact_reg(inst, reg_64_to_32(reg),
DR_QUERY_INCLUDE_COND_SRCS)))
value = REG_DEAD;
else if (xfer)
value = REG_LIVE;
else if (index > 0)
value = drvector_get_entry(&pt->reg[GPR_IDX(reg)].live, index - 1);
LOG(drcontext, DR_LOG_ALL, 3, " %s=%d", get_register_name(reg),
(int)(ptr_uint_t)value);
drvector_set_entry(&pt->reg[GPR_IDX(reg)].live, index, value);
}
/* aflags liveness */
aflags_new = instr_get_arith_flags(inst, DR_QUERY_INCLUDE_COND_SRCS);
if (xfer)
aflags_cur = EFLAGS_READ_ARITH; /* assume flags are read before written */
else {
uint aflags_read, aflags_w2r;
if (index == 0)
aflags_cur = EFLAGS_READ_ARITH; /* assume flags are read before written */
else {
aflags_cur =
(uint)(ptr_uint_t)drvector_get_entry(&pt->aflags.live, index - 1);
}
aflags_read = (aflags_new & EFLAGS_READ_ARITH);
/* if a flag is read by inst, set the read bit */
aflags_cur |= (aflags_new & EFLAGS_READ_ARITH);
/* if a flag is written and not read by inst, clear the read bit */
aflags_w2r = EFLAGS_WRITE_TO_READ(aflags_new & EFLAGS_WRITE_ARITH);
aflags_cur &= ~(aflags_w2r & ~aflags_read);
}
LOG(drcontext, DR_LOG_ALL, 3, " flags=%d\n", aflags_cur);
drvector_set_entry(&pt->aflags.live, index, (void *)(ptr_uint_t)aflags_cur);
if (instr_is_app(inst)) {
int i;
for (i = 0; i < instr_num_dsts(inst); i++)
count_app_uses(pt, instr_get_dst(inst, i));
for (i = 0; i < instr_num_srcs(inst); i++)
count_app_uses(pt, instr_get_src(inst, i));
}
index++;
}
pt->live_idx = index;
return DR_EMIT_DEFAULT;
}
static dr_emit_flags_t
drreg_event_bb_insert_early(void *drcontext, void *tag, instrlist_t *bb, instr_t *inst,
bool for_trace, bool translating, void *user_data)
{
per_thread_t *pt = get_tls_data(drcontext);
pt->cur_instr = inst;
pt->live_idx--; /* counts backward */
return DR_EMIT_DEFAULT;
}
static dr_emit_flags_t
drreg_event_bb_instru2instru_late(void *drcontext, void *tag, instrlist_t *bb,
bool for_trace, bool translating)
{
/* We preserve bb_props until late in instru2instru as there may be drreg usages
* in other passes that need to look at it.
*/
get_tls_data(drcontext)->bb_props = 0;
return DR_EMIT_DEFAULT;
}
static drreg_status_t
drreg_insert_restore_all(void *drcontext, instrlist_t *bb, instr_t *inst,
bool force_restore, OUT bool *regs_restored)
{
per_thread_t *pt = get_tls_data(drcontext);
reg_id_t reg;
instr_t *next = instr_get_next(inst);
drreg_status_t res;
/* Before each app read, or at end of bb, restore aflags to app value */
uint aflags = (uint)(ptr_uint_t)drvector_get_entry(&pt->aflags.live, pt->live_idx);
if (!pt->aflags.native &&
(force_restore ||
TESTANY(EFLAGS_READ_ARITH, instr_get_eflags(inst, DR_QUERY_DEFAULT)) ||
/* Writing just a subset needs to combine with the original unwritten */
(TESTANY(EFLAGS_WRITE_ARITH, instr_get_eflags(inst, DR_QUERY_INCLUDE_ALL)) &&
aflags != 0 /*0 means everything is dead*/) ||
/* DR slots are not guaranteed across app instrs */
pt->aflags.slot >= (int)ops.num_spill_slots)) {
/* Restore aflags to app value */
LOG(drcontext, DR_LOG_ALL, 3,
"%s @%d." PFX " aflags=0x%x use=%d: lazily restoring aflags\n", __FUNCTION__,
pt->live_idx, get_where_app_pc(inst), aflags, pt->aflags.in_use);
res = drreg_restore_aflags(drcontext, bb, inst, pt, false /*keep slot*/);
if (res != DRREG_SUCCESS) {
LOG(drcontext, DR_LOG_ALL, 1,
"%s @%d." PFX ": failed to restore flags before app read\n", __FUNCTION__,
pt->live_idx, get_where_app_pc(inst));
return res;
}
if (!pt->aflags.in_use) {
pt->aflags.native = true;
pt->slot_use[AFLAGS_SLOT] = DR_REG_NULL;
}
}
/* Before each app read, or at end of bb, restore spilled registers to app values: */
for (reg = DR_REG_START_GPR; reg <= DR_REG_STOP_GPR; reg++) {
if (regs_restored != NULL)
regs_restored[GPR_IDX(reg)] = false;
if (!pt->reg[GPR_IDX(reg)].native) {
if (force_restore || instr_reads_from_reg(inst, reg, DR_QUERY_INCLUDE_ALL) ||
/* Treat a partial write as a read, to restore rest of reg */
(instr_writes_to_reg(inst, reg, DR_QUERY_INCLUDE_ALL) &&
!instr_writes_to_exact_reg(inst, reg, DR_QUERY_INCLUDE_ALL)) ||
/* Treat a conditional write as a read and a write to handle the
* condition failing and our write handling saving the wrong value.
*/
(instr_writes_to_reg(inst, reg, DR_QUERY_INCLUDE_ALL) &&
!instr_writes_to_reg(inst, reg, DR_QUERY_DEFAULT)) ||
/* i#1954: for complex bbs we must restore before the next app instr */
(!pt->reg[GPR_IDX(reg)].in_use &&
((pt->bb_has_internal_flow &&
!TEST(DRREG_IGNORE_CONTROL_FLOW, pt->bb_props)) ||
TEST(DRREG_CONTAINS_SPANNING_CONTROL_FLOW, pt->bb_props))) ||
/* If we're out of our own slots and are using a DR slot, we have to
* restore now b/c DR slots are not guaranteed across app instrs.
*/
pt->reg[GPR_IDX(reg)].slot >= (int)ops.num_spill_slots) {
if (!pt->reg[GPR_IDX(reg)].in_use) {
LOG(drcontext, DR_LOG_ALL, 3, "%s @%d." PFX ": lazily restoring %s\n",
__FUNCTION__, pt->live_idx, get_where_app_pc(inst),
get_register_name(reg));
res = drreg_restore_reg_now(drcontext, bb, inst, pt, reg);
if (res != DRREG_SUCCESS) {
LOG(drcontext, DR_LOG_ALL, 1,
"%s @%d." PFX ": lazy restore failed\n", __FUNCTION__,
pt->live_idx, get_where_app_pc(inst));
return res;
}
ASSERT(pt->pending_unreserved > 0, "should not go negative");
pt->pending_unreserved--;
} else if (pt->aflags.xchg == reg) {
/* Bail on keeping the flags in the reg. */
drreg_move_aflags_from_reg(drcontext, bb, inst, pt, true);
} else {
/* We need to move the tool's value somewhere else.
* We use a separate slot for that (and we document that
* tools should request an extra slot for each cross-app-instr
* register).
* XXX: optimize via xchg w/ a dead reg.
*/
uint tmp_slot = find_free_slot(pt, bb, inst);
if (tmp_slot == MAX_SPILLS) {
drreg_report_error(DRREG_ERROR_OUT_OF_SLOTS,
"failed to preserve tool val around app read");
}
/* The approach:
* + spill reg (tool val) to new slot
* + restore to reg (app val) from app slot
* + <app instr>
* + restore to reg (tool val) from new slot
* XXX: if we change this, we need to update
* drreg_event_restore_state().
*/
LOG(drcontext, DR_LOG_ALL, 3,
"%s @%d." PFX ": restoring %s for app read\n", __FUNCTION__,
pt->live_idx, get_where_app_pc(inst), get_register_name(reg));
spill_reg(drcontext, pt, reg, tmp_slot, bb, inst);
restore_reg(drcontext, pt, reg, pt->reg[GPR_IDX(reg)].slot, bb, inst,
false /*keep slot*/);
restore_reg(drcontext, pt, reg, tmp_slot, bb, next, true);
/* Share the tool val spill if this inst writes too */
if (regs_restored != NULL)
regs_restored[GPR_IDX(reg)] = true;
/* We keep .native==false */
}
}
}
}
return DRREG_SUCCESS;
}
static dr_emit_flags_t
drreg_event_bb_insert_late(void *drcontext, void *tag, instrlist_t *bb, instr_t *inst,
bool for_trace, bool translating, void *user_data)
{
per_thread_t *pt = get_tls_data(drcontext);
reg_id_t reg;
instr_t *next = instr_get_next(inst);
bool restored_for_read[DR_NUM_GPR_REGS];
drreg_status_t res;
dr_pred_type_t pred = instrlist_get_auto_predicate(bb);
/* XXX i#2585: drreg should predicate spills and restores as appropriate */
instrlist_set_auto_predicate(bb, DR_PRED_NONE);
/* For unreserved regs still spilled, we lazily do the restore here. We also
* update reserved regs wrt app uses.
* The instruction list presented to us here are app instrs but may contain meta
* instrs if any were inserted in app2app. Any such meta instr here will be treated
* like an app instr.
*/
bool do_last_spill = drmgr_is_last_instr(drcontext, inst) &&
!TEST(DRREG_USER_RESTORES_AT_BB_END, pt->bb_props);
res = drreg_insert_restore_all(drcontext, bb, inst, do_last_spill, restored_for_read);
if (res != DRREG_SUCCESS)
drreg_report_error(res, "failed to restore for reads");
/* After aflags write by app, update spilled app value */
if (TESTANY(EFLAGS_WRITE_ARITH, instr_get_eflags(inst, DR_QUERY_INCLUDE_ALL)) &&
/* Is everything written later? */
(pt->live_idx == 0 ||
(ptr_uint_t)drvector_get_entry(&pt->aflags.live, pt->live_idx - 1) != 0)) {
if (pt->aflags.in_use) {
LOG(drcontext, DR_LOG_ALL, 3,
"%s @%d." PFX ": re-spilling aflags after app write\n", __FUNCTION__,
pt->live_idx, get_where_app_pc(inst));
res = drreg_spill_aflags(drcontext, bb, next /*after*/, pt);
if (res != DRREG_SUCCESS) {
drreg_report_error(res, "failed to spill aflags after app write");
}
pt->aflags.native = false;
} else if (!pt->aflags.native ||
pt->slot_use[AFLAGS_SLOT] !=
DR_REG_NULL IF_X86(
||
(pt->reg[DR_REG_XAX - DR_REG_START_GPR].in_use &&
pt->aflags.xchg == DR_REG_XAX))) {
/* give up slot */
LOG(drcontext, DR_LOG_ALL, 3,
"%s @%d." PFX ": giving up aflags slot after app write\n", __FUNCTION__,
pt->live_idx, get_where_app_pc(inst));
#ifdef X86
if (pt->reg[DR_REG_XAX - DR_REG_START_GPR].in_use &&
pt->aflags.xchg == DR_REG_XAX)
drreg_move_aflags_from_reg(drcontext, bb, inst, pt, true);
#endif
pt->slot_use[AFLAGS_SLOT] = DR_REG_NULL;
pt->aflags.native = true;
}
}
/* After each app write, update spilled app values: */
for (reg = DR_REG_START_GPR; reg <= DR_REG_STOP_GPR; reg++) {
if (pt->reg[GPR_IDX(reg)].in_use) {
if (instr_writes_to_reg(inst, reg, DR_QUERY_INCLUDE_ALL) &&
/* Don't bother if reg is dead beyond this write */
(ops.conservative || pt->live_idx == 0 ||
drvector_get_entry(&pt->reg[GPR_IDX(reg)].live, pt->live_idx - 1) ==
REG_LIVE ||
pt->aflags.xchg == reg)) {
uint tmp_slot = MAX_SPILLS;
if (pt->aflags.xchg == reg) {
/* Bail on keeping the flags in the reg. */
drreg_move_aflags_from_reg(drcontext, bb, inst, pt, true);
continue;
}
if (pt->reg[GPR_IDX(reg)].xchg != DR_REG_NULL) {
/* XXX i#511: NYI */
drreg_report_error(DRREG_ERROR_FEATURE_NOT_AVAILABLE, "xchg NYI");
}
/* Approach (we share 1st and last w/ read, if reads and writes):
* + spill reg (tool val) to new slot
* + <app instr>
* + spill reg (app val) to app slot
* + restore to reg from new slot (tool val)
* XXX: if we change this, we need to update
* drreg_event_restore_state().
*/
LOG(drcontext, DR_LOG_ALL, 3,
"%s @%d." PFX ": re-spilling %s after app write\n", __FUNCTION__,
pt->live_idx, get_where_app_pc(inst), get_register_name(reg));
if (!restored_for_read[GPR_IDX(reg)]) {
tmp_slot = find_free_slot(pt, bb, inst);
if (tmp_slot == MAX_SPILLS) {
drreg_report_error(DRREG_ERROR_OUT_OF_SLOTS,
"failed to preserve tool val wrt app write");
}
spill_reg(drcontext, pt, reg, tmp_slot, bb, inst);
}
/* If the instr reads and writes both, make sure that the app-spill
* instr is added **before** the tool-restore instrs added by
* drreg_insert_restore_all called earlier in this routine. Note
* that the tool-restore instrs consist of the actual reg restore and
* a following label (which has some data about spill slot usage).
*/
if (restored_for_read[GPR_IDX(reg)]) {
ASSERT(instr_get_prev(next) != NULL &&
instr_is_label(instr_get_prev(next)) &&
instr_get_note(instr_get_prev(next)) ==
(void *)get_drreg_note_val(DRREG_NOTE_SPILL_SLOT_ID),
"instr before 'next' should be a label with spill slot id");
ASSERT(instr_get_prev(instr_get_prev(next)) != NULL,
"missing tool value restore after app read");
spill_reg(drcontext, pt, reg, pt->reg[GPR_IDX(reg)].slot, bb,
instr_get_prev(instr_get_prev(next)));
} else {
spill_reg(drcontext, pt, reg, pt->reg[GPR_IDX(reg)].slot, bb,
next /*after*/);
}
pt->reg[GPR_IDX(reg)].ever_spilled = true;
if (!restored_for_read[GPR_IDX(reg)])
restore_reg(drcontext, pt, reg, tmp_slot, bb, next /*after*/, true);
}
} else if (!pt->reg[GPR_IDX(reg)].native &&
instr_writes_to_reg(inst, reg, DR_QUERY_INCLUDE_ALL)) {
/* For an unreserved reg that's written, just drop the slot, even
* if it was spilled at an earlier reservation point.
*/
LOG(drcontext, DR_LOG_ALL, 3,
"%s @%d." PFX ": dropping slot for unreserved reg %s after app write\n",
__FUNCTION__, pt->live_idx, get_where_app_pc(inst),
get_register_name(reg));
if (pt->reg[GPR_IDX(reg)].ever_spilled)
pt->reg[GPR_IDX(reg)].ever_spilled = false; /* no need to restore */
res = drreg_restore_reg_now(drcontext, bb, inst, pt, reg);
if (res != DRREG_SUCCESS)
drreg_report_error(res, "slot release on app write failed");
pt->pending_unreserved--;
}
}
#ifdef DEBUG
if (drmgr_is_last_instr(drcontext, inst)) {
uint i;
for (reg = DR_REG_START_GPR; reg <= DR_REG_STOP_GPR; reg++) {
ASSERT(!pt->aflags.in_use, "user failed to unreserve aflags");
ASSERT(pt->aflags.native, "user failed to unreserve aflags");
ASSERT(!pt->reg[GPR_IDX(reg)].in_use, "user failed to unreserve a register");
ASSERT(pt->reg[GPR_IDX(reg)].native, "user failed to unreserve a register");
}
for (i = 0; i < MAX_SPILLS; i++) {
if (pt->slot_use[i] != DR_REG_NULL) {
ASSERT(pt->slot_use[i] == DR_REG_NULL,
"user failed to unreserve a register");
}
}
}
#endif
instrlist_set_auto_predicate(bb, pred);
return DR_EMIT_DEFAULT;
}
drreg_status_t
drreg_restore_all(void *drcontext, instrlist_t *bb, instr_t *where)
{
return drreg_insert_restore_all(drcontext, bb, where, true,
NULL /* do not need to track reg restores */);
}
/***************************************************************************
* USE OUTSIDE INSERT PHASE
*/
/* For use outside drmgr's insert phase where we don't know the bounds of the
* app instrs, we fall back to a more expensive liveness analysis on each
* insertion.
*
* XXX: we'd want to add a new API for instru2instru that takes in
* both the save and restore points at once to allow keeping aflags in
* eax and other optimizations.
*/
static drreg_status_t
drreg_forward_analysis(void *drcontext, instr_t *start)
{
per_thread_t *pt = get_tls_data(drcontext);
instr_t *inst;
ptr_uint_t aflags_new, aflags_cur = 0;
reg_id_t reg;
/* We just use index 0 of the live vectors */
for (reg = DR_REG_START_GPR; reg <= DR_REG_STOP_GPR; reg++) {
pt->reg[GPR_IDX(reg)].app_uses = 0;
drvector_set_entry(&pt->reg[GPR_IDX(reg)].live, 0, REG_UNKNOWN);
}
/* We have to consider meta instrs as well */
for (inst = start; inst != NULL; inst = instr_get_next(inst)) {
if (instr_is_cti(inst) || instr_is_interrupt(inst) || instr_is_syscall(inst))
break;
/* GPR liveness */
for (reg = DR_REG_START_GPR; reg <= DR_REG_STOP_GPR; reg++) {
void *value = REG_UNKNOWN;
if (drvector_get_entry(&pt->reg[GPR_IDX(reg)].live, 0) != REG_UNKNOWN)
continue;
/* DRi#1849: COND_SRCS here includes addressing regs in dsts */
if (instr_reads_from_reg(inst, reg, DR_QUERY_INCLUDE_COND_SRCS))
value = REG_LIVE;
/* make sure we don't consider writes to sub-regs */
else if (instr_writes_to_exact_reg(inst, reg, DR_QUERY_INCLUDE_COND_SRCS)
/* A write to a 32-bit reg zeroes the top 32 bits for x86_64 and
* aarch64.
*/
IF_X64(||
instr_writes_to_exact_reg(inst, reg_64_to_32(reg),
DR_QUERY_INCLUDE_COND_SRCS)))
value = REG_DEAD;
if (value != REG_UNKNOWN)
drvector_set_entry(&pt->reg[GPR_IDX(reg)].live, 0, value);
}
/* aflags liveness */
aflags_new = instr_get_arith_flags(inst, DR_QUERY_INCLUDE_COND_SRCS);
/* reading and writing counts only as reading */
aflags_new &= (~(EFLAGS_READ_TO_WRITE(aflags_new)));
/* reading doesn't count if already written */
aflags_new &= (~(EFLAGS_WRITE_TO_READ(aflags_cur)));
aflags_cur |= aflags_new;
if (instr_is_app(inst)) {
int i;
for (i = 0; i < instr_num_dsts(inst); i++)
count_app_uses(pt, instr_get_dst(inst, i));
for (i = 0; i < instr_num_srcs(inst); i++)
count_app_uses(pt, instr_get_src(inst, i));
}
}
pt->live_idx = 0;
for (reg = DR_REG_START_GPR; reg <= DR_REG_STOP_GPR; reg++) {
if (drvector_get_entry(&pt->reg[GPR_IDX(reg)].live, 0) == REG_UNKNOWN)
drvector_set_entry(&pt->reg[GPR_IDX(reg)].live, 0, REG_LIVE);
}
drvector_set_entry(&pt->aflags.live, 0,
(void *)(ptr_uint_t)
/* set read bit if not written */
(EFLAGS_READ_ARITH & (~(EFLAGS_WRITE_TO_READ(aflags_cur)))));
return DRREG_SUCCESS;
}
/***************************************************************************
* REGISTER RESERVATION
*/
drreg_status_t
drreg_init_and_fill_vector(drvector_t *vec, bool allowed)
{
reg_id_t reg;
if (vec == NULL)
return DRREG_ERROR_INVALID_PARAMETER;
drvector_init(vec, DR_NUM_GPR_REGS, false /*!synch*/, NULL);
for (reg = 0; reg < DR_NUM_GPR_REGS; reg++)
drvector_set_entry(vec, reg, allowed ? (void *)(ptr_uint_t)1 : NULL);
return DRREG_SUCCESS;
}
drreg_status_t
drreg_set_vector_entry(drvector_t *vec, reg_id_t reg, bool allowed)
{
if (vec == NULL || reg < DR_REG_START_GPR || reg > DR_REG_STOP_GPR)
return DRREG_ERROR_INVALID_PARAMETER;
drvector_set_entry(vec, reg - DR_REG_START_GPR,
allowed ? (void *)(ptr_uint_t)1 : NULL);
return DRREG_SUCCESS;
}
/* Assumes liveness info is already set up in per_thread_t. Liveness should have either
* been computed by a forward liveness scan upon every insertion if called outside of
* insertion phase, see drreg_forward_analysis(). Or if called inside insertion
* phase, at the end of drmgr's analysis phase once, see drreg_event_bb_analysis().
* Please note that drreg is not yet able to properly handle multiple users if they use
* drreg from in and outside of the insertion phase, xref i#3823.
*/
static drreg_status_t
drreg_reserve_reg_internal(void *drcontext, instrlist_t *ilist, instr_t *where,
drvector_t *reg_allowed, bool only_if_no_spill,
OUT reg_id_t *reg_out)
{
per_thread_t *pt = get_tls_data(drcontext);
uint slot = MAX_SPILLS;
uint min_uses = UINT_MAX;
reg_id_t reg = DR_REG_STOP_GPR + 1, best_reg = DR_REG_NULL;
bool already_spilled = false;
if (reg_out == NULL)
return DRREG_ERROR_INVALID_PARAMETER;
/* First, try to use a previously unreserved but not yet lazily restored reg.
* This must be first to avoid accumulating slots beyond the requested max.
* Because we drop an unreserved reg when the app writes to it, we should
* never pick an unreserved and unspilled yet not currently dead reg over
* some other dead reg.
*/
if (pt->pending_unreserved > 0) {
for (reg = DR_REG_START_GPR; reg <= DR_REG_STOP_GPR; reg++) {
uint idx = GPR_IDX(reg);
if (!pt->reg[idx].native && !pt->reg[idx].in_use &&
(reg_allowed == NULL || drvector_get_entry(reg_allowed, idx) != NULL) &&
(!only_if_no_spill || pt->reg[idx].ever_spilled ||
drvector_get_entry(&pt->reg[idx].live, pt->live_idx) == REG_DEAD)) {
slot = pt->reg[idx].slot;
pt->pending_unreserved--;
already_spilled = pt->reg[idx].ever_spilled;
LOG(drcontext, DR_LOG_ALL, 3,
"%s @%d." PFX ": using un-restored %s slot %d\n", __FUNCTION__,
pt->live_idx, get_where_app_pc(where), get_register_name(reg), slot);
break;
}
}
}
if (reg > DR_REG_STOP_GPR) {
/* Look for a dead register, or the least-used register */
for (reg = DR_REG_START_GPR; reg <= DR_REG_STOP_GPR; reg++) {
uint idx = GPR_IDX(reg);
if (pt->reg[idx].in_use)
continue;
if (reg ==
dr_get_stolen_reg() IF_ARM(|| reg == DR_REG_PC)
/* Avoid xsp, even if it appears dead in things like OP_sysenter.
* On AArch64 use of SP is very restricted.
*/
IF_NOT_ARM(|| reg == DR_REG_XSP))
continue;
if (reg_allowed != NULL && drvector_get_entry(reg_allowed, idx) == NULL)
continue;
/* If we had a hint as to local vs whole-bb we could downgrade being
* dead right now as a priority
*/
if (drvector_get_entry(&pt->reg[idx].live, pt->live_idx) == REG_DEAD)
break;
if (only_if_no_spill)
continue;
if (pt->reg[idx].app_uses < min_uses) {
best_reg = reg;
min_uses = pt->reg[idx].app_uses;
}
}
}
if (reg > DR_REG_STOP_GPR) {
if (best_reg != DR_REG_NULL)
reg = best_reg;
else {
#ifdef X86
/* If aflags was unreserved but is still in xax, give it up rather than
* fail to reserve a new register.
*/
if (!pt->aflags.in_use && pt->reg[GPR_IDX(DR_REG_XAX)].in_use &&
pt->aflags.xchg == DR_REG_XAX &&
(reg_allowed == NULL ||
drvector_get_entry(reg_allowed, GPR_IDX(DR_REG_XAX)) != NULL)) {
LOG(drcontext, DR_LOG_ALL, 3,
"%s @%d." PFX ": taking xax from unreserved aflags\n", __FUNCTION__,
pt->live_idx, get_where_app_pc(where));
drreg_move_aflags_from_reg(drcontext, ilist, where, pt, true);
reg = DR_REG_XAX;
} else
#endif
return DRREG_ERROR_REG_CONFLICT;
}
}
if (slot == MAX_SPILLS) {
slot = find_free_slot(pt, ilist, where);
if (slot == MAX_SPILLS)
return DRREG_ERROR_OUT_OF_SLOTS;
}
ASSERT(!pt->reg[GPR_IDX(reg)].in_use, "overlapping uses");
pt->reg[GPR_IDX(reg)].in_use = true;
if (!already_spilled) {
/* Even if dead now, we need to own a slot in case reserved past dead point */
if (ops.conservative ||
drvector_get_entry(&pt->reg[GPR_IDX(reg)].live, pt->live_idx) == REG_LIVE) {
LOG(drcontext, DR_LOG_ALL, 3, "%s @%d." PFX ": spilling %s to slot %d\n",
__FUNCTION__, pt->live_idx, get_where_app_pc(where),
get_register_name(reg), slot);
spill_reg(drcontext, pt, reg, slot, ilist, where);
pt->reg[GPR_IDX(reg)].ever_spilled = true;
} else {
LOG(drcontext, DR_LOG_ALL, 3,
"%s @%d." PFX ": no need to spill %s to slot %d\n", __FUNCTION__,
pt->live_idx, get_where_app_pc(where), get_register_name(reg), slot);
pt->slot_use[slot] = reg;
pt->reg[GPR_IDX(reg)].ever_spilled = false;
}