1/*
2 * Copyright (c) 2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16#include <fstream>
17#include <iostream>
18#include <string>
19#include "ecmascript/log_wrapper.h"
20#include "ecmascript/platform/file.h"
21#include "prof_dump_json.h"
22#include "securec.h"
23
24static constexpr size_t OUTPUT_FILE_ARG = 2;
25static constexpr size_t ARGS_NUMBER = 3;
26
27int main(int argc, char** argv)
28{
29    if (argc != ARGS_NUMBER) {
30        std::cout << "please use this tools like:" << std::endl;
31        std::cout << "    ./apViewer input.ap out.json" << std::endl;
32        return 0;
33    }
34    std::string input = argv[1];
35    std::string output = argv[OUTPUT_FILE_ARG];
36    size_t length = native::ConvertApToJson(input.c_str(), input.length());
37    if (length == 0 || length >= SIZE_MAX) {
38        LOG_NO_TAG(ERROR) << "ConvertApToJson returned zero or invalid length!";
39        return 0;
40    }
41    char *buffer = (char *)malloc(length);
42    if (buffer == nullptr) {
43        LOG_NO_TAG(ERROR) << "malloc buffer failed";
44        return 0;
45    }
46    if (memset_s(buffer, length, 0, length) != EOK) {
47        LOG_NO_TAG(ERROR) << "clean malloc buffer failed";
48        free(buffer);
49        return 0;
50    }
51
52    auto result = native::GetConvertResult(buffer, length);
53    if (result) {
54        std::cout << "convert " << argv[1] << " to " << argv[OUTPUT_FILE_ARG] << " success!" << std::endl;
55    } else {
56        std::cout << "convert " << argv[1] << " to " << argv[OUTPUT_FILE_ARG] << " failed!" << std::endl;
57    }
58
59    std::string realOutPath;
60    if (!panda::ecmascript::RealPath(output, realOutPath, false)) {
61        LOG_NO_TAG(ERROR) << "Can not load filepath " << output;
62        free(buffer);
63        return 0;
64    }
65    std::ofstream outFile(realOutPath);
66    if (!outFile.is_open()) {
67        LOG_NO_TAG(ERROR) << "open " << realOutPath << " failed!";
68        free(buffer);
69        return 0;
70    }
71    std::string strRet(buffer, length);
72    outFile << strRet;
73    outFile.close();
74    free(buffer);
75    return 0;
76}
77