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