• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2020-2021 Huawei Device Co., Ltd.
3  *
4  * HDF is dual licensed: you can use it either under the terms of
5  * the GPL, or the BSD license, at your option.
6  * See the LICENSE file in the root of this repository for complete details.
7  */
8 #include <hcs_file.h>
9 #include <hcs_log.h>
10 #include <hcs_option.h>
11 
12 #define HCS_HEXDUMP_ENTRY_SYMBOL "hdfConfigEntrySymbol"
13 #define HCS_HEXDUMP_FILE_SUFFIX "_hex.c"
14 #define PRINT_SKIP_STEP 2
15 #define NUMS_PER_LINE 16
16 
HcsHexdumpOutput(FILE * in,FILE * out)17 int32_t HcsHexdumpOutput(FILE *in, FILE *out)
18 {
19     const char *prefix = HcsOptGetSymbolNamePrefix();
20     if (prefix == NULL) {
21         prefix = "";
22     }
23     if (fprintf(out, "static const unsigned char g_%s%s[] = {\n", prefix, HCS_HEXDUMP_ENTRY_SYMBOL) < 0) {
24         return EOUTPUT;
25     }
26     uint32_t writeCount = 0;
27     int32_t byte;
28     while ((byte = getc(in)) != EOF) {
29         if (fprintf(out, "%s0x%02x", (writeCount % NUMS_PER_LINE) ? ", " : &",\n    "[PRINT_SKIP_STEP * !writeCount],
30             byte) < 0) {
31             return EOUTPUT;
32         }
33         writeCount++;
34     }
35     if (fprintf(out, "\n};\n") < 0) {
36         return EOUTPUT;
37     }
38 
39     if (fprintf(out, "static const unsigned int g_%sLen = %u;\n", HCS_HEXDUMP_ENTRY_SYMBOL, writeCount) < 0) {
40         return EOUTPUT;
41     }
42     if (fprintf(out,
43         "void HdfGetBuildInConfigData(const unsigned char** data, unsigned int* size)\n"
44         "{\n"
45         "    *data = g_%s%s;\n"
46         "    *size = g_%s%sLen;\n"
47         "}",
48         prefix, HCS_HEXDUMP_ENTRY_SYMBOL,  prefix, HCS_HEXDUMP_ENTRY_SYMBOL) < 0) {
49         return EOUTPUT;
50     }
51     return NOERR;
52 }
53 
HcsBinaryToHexdump(const char * inputFileName)54 int32_t HcsBinaryToHexdump(const char *inputFileName)
55 {
56     struct HcsFile *source = NULL;
57     if (HcsOpenSourceFile(inputFileName, &source, "rb")) {
58         HCS_ERROR("can not open %s", inputFileName);
59         return EINVALF;
60     }
61 
62     struct HcsFile *out = HcsOpenOutputFile(HCS_HEXDUMP_FILE_SUFFIX);
63     if (out == NULL) {
64         HCS_ERROR("can not open %s", HcsGetOutPutFilePath());
65         HcsCloseFile(source);
66         return EINVALF;
67     }
68 
69     int32_t ret = HcsHexdumpOutput(source->file, out->file);
70     if (ret) {
71         HCS_ERROR("failed to gen bytecode hexdump in C style");
72     }
73     HcsCloseFile(source);
74     HcsCloseFile(out);
75     return ret;
76 }
77