Merged
fix(machine): Fix security risks #2467
W4termyAdd on Apr 13
fix(machine): Fix security risks #2467
Merged
W4termyAdd on Apr 13
Total: 7 files changed+214-50
@@ -18,11 +18,14 @@
18#include <iostream>18#include <iostream>
19#include <sstream>19#include <sstream>
20#include <sys/stat.h>20#include <sys/stat.h>
21+#include <unistd.h>
22+#include <vector>
21#include "codegen/utils/parallel_execute.h"23#include "codegen/utils/parallel_execute.h"
22#include "interface/utils/file_utils.h"24#include "interface/utils/file_utils.h"
23#include "interface/utils/op_info_manager.h"25#include "interface/utils/op_info_manager.h"
24#include "machine/compile/gen_aicore_code.h"26#include "machine/compile/gen_aicore_code.h"
25#include "machine/host/main_block.h"27#include "machine/host/main_block.h"
28+#include "machine/utils/checkinject.h"
26#include "tilefwk/platform.h"29#include "tilefwk/platform.h"
27#include "tilefwk/pypto_fwk_log.h"30#include "tilefwk/pypto_fwk_log.h"
28#include "machine/utils/machine_error.h"31#include "machine/utils/machine_error.h"
@@ -36,8 +39,7 @@ constexpr const char* BISHENG_LD_CMD = "ld.lld";
36} // namespace39} // namespace
37 40 
38static int CompileCoreMachine(41static int CompileCoreMachine(
39- const std::string& objFile, bool isCube, uint64_t tilingKey, const std::string& headFile,42+ const std::string& objFile, bool isCube, uint64_t tilingKey, const std::string& headFile, const std::string& aicoreSrcFile)
40- const std::string& aicoreSrcFile)
41{43{
42 MACHINE_LOGI("Compile src file is [%s], kernel type[%d].", aicoreSrcFile.c_str(), isCube);44 MACHINE_LOGI("Compile src file is [%s], kernel type[%d].", aicoreSrcFile.c_str(), isCube);
43 std::string ccecAicVersion = Platform::Instance().GetSoc().GetCCECVersion("AIC");45 std::string ccecAicVersion = Platform::Instance().GetSoc().GetCCECVersion("AIC");
@@ -66,13 +68,10 @@ static int CompileCoreMachine(
66 "-D__TILINGKEY__=%s "68 "-D__TILINGKEY__=%s "
67 "-D__OPTYPE__=%s "69 "-D__OPTYPE__=%s "
68 "-D__HEAD_FILE__=%s "70 "-D__HEAD_FILE__=%s "
69- "%s "71+ "%s " "%s "
70- "%s "
71 "-I%s/tileop/arch32 "72 "-I%s/tileop/arch32 "
72- "-I%s/ "73+ "-I%s/ " "-I%s/include/tileop/arch32 "
73- "-I%s/include/tileop/arch32 "74+ "-I%s/include/ " "-o %s %s %s %s",
74- "-I%s/include/ "
75- "-o %s %s %s %s",
76 BISHENG_PROGRAM_CMD, cc_opt.c_str(), std::to_string(tilingKey).c_str(), opType.c_str(), headFile.c_str(),75 BISHENG_PROGRAM_CMD, cc_opt.c_str(), std::to_string(tilingKey).c_str(), opType.c_str(), headFile.c_str(),
77 hasSubFunc.c_str(), coreType.c_str(), includePath.c_str(), includePath.c_str(),76 hasSubFunc.c_str(), coreType.c_str(), includePath.c_str(), includePath.c_str(),
78 GetCurrentSharedLibPath().c_str(), GetCurrentSharedLibPath().c_str(), objFile.c_str(),77 GetCurrentSharedLibPath().c_str(), GetCurrentSharedLibPath().c_str(), objFile.c_str(),
@@ -81,11 +80,13 @@ static int CompileCoreMachine(
81 MACHINE_LOGE(HostBackEndErr::COMPILE_AICORE_FAILED, "Compile aicore construct cmd failed.");80 MACHINE_LOGE(HostBackEndErr::COMPILE_AICORE_FAILED, "Compile aicore construct cmd failed.");
82 return ret;81 return ret;
83 }82 }
84- MACHINE_LOGD("Compile ccec command:[%s].", ccecCmd.c_str());83+ ret = Checkinject(ccecCmd.c_str(), ccecCmd.size());
85- ret = std::system(ccecCmd.c_str());
86 if (ret != 0) {84 if (ret != 0) {
87- MACHINE_LOGE(HostBackEndErr::COMPILE_CCEC_FAILED, "Compile ccec failed.");85+ MACHINE_LOGE(HostBackEndErr::COMPILE_AICORE_FAILED, "Compile aicore cmd illegal char.");
86+ return ret;
88 }87 }
88+ ret = std::system(ccecCmd.c_str());
89+ if (ret != 0) {MACHINE_LOGE(HostBackEndErr::COMPILE_CCEC_FAILED, "Compile ccec failed.");}
89 return ret;90 return ret;
90}91}
91 92 
@@ -146,6 +147,52 @@ std::string GenSubFuncCall(
146 return head_file;147 return head_file;
147}148}
148 149 
150+static int RunLdViaSecureTempScript(const std::string& ccePath, const std::string& key, const std::string& ccecCmd)
151+{
152+ std::string linkScriptTemplate = ccePath + "link_" + key + std::to_string(getpid()) + "_XXXXXX";
153+ std::vector<char> linkScriptBuffer(linkScriptTemplate.begin(), linkScriptTemplate.end());
154+ linkScriptBuffer.push_back('\0');
155+ int fd = mkstemp(linkScriptBuffer.data());
156+ if (fd < 0) {
157+ MACHINE_LOGE(HostBackEndErr::LINK_FAILED, "Create secure link script failed.");
158+ return -1;
159+ }
160+ const std::string linkScript(linkScriptBuffer.data());
161+ if (fchmod(fd, S_IRUSR | S_IWUSR | S_IXUSR) != 0) {
162+ MACHINE_LOGE(HostBackEndErr::LINK_FAILED, "Set secure link script permission failed, file[%s].", linkScript.c_str());
163+ (void)close(fd);
164+ (void)unlink(linkScript.c_str());
165+ return -1;
166+ }
167+ const std::string scriptContent = std::string("#!/bin/bash\n") + ccecCmd;
168+ ssize_t writtenSize = write(fd, scriptContent.data(), scriptContent.size());
169+ if (writtenSize < 0 || static_cast<size_t>(writtenSize) != scriptContent.size()) {
170+ MACHINE_LOGE(HostBackEndErr::LINK_FAILED, "Write secure link script failed, file[%s].", linkScript.c_str());
171+ (void)close(fd);
172+ (void)unlink(linkScript.c_str());
173+ return -1;
174+ }
175+ if (close(fd) != 0) {
176+ MACHINE_LOGE(HostBackEndErr::LINK_FAILED, "Close secure link script failed, file[%s].", linkScript.c_str());
177+ (void)unlink(linkScript.c_str());
178+ return -1;
179+ }
180+ const std::string ldCmd = "bash " + linkScript;
181+ int ret = Checkinject(ldCmd.c_str(), ldCmd.size());
182+ if (ret != 0) {
183+ MACHINE_LOGE(HostBackEndErr::LINK_FAILED, "Link kernel cmd illegal char.");
184+ return ret;
185+ }
186+ ret = std::system(ldCmd.c_str());
187+ if (unlink(linkScript.c_str()) != 0) {
188+ MACHINE_LOGW("Cleanup secure link script failed, file[%s].", linkScript.c_str());
189+ }
190+ if (ret != 0) {
191+ MACHINE_LOGE(HostBackEndErr::LINK_FAILED, "Link kernel failed.");
192+ }
193+ return ret;
194+}
195+ 
149static int LinkObject(196static int LinkObject(
150 const std::string& src_objs, std::string& objPath, const std::string& ccePath, bool relocate,197 const std::string& src_objs, std::string& objPath, const std::string& ccePath, bool relocate,
151 const std::string& key)198 const std::string& key)
@@ -164,17 +211,7 @@ static int LinkObject(
164 return ret;211 return ret;
165 }212 }
166 MACHINE_LOGD("Link ccec command: [%s].", ccecCmd.c_str());213 MACHINE_LOGD("Link ccec command: [%s].", ccecCmd.c_str());
167- const std::string linkScript = ccePath + "link_" + key + "_" + std::to_string(getpid()) + ".sh";214+ return RunLdViaSecureTempScript(ccePath, key, ccecCmd);
168- std::ofstream script(linkScript.c_str());
169- script << "#!/bin/bash\n";
170- script << ccecCmd.c_str();
171- script.close();
172- const std::string ldCmd = "bash " + linkScript;
173- ret = std::system(ldCmd.c_str());
174- if (ret != 0) {
175- MACHINE_LOGE(HostBackEndErr::LINK_FAILED, "Link kernel failed.");
176- }
177- return ret;
178}215}
179 216 
180int CompileAICoreKernel(217int CompileAICoreKernel(
@@ -19,8 +19,10 @@
19#include <nlohmann/json.hpp>19#include <nlohmann/json.hpp>
20#include "interface/program/program.h"20#include "interface/program/program.h"
21#include "interface/utils/file_utils.h"21#include "interface/utils/file_utils.h"
22+#include "interface/utils/common.h"
22#include "interface/configs/config_manager.h"23#include "interface/configs/config_manager.h"
23#include "interface/utils/op_info_manager.h"24#include "interface/utils/op_info_manager.h"
25+#include "machine/utils/checkinject.h"
24#include "machine/utils/machine_utils.h"26#include "machine/utils/machine_utils.h"
25#include "tilefwk/pypto_fwk_log.h"27#include "tilefwk/pypto_fwk_log.h"
26#include "machine/utils/machine_error.h"28#include "machine/utils/machine_error.h"
@@ -33,13 +35,24 @@ const std::string CustomKerneLib = "CUSTKFCKernel";
33 35 
34std::string GetMachineCompilerPath()36std::string GetMachineCompilerPath()
35{37{
36- // ARM arch compiler38+ constexpr const char* kAscendHomeEnv = "ASCEND_HOME_PATH";
37- const char* homePath = std::getenv("ASCEND_HOME_PATH");39+ const std::string homePath = npu::tile_fwk::GetEnvVar(kAscendHomeEnv);
38- if (homePath == nullptr) {40+ if (homePath.empty()) {
41+ MACHINE_LOGE(npu::tile_fwk::DevCommonErr::GET_ENV_FAILED,
42+ "%s is unset, empty after trimming whitespace, or exceeds max env length; device control-flow compiler "
43+ "path is disabled.",
44+ kAscendHomeEnv);
39 return "";45 return "";
40- } else {
41- return std::string(homePath) + "/toolkit/toolchain/hcc/bin/aarch64-target-linux-gnu-g++";
42 }46 }
47+ const std::string compiler =
48+ homePath + "/toolkit/toolchain/hcc/bin/aarch64-target-linux-gnu-g++";
49+ if (!npu::tile_fwk::FileExist(compiler)) {
50+ MACHINE_LOGE(npu::tile_fwk::DevCommonErr::FILE_ERROR,
51+ "%s is set but aarch64 toolchain g++ was not found at \"%s\" (canonical path must exist).",
52+ kAscendHomeEnv, compiler.c_str());
53+ return "";
54+ }
55+ return compiler;
43}56}
44const std::string DeviceMahineCompiler = GetMachineCompilerPath();57const std::string DeviceMahineCompiler = GetMachineCompilerPath();
45} // namespace58} // namespace
@@ -105,8 +118,13 @@ bool TieFwkAicpuPreCompile(std::string& preCompileO, std::string& controlAicpuPa
105 controlAicpuPath + file + " -I" + includePath + " -I" + includePath + "/include/" +118 controlAicpuPath + file + " -I" + includePath + " -I" + includePath + "/include/" +
106 " -I" + GetCurrentSharedLibPath() + "/include/" + " -o " + objFile;119 " -I" + GetCurrentSharedLibPath() + "/include/" + " -o " + objFile;
107 MACHINE_LOGD("PreCompileCmd is %s, file is %s.\n", compileCmd.c_str(), file.c_str());120 MACHINE_LOGD("PreCompileCmd is %s, file is %s.\n", compileCmd.c_str(), file.c_str());
108- int result = std::system(compileCmd.c_str());121+ int ret = Checkinject(compileCmd.c_str(), compileCmd.size());
109- if (result != 0) {122+ if (ret != 0) {
123+ MACHINE_LOGE(DevCommonErr::SYSTEM_CALL_FAILED, "Precompile %s cmd illegal char.\n", file.c_str());
124+ return false;
125+ }
126+ ret = std::system(compileCmd.c_str());
127+ if (ret != 0) {
110 MACHINE_LOGE(DevCommonErr::SYSTEM_CALL_FAILED, "Precompile %s fail\n", file.c_str());128 MACHINE_LOGE(DevCommonErr::SYSTEM_CALL_FAILED, "Precompile %s fail\n", file.c_str());
111 return false;129 return false;
112 }130 }
@@ -123,12 +141,16 @@ bool SharedAicpuCompile(const std::string& funcName, const std::string& aicpuDir
123 aicpuDirPath + "/lib" + funcName + "_control.so " + preCompileO +141 aicpuDirPath + "/lib" + funcName + "_control.so " + preCompileO +
124 " -Wl,--whole-archive " + GetCurrentSharedLibPath() + "/libpypto_ctrl_server.a" +142 " -Wl,--whole-archive " + GetCurrentSharedLibPath() + "/libpypto_ctrl_server.a" +
125 " -Wl,--no-whole-archive";143 " -Wl,--no-whole-archive";
126- auto ret = std::system(cmdGccCompile.c_str());144+ int ret = Checkinject(cmdGccCompile.c_str(), cmdGccCompile.size());
145+ if (ret != 0) {
146+ MACHINE_LOGE(DevCommonErr::SYSTEM_CALL_FAILED, "RunDeviceMachine compile cmd illegal char.\n");
147+ return false;
148+ }
149+ ret = std::system(cmdGccCompile.c_str());
127 if (ret != 0) {150 if (ret != 0) {
128 MACHINE_LOGE(DevCommonErr::SYSTEM_CALL_FAILED, "RUNDeviceMachine compile fail\n");151 MACHINE_LOGE(DevCommonErr::SYSTEM_CALL_FAILED, "RUNDeviceMachine compile fail\n");
129 return false;152 return false;
130 }153 }
131- MACHINE_LOGI("CmdGcc: %s\n", cmdGccCompile.c_str());
132 std::string srcSoPath = aicpuDirPath + "/lib" + funcName + "_control.so";154 std::string srcSoPath = aicpuDirPath + "/lib" + funcName + "_control.so";
133 std::string constrolSoName = "lib" + funcName + "_control";155 std::string constrolSoName = "lib" + funcName + "_control";
134 GenCustomOpInfo(funcName, aicpuDirPath, constrolSoName);156 GenCustomOpInfo(funcName, aicpuDirPath, constrolSoName);
@@ -22,6 +22,7 @@
22#include "interface/configs/config_manager.h"22#include "interface/configs/config_manager.h"
23#include "machine/device/dynamic/device_utils.h"23#include "machine/device/dynamic/device_utils.h"
24#include "machine/device/distributed/common.h"24#include "machine/device/distributed/common.h"
25+#include "machine/utils/checkinject.h"
25 26 
26namespace npu::tile_fwk::dynamic {27namespace npu::tile_fwk::dynamic {
27constexpr int DUMP_LEVEL_FOUR = 4;28constexpr int DUMP_LEVEL_FOUR = 4;
@@ -102,6 +103,11 @@ void DumpAicoreTaskExectInfo(DeviceArgs& args, const std::vector<void*>& perfDat
102 std::string command = "python3 " + draw_swim_lane_py_path + " \"" + jsonFilePath + "\" \"" + topo_txt_path +103 std::string command = "python3 " + draw_swim_lane_py_path + " \"" + jsonFilePath + "\" \"" + topo_txt_path +
103 "\" \"" + program_json_path +104 "\" \"" + program_json_path +
104 "\" --label_type=1 --time_convert_denominator=" + std::to_string(freq);105 "\" --label_type=1 --time_convert_denominator=" + std::to_string(freq);
106+ int ret = Checkinject(command.c_str(), command.size());
107+ if (ret != 0) {
108+ MACHINE_LOGE(DevCommonErr::SYSTEM_CALL_FAILED, "Draw swimlane cmd illegal char.");
109+ return;
110+ }
105 if (system(command.c_str()) != 0) {111 if (system(command.c_str()) != 0) {
106 MACHINE_LOGW("Failed to execute draw_swim_lane.py. Stop merging the swimlane.");112 MACHINE_LOGW("Failed to execute draw_swim_lane.py. Stop merging the swimlane.");
107 }113 }
@@ -280,12 +286,22 @@ void DumpAicpuPerfInfo(DeviceArgs& args, const std::vector<void*>& perfData, uin
280 npu::tile_fwk::config::LogTopFolder() + "/machine_runtime_operator_trace_" +286 npu::tile_fwk::config::LogTopFolder() + "/machine_runtime_operator_trace_" +
281 std::to_string(g_last_round_num) + ".json " + npu::tile_fwk::config::LogTopFolder() +287 std::to_string(g_last_round_num) + ".json " + npu::tile_fwk::config::LogTopFolder() +
282 "/merged_swimlane.json";288 "/merged_swimlane.json";
289+ int ret = Checkinject(cmd.c_str(), cmd.size());
290+ if (ret != 0) {
291+ MACHINE_LOGE(DevCommonErr::SYSTEM_CALL_FAILED, "Draw swimlane cmd illegal char.");
292+ return;
293+ }
283 if (system(cmd.c_str()) != 0) {294 if (system(cmd.c_str()) != 0) {
284 MACHINE_LOGW("Failed to execute machine_perf_trace.py, cannot get aicpu perfetto.json.");295 MACHINE_LOGW("Failed to execute machine_perf_trace.py, cannot get aicpu perfetto.json.");
285 }296 }
286 g_last_round_num = sumRoundNum;297 g_last_round_num = sumRoundNum;
287 // Auto run analyze command once DUMP_DEVICE_PERF is enabled in runtime.298 // Auto run analyze command once DUMP_DEVICE_PERF is enabled in runtime.
288 std::string analysisCmd = "python3 " + scriptPath + " analyze " + aicpuPerfilePath;299 std::string analysisCmd = "python3 " + scriptPath + " analyze " + aicpuPerfilePath;
300+ ret = Checkinject(analysisCmd.c_str(), analysisCmd.size());
301+ if (ret != 0) {
302+ MACHINE_LOGE(DevCommonErr::SYSTEM_CALL_FAILED, "Draw swimlane cmd illegal char.");
303+ return;
304+ }
289 if (system(analysisCmd.c_str()) != 0) {305 if (system(analysisCmd.c_str()) != 0) {
290 MACHINE_LOGW("Failed to execute machine_perf_trace.py analyze.");306 MACHINE_LOGW("Failed to execute machine_perf_trace.py analyze.");
291 }307 }
@@ -0,0 +1,38 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+/*!
12+ * \file checkinject.h
13+ * \brief
14+ */
15+#ifndef MACHINE_UTILS_CHECKINJECT_H
16+#define MACHINE_UTILS_CHECKINJECT_H
17+ 
18+#include <cstddef>
19+ 
20+namespace npu::tile_fwk {
21+inline int Checkinject(const char cmdStr[], size_t strLen)
22+{
23+ if (cmdStr == nullptr || strLen == 0) {
24+ return -1;
25+ }
26+ const char cmdIllegalChar[] = {';', '|', '<', '>', '`'};
27+ for (size_t i = 0; i < strLen; i++) {
28+ for (const auto& c : cmdIllegalChar) {
29+ if (cmdStr[i] == c) {
30+ return -1;
31+ }
32+ }
33+ }
34+ return 0;
35+}
36+} // namespace npu::tile_fwk
37+ 
38+#endif
@@ -26,10 +26,12 @@
26#include "interface/program/program.h"26#include "interface/program/program.h"
27#include "interface/configs/config_manager.h"27#include "interface/configs/config_manager.h"
28#include "tilefwk/pypto_fwk_log.h"28#include "tilefwk/pypto_fwk_log.h"
29+#include "machine/utils/machine_error.h"
29 30 
30#include <algorithm>31#include <algorithm>
31#include <cstddef>32#include <cstddef>
32#include <cstdint>33#include <cstdint>
34+#include <stdexcept>
33#include <unordered_map>35#include <unordered_map>
34#include <utility>36#include <utility>
35#include <queue>37#include <queue>
@@ -2218,7 +2220,13 @@ static int ParseUnrollTimes(const std::string& rawName)
2218 }2220 }
2219 std::string suffix = rawName.substr(unrollPos + unrollMask.length());2221 std::string suffix = rawName.substr(unrollPos + unrollMask.length());
2220 if (std::isdigit(suffix.front())) {2222 if (std::isdigit(suffix.front())) {
2221- unrollTimes *= std::stoi(suffix);2223+ try {
2224+ unrollTimes *= std::stoi(suffix);
2225+ } catch (const std::invalid_argument&) {
2226+ MACHINE_LOGE(DevCommonErr::PARAM_INVALID, "Invalid unroll times: %s", suffix.c_str());
2227+ } catch (const std::out_of_range&) {
2228+ MACHINE_LOGE(DevCommonErr::PARAM_INVALID, "Unroll times: %s exceeds int range", suffix.c_str());
2229+ }
2222 }2230 }
2223 }2231 }
2224 return unrollTimes;2232 return unrollTimes;
@@ -169,6 +169,19 @@ static std::string ValidateFunctionAndIO(
169 return "";169 return "";
170}170}
171 171 
172+static ExportedOperator* GetValidatedOperator(uintptr_t opAddr)
173+{
174+ if (opAddr == 0) {
175+ return nullptr;
176+ }
177+ 
178+ if (opAddr % alignof(ExportedOperator) != 0) {
179+ MACHINE_LOGE(DevCommonErr::PARAM_INVALID, "Invalid operator address alignment");
180+ return nullptr;
181+ }
182+ return reinterpret_cast<ExportedOperator*>(opAddr);
183+}
184+ 
172static void InitializeInputOutputData(185static void InitializeInputOutputData(
173 const std::vector<DeviceTensorData>& inputs, const std::vector<DeviceTensorData>& outputs)186 const std::vector<DeviceTensorData>& inputs, const std::vector<DeviceTensorData>& outputs)
174{187{
@@ -245,8 +258,10 @@ std::string OperatorDeviceRunOnceDataFromDevice(
245 if (opAddr == 0) {258 if (opAddr == 0) {
246 return "invalid operator";259 return "invalid operator";
247 }260 }
248- 261+ ExportedOperator* op = GetValidatedOperator(opAddr);
249- ExportedOperator* op = reinterpret_cast<ExportedOperator*>(opAddr);262+ if (op == nullptr) {
263+ return "invalid operator";
264+ }
250 Function* func = op->GetFunction();265 Function* func = op->GetFunction();
251 auto errorMsg = ValidateFunctionAndIO(func, inputs, outputs);266 auto errorMsg = ValidateFunctionAndIO(func, inputs, outputs);
252 if (!errorMsg.empty()) {267 if (!errorMsg.empty()) {
@@ -285,7 +300,7 @@ std::string OperatorDeviceRunOnceDataFromDevice(
285uint64_t GetWorkSpaceSize(300uint64_t GetWorkSpaceSize(
286 uintptr_t opAddr, const std::vector<DeviceTensorData>& inputs, const std::vector<DeviceTensorData>& outputs)301 uintptr_t opAddr, const std::vector<DeviceTensorData>& inputs, const std::vector<DeviceTensorData>& outputs)
287{302{
288- ExportedOperator* op = reinterpret_cast<ExportedOperator*>(opAddr);303+ ExportedOperator* op = GetValidatedOperator(opAddr);
289 if (op) {304 if (op) {
290 return op->GetWorkSpaceSize(inputs, outputs);305 return op->GetWorkSpaceSize(inputs, outputs);
291 }306 }
@@ -321,7 +336,10 @@ uintptr_t OperatorBegin()
321 336 
322std::string OperatorEnd(uintptr_t opAddr)337std::string OperatorEnd(uintptr_t opAddr)
323{338{
324- ExportedOperator* op = reinterpret_cast<ExportedOperator*>(opAddr);339+ ExportedOperator* op = GetValidatedOperator(opAddr);
340+ if (op == nullptr) {
341+ return "invalid operator";
342+ }
325 ExportedOperatorEnd(op);343 ExportedOperatorEnd(op);
326 return "";344 return "";
327}345}
@@ -330,7 +348,10 @@ int64_t BuildCache(
330 uintptr_t opAddr, const std::vector<DeviceTensorData>& inputList, const std::vector<DeviceTensorData>& outputList,348 uintptr_t opAddr, const std::vector<DeviceTensorData>& inputList, const std::vector<DeviceTensorData>& outputList,
331 [[maybe_unused]] bool isCapturing)349 [[maybe_unused]] bool isCapturing)
332{350{
333- ExportedOperator* op = reinterpret_cast<ExportedOperator*>(opAddr);351+ ExportedOperator* op = GetValidatedOperator(opAddr);
352+ if (op == nullptr) {
353+ return -1;
354+ }
334 if (config::GetRuntimeOption<int64_t>(STITCH_CFGCACHE_SIZE) != 0) {355 if (config::GetRuntimeOption<int64_t>(STITCH_CFGCACHE_SIZE) != 0) {
335 DeviceLauncherConfig config;356 DeviceLauncherConfig config;
336 DeviceLauncher::DeviceLauncherConfigFillDeviceInfo(config);357 DeviceLauncher::DeviceLauncherConfigFillDeviceInfo(config);
@@ -14,6 +14,7 @@ This is a subscript of build_ci.py
14import os14import os
15from pathlib import Path15from pathlib import Path
16import subprocess16import subprocess
17+import shutil
17 18 
18 19 
19def ini(path, prof, pe):20def ini(path, prof, pe):
@@ -72,23 +73,44 @@ def find_file_and_get_parent_dirs(target_file, search_dir='.'):
72 return parent_dirs73 return parent_dirs
73 74 
74 75 
76+def remove_prof_dirs(base_path):
77+ base = Path(base_path).resolve()
78+ for prof_dir in base.glob("PROF*"):
79+ if prof_dir.is_dir():
80+ shutil.rmtree(prof_dir)
81+ 
82+ 
75def work_flow_plot(path, level, pe):83def work_flow_plot(path, level, pe):
76- path_pro = find_file_and_get_parent_dirs("aicpu.data.*", path)84+ base_path = Path(path).resolve()
77- cmd_rm = f'rm -rf {str(path)}/PROF*'85+ path_pro = find_file_and_get_parent_dirs("aicpu.data.*", base_path)
78 if len(path_pro) < 1:86 if len(path_pro) < 1:
79- subprocess.run(cmd_rm, shell=True, capture_output=False, check=True, text=True, encoding='utf-8')87+ remove_prof_dirs(base_path)
80- assert False, f'{str(path)} No Profiling, Do not to plot'88+ assert False, f'{str(base_path)} No Profiling, Do not to plot'
81- save_path = Path(path, "Profiling/work_flow")89+ save_path = base_path / "Profiling/work_flow"
82 if not save_path.exists():90 if not save_path.exists():
83 os.makedirs(save_path)91 os.makedirs(save_path)
84 print(save_path)92 print(save_path)
85- cmd = f"python3 ./tools/profiling/tilefwk_prof_data_parser.py -p {path_pro[0]} --output={str(save_path)} -t"93+ cmd = [
86- print(cmd)94+ "python3",
87- subprocess.run(cmd, shell=True, capture_output=False, check=True, text=True, encoding='utf-8')95+ "./tools/profiling/tilefwk_prof_data_parser.py",
96+ "-p",
97+ str(path_pro[0]),
98+ f"--output={str(save_path)}",
99+ "-t",
100+ ]
101+ print(" ".join(cmd))
102+ subprocess.run(cmd, shell=False, capture_output=False, check=True, text=True, encoding='utf-8')
88 if level == 2:103 if level == 2:
89- cmd = f"python3 ./tools/profiling/tilefwk_pmu_to_csv.py -p {path_pro[0]} --output={str(save_path)} -pe={pe}"104+ cmd = [
90- print(cmd)105+ "python3",
91- subprocess.run(cmd, shell=True, capture_output=False, check=True, text=True, encoding='utf-8')106+ "./tools/profiling/tilefwk_pmu_to_csv.py",
107+ "-p",
108+ str(path_pro[0]),
109+ f"--output={str(save_path)}",
110+ f"-pe={pe}",
111+ ]
112+ print(" ".join(cmd))
113+ subprocess.run(cmd, shell=False, capture_output=False, check=True, text=True, encoding='utf-8')
92 #删除Prof落盘日志,避免有干扰114 #删除Prof落盘日志,避免有干扰
93- print(cmd_rm)115+ print(f"cleanup PROF* under {str(base_path)}")
94- subprocess.run(cmd_rm, shell=True, capture_output=False, check=True, text=True, encoding='utf-8')116+ remove_prof_dirs(base_path)