File: release.cc

package info (click to toggle)
open-roms 0.0~git20210824.e4e324c-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 10,184 kB
  • sloc: asm: 25,386; cpp: 3,333; ansic: 1,667; makefile: 709
file content (679 lines) | stat: -rw-r--r-- 16,934 bytes parent folder | download | duplicates (2)
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
//
// Utility to prepare a release with automatically
// assigned version numbers
//

#include "common.h"

#include <stdlib.h>
#include <time.h>
#include <unistd.h>

#include <algorithm>
#include <cstring>
#include <fstream>
#include <ios>
#include <list>
#include <vector>

typedef struct
{
    std::string romTypeName;
    size_t  fileSize;
    size_t  signatureOffset1; // offset to 'OR' string
    size_t  signatureOffset2; // offset to 'OR' string
    size_t  dosDateOffset;    // offset to date of internal DOS
    size_t  idBasicOffset;    // offset to BASIC identification string
    size_t  idKernalOffset;   // offset to KERNAL identification byte

} ROMTypeDescriptionEntry;

const std::vector<ROMTypeDescriptionEntry> ROM_DEFINITIONS =
{
    {
        "BASIC",
        8192,         // file size
        0x1F52,       // signature offset 1
        0,            // signature offset 2
        0,            // DOS date offset
        0x0007,       // BASIC ID offset
        0             // KERNAL ID offset
    },
    
    {
        "KERNAL",
        8192,         // file size
        0x04B9,       // signature offset 1
        0,            // signature offset 2
        0,            // DOS date offset
        0,            // BASIC ID offset
        0x1F80        // KERNAL ID offset
    },

    {
        "CART",
        32896,        // file size
        0x203C,       // signature offset 1
        0,            // signature offset 2
        0,            // DOS date offset
        0,            // BASIC ID offset
        0             // KERNAL ID offset
    },

    {
        "MEGA65",
        128 * 1024,   // file size
        0xBF52,       // signature offset 1
        0xE4B9,       // signature offset 2
        0x10,          // DOS date offset
        0xA007,       // BASIC ID offset
        0xFF80        // KERNAL ID offset
    },
};

const uint32_t MAX_FILE_SIZE = 128 * 1024;

const std::vector<uint8_t> STR_BASIC    = { 0x42, 0x41, 0x53, 0x49, 0x43 };
const std::vector<uint8_t> STR_OR       = { 0x4F, 0x52 };
const std::vector<uint8_t> STR_SNAPSHOT = { 0x28, 0x44, 0x45, 0x56, 0x45, 0x4C, 0x20, 0x53, 
                                            0x4E, 0x41, 0x50, 0x53, 0x48, 0x4F, 0x54, 0x29,
                                            0x00 };
const std::vector<uint8_t> STR_DOSDATE  = { 0x4F, 0x58, 0x58, 0x58, 0x58, 0x58, 0x58, 0x58, 0x58 };

const std::string STR_DEV   = "DEV.";
const std::string STR_BLOCK = "DO NOT DISTRIBUTE";

//
// Command and enviroment line settings
//

std::string CMD_inDir   = "./build";
std::string CMD_outDir  = "./bin";

std::list<std::string> CMD_fileList;

std::string ENV_developerId;
std::string ENV_dateString;
std::string ENV_dateStringExt;

//
// Common helper functions
//

void printUsage()
{
    std::cout << "\n" <<
        "usage: release [-i <input (build) directory>] [-o <output (release) directory>]" << "\n" <<
        "               <file list>" << "\n\n";
}

//
// Class definitions
//

class ROMFile
{
public:

    ROMFile(const std::string &baseFileName);

    void embedRevisionStr(const std::string &newRevisionStr, const std::string &newRevisionStrDOS);
    void save();

    const ROMTypeDescriptionEntry *descPtr;

    bool    sameContent;
    bool    sameDeveloper;
    bool    sameDate;       // only set if sameDeveloper
    uint8_t oldDailyRelId;  // only set if sameDeveloper and sameDate

private:

    void readSrcFile();
    void readDstFile();

    void recognizeSrcFile();
    void dropUnmatchingDst();
    void analyzeContent();

    std::string baseFileName;

    std::vector<uint8_t> srcFileContent;
    std::vector<uint8_t> dstFileContent;
};

//
// Global variables
//

size_t             GLOBAL_maxFileNameLen    = 0;
std::list<ROMFile> GLOBAL_ROMFiles;

//
// Top-level functions
//

void parseCommandLine(int argc, char **argv)
{
    int opt;

    // Retrieve command line options

    while ((opt = getopt(argc, argv, "i:o:")) != -1)
    {
        switch(opt)
        {
            case 'i': CMD_inDir    = optarg; break;
            case 'o': CMD_outDir   = optarg; break;
            default: printUsage(); ERROR();
        }
    }

    // Retrieve file/directory list

    for (int idx = optind; idx < argc; idx++)
    {
        CMD_fileList.push_back(argv[idx]);
    }

    if (CMD_fileList.empty()) { printUsage(); ERROR("empty file list"); }
}

void getDeveloperId()
{
	const char* id = getenv("OPEN_ROMS_DEVELOPER_ID");

	// Check whether the developer ID is suitable

	if (id == nullptr)
	{
		ERROR("environment variable OPEN_ROMS_DEVELOPER_ID not set");
	}

	ENV_developerId = id;

	if (ENV_developerId.length() < 2 || ENV_developerId.length() > 3)
	{
		ERROR("OPEN_ROMS_DEVELOPER_ID has to be 2 or 3 characters long");
	}

	for (const char &c : ENV_developerId)
	{
		if (!(c >= 'A' && c <= 'Z'))
		{
			ERROR("OPEN_ROMS_DEVELOPER_ID can only contain uppercase letters");
		}
	}
}

void getDate()
{
    time_t t     = time(NULL);
    struct tm tm = *localtime(&t);

    const std::string year    = std::to_string(tm.tm_year % 100);
    const std::string yearExt = std::to_string((tm.tm_year + 1900) / 100);
    const std::string month   = std::to_string(tm.tm_mon + 1);
    const std::string day     = std::to_string(tm.tm_mday);

    const std::string zero    = "0";

    ENV_dateString    = (year.size()    == 2 ? year    : zero + year) +
                        (month.size()   == 2 ? month   : zero + month) +
                        (day.size()     == 2 ? day     : zero + day);

    ENV_dateStringExt = (yearExt.size() == 2 ? yearExt : zero + yearExt);

    if (ENV_dateString.size() != 6 || ENV_dateStringExt.size() != 2) ERROR("could not retrieve date");
}

void printBanner()
{
    printBannerLineTop();
    std::cout << "// Preparing ROM set release" << "\n";
    printBannerLineBottom();
}

void readFiles()
{
    for (auto &fileName : CMD_fileList) GLOBAL_ROMFiles.push_back(ROMFile(fileName));
}

void decideIfUpdate()
{
    // Check if we have any file at all

    if (GLOBAL_ROMFiles.empty())
    {
        ERROR("no files to update");
    }

    // Check if we have at least one file with changed content

    bool sameContent = true;
    for (auto &file : GLOBAL_ROMFiles)
    {
        if (!file.sameContent)
        {
            sameContent = false;
            break;
        }
    }

    if (sameContent)
    {
        ERROR("same content in all the files");
    }
}

void saveFiles()
{
    // Determine a daily revision sequence ID

    uint8_t relId = 0;
    for (auto &file : GLOBAL_ROMFiles)
    {
        if (file.sameDeveloper && file.sameDate)
        {
            relId = std::max(file.oldDailyRelId, relId);
        }
    }
    relId++;

    if (relId > 9)
    {
        ERROR("too many releases this day");
    }

    // Create a new revision string

    const std::string newRevStr    = STR_DEV + ENV_dateString + "." + ENV_developerId + "." + std::to_string(relId);
    const std::string newRevStrDOS = ENV_dateString + ENV_dateStringExt;

    for (auto &file : GLOBAL_ROMFiles)
    {
        file.embedRevisionStr(newRevStr, newRevStrDOS);
    }

    std::cout << "Files for release '" << newRevStr << "':\n\n";

    // Save the files

    for (auto &file : GLOBAL_ROMFiles)
    {
        file.save();
    }
}

//
// Main function
//

int main(int argc, char **argv)
{
    parseCommandLine(argc, argv);
    getDeveloperId();
    getDate();

    printBanner();

    readFiles();
    decideIfUpdate();
    saveFiles();

    std::cout << "\n";

    return 0;
}

//
// Class 'ROMFile'
//

ROMFile::ROMFile(const std::string &baseFileName) :
    descPtr(nullptr),
    sameContent(false),
    sameDeveloper(false),
    sameDate(false),
    oldDailyRelId(0),
    baseFileName(baseFileName)
{
    GLOBAL_maxFileNameLen = std::max(GLOBAL_maxFileNameLen, baseFileName.length());

    readSrcFile();
    readDstFile();

    recognizeSrcFile();
    dropUnmatchingDst();
    analyzeContent();
}

void ROMFile::readSrcFile()
{
    // Read the source file

    const std::string srcFileNamePath = CMD_inDir + DIR_SEPARATOR + baseFileName;

    std::ifstream srcFile;
    srcFile.open(srcFileNamePath, std::ios::in | std::ios::binary | std::ios::ate);

    if (!srcFile.good()) ERROR(std::string("unable to open ROM file '") + srcFileNamePath + "'");

    auto srcSize = srcFile.tellg();
    if (srcSize > MAX_FILE_SIZE) ERROR(std::string("incorrect size of ROM file '") + srcFileNamePath + "'");

    srcFileContent.resize(srcSize);
    srcFile.seekg (0, srcFile.beg);
    srcFile.read((char *) srcFileContent.data(), srcFileContent.size());

    if (!srcFile.good()) ERROR(std::string("unable to read ROM file '") + srcFileNamePath + "'");
    srcFile.close();   

    // Check if it is OK to distribute the file

    for (size_t idx = 0; idx < srcFileContent.size() - STR_BLOCK.size(); idx++)
    {
        if (memcmp(&srcFileContent[idx], STR_BLOCK.c_str(), STR_BLOCK.size()) == 0)
        {
            ERROR(std::string("not allowed to distribute ROM file '") + srcFileNamePath + "'");
        }
    }
}

void ROMFile::readDstFile()
{
    // Read the destination file (if exists and it's size matches)

    const std::string dstFileNamePath = CMD_outDir + DIR_SEPARATOR + baseFileName;

    std::ifstream dstFile;
    dstFile.open(dstFileNamePath, std::ios::in | std::ios::binary | std::ios::ate);

    bool continueReading = dstFile.good();

    if (continueReading && dstFile.tellg() != unsigned(srcFileContent.size())) continueReading = false;

    if (continueReading)
    {
        dstFileContent.resize(srcFileContent.size());
        dstFile.seekg (0, dstFile.beg);
        dstFile.read((char *) dstFileContent.data(), dstFileContent.size());       
    }

    if (!dstFile.good()) dstFileContent.clear();
    dstFile.close();
}

void ROMFile::recognizeSrcFile()
{
    // Recognize source file type

    auto checkSignature = [this](size_t signatureOffset) -> bool
    {
        if (signatureOffset == 0)
        {
            return true;
        }

        if (memcmp(&srcFileContent[signatureOffset], STR_OR.data(), STR_OR.size()) != 0)
        {
            return false;
        }

        auto snapshotStrOffset = signatureOffset + STR_OR.size() + 1;
        if (memcmp(&srcFileContent[snapshotStrOffset], STR_SNAPSHOT.data(), STR_SNAPSHOT.size()) != 0)
        {
            return false;
        }

        auto zeroByteoffset = snapshotStrOffset + 0x10;
        if (srcFileContent[zeroByteoffset] != 0)
        {
            return false;
        }

        return true;
    };

    auto checkDosDate = [this](size_t dosDateOffset) -> bool
    {
        if (dosDateOffset == 0)
        {
            return true;
        }

        if (memcmp(&srcFileContent[dosDateOffset], STR_DOSDATE.data(), STR_DOSDATE.size()) != 0)
        {
            return false;
        }

        return true;
    };

    for (auto &SPEC : ROM_DEFINITIONS)
    {
        if (srcFileContent.size() != SPEC.fileSize) continue;

        if ((SPEC.idBasicOffset != 0) &&
            memcmp(&srcFileContent[SPEC.idBasicOffset], STR_BASIC.data(), STR_BASIC.size()) != 0)
        {
            continue;
        }

        if ((SPEC.idKernalOffset != 0) && srcFileContent[SPEC.idKernalOffset] != 0xF0)
        {
            continue;
        }

        if (!checkDosDate(SPEC.dosDateOffset))
        {
            continue;
        }

        if (!checkSignature(SPEC.signatureOffset1) || !checkSignature(SPEC.signatureOffset2))
        {
            continue;
        }

        descPtr = &SPEC;
        break;
    }

    if (descPtr == nullptr)
    {
        ERROR(std::string("'") + CMD_inDir + DIR_SEPARATOR + baseFileName +
              "' is not a supported unversioned Open ROMs image");
    }
}

void ROMFile::dropUnmatchingDst()
{
    // Drop unmatching destination file data

    if (!dstFileContent.empty() && (descPtr->idBasicOffset != 0) &&
        memcmp(&dstFileContent[descPtr->idBasicOffset], STR_BASIC.data(), STR_BASIC.size()) != 0)
    {
        dstFileContent.clear();
    }

    if (!dstFileContent.empty() && (descPtr->idKernalOffset != 0) &&
        dstFileContent[descPtr->idKernalOffset] != 0xF0)
    {
        dstFileContent.clear();
    }

    if (!dstFileContent.empty() && (descPtr->signatureOffset1 != 0) &&
        memcmp(&dstFileContent[descPtr->signatureOffset1], STR_OR.data(), STR_OR.size()) != 0)
    {
        dstFileContent.clear();
    }

    if (!dstFileContent.empty() && (descPtr->signatureOffset2 != 0) &&
        memcmp(&dstFileContent[descPtr->signatureOffset2], STR_OR.data(), STR_OR.size()) != 0)
    {
        dstFileContent.clear();
    }
}

void ROMFile::analyzeContent()
{
    auto revOffset1 = (descPtr->signatureOffset1 != 0) ? (descPtr->signatureOffset1 + 3) : 0;
    auto revOffset2 = (descPtr->signatureOffset2 != 0) ? (descPtr->signatureOffset2 + 3) : 0;
    auto revOffset3 = (descPtr->dosDateOffset    != 0) ? descPtr->dosDateOffset          : 0;
    
    if (revOffset1 == 0)
    {
        revOffset1 = revOffset2;
        revOffset2 = 0;
    }

    if (revOffset1 == 0)
    {
        return;
    }

    if (dstFileContent.empty())
    {
        return;
    }

    // If two ID strings are present, they should be the same

    if (0 != revOffset1 && 0 != revOffset2 &&
        memcmp(&dstFileContent[revOffset1], &dstFileContent[revOffset2], 0x10) != 0)
    {
        return;
    }

    // Check if meaningful file content is really different

    sameContent = true;
    for (uint32_t idx = 0; idx < descPtr->fileSize; idx++)
    {
        if (revOffset1 != 0 && idx - revOffset1 < 0x10)
        {
            continue;
        }

        if (revOffset2 != 0 && idx - revOffset2 < 0x10)
        {
            continue;
        }

        if (revOffset3 != 0 && idx - revOffset3 < 0x10)
        {
            continue;
        }

        if (srcFileContent[idx] != dstFileContent[idx])
        {
            sameContent = false;
            break;
        }
    }

    // Determine expected length of developer ID

    uint8_t devIdLen = ENV_developerId.length();

    // Determine if old version is a devel version compatible with this tool

    if (memcmp(&dstFileContent[revOffset1], STR_DEV.data(), STR_DEV.size()) != 0)
    {
        return;
    }

    uint16_t idxDate  = revOffset1 + STR_DEV.size();
    uint16_t idxLimit = idxDate + ENV_dateString.length();

    uint16_t idx = idxDate;
    for (; idx < idxLimit; idx++)
    {
        if (dstFileContent[idx] < '0' || dstFileContent[idx] > '9')
        {
            return;
        }
    }

    if (dstFileContent[idx]                != '.' ||
        dstFileContent[idx + devIdLen + 1] != '.' ||
        dstFileContent[idx + devIdLen + 2]  < '0' ||
        dstFileContent[idx + devIdLen + 2]  > '9' ||
        dstFileContent[idx + devIdLen + 3] != 0)
    {
        return;
    }

    // Retrieve release data

    if (memcmp(&dstFileContent[idx + 1], ENV_developerId.data(), ENV_developerId.size()) != 0)
    {
        return; // different developer
    }

    sameDeveloper = true;

    if (memcmp(&dstFileContent[idxDate], ENV_dateString.data(), ENV_dateString.size()) != 0)
    {
        return; // different date
    }    
    
    sameDate = true;
    oldDailyRelId = dstFileContent[idx + devIdLen + 2] - '0';
}

void ROMFile::embedRevisionStr(const std::string &newRevisionStr, const std::string &newRevisionStrDOS)
{
    std::string revStr    = newRevisionStr;

    while (revStr.length() < 16) revStr = revStr + '\0';

    if (descPtr->signatureOffset1 != 0)
    {
        memcpy(&srcFileContent[descPtr->signatureOffset1 + 3],
               revStr.data(), revStr.size());       
    }

    if (descPtr->signatureOffset2 != 0)
    {
        memcpy(&srcFileContent[descPtr->signatureOffset2 + 3],
               revStr.data(), revStr.size());       
    }

    if (descPtr->dosDateOffset != 0)
    {
        memcpy(&srcFileContent[descPtr->dosDateOffset + 1],
               newRevisionStrDOS.data(), newRevisionStrDOS.size());       
    }

}

void ROMFile::save()
{
    const std::string outFileNamePath = CMD_outDir + DIR_SEPARATOR + baseFileName;

    // Print out file name and metadata

    std::string spacing;
    spacing.resize(GLOBAL_maxFileNameLen + 4 - baseFileName.length(), ' ');

    std::cout << "    " << outFileNamePath << spacing << descPtr->romTypeName;

    if (sameContent)
    {
        spacing.resize(10 - descPtr->romTypeName.length(), ' ');
        std::cout << spacing << "(unchanged)";
    }

    std::cout << "\n";

    std::ofstream outFile;
    outFile.open(outFileNamePath, std::ios::out | std::ios::binary | std::ios::trunc);

    if (!outFile.good()) ERROR(std::string("unable to open output file '") + outFileNamePath + "'");

    outFile.write((char *) srcFileContent.data(), srcFileContent.size());

    if (!outFile.good()) ERROR(std::string("unable to write file '") + outFileNamePath + "'");
    outFile.close();   
}