-
Notifications
You must be signed in to change notification settings - Fork 0
/
mdriver.c
1812 lines (1565 loc) · 56.5 KB
/
mdriver.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
/*
* Mdriver.c - Autolab version of the CS:APP Malloc Lab Driver
*
* Uses a collection of trace files to tests a malloc/free
* implementation in mm.c.
*
* Copyright (c) 2004-2016, R. Bryant and D. O'Hallaron, All rights
* reserved. May not be used, modified, or copied without permission.
*/
#include <assert.h>
#include <errno.h>
#include <float.h>
#include <setjmp.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <stdbool.h>
#include <math.h>
#include "mm.h"
#include "memlib.h"
#include "fcyc.h"
#include "config.h"
#include "stree.h"
/**********************
* Constants and macros
**********************/
/* Misc */
#define MAXLINE 1024 /* max string size */
#define HDRLINES 4 /* number of header lines in a trace file */
#define LINENUM(i) (i+HDRLINES+1) /* cnvt trace request nums to linenums (origin 1) */
#ifndef REF_ONLY
#define REF_ONLY 0
#endif
/* Returns true if p is ALIGNMENT-byte aligned */
#define IS_ALIGNED(p) ((((unsigned long)(p)) % ALIGNMENT) == 0)
/* weights */
typedef enum { WNONE, WALL, WUTIL, WPERF } weight_t;
/******************************
* The key compound data types
*****************************/
/*
* There are two different, easily-confusable concepts:
* - opnum: which line in the file.
* - index: the block number ; corresponds to something allocated.
* Remember that index (-1) is the null pointer.
*/
/*
* Records the extent of each block's payload.
* Organized as doubly linked list
*/
typedef struct range_t {
char *lo; /* low payload address */
char *hi; /* high payload address */
long index; /* same index as free; for debugging */
struct range_t *next;
struct range_t *prev;
} range_t;
/*
* All information about set of ranges represented as doubly-linked
* list of ranges, plus a splay tree keyed by lo addresses
*/
typedef struct {
range_t *list;
tree_t *lo_tree;
} range_set_t;
/* Characterizes a single trace operation (allocator request) */
typedef struct {
enum { ALLOC, FREE, REALLOC } type; /* type of request */
long index; /* index for free() to use later */
size_t size; /* byte size of alloc/realloc request */
} traceop_t;
/* Holds the information for one trace file */
typedef struct {
char filename[MAXLINE];
size_t data_bytes; /* Peak number of data bytes allocated during trace */
int num_ids; /* number of alloc/realloc ids */
int num_ops; /* number of distinct requests */
weight_t weight; /* weight for this trace */
traceop_t *ops; /* array of requests */
char **blocks; /* array of ptrs returned by malloc/realloc... */
size_t *block_sizes; /* ... and a corresponding array of payload sizes */
int *block_rand_base; /* index into random_data, if debug is on */
} trace_t;
/*
* Holds the params to the xxx_speed functions, which are timed by fcyc.
* This struct is necessary because fcyc accepts only a pointer array
* as input.
*/
typedef struct {
trace_t *trace;
range_set_t *ranges;
} speed_t;
/* Summarizes the important stats for some malloc function on some trace */
typedef struct {
/* set in read_trace */
char filename[MAXLINE];
weight_t weight;
double ops; /* number of ops (malloc/free/realloc) in the trace */
/* run-time stats defined for both libc and student */
bool valid; /* was the trace processed correctly by the allocator? */
double secs; /* number of secs needed to run the trace */
/* defined only for the student malloc package */
double util; /* space utilization for this trace (always 0 for libc) */
/* Note: secs and util are only defined if valid is true */
} stats_t;
/* Summarizes the key statistics for a set of traces */
typedef struct {
double util; /* average utilization expressed as a percentage */
double ops; /* total number of operations */
double secs; /* total number of elapsed seconds */
double tput; /* average throughput expressed in Kops/s */
} sum_stats_t;
/********************
* For debugging. If debug-mode is on, then we have each block start
* at a "random" place (a hash of the index), and copy random data
* into it. With DBG_CHEAP, we check that the data survived when we
* realloc and when we free. With DBG_EXPENSIVE, we check every block
* every operation.
* randint_t should be a byte, in case students return unaligned memory.
*******************/
#define RANDOM_DATA_LEN (1<<16)
typedef unsigned char randint_t;
static const char randint_t_name[] = "byte";
static randint_t random_data[RANDOM_DATA_LEN];
/********************
* Global variables
*******************/
/* Global values */
typedef enum { DBG_NONE, DBG_CHEAP, DBG_EXPENSIVE } debug_mode_t;
static debug_mode_t debug_mode = REF_ONLY ? DBG_NONE : DBG_CHEAP;
int verbose = REF_ONLY ? 0 : 1; /* global flag for verbose output */
static int errors = 0; /* number of errs found when running student malloc */
static bool onetime_flag = false;
static bool tab_mode = false; /* Print output as tab-separated fields */
static size_t maxfill = MAXFILL;
/* by default, no timeouts */
static int set_timeout = 0;
/* Directory where default tracefiles are found */
static char tracedir[MAXLINE] = TRACEDIR;
/* The following are null-terminated lists of tracefiles that may or may not get used */
/* The filenames of the default tracefiles */
static char *default_tracefiles[] = {
DEFAULT_TRACEFILES, NULL
};
/* Store names of trace files as array of char *'s */
static int num_global_tracefiles = 0;
static char **global_tracefiles = NULL;
/* Summary statistics for libc and student's mm.c submissions */
static sum_stats_t global_libc_sum_stats;
static sum_stats_t global_mm_sum_stats;
/* Performance statistics for driver */
/*********************
* Function prototypes
*********************/
/* This function enables generating the set of trace files */
static void add_tracefile(char *trace);
/* these functions manipulate range sets */
static range_set_t *new_range_set();
static bool add_range(range_set_t *ranges, char *lo, size_t size,
const trace_t *trace, int opnum, int index);
static void remove_range(range_set_t *ranges, char *lo);
static void free_range_set(range_set_t *ranges);
/* These functions implement the debugging code */
static void init_random_data(void);
static bool check_index(const trace_t *trace, int opnum, int index, int realloc);
static void randomize_block(trace_t *trace, int index);
/* These functions read, allocate, and free storage for traces */
static trace_t *read_trace(stats_t *stats, const char *tracedir,
const char *filename);
static void reinit_trace(trace_t *trace);
static void free_trace(trace_t *trace);
/* Routines for evaluating the correctness and speed of libc malloc */
static bool eval_libc_valid(trace_t *trace);
static void eval_libc_speed(void *ptr);
/* Routines for evaluating correctnes, space utilization, and speed
of the student's malloc package in mm.c */
static bool eval_mm_valid(trace_t *trace, range_set_t *ranges);
static double eval_mm_util(trace_t *trace, int tracenum);
static void eval_mm_speed(void *ptr);
/* Various helper routines */
static void printresults(int n, stats_t *stats, sum_stats_t *sumstats);
static void usage(char *prog);
static void malloc_error(const trace_t *trace, int opnum, const char *fmt, ...)
__attribute__((format(printf, 3,4)));
static void unix_error(const char *fmt, ...)
__attribute__((format(printf, 1,2), noreturn));
static void app_error(const char *fmt, ...)
__attribute__((format(printf, 1,2), noreturn));
static sigjmp_buf timeout_jmpbuf;
/* Timeout signal handler */
static void timeout_handler(int sig __attribute__((unused))) {
fprintf(stderr, "The driver timed out after %d secs\n", set_timeout);
errors = 1;
longjmp(timeout_jmpbuf, 1);
}
/* Compute throughput from reference implementation */
static double measure_ref_throughput();
/*
* Run the tests; return the number of tests run (may be less than
* num_tracefiles, if there's a timeout)
*/
static void run_tests(int num_tracefiles, const char *tracedir,
char **tracefiles,
stats_t *mm_stats, speed_t *speed_params) {
volatile int i;
for (i=0; i < num_tracefiles; i++) {
/* initialize simulated memory system in memlib.c *
* start each trace with a clean system */
mem_init();
range_set_t *ranges = new_range_set();
// NOTE: If times out, then it will reread the trace file
trace_t *trace;
trace = read_trace(&mm_stats[i], tracedir, tracefiles[i]);
strcpy(mm_stats[i].filename, trace->filename);
mm_stats[i].ops = trace->num_ops;
/* Prepare for timeout */
if (setjmp(timeout_jmpbuf) != 0) {
mm_stats[i].valid = false;
} else {
if (verbose > 1)
printf("Checking mm_malloc for correctness, ");
mm_stats[i].valid =
/* Do 2 tests, since may fail to reinitialize properly */
eval_mm_valid(trace, ranges) && eval_mm_valid(trace, ranges);
if (onetime_flag) {
free_trace(trace);
return;
}
}
if (mm_stats[i].valid) {
if (verbose > 1)
printf("efficiency, ");
mm_stats[i].util = eval_mm_util(trace, i);
speed_params->trace = trace;
speed_params->ranges = ranges;
if (verbose > 1)
printf("and performance.\n");
mm_stats[i].secs = fsec(eval_mm_speed, speed_params);
}
#if 0
printf(" %d operations. %ld comparisons. Avg = %.1f\n",
trace->num_ops, ranges->lo_tree->comparison_count,
(double) ranges->lo_tree->comparison_count / trace->num_ops);
#endif
free_trace(trace);
free_range_set(ranges);
/* clean up memory system */
mem_deinit();
}
}
double score_component(double perf, double min_perf, double max_perf)
{
if (perf < min_perf) {
return 0.0;
} else if (perf > max_perf) {
return 1.0;
} else {
return (perf - min_perf) / (max_perf - min_perf);
}
}
/**************
* Main routine
**************/
int main(int argc, char **argv)
{
int i;
global_tracefiles = NULL; /* array of trace file names */
num_global_tracefiles = 0; /* the number of traces in that array */
stats_t *libc_stats = NULL;/* libc stats for each trace */
stats_t *mm_stats = NULL; /* mm (i.e. student) stats for each trace */
speed_t speed_params; /* input parameters to the xx_speed routines */
bool run_libc = false; /* If set, run libc malloc (set by -l) */
/* temporaries used to compute the performance index */
double secs, ops, util;
double avg_mm_util, avg_mm_throughput = 0;
// double p1_checkpoint;
double p1, p2, perfindex;
double correctindex;
double util_weight = 0, perf_weight = 0;
int numcorrect;
setbuf(stdout, 0);
setbuf(stderr, 0);
double min_throughput_checkpoint = 5000;
double max_throughput_checkpoint = 10000;;
double min_throughput = 5000;
double max_throughput = 10000;;
#if !REF_ONLY
double ref_throughput;
char c;
/*
* Read and interpret the command line arguments
*/
while ((c = getopt(argc, argv, "d:f:c:s:t:v:hOVlDT")) != EOF) {
switch (c) {
case 'f': /* Use one specific trace file only (relative to curr dir) */
add_tracefile(optarg);
strcpy(tracedir, "./");
break;
case 'c': /* Use one specific trace file and run only once */
add_tracefile(optarg);
onetime_flag = true;
strcpy(tracedir, "./");
break;
case 't': /* Directory where the traces are located */
if (num_global_tracefiles == 1) /* ignore if -f already encountered */
break;
strcpy(tracedir, optarg);
if (tracedir[strlen(tracedir)-1] != '/')
strcat(tracedir, "/"); /* path always ends with "/" */
break;
case 'l': /* Run libc malloc */
run_libc = true;
break;
case 'V': /* Increase verbosity level */
verbose += 1;
break;
case 'v': /* Set verbosity level */
verbose = atoi(optarg);
break;
case 'd':
debug_mode = atoi(optarg);
break;
case 'D':
debug_mode = DBG_EXPENSIVE;
break;
case 's':
set_timeout = atoi(optarg);
break;
case 'T':
tab_mode = true;
break;
case 'h': /* Print this message */
usage(argv[0]);
exit(0);
default:
usage(argv[0]);
exit(1);
}
}
#endif /* !REF_ONLY */
if (num_global_tracefiles == 0) {
int i;
for (i = 0; default_tracefiles[i]; i++)
add_tracefile(default_tracefiles[i]);
}
if (debug_mode != DBG_NONE) {
init_random_data();
}
/* Initialize the timeout */
if (set_timeout > 0) {
signal(SIGALRM, timeout_handler);
alarm(set_timeout);
}
/*
* Optionally run and evaluate the libc malloc package
*/
if (run_libc) {
if (verbose > 1)
printf("\nTesting libc malloc\n");
/* Allocate libc stats array, with one stats_t struct per tracefile */
libc_stats = (stats_t *)calloc(num_global_tracefiles, sizeof(stats_t));
if (libc_stats == NULL)
unix_error("libc_stats calloc in main failed");
/* Evaluate the libc malloc package using the K-best scheme */
for (i=0; i < num_global_tracefiles; i++) {
trace_t *trace = read_trace(&libc_stats[i], tracedir, global_tracefiles[i]);
if (verbose > 1)
printf("Checking libc malloc for correctness, ");
libc_stats[i].valid = eval_libc_valid(trace);
if (libc_stats[i].valid) {
speed_params.trace = trace;
if (verbose > 1)
printf("and performance.\n");
libc_stats[i].secs = fsec(eval_libc_speed, &speed_params);
}
free_trace(trace);
}
/* Display the libc results in a compact table and return the
summary statistics */
if (verbose) {
printf("\nResults for libc malloc:\n");
printresults(num_global_tracefiles, libc_stats, &global_libc_sum_stats);
}
}
#if !REF_ONLY
/*
* Get benchmark throughput
*/
ref_throughput = measure_ref_throughput();
min_throughput_checkpoint = ref_throughput * MIN_SPEED_RATIO_CHECKPOINT;
max_throughput_checkpoint = ref_throughput * MAX_SPEED_RATIO_CHECKPOINT;
min_throughput = ref_throughput * MIN_SPEED_RATIO;
max_throughput = ref_throughput * MAX_SPEED_RATIO;
#endif
/*
* Always run and evaluate the student's mm package
*/
if (verbose > 1)
printf("\nTesting mm malloc\n");
/* Allocate the mm stats array, with one stats_t struct per tracefile */
mm_stats = (stats_t *)calloc(num_global_tracefiles, sizeof(stats_t));
if (mm_stats == NULL)
unix_error("mm_stats calloc in main failed");
run_tests(num_global_tracefiles, tracedir, global_tracefiles, mm_stats,
&speed_params);
/* Display the mm results in a compact table */
if (verbose) {
if (onetime_flag) {
printf("\n\ncorrectness check finished, by running tracefile \"%s\".\n",
global_tracefiles[num_global_tracefiles-1]);
if (mm_stats[num_global_tracefiles-1].valid) {
printf(" => correct.\n\n");
} else {
printf(" => incorrect.\n\n");
}
} else {
printf("\nResults for mm malloc:\n");
printresults(num_global_tracefiles, mm_stats, &global_mm_sum_stats);
printf("\n");
}
}
/* Optionally compare the performance of mm and libc */
if (run_libc) {
printf("Comparison with libc malloc: mm/libc = %.0f Kops / %.0f Kops = %.2f\n",
(float)global_mm_sum_stats.tput, (float)global_libc_sum_stats.tput,
(float)(global_mm_sum_stats.tput/global_libc_sum_stats.tput));
}
/*
* Accumulate the aggregate statistics for the student's mm package
*/
secs = 0;
ops = 0;
util = 0;
numcorrect = 0;
/*
* trace weight:
* weight 0 => ignore
* 1 => count both util and perf
* 2 => count only util
* 3 => count only perf
*/
for (i=0; i < num_global_tracefiles; i++) {
if (mm_stats[i].weight == WALL || mm_stats[i].weight == WPERF)
{
secs += mm_stats[i].secs;
ops += mm_stats[i].ops;
perf_weight++;
}
if (mm_stats[i].weight == WALL || mm_stats[i].weight == WUTIL)
{
util += mm_stats[i].util;
util_weight++;
}
if (mm_stats[i].valid)
numcorrect++;
}
/*
* Compute and print the correctness and performance index
*/
correctindex = ((double)numcorrect / (double)num_global_tracefiles) * 50.0;
if (errors == 0) {
if (util_weight == 0) {
avg_mm_util = 0;
} else {
avg_mm_util = util/util_weight;
}
if (perf_weight == 0) {
avg_mm_throughput = 0;
} else {
/* Measure in KOPS */
avg_mm_throughput = (secs == 0) ? 0 : ops/secs * 0.001;
}
// p1_checkpoint = score_component(avg_mm_util, MIN_SPACE_CHECKPOINT, MAX_SPACE_CHECKPOINT);
// p2_checkpoint = score_component(avg_mm_throughput, min_throughput_checkpoint, max_throughput_checkpoint);
// perfindex_checkpoint = (p1_checkpoint * UTIL_WEIGHT + p2_checkpoint * (1.0 - UTIL_WEIGHT)) * 100.0;
p1 = score_component(avg_mm_util, MIN_SPACE, MAX_SPACE);
p2 = score_component(avg_mm_throughput, min_throughput, max_throughput);
perfindex = (p1 * UTIL_WEIGHT + p2 * (1.0 - UTIL_WEIGHT)) * 100.0;
#if !REF_ONLY
if (!tab_mode) {
printf("Average utilization = %.1f%%. Average throughput = %.0f Kops/sec\n",
avg_mm_util * 100.0,
avg_mm_throughput);
}
#endif
}
else { /* There were errors */
// p1_checkpoint = 0.0;
// p2_checkpoint = 0.0;
// perfindex_checkpoint = 0.0;
p1 = 0.0;
p2 = 0.0;
perfindex = 0.0;
avg_mm_util = 0.0;
avg_mm_throughput = 0.0;
printf("Terminated with %d errors\n", errors);
}
#if REF_ONLY
printf("%.0f\n", avg_mm_throughput);
#else /* !REF_ONLY */
if (verbose > 0) {
printf("\n");
printf("***Checkpoint 1 correctness index = %.1f/50.0***\n",
correctindex);
printf("\n");
// printf("***Checkpoint 2 perf index = %.1f (util) + %.1f (thru) = %.1f/100.0***\n",
// p1_checkpoint*UTIL_WEIGHT*100,
// p2_checkpoint*(1.0 - UTIL_WEIGHT)*100,
// perfindex_checkpoint);
printf("Average utilization = %.1f%%. Average throughput = %.0f Kops/sec\n",
avg_mm_util * 100.0,
avg_mm_throughput);
printf("Utilization targets: min=%.1f%%, max=%.1f%%\n",
MIN_SPACE_CHECKPOINT * 100.0, MAX_SPACE_CHECKPOINT * 100.0);
printf("Throughput targets: min=%.0f, max=%.0f, benchmark=%.0f\n",
min_throughput_checkpoint, max_throughput_checkpoint, ref_throughput);
printf("\n");
printf("***Final perf index = %.1f (util) + %.1f (thru) = %.1f/100.0***\n",
p1*UTIL_WEIGHT*100,
p2*(1.0 - UTIL_WEIGHT)*100,
perfindex);
printf("Average utilization = %.1f%%. Average throughput = %.0f Kops/sec\n",
avg_mm_util * 100.0,
avg_mm_throughput);
printf("Utilization targets: min=%.1f%%, max=%.1f%%\n",
MIN_SPACE * 100.0, MAX_SPACE * 100.0);
printf("Throughput targets: min=%.0f, max=%.0f, benchmark=%.0f\n",
min_throughput, max_throughput, ref_throughput);
printf("\n");
}
printf("Score: Checkpoint 1: %d / 50, Final: %d / 100\n",
(int)ceil(correctindex),
(int)ceil(perfindex));
#endif
exit(0);
}
/*****************************************************************
* Add trace to global list of tracefiles
****************************************************************/
static void add_tracefile(char *trace) {
global_tracefiles = realloc(global_tracefiles,
(num_global_tracefiles+1) * sizeof(char *));
global_tracefiles[num_global_tracefiles++] = strdup(trace);
}
/*****************************************************************
* The following routines manipulate the range list, which keeps
* track of the extent of every allocated block payload. We use the
* range list to detect any overlapping allocated blocks.
****************************************************************/
/*
* new_range_set - Create an empty range set
*/
static range_set_t *new_range_set() {
range_set_t *ranges = (range_set_t *) malloc(sizeof(range_set_t));
ranges->list = NULL;
ranges->lo_tree = tree_new();
return ranges;
}
/*
* add_range - As directed by request opnum in trace tracenum,
* we've just called the student's mm_malloc to allocate a block of
* size bytes at addr lo. After checking the block for correctness,
* we create a range struct for this block and add it to the range list.
*/
static bool add_range(range_set_t *ranges, char *lo, size_t size,
const trace_t *trace, int opnum, int index) {
char *hi = lo + size - 1;
assert(size > 0);
/* Payload addresses must be ALIGNMENT-byte aligned */
if (!IS_ALIGNED(lo)) {
malloc_error(trace, opnum,
"Payload address (%p) not aligned to %d bytes", lo, ALIGNMENT);
return false;
}
/* The payload must lie within the extent of the heap */
if ((lo < (char *)mem_heap_lo()) || (lo > (char *)mem_heap_hi()) ||
(hi < (char *)mem_heap_lo()) || (hi > (char *)mem_heap_hi())) {
malloc_error(trace, opnum,
"Payload (%p:%p) lies outside heap (%p:%p)",
lo, hi, mem_heap_lo(), mem_heap_hi());
return false;
}
/* If we can't afford the linear-time loop, we check less thoroughly and
just assume the overlap will be caught by writing random bits. */
if (debug_mode == DBG_NONE) return 1;
/* Look in the tree for the predecessor block */
range_t *prev = tree_find_nearest(ranges->lo_tree, (long unsigned) lo);
range_t *next = prev ? prev->next : NULL;
/* See if it overlaps previous or next blocks */
if (prev && lo <= prev->hi) {
malloc_error(trace, opnum,
"Payload (%p:%p) overlaps another payload (%p:%p)\n",
lo, hi, prev->lo, prev->hi);
return false;
}
if (next && hi >= next->lo) {
malloc_error(trace, opnum,
"Payload (%p:%p) overlaps another payload (%p:%p)\n",
lo, hi, next->lo, next->hi);
return false;
}
/*
* Everything looks OK, so remember the extent of this block
* by creating a range struct and adding it the range list.
*/
range_t *p;
if ((p = (range_t *)malloc(sizeof(range_t))) == NULL)
unix_error("malloc error in add_range");
p->prev = prev;
if (prev)
prev->next = p;
else
ranges->list = p;
p->next = next;
if (next)
next->prev = p;
p->lo = lo;
p->hi = hi;
p->index = index;
tree_insert(ranges->lo_tree, (long unsigned) lo, (void *) p);
return true;
}
/*
* remove_range - Free the range record of block whose payload starts at lo
*/
static void remove_range(range_set_t *ranges, char *lo)
{
range_t *p = (range_t *) tree_remove(ranges->lo_tree, (long unsigned) lo);
if (!p)
return;
range_t *prev = p->prev;
range_t *next = p->next;
if (prev)
prev->next = next;
else
ranges->list = next;
if (next)
next->prev = prev;
free(p);
}
/*
* free_range_set - free all of the range records for a trace
*/
static void free_range_set(range_set_t *ranges)
{
tree_free(ranges->lo_tree, free);
free(ranges);
}
/**********************************************
* The following routines handle the random data used for
* checking memory access.
*********************************************/
static void init_random_data(void) {
int len;
if (debug_mode == DBG_NONE) return;
for(len = 0; len < RANDOM_DATA_LEN; ++len) {
random_data[len] = random();
}
}
static void randomize_block(trace_t *traces, int index) {
size_t size, fsize, fsize_end;
size_t i;
randint_t *block, *block_end;
int base;
if (debug_mode == DBG_NONE) return;
traces->block_rand_base[index] = random();
block = (randint_t*)traces->blocks[index];
size = traces->block_sizes[index] / sizeof(*block);
if (size == 0)
return;
fsize = size;
if (fsize > maxfill) {
fsize = maxfill;
if (size > (2 * fsize)) {
fsize_end = fsize;
block_end = block + (size - fsize_end);
} else {
fsize_end = size - fsize;
block_end = block + fsize;
}
} else {
fsize_end = 0;
block_end = NULL;
}
base = traces->block_rand_base[index];
// NOTE: It's expensive to do this one byte at a time.
// NOTE: It would be nice to also fill in at end of block, but
// this gets messy with REALLOC
for(i = 0; i < fsize; i++) {
mem_write(&block[i],
random_data[(base + i) % RANDOM_DATA_LEN],
sizeof(randint_t));
}
for(i = 0; i < fsize_end; i++) {
mem_write(&block_end[i],
random_data[(base + i) % RANDOM_DATA_LEN],
sizeof(randint_t));
}
}
static bool check_index(const trace_t *trace, int opnum, int index, int realloc) {
size_t size, fsize, fsize_end;
size_t i;
randint_t *block, *block_end;
int base;
int ngarbled = 0;
int firstgarbled = -1;
if (index < 0) return true; /* we're doing free(NULL) */
if (debug_mode == DBG_NONE) return true;
block = (randint_t*)trace->blocks[index];
size = trace->block_sizes[index] / sizeof(*block);
if (size == 0)
return true;
fsize = size;
if (fsize > maxfill) {
fsize = maxfill;
if (size > (2 * fsize)) {
fsize_end = fsize;
block_end = block + (size - fsize_end);
} else {
fsize_end = size - fsize;
block_end = block + fsize;
}
} else {
fsize_end = 0;
block_end = NULL;
}
if (realloc) { // skip check after realloc
fsize_end = 0;
}
base = trace->block_rand_base[index];
// NOTE: It's expensive to do this one byte at a time.
for(i = 0; i < fsize; i++) {
if (mem_read(&block[i], sizeof(randint_t)) != random_data[(base + i) % RANDOM_DATA_LEN]) {
if (firstgarbled == -1) firstgarbled = i;
ngarbled++;
}
}
for(i = 0; i < fsize_end; i++) {
if (mem_read(&block_end[i], sizeof(randint_t)) != random_data[(base + i) % RANDOM_DATA_LEN]) {
if (firstgarbled == -1) firstgarbled = i;
ngarbled++;
}
}
if (ngarbled != 0) {
malloc_error(trace, opnum, "block %d has %d garbled %s%s, "
"starting at byte %zu", index, ngarbled, randint_t_name,
ngarbled > 1 ? "s" : "", sizeof(randint_t) * firstgarbled);
return false;
}
return true;
}
/**********************************************
* The following routines manipulate tracefiles
*********************************************/
/*
* read_trace - read a trace file and store it in memory
*/
static trace_t *read_trace(stats_t *stats, const char *tracedir,
const char *filename)
{
FILE *tracefile;
trace_t *trace;
char type[MAXLINE];
int index;
size_t size;
int max_index = 0;
int op_index;
int ignore = 0;
if (verbose > 1)
printf("Reading tracefile: %s\n", filename);
/* Allocate the trace record */
if ((trace = (trace_t *) malloc(sizeof(trace_t))) == NULL)
unix_error("malloc 1 failed in read_trace");
/* Read the trace file header */
strcpy(trace->filename, tracedir);
strcat(trace->filename, filename);
if ((tracefile = fopen(trace->filename, "r")) == NULL) {
unix_error("Could not open %s in read_trace", trace->filename);
}
int iweight;
ignore += fscanf(tracefile, "%d", &iweight);
trace->weight = iweight;
ignore += fscanf(tracefile, "%d", &trace->num_ids);
ignore += fscanf(tracefile, "%d", &trace->num_ops);
ignore += fscanf(tracefile, "%zd", &trace->data_bytes);
if (((unsigned int)trace->weight) > 3u) {
app_error("%s: weight can only be in {0, 1, 2 3}", trace->filename);
}
/* We'll store each request line in the trace in this array */
if ((trace->ops =
(traceop_t *)malloc(trace->num_ops * sizeof(traceop_t))) == NULL)
unix_error("malloc 2 failed in read_trace");
/* We'll keep an array of pointers to the allocated blocks here... */
if ((trace->blocks =
(char **)calloc(trace->num_ids, sizeof(char *))) == NULL)
unix_error("malloc 3 failed in read_trace");
/* ... along with the corresponding byte sizes of each block */
if ((trace->block_sizes =
(size_t *)calloc(trace->num_ids, sizeof(size_t))) == NULL)
unix_error("malloc 4 failed in read_trace");
/* and, if we're debugging, the offset into the random data */
if ((trace->block_rand_base =
calloc(trace->num_ids, sizeof(*trace->block_rand_base))) == NULL)
unix_error("malloc 5 failed in read_trace");
/* read every request line in the trace file */
index = 0;
op_index = 0;
while (fscanf(tracefile, "%s", type) != EOF) {
switch(type[0]) {
case 'a':
ignore += fscanf(tracefile, "%u %lu", &index, &size);
trace->ops[op_index].type = ALLOC;
trace->ops[op_index].index = index;
trace->ops[op_index].size = size;
max_index = (index > max_index) ? index : max_index;
break;
case 'r':
ignore += fscanf(tracefile, "%u %lu", &index, &size);
trace->ops[op_index].type = REALLOC;
trace->ops[op_index].index = index;
trace->ops[op_index].size = size;
max_index = (index > max_index) ? index : max_index;
break;
case 'f':
ignore += fscanf(tracefile, "%u", &index);
trace->ops[op_index].type = FREE;
trace->ops[op_index].index = index;
break;
default:
app_error("Bogus type character (%c) in tracefile %s\n",
type[0], trace->filename);
}
op_index++;
if (op_index == trace->num_ops) break;
}
fclose(tracefile);
assert(max_index == trace->num_ids - 1);
assert(trace->num_ops == op_index);
/* fill in the stats */
strcpy(stats->filename, trace->filename);
stats->weight = trace->weight;
stats->ops = trace->num_ops;
return trace;
}
/*
* reinit_trace - get the trace ready for another run.
*/