summaryrefslogtreecommitdiffstatshomepage
path: root/src/emu/romload.c
blob: b0b84c4cee3f8c4fd9d969278e89ca9942c16440 (plain) (blame)
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
/*********************************************************************

    romload.c

    ROM loading functions.

    Copyright Nicola Salmoria and the MAME Team.
    Visit http://mamedev.org for licensing and usage restrictions.

*********************************************************************/

#include "osdepend.h"
#include "driver.h"
#include "hash.h"
#include "png.h"
#include "harddisk.h"
#include "config.h"
#include "ui.h"
#include "deprecat.h"


#define LOG_LOAD 0
#define LOG(x) do { if (LOG_LOAD) debugload x; } while(0)



/***************************************************************************
    TYPE DEFINITIONS
***************************************************************************/

typedef struct _open_chd open_chd;
struct _open_chd
{
	open_chd *			next;					/* pointer to next in the list */
	chd_file *			origchd;				/* handle to the original CHD */
	mame_file *			origfile;				/* file handle to the original CHD file */
	chd_file *			diffchd;				/* handle to the diff CHD */
	mame_file *			difffile;				/* file handle to the diff CHD file */
};



/***************************************************************************
    GLOBAL VARIABLES
***************************************************************************/

/* disks */
static open_chd *chd_list;
static open_chd **chd_list_tailptr;

/* system BIOS */
static int system_bios;

static int total_rom_load_warnings;



/***************************************************************************
    FUNCTION PROTOTYPES
***************************************************************************/

static void rom_exit(running_machine *machine);



/***************************************************************************
    HARD DISK HANDLING
***************************************************************************/

chd_file *get_disk_handle(int diskindex)
{
	open_chd *curdisk;
	for (curdisk = chd_list; curdisk != NULL && diskindex-- != 0; curdisk = curdisk->next) ;
	if (curdisk != NULL)
		return (curdisk->diffchd != NULL) ? curdisk->diffchd : curdisk->origchd;
	return NULL;
}



/***************************************************************************
    ROM LOADING
***************************************************************************/

/*-------------------------------------------------
    rom_first_region - return pointer to first ROM
    region
-------------------------------------------------*/

const rom_entry *rom_first_region(const game_driver *drv)
{
	return (drv->rom != NULL && !ROMENTRY_ISEND(drv->rom)) ? drv->rom : NULL;
}


/*-------------------------------------------------
    rom_next_region - return pointer to next ROM
    region
-------------------------------------------------*/

const rom_entry *rom_next_region(const rom_entry *romp)
{
	romp++;
	while (!ROMENTRY_ISREGIONEND(romp))
		romp++;
	return ROMENTRY_ISEND(romp) ? NULL : romp;
}


/*-------------------------------------------------
    rom_first_file - return pointer to first ROM
    file
-------------------------------------------------*/

const rom_entry *rom_first_file(const rom_entry *romp)
{
	romp++;
	while (!ROMENTRY_ISFILE(romp) && !ROMENTRY_ISREGIONEND(romp))
		romp++;
	return ROMENTRY_ISREGIONEND(romp) ? NULL : romp;
}


/*-------------------------------------------------
    rom_next_file - return pointer to next ROM
    file
-------------------------------------------------*/

const rom_entry *rom_next_file(const rom_entry *romp)
{
	romp++;
	while (!ROMENTRY_ISFILE(romp) && !ROMENTRY_ISREGIONEND(romp))
		romp++;
	return ROMENTRY_ISREGIONEND(romp) ? NULL : romp;
}


/*-------------------------------------------------
    rom_first_chunk - return pointer to first ROM
    chunk
-------------------------------------------------*/

const rom_entry *rom_first_chunk(const rom_entry *romp)
{
	return (ROMENTRY_ISFILE(romp)) ? romp : NULL;
}


/*-------------------------------------------------
    rom_next_chunk - return pointer to next ROM
    chunk
-------------------------------------------------*/

const rom_entry *rom_next_chunk(const rom_entry *romp)
{
	romp++;
	return (ROMENTRY_ISCONTINUE(romp) || ROMENTRY_ISIGNORE(romp)) ? romp : NULL;
}


/*-------------------------------------------------
    debugload - log data to a file
-------------------------------------------------*/

static void CLIB_DECL ATTR_PRINTF(1,2) debugload(const char *string, ...)
{
	static int opened;
	va_list arg;
	FILE *f;

	f = fopen("romload.log", opened++ ? "a" : "w");
	if (f)
	{
		va_start(arg, string);
		vfprintf(f, string, arg);
		va_end(arg);
		fclose(f);
	}
}


/*-------------------------------------------------
    determine_bios_rom - determine system_bios
    from SystemBios structure and OPTION_BIOS
-------------------------------------------------*/

static int determine_bios_rom(rom_load_data *romdata, const rom_entry *romp)
{
	const char *specbios = options_get_string(mame_options(), OPTION_BIOS);
	const rom_entry *rom;
	int bios_count = 0;
	int bios_no = 0;

	/* look for a BIOS with a matching name */
	for (rom = romp; !ROMENTRY_ISEND(rom); rom++)
		if (ROMENTRY_ISSYSTEM_BIOS(rom))
		{
			const char *biosname = ROM_GETNAME(rom);
			int bios_flags = ROM_GETBIOSFLAGS(rom);
			char bios_number[20];

			/* Allow '-bios n' to still be used */
			sprintf(bios_number, "%d", bios_flags - 1);
			if (strcmp(bios_number, specbios) == 0 || strcmp(biosname, specbios) == 0)
				bios_no = bios_flags;
			bios_count++;
		}

	/* if none found, use the default */
	if (bios_no == 0 && bios_count > 0)
	{
		/* if we got neither an empty string nor 'default' then warn the user */
		if (specbios[0] != 0 && strcmp(specbios, "default") != 0)
		{
			sprintf(&romdata->errorbuf[strlen(romdata->errorbuf)], "%s: invalid bios\n", specbios);
			romdata->warnings++;
		}

		/* set to default */
		bios_no = 1;
	}

	LOG(("Using System BIOS: %d\n", bios_no));
	return bios_no;
}


/*-------------------------------------------------
    count_roms - counts the total number of ROMs
    that will need to be loaded
-------------------------------------------------*/

static int count_roms(const rom_entry *romp)
{
	const rom_entry *region, *rom;
	int count = 0;

	/* loop over regions, then over files */
	for (region = romp; region; region = rom_next_region(region))
		for (rom = rom_first_file(region); rom; rom = rom_next_file(rom))
		{
			int bios_flags = ROM_GETBIOSFLAGS(rom);
			if (!bios_flags || (bios_flags == system_bios)) /* alternate bios sets */
				count++;
		}

	/* return the total count */
	return count;
}


/*-------------------------------------------------
    fill_random - fills an area of memory with
    random data
-------------------------------------------------*/

static void fill_random(UINT8 *base, UINT32 length)
{
	while (length--)
		*base++ = mame_rand(Machine);
}


/*-------------------------------------------------
    handle_missing_file - handles error generation
    for missing files
-------------------------------------------------*/

static void handle_missing_file(rom_load_data *romdata, const rom_entry *romp)
{
	/* optional files are okay */
	if (ROM_ISOPTIONAL(romp))
	{
		sprintf(&romdata->errorbuf[strlen(romdata->errorbuf)], "OPTIONAL %s NOT FOUND\n", ROM_GETNAME(romp));
		romdata->warnings++;
	}

	/* no good dumps are okay */
	else if (ROM_NOGOODDUMP(romp))
	{
		sprintf(&romdata->errorbuf[strlen(romdata->errorbuf)], "%s NOT FOUND (NO GOOD DUMP KNOWN)\n", ROM_GETNAME(romp));
		romdata->warnings++;
	}

	/* anything else is bad */
	else
	{
		sprintf(&romdata->errorbuf[strlen(romdata->errorbuf)], "%s NOT FOUND\n", ROM_GETNAME(romp));
		romdata->errors++;
	}
}


/*-------------------------------------------------
    dump_wrong_and_correct_checksums - dump an
    error message containing the wrong and the
    correct checksums for a given ROM
-------------------------------------------------*/

static void dump_wrong_and_correct_checksums(rom_load_data* romdata, const char* hash, const char* acthash)
{
	unsigned i;
	char chksum[256];
	unsigned found_functions;
	unsigned wrong_functions;

	found_functions = hash_data_used_functions(hash) & hash_data_used_functions(acthash);

	hash_data_print(hash, found_functions, chksum);
	sprintf(&romdata->errorbuf[strlen(romdata->errorbuf)], "    EXPECTED: %s\n", chksum);

	/* We dump informations only of the functions for which MAME provided
        a correct checksum. Other functions we might have calculated are
        useless here */
	hash_data_print(acthash, found_functions, chksum);
	sprintf(&romdata->errorbuf[strlen(romdata->errorbuf)], "       FOUND: %s\n", chksum);

	/* For debugging purposes, we check if the checksums available in the
       driver are correctly specified or not. This can be done by checking
       the return value of one of the extract functions. Maybe we want to
       activate this only in debug buils, but many developers only use
       release builds, so I keep it as is for now. */
	wrong_functions = 0;
	for (i = 0; i < HASH_NUM_FUNCTIONS; i++)
		if (hash_data_extract_printable_checksum(hash, 1 << i, chksum) == 2)
			wrong_functions |= 1 << i;

	if (wrong_functions)
	{
		for (i = 0; i < HASH_NUM_FUNCTIONS; i++)
			if (wrong_functions & (1 << i))
			{
				sprintf(&romdata->errorbuf[strlen(romdata->errorbuf)],
					"\tInvalid %s checksum treated as 0 (check leading zeros)\n",
					hash_function_name(1 << i));

				romdata->warnings++;
			}
	}
}


/*-------------------------------------------------
    verify_length_and_hash - verify the length
    and hash signatures of a file
-------------------------------------------------*/

static void verify_length_and_hash(rom_load_data *romdata, const char *name, UINT32 explength, const char* hash)
{
	UINT32 actlength;
	const char* acthash;

	/* we've already complained if there is no file */
	if (!romdata->file)
		return;

	/* get the length and CRC from the file */
	actlength = mame_fsize(romdata->file);
	acthash = mame_fhash(romdata->file, hash_data_used_functions(hash));

	/* verify length */
	if (explength != actlength)
	{
		sprintf(&romdata->errorbuf[strlen(romdata->errorbuf)], "%s WRONG LENGTH (expected: %08x found: %08x)\n", name, explength, actlength);
		romdata->warnings++;
	}

	/* If there is no good dump known, write it */
	if (hash_data_has_info(hash, HASH_INFO_NO_DUMP))
	{
			sprintf(&romdata->errorbuf[strlen(romdata->errorbuf)], "%s NO GOOD DUMP KNOWN\n", name);
		romdata->warnings++;
	}
	/* verify checksums */
	else if (!hash_data_is_equal(hash, acthash, 0))
	{
		/* otherwise, it's just bad */
		sprintf(&romdata->errorbuf[strlen(romdata->errorbuf)], "%s WRONG CHECKSUMS:\n", name);

		dump_wrong_and_correct_checksums(romdata, hash, acthash);

		romdata->warnings++;
	}
	/* If it matches, but it is actually a bad dump, write it */
	else if (hash_data_has_info(hash, HASH_INFO_BAD_DUMP))
	{
		sprintf(&romdata->errorbuf[strlen(romdata->errorbuf)], "%s ROM NEEDS REDUMP\n",name);
		romdata->warnings++;
	}
}


/*-------------------------------------------------
    display_loading_rom_message - display
    messages about ROM loading to the user
-------------------------------------------------*/

static void display_loading_rom_message(const char *name, rom_load_data *romdata)
{
	char buffer[200];

	if (name != NULL)
		sprintf(buffer, "Loading (%d%%)", 100 * romdata->romsloaded / romdata->romstotal);
	else
		sprintf(buffer, "Loading Complete");

	ui_set_startup_text(Machine, buffer, FALSE);
}


/*-------------------------------------------------
    display_rom_load_results - display the final
    results of ROM loading
-------------------------------------------------*/

static void display_rom_load_results(rom_load_data *romdata)
{
	/* final status display */
	display_loading_rom_message(NULL, romdata);

	/* if we had errors, they are fatal */
	if (romdata->errors != 0)
	{
		const char *rgntag, *nextrgntag;
		
		/* clean up any regions */
		for (rgntag = memory_region_next(Machine, NULL); rgntag != NULL; rgntag = nextrgntag)
		{
			nextrgntag = memory_region_next(Machine, rgntag);
			memory_region_free(Machine, rgntag);
		}

		/* create the error message and exit fatally */
		strcat(romdata->errorbuf, "ERROR: required files are missing, the game cannot be run.");
		fatalerror_exitcode(MAMERR_MISSING_FILES, "%s", romdata->errorbuf);
	}

	/* if we had warnings, output them, but continue */
	if (romdata->warnings)
	{
		strcat(romdata->errorbuf, "WARNING: the game might not run correctly.");
		mame_printf_warning("%s\n", romdata->errorbuf);
	}
}


/*-------------------------------------------------
    region_post_process - post-process a region,
    byte swapping and inverting data as necessary
-------------------------------------------------*/

static void region_post_process(running_machine *machine, rom_load_data *romdata, const char *rgntag)
{
	UINT32 regionlength = memory_region_length(machine, rgntag);
	UINT32 regionflags = memory_region_flags(machine, rgntag);
	UINT8 *regionbase = memory_region(machine, rgntag);
	int littleendian = ((regionflags & ROMREGION_ENDIANMASK) == ROMREGION_LE);
	int datawidth = 1 << ((regionflags & ROMREGION_WIDTHMASK) >> 8);
	UINT8 *base;
	int i, j;

	LOG(("+ datawidth=%d little=%d\n", datawidth, littleendian));

	/* if the region is inverted, do that now */
	if (regionflags & ROMREGION_INVERTMASK)
	{
		LOG(("+ Inverting region\n"));
		for (i = 0, base = regionbase; i < regionlength; i++)
			*base++ ^= 0xff;
	}

	/* swap the endianness if we need to */
#ifdef LSB_FIRST
	if (datawidth > 1 && !littleendian)
#else
	if (datawidth > 1 && littleendian)
#endif
	{
		LOG(("+ Byte swapping region\n"));
		for (i = 0, base = regionbase; i < regionlength; i += datawidth)
		{
			UINT8 temp[8];
			memcpy(temp, base, datawidth);
			for (j = datawidth - 1; j >= 0; j--)
				*base++ = temp[j];
		}
	}
}


/*-------------------------------------------------
    open_rom_file - open a ROM file, searching
    up the parent and loading by checksum
-------------------------------------------------*/

static int open_rom_file(rom_load_data *romdata, const rom_entry *romp)
{
	file_error filerr = FILERR_NOT_FOUND;
	const game_driver *drv;

	++romdata->romsloaded;

	/* update status display */
	display_loading_rom_message(ROM_GETNAME(romp), romdata);

	/* Attempt reading up the chain through the parents. It automatically also
       attempts any kind of load by checksum supported by the archives. */
	romdata->file = NULL;
	for (drv = Machine->gamedrv; !romdata->file && drv; drv = driver_get_clone(drv))
		if (drv->name && *drv->name)
		{
			UINT8 crcs[4];
			astring *fname;

			fname = astring_assemble_3(astring_alloc(), drv->name, PATH_SEPARATOR, ROM_GETNAME(romp));
			if (hash_data_extract_binary_checksum(ROM_GETHASHDATA(romp), HASH_CRC, crcs))
			{
				UINT32 crc = (crcs[0] << 24) | (crcs[1] << 16) | (crcs[2] << 8) | crcs[3];
				filerr = mame_fopen_crc(SEARCHPATH_ROM, astring_c(fname), crc, OPEN_FLAG_READ, &romdata->file);
			}
			else
				filerr = mame_fopen(SEARCHPATH_ROM, astring_c(fname), OPEN_FLAG_READ, &romdata->file);
			astring_free(fname);
		}

	/* return the result */
	return (filerr == FILERR_NONE);
}


/*-------------------------------------------------
    rom_fread - cheesy fread that fills with
    random data for a NULL file
-------------------------------------------------*/

static int rom_fread(rom_load_data *romdata, UINT8 *buffer, int length)
{
	/* files just pass through */
	if (romdata->file)
		return mame_fread(romdata->file, buffer, length);

	/* otherwise, fill with randomness */
	else
		fill_random(buffer, length);

	return length;
}


/*-------------------------------------------------
    read_rom_data - read ROM data for a single
    entry
-------------------------------------------------*/

static int read_rom_data(rom_load_data *romdata, const rom_entry *romp)
{
	int datashift = ROM_GETBITSHIFT(romp);
	int datamask = ((1 << ROM_GETBITWIDTH(romp)) - 1) << datashift;
	int numbytes = ROM_GETLENGTH(romp);
	int groupsize = ROM_GETGROUPSIZE(romp);
	int skip = ROM_GETSKIPCOUNT(romp);
	int reversed = ROM_ISREVERSED(romp);
	int numgroups = (numbytes + groupsize - 1) / groupsize;
	UINT8 *base = romdata->regionbase + ROM_GETOFFSET(romp);
	int i;

	LOG(("Loading ROM data: offs=%X len=%X mask=%02X group=%d skip=%d reverse=%d\n", ROM_GETOFFSET(romp), numbytes, datamask, groupsize, skip, reversed));

	/* make sure the length was an even multiple of the group size */
	if (numbytes % groupsize != 0)
		fatalerror("Error in RomModule definition: %s length not an even multiple of group size\n", ROM_GETNAME(romp));

	/* make sure we only fill within the region space */
	if (ROM_GETOFFSET(romp) + numgroups * groupsize + (numgroups - 1) * skip > romdata->regionlength)
		fatalerror("Error in RomModule definition: %s out of memory region space\n", ROM_GETNAME(romp));

	/* make sure the length was valid */
	if (numbytes == 0)
		fatalerror("Error in RomModule definition: %s has an invalid length\n", ROM_GETNAME(romp));

	/* special case for simple loads */
	if (datamask == 0xff && (groupsize == 1 || !reversed) && skip == 0)
		return rom_fread(romdata, base, numbytes);

	/* chunky reads for complex loads */
	skip += groupsize;
	while (numbytes)
	{
		int evengroupcount = (sizeof(romdata->tempbuf) / groupsize) * groupsize;
		int bytesleft = (numbytes > evengroupcount) ? evengroupcount : numbytes;
		UINT8 *bufptr = romdata->tempbuf;

		/* read as much as we can */
		LOG(("  Reading %X bytes into buffer\n", bytesleft));
		if (rom_fread(romdata, romdata->tempbuf, bytesleft) != bytesleft)
			return 0;
		numbytes -= bytesleft;

		LOG(("  Copying to %p\n", base));

		/* unmasked cases */
		if (datamask == 0xff)
		{
			/* non-grouped data */
			if (groupsize == 1)
				for (i = 0; i < bytesleft; i++, base += skip)
					*base = *bufptr++;

			/* grouped data -- non-reversed case */
			else if (!reversed)
				while (bytesleft)
				{
					for (i = 0; i < groupsize && bytesleft; i++, bytesleft--)
						base[i] = *bufptr++;
					base += skip;
				}

			/* grouped data -- reversed case */
			else
				while (bytesleft)
				{
					for (i = groupsize - 1; i >= 0 && bytesleft; i--, bytesleft--)
						base[i] = *bufptr++;
					base += skip;
				}
		}

		/* masked cases */
		else
		{
			/* non-grouped data */
			if (groupsize == 1)
				for (i = 0; i < bytesleft; i++, base += skip)
					*base = (*base & ~datamask) | ((*bufptr++ << datashift) & datamask);

			/* grouped data -- non-reversed case */
			else if (!reversed)
				while (bytesleft)
				{
					for (i = 0; i < groupsize && bytesleft; i++, bytesleft--)
						base[i] = (base[i] & ~datamask) | ((*bufptr++ << datashift) & datamask);
					base += skip;
				}

			/* grouped data -- reversed case */
			else
				while (bytesleft)
				{
					for (i = groupsize - 1; i >= 0 && bytesleft; i--, bytesleft--)
						base[i] = (base[i] & ~datamask) | ((*bufptr++ << datashift) & datamask);
					base += skip;
				}
		}
	}
	LOG(("  All done\n"));
	return ROM_GETLENGTH(romp);
}


/*-------------------------------------------------
    fill_rom_data - fill a region of ROM space
-------------------------------------------------*/

static void fill_rom_data(rom_load_data *romdata, const rom_entry *romp)
{
	UINT32 numbytes = ROM_GETLENGTH(romp);
	UINT8 *base = romdata->regionbase + ROM_GETOFFSET(romp);

	/* make sure we fill within the region space */
	if (ROM_GETOFFSET(romp) + numbytes > romdata->regionlength)
		fatalerror("Error in RomModule definition: FILL out of memory region space\n");

	/* make sure the length was valid */
	if (numbytes == 0)
		fatalerror("Error in RomModule definition: FILL has an invalid length\n");

	/* fill the data (filling value is stored in place of the hashdata) */
	memset(base, (FPTR)ROM_GETHASHDATA(romp) & 0xff, numbytes);
}


/*-------------------------------------------------
    copy_rom_data - copy a region of ROM space
-------------------------------------------------*/

static void copy_rom_data(rom_load_data *romdata, const rom_entry *romp)
{
	UINT8 *base = romdata->regionbase + ROM_GETOFFSET(romp);
	const char *srcrgntag = ROM_GETNAME(romp);
	UINT32 numbytes = ROM_GETLENGTH(romp);
	UINT32 srcoffs = (FPTR)ROM_GETHASHDATA(romp);  /* srcoffset in place of hashdata */
	UINT8 *srcbase;

	/* make sure we copy within the region space */
	if (ROM_GETOFFSET(romp) + numbytes > romdata->regionlength)
		fatalerror("Error in RomModule definition: COPY out of target memory region space\n");

	/* make sure the length was valid */
	if (numbytes == 0)
		fatalerror("Error in RomModule definition: COPY has an invalid length\n");

	/* make sure the source was valid */
	srcbase = memory_region(Machine, srcrgntag);
	if (srcbase == NULL)
		fatalerror("Error in RomModule definition: COPY from an invalid region\n");

	/* make sure we find within the region space */
	if (srcoffs + numbytes > memory_region_length(Machine, srcrgntag))
		fatalerror("Error in RomModule definition: COPY out of source memory region space\n");

	/* fill the data */
	memcpy(base, srcbase + srcoffs, numbytes);
}


/*-------------------------------------------------
    process_rom_entries - process all ROM entries
    for a region
-------------------------------------------------*/

static void process_rom_entries(rom_load_data *romdata, const rom_entry *romp)
{
	UINT32 lastflags = 0;

	/* loop until we hit the end of this region */
	while (!ROMENTRY_ISREGIONEND(romp))
	{
		/* if this is a continue entry, it's invalid */
		if (ROMENTRY_ISCONTINUE(romp))
			fatalerror("Error in RomModule definition: ROM_CONTINUE not preceded by ROM_LOAD\n");

		/* if this is an ignore entry, it's invalid */
		if (ROMENTRY_ISIGNORE(romp))
			fatalerror("Error in RomModule definition: ROM_IGNORE not preceded by ROM_LOAD\n");

		/* if this is a reload entry, it's invalid */
		if (ROMENTRY_ISRELOAD(romp))
			fatalerror("Error in RomModule definition: ROM_RELOAD not preceded by ROM_LOAD\n");

		/* handle fills */
		if (ROMENTRY_ISFILL(romp))
			fill_rom_data(romdata, romp++);

		/* handle copies */
		else if (ROMENTRY_ISCOPY(romp))
			copy_rom_data(romdata, romp++);

		/* handle files */
		else if (ROMENTRY_ISFILE(romp))
		{
			int bios_flags = ROM_GETBIOSFLAGS(romp);
			if (!bios_flags || (bios_flags == system_bios)) /* alternate bios sets */
			{
				const rom_entry *baserom = romp;
				int explength = 0;

				/* open the file */
				LOG(("Opening ROM file: %s\n", ROM_GETNAME(romp)));
				if (!open_rom_file(romdata, romp))
					handle_missing_file(romdata, romp);

				/* loop until we run out of reloads */
				do
				{
					/* loop until we run out of continues/ignores */
					do
					{
						rom_entry modified_romp = *romp++;
						int readresult;

						/* handle flag inheritance */
						if (!ROM_INHERITSFLAGS(&modified_romp))
							lastflags = modified_romp._flags;
						else
							modified_romp._flags = (modified_romp._flags & ~ROM_INHERITEDFLAGS) | lastflags;

						explength += ROM_GETLENGTH(&modified_romp);

						/* attempt to read using the modified entry */
						if (!ROMENTRY_ISIGNORE(&modified_romp))
							readresult = read_rom_data(romdata, &modified_romp);
					}
					while (ROMENTRY_ISCONTINUE(romp) || ROMENTRY_ISIGNORE(romp));

					/* if this was the first use of this file, verify the length and CRC */
					if (baserom)
					{
						LOG(("Verifying length (%X) and checksums\n", explength));
						verify_length_and_hash(romdata, ROM_GETNAME(baserom), explength, ROM_GETHASHDATA(baserom));
						LOG(("Verify finished\n"));
					}

					/* reseek to the start and clear the baserom so we don't reverify */
					if (romdata->file)
						mame_fseek(romdata->file, 0, SEEK_SET);
					baserom = NULL;
					explength = 0;
				}
				while (ROMENTRY_ISRELOAD(romp));

				/* close the file */
				if (romdata->file)
				{
					LOG(("Closing ROM file\n"));
					mame_fclose(romdata->file);
					romdata->file = NULL;
				}
			}
			else
			{
				romp++; /* skip over file */
			}
		}
		else
		{
			romp++;	/* something else; skip */
		}
	}
}


/*-------------------------------------------------
    open_disk_image - open a DISK image, searching
    up the parent and loading by checksum
-------------------------------------------------*/

chd_error open_disk_image(const game_driver *gamedrv, const rom_entry *romp, mame_file **image_file, chd_file **image_chd)
{
	return open_disk_image_options(mame_options(), gamedrv, romp, image_file, image_chd);
}


/*-------------------------------------------------
    open_disk_image_options - open a DISK image, searching
    up the parent and loading by checksum
-------------------------------------------------*/

chd_error open_disk_image_options(core_options *options, const game_driver *gamedrv, const rom_entry *romp, mame_file **image_file, chd_file **image_chd)
{
	const game_driver *drv, *searchdrv;
	const rom_entry *region, *rom;
	file_error filerr;
	chd_error err;

	*image_file = NULL;
	*image_chd = NULL;

	/* attempt to open the properly named file, scanning up through parent directories */
	filerr = FILERR_NOT_FOUND;
	for (searchdrv = gamedrv; searchdrv != NULL && filerr != FILERR_NONE; searchdrv = driver_get_clone(searchdrv))
	{
		astring *fname = astring_assemble_4(astring_alloc(), searchdrv->name, PATH_SEPARATOR, ROM_GETNAME(romp), ".chd");
		filerr = mame_fopen_options(options, SEARCHPATH_IMAGE, astring_c(fname), OPEN_FLAG_READ, image_file);
		astring_free(fname);
	}

	/* did the file open succeed? */
	if (filerr == FILERR_NONE)
	{
		/* try to open the CHD */
		err = chd_open_file(mame_core_file(*image_file), CHD_OPEN_READ, NULL, image_chd);
		if (err == CHDERR_NONE)
			return err;

		/* close the file on failure */
		mame_fclose(*image_file);
		*image_file = NULL;
	}
	else
		err = CHDERR_FILE_NOT_FOUND;

	/* otherwise, look at our parents for a CHD with an identical checksum */
	/* and try to open that */
	for (drv = gamedrv; drv != NULL; drv = driver_get_clone(drv))
		for (region = rom_first_region(drv); region != NULL; region = rom_next_region(region))
			if (ROMREGION_ISDISKDATA(region))
				for (rom = rom_first_file(region); rom != NULL; rom = rom_next_file(rom))

					/* look for a differing name but with the same hash data */
					if (strcmp(ROM_GETNAME(romp), ROM_GETNAME(rom)) != 0 &&
						hash_data_is_equal(ROM_GETHASHDATA(romp), ROM_GETHASHDATA(rom), 0))
					{
						/* attempt to open the properly named file, scanning up through parent directories */
						filerr = FILERR_NOT_FOUND;
						for (searchdrv = drv; searchdrv != NULL && filerr != FILERR_NONE; searchdrv = driver_get_clone(searchdrv))
						{
							astring *fname = astring_assemble_4(astring_alloc(), searchdrv->name, PATH_SEPARATOR, ROM_GETNAME(rom), ".chd");
							filerr = mame_fopen_options(options, SEARCHPATH_IMAGE, astring_c(fname), OPEN_FLAG_READ, image_file);
							astring_free(fname);
						}

						/* did the file open succeed? */
						if (filerr == FILERR_NONE)
						{
							/* try to open the CHD */
							err = chd_open_file(mame_core_file(*image_file), CHD_OPEN_READ, NULL, image_chd);
							if (err == CHDERR_NONE)
								return err;

							/* close the file on failure */
							mame_fclose(*image_file);
							*image_file = NULL;
						}
					}

	return err;
}


/*-------------------------------------------------
    open_disk_diff - open a DISK diff file
-------------------------------------------------*/

static chd_error open_disk_diff(const game_driver *drv, const rom_entry *romp, chd_file *source, mame_file **diff_file, chd_file **diff_chd)
{
	astring *fname = astring_assemble_2(astring_alloc(), ROM_GETNAME(romp), ".dif");
	file_error filerr;
	chd_error err;

	*diff_file = NULL;
	*diff_chd = NULL;

	/* try to open the diff */
	LOG(("Opening differencing image file: %s\n", astring_c(fname)));
	filerr = mame_fopen(SEARCHPATH_IMAGE_DIFF, astring_c(fname), OPEN_FLAG_READ | OPEN_FLAG_WRITE, diff_file);
	if (filerr != FILERR_NONE)
	{
		/* didn't work; try creating it instead */
		LOG(("Creating differencing image: %s\n", astring_c(fname)));
		filerr = mame_fopen(SEARCHPATH_IMAGE_DIFF, astring_c(fname), OPEN_FLAG_READ | OPEN_FLAG_WRITE | OPEN_FLAG_CREATE | OPEN_FLAG_CREATE_PATHS, diff_file);
		if (filerr != FILERR_NONE)
		{
			err = CHDERR_FILE_NOT_FOUND;
			goto done;
		}

		/* create the CHD */
		err = chd_create_file(mame_core_file(*diff_file), 0, 0, CHDCOMPRESSION_NONE, source);
		if (err != CHDERR_NONE)
			goto done;
	}

	LOG(("Opening differencing image file: %s\n", astring_c(fname)));
	err = chd_open_file(mame_core_file(*diff_file), CHD_OPEN_READWRITE, source, diff_chd);
	if (err != CHDERR_NONE)
		goto done;

done:
	astring_free(fname);
	if ((err != CHDERR_NONE) && (*diff_file != NULL))
	{
		mame_fclose(*diff_file);
		*diff_file = NULL;
	}
	return err;
}


/*-------------------------------------------------
    process_disk_entries - process all disk entries
    for a region
-------------------------------------------------*/

static void process_disk_entries(rom_load_data *romdata, const rom_entry *romp)
{
	/* loop until we hit the end of this region */
	while (!ROMENTRY_ISREGIONEND(romp))
	{
		/* handle files */
		if (ROMENTRY_ISFILE(romp))
		{
			char acthash[HASH_BUF_SIZE];
			open_chd chd = { 0 };
			chd_header header;
			astring *filename;
			chd_error err;

			/* make the filename of the source */
			filename = astring_assemble_2(astring_alloc(), ROM_GETNAME(romp), ".chd");

			/* first open the source drive */
			LOG(("Opening disk image: %s\n", astring_c(filename)));
			err = open_disk_image(Machine->gamedrv, romp, &chd.origfile, &chd.origchd);
			if (err != CHDERR_NONE)
			{
				if (err == CHDERR_UNSUPPORTED_VERSION)
					sprintf(&romdata->errorbuf[strlen(romdata->errorbuf)], "%s UNSUPPORTED CHD VERSION\n", astring_c(filename));
				else
					sprintf(&romdata->errorbuf[strlen(romdata->errorbuf)], "%s NOT FOUND\n", astring_c(filename));

				/* if this is NO_DUMP, keep going, though the system may not be able to handle it */
				if (hash_data_has_info(ROM_GETHASHDATA(romp), HASH_INFO_NO_DUMP))
					romdata->warnings++;
				else
					romdata->errors++;
				goto next;
			}

			/* get the header and extract the MD5/SHA1 */
			header = *chd_get_header(chd.origchd);
			hash_data_clear(acthash);
			hash_data_insert_binary_checksum(acthash, HASH_MD5, header.md5);
			hash_data_insert_binary_checksum(acthash, HASH_SHA1, header.sha1);

			/* verify the MD5 */
			if (!hash_data_is_equal(ROM_GETHASHDATA(romp), acthash, 0))
			{
				sprintf(&romdata->errorbuf[strlen(romdata->errorbuf)], "%s WRONG CHECKSUMS:\n", astring_c(filename));
				dump_wrong_and_correct_checksums(romdata, ROM_GETHASHDATA(romp), acthash);
				romdata->warnings++;
			}
			else if (hash_data_has_info(ROM_GETHASHDATA(romp), HASH_INFO_BAD_DUMP))
			{
				sprintf(&romdata->errorbuf[strlen(romdata->errorbuf)], "%s CHD NEEDS REDUMP\n", astring_c(filename));
				romdata->warnings++;
			}

			/* if not read-only, make the diff file */
			if (!DISK_ISREADONLY(romp))
			{
				/* try to open or create the diff */
				err = open_disk_diff(Machine->gamedrv, romp, chd.origchd, &chd.difffile, &chd.diffchd);
				if (err != CHDERR_NONE)
				{
					if (err == CHDERR_UNSUPPORTED_VERSION)
						sprintf(&romdata->errorbuf[strlen(romdata->errorbuf)], "%s UNSUPPORTED CHD VERSION\n", astring_c(filename));
					else
						sprintf(&romdata->errorbuf[strlen(romdata->errorbuf)], "%s: CAN'T OPEN DIFF FILE\n", astring_c(filename));
					romdata->errors++;
					goto next;
				}
			}

			/* we're okay, add to the list of disks */
			LOG(("Assigning to handle %d\n", DISK_GETINDEX(romp)));
			*chd_list_tailptr = auto_malloc(sizeof(**chd_list_tailptr));
			**chd_list_tailptr = chd;
			chd_list_tailptr = &(*chd_list_tailptr)->next;
next:
			romp++;
			astring_free(filename);
		}
	}
}


/*-------------------------------------------------
    normalize_flags_for_cpu - modify the region
    flags for the given CPU index
-------------------------------------------------*/

static UINT32 normalize_flags_for_cpu(running_machine *machine, UINT32 startflags, const char *rgntag)
{
	int cpunum = mame_find_cpu_index(machine, rgntag);
	if (cpunum >= 0)
	{
		int cputype = machine->config->cpu[cpunum].type;
		int buswidth;

		/* set the endianness */
		startflags &= ~ROMREGION_ENDIANMASK;
		if (cputype_endianness(cputype) == CPU_IS_LE)
			startflags |= ROMREGION_LE;
		else
			startflags |= ROMREGION_BE;

		/* set the width */
		startflags &= ~ROMREGION_WIDTHMASK;
		buswidth = cputype_databus_width(cputype, ADDRESS_SPACE_PROGRAM);
		if (buswidth <= 8)
			startflags |= ROMREGION_8BIT;
		else if (buswidth <= 16)
			startflags |= ROMREGION_16BIT;
		else if (buswidth <= 32)
			startflags |= ROMREGION_32BIT;
		else
			startflags |= ROMREGION_64BIT;
	}
	return startflags;
}


/*-------------------------------------------------
    rom_init - new, more flexible ROM
    loading system
-------------------------------------------------*/

void rom_init(running_machine *machine, const rom_entry *romp)
{
	static rom_load_data romdata;
	const rom_entry *region;

	/* if no roms, bail */
	if (romp == NULL)
		return;

	/* make sure we get called back on the way out */
	add_exit_callback(machine, rom_exit);

	/* reset the romdata struct */
	memset(&romdata, 0, sizeof(romdata));

	/* determine the correct biosset to load based on OPTION_BIOS string */
	system_bios = determine_bios_rom(&romdata, romp);

	romdata.romstotal = count_roms(romp);

	/* reset the disk list */
	chd_list = NULL;
	chd_list_tailptr = &chd_list;

	/* loop until we hit the end */
	for (region = romp; region; region = rom_next_region(region))
	{
		UINT32 regionlength = ROMREGION_GETLENGTH(region);
		UINT32 regionflags = ROMREGION_GETFLAGS(region);
		const char *regiontag = ROMREGION_GETTAG(region);

		LOG(("Processing region \"%s\" (length=%X)\n", regiontag, regionlength));

		/* the first entry must be a region */
		assert(ROMENTRY_ISREGION(region));

		/* if this is a CPU region, override with the CPU width and endianness */
		if (mame_find_cpu_index(machine, regiontag) >= 0)
			regionflags = normalize_flags_for_cpu(machine, regionflags, regiontag);

		/* remember the base and length */
		romdata.regionbase = memory_region_alloc(machine, regiontag, regionlength, regionflags);
		romdata.regionlength = regionlength;
		LOG(("Allocated %X bytes @ %p\n", romdata.regionlength, romdata.regionbase));

		/* clear the region if it's requested */
		if (ROMREGION_ISERASE(region))
			memset(romdata.regionbase, ROMREGION_GETERASEVAL(region), romdata.regionlength);

		/* or if it's sufficiently small (<= 4MB) */
		else if (romdata.regionlength <= 0x400000)
			memset(romdata.regionbase, 0, romdata.regionlength);

#ifdef MAME_DEBUG
		/* if we're debugging, fill region with random data to catch errors */
		else
			fill_random(romdata.regionbase, romdata.regionlength);
#endif

		/* now process the entries in the region */
		if (ROMREGION_ISROMDATA(region))
			process_rom_entries(&romdata, region + 1);
		else if (ROMREGION_ISDISKDATA(region))
			process_disk_entries(&romdata, region + 1);

		/* finally, post-process for endianness and inversion */
		region_post_process(machine, &romdata, regiontag);
	}

	/* display the results and exit */
	total_rom_load_warnings = romdata.warnings;

	display_rom_load_results(&romdata);
}


/*-------------------------------------------------
    rom_exit - clean up after ourselves
-------------------------------------------------*/

static void rom_exit(running_machine *machine)
{
	const char *rgntag, *nextrgntag;
	open_chd *curchd;

	/* free the memory allocated for various regions */
	for (rgntag = memory_region_next(machine, NULL); rgntag != NULL; rgntag = nextrgntag)
	{
		nextrgntag = memory_region_next(machine, rgntag);
		memory_region_free(machine, rgntag);
	}

	/* close all hard drives */
	for (curchd = chd_list; curchd != NULL; curchd = curchd->next)
	{
		if (curchd->diffchd != NULL)
			chd_close(curchd->diffchd);
		if (curchd->difffile != NULL)
			mame_fclose(curchd->difffile);
		if (curchd->origchd != NULL)
			chd_close(curchd->origchd);
		if (curchd->origfile != NULL)
			mame_fclose(curchd->origfile);
	}
}


int rom_load_warnings(void)
{
	return total_rom_load_warnings;
}