xref: /XiangShan/tools/readmemh/split-readmemh.c (revision c6d439803a044ea209139672b25e35fe8d7f4aa0)
1 /***************************************************************************************
2 * Copyright (c) 2020-2021 Institute of Computing Technology, Chinese Academy of Sciences
3 *
4 * XiangShan is licensed under Mulan PSL v2.
5 * You can use this software according to the terms and conditions of the Mulan PSL v2.
6 * You may obtain a copy of Mulan PSL v2 at:
7 *          http://license.coscl.org.cn/MulanPSL2
8 *
9 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
10 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
11 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
12 *
13 * See the Mulan PSL v2 for more details.
14 ***************************************************************************************/
15 
16 #include <stdio.h>
17 #include <assert.h>
18 #include <stdint.h>
19 #include <string.h>
20 
21 char outname [4][4096];
22 
23 int main(int argc, char *argv[]) {
24   assert(argc == 2);
25 
26   FILE *in = fopen(argv[1], "rb");
27   assert(in != NULL);
28 
29   strcat(stpcpy(outname[0], argv[1]), "_0");
30   strcat(stpcpy(outname[1], argv[1]), "_1");
31   strcat(stpcpy(outname[2], argv[1]), "_2");
32   strcat(stpcpy(outname[3], argv[1]), "_3");
33 
34   FILE *out[4];
35   out[0] = fopen(outname[0], "w");
36   out[1] = fopen(outname[1], "w");
37   out[2] = fopen(outname[2], "w");
38   out[3] = fopen(outname[3], "w");
39   assert(out[0] != NULL && out[1] != NULL && out[2] != NULL && out[3] != NULL);
40 
41   char line[128];
42   int idx = 0;
43   while (fgets(line, 128, in) != NULL) {
44     if (line[0] == '@') {
45       uint32_t addr;
46       sscanf(line + 1, "%x", &addr);
47       assert(addr % 4 == 0);
48       fprintf(out[0], "\n@%08x\n", addr / 4);
49       fprintf(out[1], "\n@%08x\n", addr / 4);
50       fprintf(out[2], "\n@%08x\n", addr / 4);
51       fprintf(out[3], "\n@%08x\n", addr / 4);
52       idx = 0;
53     }
54     else {
55       // remove white spaces at the end
56       char *p = line + strlen(line) - 1;
57       while (p >= line && (*p == ' ' || *p == '\n' || *p == '\r')) p --;
58       p[1] = '\0';
59 
60       p = line;
61       char *byte;
62       while ((byte = strsep(&p, " "))) {
63         fprintf(out[idx % 4], "%s ", byte);
64         idx ++;
65       }
66 
67       if ((idx >> 2) % 16 == 0) {
68         fprintf(out[0], "\n");
69         fprintf(out[1], "\n");
70         fprintf(out[2], "\n");
71         fprintf(out[3], "\n");
72       }
73     }
74   }
75 
76   fclose(in);
77   fclose(out[0]);
78   fclose(out[1]);
79   fclose(out[2]);
80   fclose(out[3]);
81 
82   return 0;
83 }
84