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.

util.cc 24 kB

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
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
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  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. FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY bool ReadProtoFromBinaryFile(const char *file, Message *proto) {
  65. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG((file == nullptr || proto == nullptr), return false,
  66. "Input parameter file or proto is nullptr!");
  67. std::string real_path = RealPath(file);
  68. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(real_path.empty(), return false, "pb file path '%s' not valid", file);
  69. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(GetFileLength(real_path) == kFileSizeOutLimitedOrOpenFailed, return false,
  70. "file size not valid.");
  71. std::ifstream fs(real_path, std::ifstream::in | std::ifstream::binary);
  72. if (!fs.is_open()) {
  73. ErrorManager::GetInstance().ATCReportErrMessage("E19001", {"file", "errmsg"}, {file, "ifstream is_open failed"});
  74. GELOGE(ge::FAILED, "Open real path[%s] failed.", file);
  75. return false;
  76. }
  77. google::protobuf::io::IstreamInputStream istream(&fs);
  78. google::protobuf::io::CodedInputStream coded_stream(&istream);
  79. bool ret = ReadProtoFromCodedInputStream(coded_stream, proto);
  80. fs.close();
  81. if (!ret) {
  82. ErrorManager::GetInstance().ATCReportErrMessage("E19005", {"file"}, {file});
  83. GELOGE(ge::FAILED, "Parse file[%s] failed.", file);
  84. return ret;
  85. }
  86. return ret;
  87. }
  88. FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY bool ReadProtoFromArray(const void *data, int size, Message *proto) {
  89. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG((proto == nullptr || data == nullptr || size == 0), return false,
  90. "incorrect parameter. proto is nullptr || data is nullptr || size is 0");
  91. google::protobuf::io::CodedInputStream coded_stream(reinterpret_cast<uint8_t *>(const_cast<void *>(data)), size);
  92. return ReadProtoFromCodedInputStream(coded_stream, proto);
  93. }
  94. // Get file length
  95. long GetFileLength(const std::string &input_file) {
  96. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(input_file.empty(), return -1, "input_file path is null.");
  97. std::string real_path = RealPath(input_file.c_str());
  98. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(real_path.empty(), return -1, "input_file path '%s' not valid", input_file.c_str());
  99. unsigned long long file_length = 0;
  100. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(
  101. mmGetFileSize(input_file.c_str(), &file_length) != EN_OK,
  102. ErrorManager::GetInstance().ATCReportErrMessage("E19001", {"file", "errmsg"}, {input_file, strerror(errno)});
  103. return kFileSizeOutLimitedOrOpenFailed, "Open file[%s] failed. errmsg:%s", input_file.c_str(), strerror(errno));
  104. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG((file_length == 0),
  105. ErrorManager::GetInstance().ATCReportErrMessage("E19015", {"filepath"}, {input_file});
  106. return -1, "File[%s] size is 0, not valid.", input_file.c_str());
  107. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(
  108. file_length > kMaxFileSizeLimit, ErrorManager::GetInstance().ATCReportErrMessage(
  109. "E19016", {"filepath", "filesize", "maxlen"},
  110. {input_file, std::to_string(file_length), std::to_string(kMaxFileSizeLimit)});
  111. return kFileSizeOutLimitedOrOpenFailed, "File[%s] size %lld is out of limit: %d.", input_file.c_str(), file_length,
  112. kMaxFileSizeLimit);
  113. return static_cast<long>(file_length);
  114. }
  115. /** @ingroup domi_common
  116. * @brief Read all data from binary file
  117. * @param [in] file_name File path
  118. * @param [out] buffer The address of the output memory, which needs to be released by the caller
  119. * @param [out] length Output memory size
  120. * @return false fail
  121. * @return true success
  122. */
  123. FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY bool ReadBytesFromBinaryFile(const char *file_name, char **buffer,
  124. int &length) {
  125. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG((file_name == nullptr), return false, "incorrect parameter. file is nullptr");
  126. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG((buffer == nullptr), return false, "incorrect parameter. buffer is nullptr");
  127. std::string real_path = RealPath(file_name);
  128. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(real_path.empty(), return false, "file path '%s' not valid", file_name);
  129. std::ifstream file(real_path.c_str(), std::ios::binary | std::ios::ate);
  130. if (!file.is_open()) {
  131. GELOGE(ge::FAILED, "Read file %s failed.", file_name);
  132. return false;
  133. }
  134. length = static_cast<int>(file.tellg());
  135. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG((length <= 0), file.close(); return false, "file length <= 0");
  136. file.seekg(0, std::ios::beg);
  137. *buffer = new (std::nothrow) char[length]();
  138. GE_CHK_BOOL_TRUE_EXEC_RET_STATUS(*buffer == nullptr, false, file.close(), "new an object failed.");
  139. file.read(*buffer, length);
  140. file.close();
  141. return true;
  142. }
  143. FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY bool ReadBytesFromBinaryFile(const char *file_name,
  144. std::vector<char> &buffer) {
  145. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG((file_name == nullptr), return false, "incorrect parameter. file path is null");
  146. std::string real_path = RealPath(file_name);
  147. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(real_path.empty(), return false, "file path '%s' not valid", file_name);
  148. std::ifstream file(real_path.c_str(), std::ios::binary | std::ios::ate);
  149. if (!file.is_open()) {
  150. GELOGE(ge::FAILED, "Read file %s failed.", file_name);
  151. return false;
  152. }
  153. std::streamsize size = file.tellg();
  154. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG((size <= 0), file.close(); return false, "file length <= 0, not valid.");
  155. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(size > static_cast<int64_t>(kMaxFileSizeLimit), file.close();
  156. return false, "file size %ld is out of limit: %d.", size, kMaxFileSizeLimit);
  157. file.seekg(0, std::ios::beg); // [no need to check value]
  158. buffer.resize(static_cast<uint64_t>(size)); // [no need to check value]
  159. file.read(&buffer[0], size); // [no need to check value]
  160. file.close();
  161. GELOGI("Read size:%ld", size);
  162. return true;
  163. }
  164. /**
  165. * @ingroup domi_common
  166. * @brief Create directory, support to create multi-level directory
  167. * @param [in] directory_path Path, can be multi-level directory
  168. * @return -1 fail
  169. * @return 0 success
  170. */
  171. FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY int CreateDirectory(const std::string &directory_path) {
  172. GE_CHK_BOOL_EXEC(!directory_path.empty(), return -1, "directory path is empty.");
  173. auto dir_path_len = directory_path.length();
  174. if (dir_path_len >= MMPA_MAX_PATH) {
  175. ErrorManager::GetInstance().ATCReportErrMessage("E19002", {"filepath", "size"},
  176. {directory_path, std::to_string(MMPA_MAX_PATH)});
  177. GELOGW("Path[%s] len is too long, it must be less than %d", directory_path.c_str(), MMPA_MAX_PATH);
  178. return -1;
  179. }
  180. char tmp_dir_path[MMPA_MAX_PATH] = {0};
  181. for (size_t i = 0; i < dir_path_len; i++) {
  182. tmp_dir_path[i] = directory_path[i];
  183. if ((tmp_dir_path[i] == '\\') || (tmp_dir_path[i] == '/')) {
  184. if (mmAccess2(tmp_dir_path, M_F_OK) != EN_OK) {
  185. int32_t ret = mmMkdir(tmp_dir_path, M_IRUSR | M_IWUSR | M_IXUSR); // 700
  186. if (ret != 0) {
  187. if (errno != EEXIST) {
  188. ErrorManager::GetInstance().ATCReportErrMessage("E19006", {"path"}, {directory_path});
  189. GELOGW("Can not create directory %s. Make sure the directory exists and writable. errmsg:%s",
  190. directory_path.c_str(), strerror(errno));
  191. return ret;
  192. }
  193. }
  194. }
  195. }
  196. }
  197. int32_t ret = mmMkdir(const_cast<char *>(directory_path.c_str()), M_IRUSR | M_IWUSR | M_IXUSR); // 700
  198. if (ret != 0) {
  199. if (errno != EEXIST) {
  200. ErrorManager::GetInstance().ATCReportErrMessage("E19006", {"path"}, {directory_path});
  201. GELOGW("Can not create directory %s. Make sure the directory exists and writable. errmsg:%s",
  202. directory_path.c_str(), strerror(errno));
  203. return ret;
  204. }
  205. }
  206. return 0;
  207. }
  208. FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY std::string CurrentTimeInStr() {
  209. std::time_t now = std::time(nullptr);
  210. std::tm *ptm = std::localtime(&now);
  211. if (ptm == nullptr) {
  212. GELOGE(ge::FAILED, "Localtime failed.");
  213. return "";
  214. }
  215. const int kTimeBufferLen = 32;
  216. char buffer[kTimeBufferLen + 1] = {0};
  217. // format: 20171122042550
  218. std::strftime(buffer, kTimeBufferLen, "%Y%m%d%H%M%S", ptm);
  219. return std::string(buffer);
  220. }
  221. FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY bool ReadProtoFromText(const char *file,
  222. google::protobuf::Message *message) {
  223. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG((file == nullptr || message == nullptr), return false,
  224. "incorrect parameter. nullptr == file || nullptr == message");
  225. std::string real_path = RealPath(file);
  226. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(real_path.empty(), ErrorManager::GetInstance().ATCReportErrMessage(
  227. "E19000", {"path", "errmsg"}, {file, strerror(errno)});
  228. return false, "Path[%s]'s realpath is empty, errmsg[%s]", file, strerror(errno));
  229. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(GetFileLength(real_path) == -1, return false, "file size not valid.");
  230. std::ifstream fs(real_path.c_str(), std::ifstream::in);
  231. if (!fs.is_open()) {
  232. ErrorManager::GetInstance().ATCReportErrMessage("E19017", {"realpth", "protofile"}, {real_path, file});
  233. GELOGE(ge::FAILED, "Fail to open proto file real path is '%s' when orginal file path is '%s'.", real_path.c_str(),
  234. file);
  235. return false;
  236. }
  237. google::protobuf::io::IstreamInputStream input(&fs);
  238. bool ret = google::protobuf::TextFormat::Parse(&input, message);
  239. GE_IF_BOOL_EXEC(!ret, ErrorManager::GetInstance().ATCReportErrMessage("E19018", {"protofile"}, {file});
  240. GELOGE(ret,
  241. "Parse file[%s] through [google::protobuf::TextFormat::Parse] failed, "
  242. "please check whether the file is a valid protobuf format file.",
  243. file));
  244. fs.close();
  245. return ret;
  246. }
  247. FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY bool ReadProtoFromMem(const char *data, int size,
  248. google::protobuf::Message *message) {
  249. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG((data == nullptr || message == nullptr), return false,
  250. "incorrect parameter. data is nullptr || message is nullptr");
  251. std::string str(data, static_cast<size_t>(size));
  252. std::istringstream fs(str);
  253. google::protobuf::io::IstreamInputStream input(&fs);
  254. bool ret = google::protobuf::TextFormat::Parse(&input, message);
  255. GE_IF_BOOL_EXEC(
  256. !ret, GELOGE(ret, "Call [google::protobuf::TextFormat::Parse] func ret fail, please check your text file."));
  257. return ret;
  258. }
  259. FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY uint64_t GetCurrentTimestamp() {
  260. mmTimeval tv{};
  261. int ret = mmGetTimeOfDay(&tv, nullptr);
  262. GE_LOGE_IF(ret != EN_OK, "Func gettimeofday may failed, ret:%d, errmsg:%s", ret, strerror(errno));
  263. auto total_use_time = tv.tv_usec + tv.tv_sec * 1000000; // 1000000: seconds to microseconds
  264. return static_cast<uint64_t>(total_use_time);
  265. }
  266. FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY uint32_t GetCurrentSecondTimestap() {
  267. mmTimeval tv{};
  268. int ret = mmGetTimeOfDay(&tv, nullptr);
  269. GE_LOGE_IF(ret != EN_OK, "Func gettimeofday may failed, ret:%d, errmsg:%s", ret, strerror(errno));
  270. auto total_use_time = tv.tv_sec; // seconds
  271. return static_cast<uint32_t>(total_use_time);
  272. }
  273. FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY bool CheckInt64MulOverflow(int64_t a, int64_t b) {
  274. if (a > 0) {
  275. if (b > 0) {
  276. if (a > (INT64_MAX / b)) {
  277. return false;
  278. }
  279. } else {
  280. if (b < (INT64_MIN / a)) {
  281. return false;
  282. }
  283. }
  284. } else {
  285. if (b > 0) {
  286. if (a < (INT64_MIN / b)) {
  287. return false;
  288. }
  289. } else {
  290. if ((a != 0) && (b < (INT64_MAX / a))) {
  291. return false;
  292. }
  293. }
  294. }
  295. return true;
  296. }
  297. FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY std::string RealPath(const char *path) {
  298. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(path == nullptr, return "", "path pointer is NULL.");
  299. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(strlen(path) >= MMPA_MAX_PATH,
  300. ErrorManager::GetInstance().ATCReportErrMessage("E19002", {"filepath", "size"},
  301. {path, std::to_string(MMPA_MAX_PATH)});
  302. return "", "Path[%s] len is too long, it must be less than %d", path, MMPA_MAX_PATH);
  303. // Nullptr is returned when the path does not exist or there is no permission
  304. // Return absolute path when path is accessible
  305. std::string res;
  306. char resolved_path[MMPA_MAX_PATH] = {0};
  307. if (mmRealPath(path, resolved_path, MMPA_MAX_PATH) == EN_OK) {
  308. res = resolved_path;
  309. }
  310. return res;
  311. }
  312. FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY bool CheckInputPathValid(const std::string &file_path,
  313. const std::string &atc_param) {
  314. // The specified path is empty
  315. std::map<std::string, std::string> args_map;
  316. if (file_path.empty()) {
  317. ErrorManager::GetInstance().ATCReportErrMessage("E10004", {"parameter"}, {atc_param});
  318. GELOGW("Input parameter %s is empty.", file_path.c_str());
  319. return false;
  320. }
  321. std::string real_path = RealPath(file_path.c_str());
  322. // Unable to get absolute path (does not exist or does not have permission to access)
  323. if (real_path.empty()) {
  324. ErrorManager::GetInstance().ATCReportErrMessage("E19000", {"path", "errmsg"}, {file_path, strerror(errno)});
  325. GELOGW("Path[%s]'s realpath is empty, errmsg[%s]", file_path.c_str(), strerror(errno));
  326. return false;
  327. }
  328. // A regular matching expression to verify the validity of the input file path
  329. // Path section: Support upper and lower case letters, numbers dots(.) chinese and underscores
  330. // File name section: Support upper and lower case letters, numbers, underscores chinese and dots(.)
  331. #ifdef __GNUC__
  332. std::string mode = "^[\u4e00-\u9fa5A-Za-z0-9./_-]+$";
  333. #else
  334. std::string mode = "^[a-zA-Z]:([\\\\/][^\\s\\\\/:*?<>\"|][^\\\\/:*?<>\"|]*)*([/\\\\][^\\s\\\\/:*?<>\"|])?$";
  335. #endif
  336. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(
  337. !ValidateStr(real_path, mode),
  338. ErrorManager::GetInstance().ATCReportErrMessage("E10001", {"parameter", "value", "reason"},
  339. {atc_param, real_path, kPathValidReason});
  340. return false, "Invalid value for %s[%s], %s.", atc_param.c_str(), real_path.c_str(), kPathValidReason);
  341. // The absolute path points to a file that is not readable
  342. if (mmAccess2(real_path.c_str(), M_R_OK) != EN_OK) {
  343. ErrorManager::GetInstance().ATCReportErrMessage("E19003", {"file", "errmsg"}, {file_path.c_str(), strerror(errno)});
  344. GELOGW("Read file[%s] failed, errmsg[%s]", file_path.c_str(), strerror(errno));
  345. return false;
  346. }
  347. return true;
  348. }
  349. FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY bool CheckOutputPathValid(const std::string &file_path,
  350. const std::string &atc_param) {
  351. // The specified path is empty
  352. if (file_path.empty()) {
  353. ErrorManager::GetInstance().ATCReportErrMessage("E10004", {"parameter"}, {atc_param});
  354. GELOGW("Input parameter's value is empty.");
  355. return false;
  356. }
  357. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(strlen(file_path.c_str()) >= MMPA_MAX_PATH,
  358. ErrorManager::GetInstance().ATCReportErrMessage(
  359. "E19002", {"filepath", "size"}, {file_path, std::to_string(MMPA_MAX_PATH)});
  360. return "", "Path[%s] len is too long, it must be less than %d", file_path.c_str(),
  361. MMPA_MAX_PATH);
  362. // A regular matching expression to verify the validity of the input file path
  363. // Path section: Support upper and lower case letters, numbers dots(.) chinese and underscores
  364. // File name section: Support upper and lower case letters, numbers, underscores chinese and dots(.)
  365. #ifdef __GNUC__
  366. std::string mode = "^[\u4e00-\u9fa5A-Za-z0-9./_-]+$";
  367. #else
  368. std::string mode = "^[a-zA-Z]:([\\\\/][^\\s\\\\/:*?<>\"|][^\\\\/:*?<>\"|]*)*([/\\\\][^\\s\\\\/:*?<>\"|])?$";
  369. #endif
  370. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(
  371. !ValidateStr(file_path, mode),
  372. ErrorManager::GetInstance().ATCReportErrMessage("E10001", {"parameter", "value", "reason"},
  373. {atc_param, file_path, kPathValidReason});
  374. return false, "Invalid value for %s[%s], %s.", atc_param.c_str(), file_path.c_str(), kPathValidReason);
  375. std::string real_path = RealPath(file_path.c_str());
  376. // Can get absolute path (file exists)
  377. if (!real_path.empty()) {
  378. // File is not readable or writable
  379. if (mmAccess2(real_path.c_str(), M_W_OK | M_F_OK) != EN_OK) {
  380. ErrorManager::GetInstance().ATCReportErrMessage("E19004", {"file", "errmsg"}, {real_path, strerror(errno)});
  381. GELOGW("Write file[%s] failed, errmsg[%s]", real_path.c_str(), strerror(errno));
  382. return false;
  383. }
  384. } else {
  385. // Find the last separator
  386. int path_split_pos = static_cast<int>(file_path.size() - 1);
  387. for (; path_split_pos >= 0; path_split_pos--) {
  388. if (file_path[path_split_pos] == '\\' || file_path[path_split_pos] == '/') {
  389. break;
  390. }
  391. }
  392. if (path_split_pos == 0) {
  393. return true;
  394. }
  395. if (path_split_pos != -1) {
  396. std::string prefix_path = std::string(file_path).substr(0, static_cast<size_t>(path_split_pos));
  397. // Determine whether the specified path is valid by creating the path
  398. if (CreateDirectory(prefix_path) != 0) {
  399. ErrorManager::GetInstance().ATCReportErrMessage("E19006", {"path"}, {file_path});
  400. GELOGW("Can not create directory[%s].", file_path.c_str());
  401. return false;
  402. }
  403. }
  404. }
  405. return true;
  406. }
  407. FMK_FUNC_HOST_VISIBILITY bool ValidateStr(const std::string &str, const std::string &mode) {
  408. #ifdef __GNUC__
  409. char ebuff[kMaxBuffSize];
  410. regex_t reg;
  411. int cflags = REG_EXTENDED | REG_NOSUB;
  412. int ret = regcomp(&reg, mode.c_str(), cflags);
  413. if (ret) {
  414. regerror(ret, &reg, ebuff, kMaxBuffSize);
  415. GELOGW("regcomp failed, reason: %s", ebuff);
  416. regfree(&reg);
  417. return true;
  418. }
  419. ret = regexec(&reg, str.c_str(), 0, NULL, 0);
  420. if (ret) {
  421. regerror(ret, &reg, ebuff, kMaxBuffSize);
  422. GELOGE(ge::PARAM_INVALID, "regexec failed, reason: %s", ebuff);
  423. regfree(&reg);
  424. return false;
  425. }
  426. regfree(&reg);
  427. return true;
  428. #else
  429. std::wstring wstr(str.begin(), str.end());
  430. std::wstring wmode(mode.begin(), mode.end());
  431. std::wsmatch match;
  432. bool res = false;
  433. try {
  434. std::wregex reg(wmode, std::regex::icase);
  435. // Matching string part
  436. res = regex_match(wstr, match, reg);
  437. res = regex_search(str, std::regex("[`!@#$%^&*()|{}';',<>?]"));
  438. } catch (std::exception &ex) {
  439. GELOGW("The directory %s is invalid, error: %s.", str.c_str(), ex.what());
  440. return false;
  441. }
  442. return !(res) && (str.size() == match.str().size());
  443. #endif
  444. }
  445. FMK_FUNC_HOST_VISIBILITY bool IsValidFile(const char *file_path) {
  446. if (file_path == nullptr) {
  447. GELOGE(PARAM_INVALID, "Config path is null.");
  448. return false;
  449. }
  450. if (!CheckInputPathValid(file_path)) {
  451. GELOGE(PARAM_INVALID, "Config path is invalid: %s", file_path);
  452. return false;
  453. }
  454. // Normalize the path
  455. std::string resolved_file_path = RealPath(file_path);
  456. if (resolved_file_path.empty()) {
  457. GELOGE(PARAM_INVALID, "Invalid input file path [%s], make sure that the file path is correct.", file_path);
  458. return false;
  459. }
  460. mmStat_t stat = {0};
  461. int32_t ret = mmStatGet(resolved_file_path.c_str(), &stat);
  462. if (ret != EN_OK) {
  463. GELOGE(PARAM_INVALID, "cannot get config file status, which path is %s, maybe not exist, return %d, errcode %d",
  464. resolved_file_path.c_str(), ret, mmGetErrorCode());
  465. return false;
  466. }
  467. if ((stat.st_mode & S_IFMT) != S_IFREG) {
  468. GELOGE(PARAM_INVALID, "config file is not a common file, which path is %s, mode is %u", resolved_file_path.c_str(),
  469. stat.st_mode);
  470. return false;
  471. }
  472. if (stat.st_size > kMaxConfigFileByte) {
  473. GELOGE(PARAM_INVALID, "config file %s size[%ld] is larger than max config file Bytes[%u]",
  474. resolved_file_path.c_str(), stat.st_size, kMaxConfigFileByte);
  475. return false;
  476. }
  477. return true;
  478. }
  479. FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY Status CheckPath(const char *path, size_t length) {
  480. if (path == nullptr) {
  481. GELOGE(PARAM_INVALID, "Config path is invalid.");
  482. return PARAM_INVALID;
  483. }
  484. if (strlen(path) != length) {
  485. GELOGE(PARAM_INVALID, "Path is invalid or length of config path is not equal to given length.");
  486. return PARAM_INVALID;
  487. }
  488. if (length == 0 || length > MMPA_MAX_PATH) {
  489. GELOGE(PARAM_INVALID, "Length of config path is invalid.");
  490. return PARAM_INVALID;
  491. }
  492. INT32 is_dir = mmIsDir(path);
  493. if (is_dir != EN_OK) {
  494. GELOGE(PATH_INVALID, "Open directory %s failed, maybe it is not exit or not a dir. errmsg:%s",
  495. path, strerror(errno));
  496. return PATH_INVALID;
  497. }
  498. if (mmAccess2(path, M_R_OK) != EN_OK) {
  499. GELOGE(PATH_INVALID, "Read path[%s] failed, errmsg[%s]", path, strerror(errno));
  500. return PATH_INVALID;
  501. }
  502. return SUCCESS;
  503. }
  504. } // namespace ge

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