You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
4 years ago
4 years ago
5 years ago
4 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. /**
  2. * Copyright 2020 Huawei Technologies Co., Ltd
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "framework/common/util.h"
  17. #include <sys/stat.h>
  18. #ifdef __GNUC__
  19. #include <regex.h>
  20. #else
  21. #include <regex>
  22. #endif
  23. #include <algorithm>
  24. #include <climits>
  25. #include <cstdlib>
  26. #include <ctime>
  27. #include <fstream>
  28. #include "common/util/error_manager/error_manager.h"
  29. #include "external/ge/ge_api_error_codes.h"
  30. #include "framework/common/debug/ge_log.h"
  31. #include "framework/common/fmk_types.h"
  32. #include "framework/common/ge_inner_error_codes.h"
  33. #include "google/protobuf/io/coded_stream.h"
  34. #include "google/protobuf/io/zero_copy_stream_impl.h"
  35. #include "mmpa/mmpa_api.h"
  36. using google::protobuf::io::CodedInputStream;
  37. using google::protobuf::io::FileInputStream;
  38. using google::protobuf::io::ZeroCopyInputStream;
  39. namespace {
  40. /*
  41. * kProtoReadBytesLimit and kWarningThreshold are real arguments of CodedInputStream::SetTotalBytesLimit.
  42. * In order to prevent integer overflow and excessive memory allocation during protobuf processing,
  43. * it is necessary to limit the length of proto message (call SetTotalBytesLimit function).
  44. * In theory, the minimum message length that causes an integer overflow is 512MB, and the default is 64MB.
  45. * If the limit of warning_threshold is exceeded, the exception information will be printed in stderr.
  46. * If such an exception is encountered during operation,
  47. * the proto file can be divided into several small files or the limit value can be increased.
  48. */
  49. const int kFileSizeOutLimitedOrOpenFailed = -1;
  50. const int kProtoReadBytesLimit = INT_MAX; // Max size of 2 GB minus 1 byte.
  51. const int kWarningThreshold = 1073741824; // 536870912 * 2 536870912 represent 512M
  52. /// The maximum length of the file.
  53. const uint32_t kMaxFileSizeLimit = UINT32_MAX; // 4G for now
  54. const int kMaxBuffSize = 256;
  55. const char *const kPathValidReason = "The path can only contain 'a-z' 'A-Z' '0-9' '-' '.' '_' and chinese character";
  56. constexpr uint32_t kMaxConfigFileByte = 10485760; // 10 * 1024 * 1024
  57. } // namespace
  58. namespace ge {
  59. static bool ReadProtoFromCodedInputStream(CodedInputStream &coded_stream, Message *proto) {
  60. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(proto == nullptr, return false, "incorrect parameter. nullptr == proto");
  61. coded_stream.SetTotalBytesLimit(kProtoReadBytesLimit, kWarningThreshold);
  62. return proto->ParseFromCodedStream(&coded_stream);
  63. }
  64. bool ReadProtoFromArray(const void *data, int size, Message *proto) {
  65. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG((proto == nullptr || data == nullptr || size == 0), return false,
  66. "incorrect parameter. proto is nullptr || data is nullptr || size is 0");
  67. google::protobuf::io::CodedInputStream coded_stream(reinterpret_cast<uint8_t *>(const_cast<void *>(data)), size);
  68. return ReadProtoFromCodedInputStream(coded_stream, proto);
  69. }
  70. // Get file length
  71. long GetFileLength(const std::string &input_file) {
  72. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(input_file.empty(), return -1, "input_file path is null.");
  73. std::string real_path = RealPath(input_file.c_str());
  74. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(real_path.empty(), return -1, "input_file path '%s' not valid", input_file.c_str());
  75. unsigned long long file_length = 0;
  76. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(
  77. mmGetFileSize(input_file.c_str(), &file_length) != EN_OK,
  78. ErrorManager::GetInstance().ATCReportErrMessage("E19001", {"file", "errmsg"}, {input_file, strerror(errno)});
  79. return kFileSizeOutLimitedOrOpenFailed, "Open file[%s] failed. errmsg:%s", input_file.c_str(), strerror(errno));
  80. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG((file_length == 0),
  81. REPORT_INNER_ERROR("E19999", "file:%s size is 0, not valid", input_file.c_str());
  82. return -1, "File[%s] size is 0, not valid.", input_file.c_str());
  83. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(
  84. file_length > kMaxFileSizeLimit,
  85. REPORT_INNER_ERROR("E19999", "file:%s size:%lld is out of limit: %d.", input_file.c_str(), file_length,
  86. kMaxFileSizeLimit);
  87. return kFileSizeOutLimitedOrOpenFailed, "File[%s] size %lld is out of limit: %d.", input_file.c_str(), file_length,
  88. kMaxFileSizeLimit);
  89. return static_cast<long>(file_length);
  90. }
  91. /** @ingroup domi_common
  92. * @brief Read all data from binary file
  93. * @param [in] file_name File path
  94. * @param [out] buffer The address of the output memory, which needs to be released by the caller
  95. * @param [out] length Output memory size
  96. * @return false fail
  97. * @return true success
  98. */
  99. bool ReadBytesFromBinaryFile(const char *file_name, char **buffer, int &length) {
  100. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG((file_name == nullptr), return false, "incorrect parameter. file is nullptr");
  101. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG((buffer == nullptr), return false, "incorrect parameter. buffer is nullptr");
  102. std::string real_path = RealPath(file_name);
  103. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(real_path.empty(), return false, "file path '%s' not valid", file_name);
  104. std::ifstream file(real_path.c_str(), std::ios::binary | std::ios::ate);
  105. if (!file.is_open()) {
  106. GELOGE(ge::FAILED, "[Read][File]Failed, file %s", file_name);
  107. REPORT_CALL_ERROR("E19999", "Read file %s failed", file_name);
  108. return false;
  109. }
  110. length = static_cast<int>(file.tellg());
  111. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG((length <= 0), file.close(); return false, "file length <= 0");
  112. file.seekg(0, std::ios::beg);
  113. *buffer = new (std::nothrow) char[length]();
  114. GE_CHK_BOOL_TRUE_EXEC_RET_STATUS(*buffer == nullptr, false, file.close(), "new an object failed.");
  115. file.read(*buffer, length);
  116. file.close();
  117. return true;
  118. }
  119. bool ReadBytesFromBinaryFile(const char *file_name, std::vector<char> &buffer) {
  120. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG((file_name == nullptr), return false, "incorrect parameter. file path is null");
  121. std::string real_path = RealPath(file_name);
  122. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(real_path.empty(), return false, "file path '%s' not valid", file_name);
  123. std::ifstream file(real_path.c_str(), std::ios::binary | std::ios::ate);
  124. if (!file.is_open()) {
  125. GELOGE(ge::FAILED, "[Read][File]Failed, file %s", file_name);
  126. REPORT_CALL_ERROR("E19999", "Read file %s failed", file_name);
  127. return false;
  128. }
  129. std::streamsize size = file.tellg();
  130. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG((size <= 0), file.close(); return false, "file length <= 0, not valid.");
  131. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(size > static_cast<int64_t>(kMaxFileSizeLimit), file.close();
  132. return false, "file size %ld is out of limit: %d.", size, kMaxFileSizeLimit);
  133. file.seekg(0, std::ios::beg); // [no need to check value]
  134. buffer.resize(static_cast<uint64_t>(size)); // [no need to check value]
  135. file.read(&buffer[0], size); // [no need to check value]
  136. file.close();
  137. GELOGI("Read size:%ld", size);
  138. return true;
  139. }
  140. /**
  141. * @ingroup domi_common
  142. * @brief Create directory, support to create multi-level directory
  143. * @param [in] directory_path Path, can be multi-level directory
  144. * @return -1 fail
  145. * @return 0 success
  146. */
  147. int CreateDirectory(const std::string &directory_path) {
  148. GE_CHK_BOOL_EXEC(!directory_path.empty(), return -1, "directory path is empty.");
  149. auto dir_path_len = directory_path.length();
  150. if (dir_path_len >= MMPA_MAX_PATH) {
  151. ErrorManager::GetInstance().ATCReportErrMessage("E19002", {"filepath", "size"},
  152. {directory_path, std::to_string(MMPA_MAX_PATH)});
  153. GELOGW("Path[%s] len is too long, it must be less than %d", directory_path.c_str(), MMPA_MAX_PATH);
  154. return -1;
  155. }
  156. char tmp_dir_path[MMPA_MAX_PATH] = {0};
  157. for (size_t i = 0; i < dir_path_len; i++) {
  158. tmp_dir_path[i] = directory_path[i];
  159. if ((tmp_dir_path[i] == '\\') || (tmp_dir_path[i] == '/')) {
  160. if (mmAccess2(tmp_dir_path, M_F_OK) != EN_OK) {
  161. int32_t ret = mmMkdir(tmp_dir_path, M_IRUSR | M_IWUSR | M_IXUSR); // 700
  162. if (ret != 0) {
  163. if (errno != EEXIST) {
  164. REPORT_CALL_ERROR("E19999",
  165. "Can not create directory %s. Make sure the directory exists and writable. errmsg:%s",
  166. directory_path.c_str(), strerror(errno));
  167. GELOGW("Can not create directory %s. Make sure the directory exists and writable. errmsg:%s",
  168. directory_path.c_str(), strerror(errno));
  169. return ret;
  170. }
  171. }
  172. }
  173. }
  174. }
  175. int32_t ret = mmMkdir(const_cast<char *>(directory_path.c_str()), M_IRUSR | M_IWUSR | M_IXUSR); // 700
  176. if (ret != 0) {
  177. if (errno != EEXIST) {
  178. REPORT_CALL_ERROR("E19999",
  179. "Can not create directory %s. Make sure the directory exists and writable. errmsg:%s",
  180. directory_path.c_str(), strerror(errno));
  181. GELOGW("Can not create directory %s. Make sure the directory exists and writable. errmsg:%s",
  182. directory_path.c_str(), strerror(errno));
  183. return ret;
  184. }
  185. }
  186. return 0;
  187. }
  188. std::string CurrentTimeInStr() {
  189. std::time_t now = std::time(nullptr);
  190. std::tm *ptm = std::localtime(&now);
  191. if (ptm == nullptr) {
  192. GELOGE(ge::FAILED, "[Check][Param]Localtime incorrect, errmsg %s", strerror(errno));
  193. REPORT_CALL_ERROR("E19999", "Localtime incorrect, errmsg %s", strerror(errno));
  194. return "";
  195. }
  196. const int kTimeBufferLen = 32;
  197. char buffer[kTimeBufferLen + 1] = {0};
  198. // format: 20171122042550
  199. std::strftime(buffer, kTimeBufferLen, "%Y%m%d%H%M%S", ptm);
  200. return std::string(buffer);
  201. }
  202. bool ReadProtoFromText(const char *file, google::protobuf::Message *message) {
  203. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG((file == nullptr || message == nullptr), return false,
  204. "incorrect parameter. nullptr == file || nullptr == message");
  205. std::string real_path = RealPath(file);
  206. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(real_path.empty(), ErrorManager::GetInstance().ATCReportErrMessage(
  207. "E19000", {"path", "errmsg"}, {file, strerror(errno)});
  208. return false, "Path[%s]'s realpath is empty, errmsg[%s]", file, strerror(errno));
  209. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(GetFileLength(real_path) == -1, return false, "file size not valid.");
  210. std::ifstream fs(real_path.c_str(), std::ifstream::in);
  211. if (!fs.is_open()) {
  212. REPORT_INNER_ERROR("E19999", "open file:%s failed", real_path.c_str());
  213. GELOGE(ge::FAILED, "[Open][ProtoFile]Failed, real path %s, orginal file path %s",
  214. real_path.c_str(), file);
  215. return false;
  216. }
  217. google::protobuf::io::IstreamInputStream input(&fs);
  218. bool ret = google::protobuf::TextFormat::Parse(&input, message);
  219. GE_IF_BOOL_EXEC(!ret, ErrorManager::GetInstance().ATCReportErrMessage("E19018", {"protofile"}, {file});
  220. GELOGE(ret, "[Parse][File]Through [google::protobuf::TextFormat::Parse] failed, "
  221. "file %s", file));
  222. fs.close();
  223. return ret;
  224. }
  225. bool ReadProtoFromMem(const char *data, int size, google::protobuf::Message *message) {
  226. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG((data == nullptr || message == nullptr), return false,
  227. "incorrect parameter. data is nullptr || message is nullptr");
  228. std::string str(data, static_cast<size_t>(size));
  229. std::istringstream fs(str);
  230. google::protobuf::io::IstreamInputStream input(&fs);
  231. bool ret = google::protobuf::TextFormat::Parse(&input, message);
  232. GE_IF_BOOL_EXEC(
  233. !ret, GELOGE(ret, "Call [google::protobuf::TextFormat::Parse] func ret fail, please check your text file."));
  234. return ret;
  235. }
  236. uint64_t GetCurrentTimestamp() {
  237. mmTimeval tv{};
  238. int ret = mmGetTimeOfDay(&tv, nullptr);
  239. GE_LOGE_IF(ret != EN_OK, "Func gettimeofday may failed, ret:%d, errmsg:%s", ret, strerror(errno));
  240. auto total_use_time = tv.tv_usec + tv.tv_sec * 1000000; // 1000000: seconds to microseconds
  241. return static_cast<uint64_t>(total_use_time);
  242. }
  243. uint32_t GetCurrentSecondTimestap() {
  244. mmTimeval tv{};
  245. int ret = mmGetTimeOfDay(&tv, nullptr);
  246. GE_LOGE_IF(ret != EN_OK, "Func gettimeofday may failed, ret:%d, errmsg:%s", ret, strerror(errno));
  247. auto total_use_time = tv.tv_sec; // seconds
  248. return static_cast<uint32_t>(total_use_time);
  249. }
  250. bool CheckInt64MulOverflow(int64_t a, int64_t b) {
  251. if (a > 0) {
  252. if (b > 0) {
  253. if (a > (INT64_MAX / b)) {
  254. return false;
  255. }
  256. } else {
  257. if (b < (INT64_MIN / a)) {
  258. return false;
  259. }
  260. }
  261. } else {
  262. if (b > 0) {
  263. if (a < (INT64_MIN / b)) {
  264. return false;
  265. }
  266. } else {
  267. if ((a != 0) && (b < (INT64_MAX / a))) {
  268. return false;
  269. }
  270. }
  271. }
  272. return true;
  273. }
  274. std::string RealPath(const char *path) {
  275. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(path == nullptr, return "", "path pointer is NULL.");
  276. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(strlen(path) >= MMPA_MAX_PATH,
  277. ErrorManager::GetInstance().ATCReportErrMessage("E19002", {"filepath", "size"},
  278. {path, std::to_string(MMPA_MAX_PATH)});
  279. return "", "Path[%s] len is too long, it must be less than %d", path, MMPA_MAX_PATH);
  280. // Nullptr is returned when the path does not exist or there is no permission
  281. // Return absolute path when path is accessible
  282. std::string res;
  283. char resolved_path[MMPA_MAX_PATH] = {0};
  284. if (mmRealPath(path, resolved_path, MMPA_MAX_PATH) == EN_OK) {
  285. res = resolved_path;
  286. }
  287. return res;
  288. }
  289. void PathValidErrReport(const std::string &file_path, const std::string &atc_param, const std::string &reason) {
  290. if (!atc_param.empty()) {
  291. REPORT_INPUT_ERROR("E10001", std::vector<std::string>({"parameter", "value", "reason"}),
  292. std::vector<std::string>({atc_param, file_path, reason}));
  293. } else {
  294. REPORT_INNER_ERROR("E19999", "Path[%s] invalid, reason:%s", file_path.c_str(), reason.c_str());
  295. }
  296. }
  297. bool CheckInputPathValid(const std::string &file_path, const std::string &atc_param) {
  298. // The specified path is empty
  299. std::map<std::string, std::string> args_map;
  300. if (file_path.empty()) {
  301. if (!atc_param.empty()) {
  302. REPORT_INPUT_ERROR("E10004", std::vector<std::string>({"parameter"}), std::vector<std::string>({atc_param}));
  303. } else {
  304. REPORT_INNER_ERROR("E19999", "Param file_path is empty, check invalid.");
  305. }
  306. GELOGW("Input parameter %s is empty.", file_path.c_str());
  307. return false;
  308. }
  309. std::string real_path = RealPath(file_path.c_str());
  310. // Unable to get absolute path (does not exist or does not have permission to access)
  311. if (real_path.empty()) {
  312. std::string reason = "realpath error, errmsg:" + std::string(strerror(errno));
  313. PathValidErrReport(file_path, atc_param, reason);
  314. GELOGW("Path[%s]'s realpath is empty, errmsg[%s]", file_path.c_str(), strerror(errno));
  315. return false;
  316. }
  317. // A regular matching expression to verify the validity of the input file path
  318. // Path section: Support upper and lower case letters, numbers dots(.) chinese and underscores
  319. // File name section: Support upper and lower case letters, numbers, underscores chinese and dots(.)
  320. #ifdef __GNUC__
  321. std::string mode = "^[\u4e00-\u9fa5A-Za-z0-9./_-]+$";
  322. #else
  323. std::string mode = "^[a-zA-Z]:([\\\\/][^\\s\\\\/:*?<>\"|][^\\\\/:*?<>\"|]*)*([/\\\\][^\\s\\\\/:*?<>\"|])?$";
  324. #endif
  325. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(
  326. !ValidateStr(real_path, mode),
  327. PathValidErrReport(file_path, atc_param, kPathValidReason);
  328. return false, "Invalid value for %s[%s], %s.", atc_param.c_str(), real_path.c_str(), kPathValidReason);
  329. // The absolute path points to a file that is not readable
  330. if (mmAccess2(real_path.c_str(), M_R_OK) != EN_OK) {
  331. PathValidErrReport(file_path, atc_param, "cat not access, errmsg:" + std::string(strerror(errno)));
  332. GELOGW("Read file[%s] failed, errmsg[%s]", file_path.c_str(), strerror(errno));
  333. return false;
  334. }
  335. return true;
  336. }
  337. bool CheckOutputPathValid(const std::string &file_path, const std::string &atc_param) {
  338. // The specified path is empty
  339. if (file_path.empty()) {
  340. if (!atc_param.empty()) {
  341. REPORT_INPUT_ERROR("E10004", std::vector<std::string>({"parameter"}), std::vector<std::string>({atc_param}));
  342. } else {
  343. REPORT_INNER_ERROR("E19999", "Param file_path is empty, check invalid.");
  344. }
  345. ErrorManager::GetInstance().ATCReportErrMessage("E10004", {"parameter"}, {atc_param});
  346. GELOGW("Input parameter's value is empty.");
  347. return false;
  348. }
  349. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(strlen(file_path.c_str()) >= MMPA_MAX_PATH,
  350. std::string reason = "len is too long, it must be less than " +
  351. std::to_string(MMPA_MAX_PATH);
  352. PathValidErrReport(file_path, atc_param, reason);
  353. return false, "Path[%s] len is too long, it must be less than %d", file_path.c_str(),
  354. MMPA_MAX_PATH);
  355. // A regular matching expression to verify the validity of the input file path
  356. // Path section: Support upper and lower case letters, numbers dots(.) chinese and underscores
  357. // File name section: Support upper and lower case letters, numbers, underscores chinese and dots(.)
  358. #ifdef __GNUC__
  359. std::string mode = "^[\u4e00-\u9fa5A-Za-z0-9./_-]+$";
  360. #else
  361. std::string mode = "^[a-zA-Z]:([\\\\/][^\\s\\\\/:*?<>\"|][^\\\\/:*?<>\"|]*)*([/\\\\][^\\s\\\\/:*?<>\"|])?$";
  362. #endif
  363. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(
  364. !ValidateStr(file_path, mode),
  365. PathValidErrReport(file_path, atc_param, kPathValidReason);
  366. return false, "Invalid value for %s[%s], %s.", atc_param.c_str(), file_path.c_str(), kPathValidReason);
  367. std::string real_path = RealPath(file_path.c_str());
  368. // Can get absolute path (file exists)
  369. if (!real_path.empty()) {
  370. // File is not readable or writable
  371. if (mmAccess2(real_path.c_str(), M_W_OK | M_F_OK) != EN_OK) {
  372. PathValidErrReport(file_path, atc_param, "cat not access, errmsg:" + std::string(strerror(errno)));
  373. GELOGW("Write file[%s] failed, errmsg[%s]", real_path.c_str(), strerror(errno));
  374. return false;
  375. }
  376. } else {
  377. // Find the last separator
  378. int path_split_pos = static_cast<int>(file_path.size() - 1);
  379. for (; path_split_pos >= 0; path_split_pos--) {
  380. if (file_path[path_split_pos] == '\\' || file_path[path_split_pos] == '/') {
  381. break;
  382. }
  383. }
  384. if (path_split_pos == 0) {
  385. return true;
  386. }
  387. if (path_split_pos != -1) {
  388. std::string prefix_path = std::string(file_path).substr(0, static_cast<size_t>(path_split_pos));
  389. // Determine whether the specified path is valid by creating the path
  390. if (CreateDirectory(prefix_path) != 0) {
  391. PathValidErrReport(file_path, atc_param, "Can not create directory");
  392. GELOGW("Can not create directory[%s].", file_path.c_str());
  393. return false;
  394. }
  395. }
  396. }
  397. return true;
  398. }
  399. FMK_FUNC_HOST_VISIBILITY bool ValidateStr(const std::string &str, const std::string &mode) {
  400. #ifdef __GNUC__
  401. char ebuff[kMaxBuffSize];
  402. regex_t reg;
  403. int cflags = REG_EXTENDED | REG_NOSUB;
  404. int ret = regcomp(&reg, mode.c_str(), cflags);
  405. if (ret) {
  406. regerror(ret, &reg, ebuff, kMaxBuffSize);
  407. GELOGW("regcomp failed, reason: %s", ebuff);
  408. regfree(&reg);
  409. return true;
  410. }
  411. ret = regexec(&reg, str.c_str(), 0, NULL, 0);
  412. if (ret) {
  413. regerror(ret, &reg, ebuff, kMaxBuffSize);
  414. GELOGE(ge::PARAM_INVALID, "[Rgexec][Param]Failed, reason %s", ebuff);
  415. REPORT_CALL_ERROR("E19999", "Rgexec failed, reason %s", ebuff);
  416. regfree(&reg);
  417. return false;
  418. }
  419. regfree(&reg);
  420. return true;
  421. #else
  422. std::wstring wstr(str.begin(), str.end());
  423. std::wstring wmode(mode.begin(), mode.end());
  424. std::wsmatch match;
  425. bool res = false;
  426. try {
  427. std::wregex reg(wmode, std::regex::icase);
  428. // Matching string part
  429. res = regex_match(wstr, match, reg);
  430. res = regex_search(str, std::regex("[`!@#$%^&*()|{}';',<>?]"));
  431. } catch (std::exception &ex) {
  432. GELOGW("The directory %s is invalid, error: %s.", str.c_str(), ex.what());
  433. return false;
  434. }
  435. return !(res) && (str.size() == match.str().size());
  436. #endif
  437. }
  438. FMK_FUNC_HOST_VISIBILITY bool IsValidFile(const char *file_path) {
  439. if (file_path == nullptr) {
  440. GELOGE(PARAM_INVALID, "[Check][Param]Config path is null");
  441. REPORT_INNER_ERROR("E19999", "Config path is null");
  442. return false;
  443. }
  444. if (!CheckInputPathValid(file_path)) {
  445. GELOGE(PARAM_INVALID, "[Check][Param]Config path %s is invalid", file_path);
  446. REPORT_CALL_ERROR("E19999", "Config path %s is invalid", file_path);
  447. return false;
  448. }
  449. // Normalize the path
  450. std::string resolved_file_path = RealPath(file_path);
  451. if (resolved_file_path.empty()) {
  452. GELOGE(PARAM_INVALID, "[Check][Param]Invalid input file path %s, errmsg %s", file_path, strerror(errno));
  453. REPORT_CALL_ERROR("E19999", "Invalid input file path %s, errmsg %s", file_path, strerror(errno));
  454. return false;
  455. }
  456. mmStat_t stat = {0};
  457. int32_t ret = mmStatGet(resolved_file_path.c_str(), &stat);
  458. if (ret != EN_OK) {
  459. GELOGE(PARAM_INVALID, "[Get][FileStatus]Failed, which path %s maybe not exist, "
  460. "return %d, errcode %d", resolved_file_path.c_str(), ret, mmGetErrorCode());
  461. REPORT_CALL_ERROR("E19999", "Get config file status failed, which path %s maybe not exist, "
  462. "return %d, errcode %d", resolved_file_path.c_str(), ret, mmGetErrorCode());
  463. return false;
  464. }
  465. if ((stat.st_mode & S_IFMT) != S_IFREG) {
  466. GELOGE(PARAM_INVALID, "[Check][Param]Config file is not a common file, which path is %s, "
  467. "mode is %u", resolved_file_path.c_str(), stat.st_mode);
  468. REPORT_CALL_ERROR("E19999", "Config file is not a common file, which path is %s, "
  469. "mode is %u", resolved_file_path.c_str(), stat.st_mode);
  470. return false;
  471. }
  472. if (stat.st_size > kMaxConfigFileByte) {
  473. GELOGE(PARAM_INVALID, "[Check][Param]Config file %s size %ld is larger than max config "
  474. "file Bytes %u", resolved_file_path.c_str(), stat.st_size, kMaxConfigFileByte);
  475. REPORT_CALL_ERROR("E19999", "Config file %s size %ld is larger than max config file Bytes %u",
  476. resolved_file_path.c_str(), stat.st_size, kMaxConfigFileByte);
  477. return false;
  478. }
  479. return true;
  480. }
  481. Status CheckPath(const char *path, size_t length) {
  482. if (path == nullptr) {
  483. GELOGE(PARAM_INVALID, "[Check][Param]Config path is invalid");
  484. REPORT_CALL_ERROR("E19999", "Config path is invalid");
  485. return PARAM_INVALID;
  486. }
  487. if (strlen(path) != length) {
  488. GELOGE(PARAM_INVALID, "[Check][Param]Path %s is invalid or length %zu "
  489. "not equal to given length %zu", path, strlen(path), length);
  490. REPORT_CALL_ERROR("E19999", "Path %s is invalid or length %zu "
  491. "not equal to given length %zu", path, strlen(path), length);
  492. return PARAM_INVALID;
  493. }
  494. if (length == 0 || length > MMPA_MAX_PATH) {
  495. GELOGE(PARAM_INVALID, "[Check][Param]Length of config path %zu is invalid", length);
  496. REPORT_INNER_ERROR("E19999", "Length of config path %zu is invalid", length);
  497. return PARAM_INVALID;
  498. }
  499. INT32 is_dir = mmIsDir(path);
  500. if (is_dir != EN_OK) {
  501. GELOGE(PATH_INVALID, "[Open][Directory]Failed, directory path %s, errmsg %s",
  502. path, strerror(errno));
  503. REPORT_CALL_ERROR("E19999", "Open directory %s failed, errmsg %s", path, strerror(errno));
  504. return PATH_INVALID;
  505. }
  506. if (mmAccess2(path, M_R_OK) != EN_OK) {
  507. GELOGE(PATH_INVALID, "[Read][Path]Failed, path %s, errmsg %s", path, strerror(errno));
  508. REPORT_CALL_ERROR("E19999", "Read path %s failed, errmsg %s", path, strerror(errno));
  509. return PATH_INVALID;
  510. }
  511. return SUCCESS;
  512. }
  513. } // namespace ge

图引擎模块(GE)是MindSpore的一个子模块,其代码由C++实现,位于前端模块ME和底层硬件之间,起到承接作用。图引擎模块以ME下发的图作为输入,然后进行一系列的深度图优化操作,最后输出一张可以在底层硬件上高效运行的图。GE针对昇腾AI处理器的硬件结构特点,做了特定的优化工作,以此来充分发挥出昇腾AI处理器的强大算力。在进行模型训练/推理时,GE会被自动调用而用户并不感知。GE主要由GE API和GE Core两部分组成,详细的架构图如下所示