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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  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. %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.", directory_path.c_str());
  190. return ret;
  191. }
  192. }
  193. }
  194. }
  195. }
  196. int32_t ret = mmMkdir(const_cast<char *>(directory_path.c_str()), M_IRUSR | M_IWUSR | M_IXUSR); // 700
  197. if (ret != 0) {
  198. if (errno != EEXIST) {
  199. ErrorManager::GetInstance().ATCReportErrMessage("E19006", {"path"}, {directory_path});
  200. GELOGW("Can not create directory %s. Make sure the directory exists and writable.", directory_path.c_str());
  201. return ret;
  202. }
  203. }
  204. return 0;
  205. }
  206. FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY std::string CurrentTimeInStr() {
  207. std::time_t now = std::time(nullptr);
  208. std::tm *ptm = std::localtime(&now);
  209. if (ptm == nullptr) {
  210. GELOGE(ge::FAILED, "Localtime failed.");
  211. return "";
  212. }
  213. const int kTimeBufferLen = 32;
  214. char buffer[kTimeBufferLen + 1] = {0};
  215. // format: 20171122042550
  216. std::strftime(buffer, kTimeBufferLen, "%Y%m%d%H%M%S", ptm);
  217. return std::string(buffer);
  218. }
  219. FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY bool ReadProtoFromText(const char *file,
  220. google::protobuf::Message *message) {
  221. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG((file == nullptr || message == nullptr), return false,
  222. "incorrect parameter. nullptr == file || nullptr == message");
  223. std::string real_path = RealPath(file);
  224. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(real_path.empty(), ErrorManager::GetInstance().ATCReportErrMessage(
  225. "E19000", {"path", "errmsg"}, {file, strerror(errno)});
  226. return false, "Path[%s]'s realpath is empty, errmsg[%s]", file, strerror(errno));
  227. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(GetFileLength(real_path) == -1, return false, "file size not valid.");
  228. std::ifstream fs(real_path.c_str(), std::ifstream::in);
  229. if (!fs.is_open()) {
  230. ErrorManager::GetInstance().ATCReportErrMessage("E19017", {"realpth", "protofile"}, {real_path, file});
  231. GELOGE(ge::FAILED, "Fail to open proto file real path is '%s' when orginal file path is '%s'.", real_path.c_str(),
  232. file);
  233. return false;
  234. }
  235. google::protobuf::io::IstreamInputStream input(&fs);
  236. bool ret = google::protobuf::TextFormat::Parse(&input, message);
  237. GE_IF_BOOL_EXEC(!ret, ErrorManager::GetInstance().ATCReportErrMessage("E19018", {"protofile"}, {file});
  238. GELOGE(ret,
  239. "Parse file[%s] through [google::protobuf::TextFormat::Parse] failed, "
  240. "please check whether the file is a valid protobuf format file.",
  241. file));
  242. fs.close();
  243. return ret;
  244. }
  245. FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY bool ReadProtoFromMem(const char *data, int size,
  246. google::protobuf::Message *message) {
  247. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG((data == nullptr || message == nullptr), return false,
  248. "incorrect parameter. data is nullptr || message is nullptr");
  249. std::string str(data, static_cast<size_t>(size));
  250. std::istringstream fs(str);
  251. google::protobuf::io::IstreamInputStream input(&fs);
  252. bool ret = google::protobuf::TextFormat::Parse(&input, message);
  253. GE_IF_BOOL_EXEC(
  254. !ret, GELOGE(ret, "Call [google::protobuf::TextFormat::Parse] func ret fail, please check your text file."));
  255. return ret;
  256. }
  257. FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY uint64_t GetCurrentTimestamp() {
  258. mmTimeval tv{};
  259. int ret = mmGetTimeOfDay(&tv, nullptr);
  260. GE_LOGE_IF(ret != EN_OK, "Func gettimeofday may failed: ret=%d", ret);
  261. auto total_use_time = tv.tv_usec + tv.tv_sec * 1000000; // 1000000: seconds to microseconds
  262. return static_cast<uint64_t>(total_use_time);
  263. }
  264. FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY uint32_t GetCurrentSecondTimestap() {
  265. mmTimeval tv{};
  266. int ret = mmGetTimeOfDay(&tv, nullptr);
  267. GE_LOGE_IF(ret != EN_OK, "Func gettimeofday may failed: ret=%d", ret);
  268. auto total_use_time = tv.tv_sec; // seconds
  269. return static_cast<uint32_t>(total_use_time);
  270. }
  271. FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY bool CheckInt64MulOverflow(int64_t a, int64_t b) {
  272. if (a > 0) {
  273. if (b > 0) {
  274. if (a > (INT64_MAX / b)) {
  275. return false;
  276. }
  277. } else {
  278. if (b < (INT64_MIN / a)) {
  279. return false;
  280. }
  281. }
  282. } else {
  283. if (b > 0) {
  284. if (a < (INT64_MIN / b)) {
  285. return false;
  286. }
  287. } else {
  288. if ((a != 0) && (b < (INT64_MAX / a))) {
  289. return false;
  290. }
  291. }
  292. }
  293. return true;
  294. }
  295. FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY std::string RealPath(const char *path) {
  296. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(path == nullptr, return "", "path pointer is NULL.");
  297. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(strlen(path) >= MMPA_MAX_PATH,
  298. ErrorManager::GetInstance().ATCReportErrMessage("E19002", {"filepath", "size"},
  299. {path, std::to_string(MMPA_MAX_PATH)});
  300. return "", "Path[%s] len is too long, it must be less than %d", path, MMPA_MAX_PATH);
  301. // Nullptr is returned when the path does not exist or there is no permission
  302. // Return absolute path when path is accessible
  303. std::string res;
  304. char resolved_path[MMPA_MAX_PATH] = {0};
  305. if (mmRealPath(path, resolved_path, MMPA_MAX_PATH) == EN_OK) {
  306. res = resolved_path;
  307. }
  308. return res;
  309. }
  310. FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY bool CheckInputPathValid(const std::string &file_path,
  311. const std::string &atc_param) {
  312. // The specified path is empty
  313. std::map<std::string, std::string> args_map;
  314. if (file_path.empty()) {
  315. ErrorManager::GetInstance().ATCReportErrMessage("E10004", {"parameter"}, {atc_param});
  316. GELOGW("Input parameter %s is empty.", file_path.c_str());
  317. return false;
  318. }
  319. std::string real_path = RealPath(file_path.c_str());
  320. // Unable to get absolute path (does not exist or does not have permission to access)
  321. if (real_path.empty()) {
  322. ErrorManager::GetInstance().ATCReportErrMessage("E19000", {"path", "errmsg"}, {file_path, strerror(errno)});
  323. GELOGW("Path[%s]'s realpath is empty, errmsg[%s]", file_path.c_str(), strerror(errno));
  324. return false;
  325. }
  326. // A regular matching expression to verify the validity of the input file path
  327. // Path section: Support upper and lower case letters, numbers dots(.) chinese and underscores
  328. // File name section: Support upper and lower case letters, numbers, underscores chinese and dots(.)
  329. #ifdef __GNUC__
  330. std::string mode = "^[\u4e00-\u9fa5A-Za-z0-9./_-]+$";
  331. #else
  332. std::string mode = "^[a-zA-Z]:([\\\\/][^\\s\\\\/:*?<>\"|][^\\\\/:*?<>\"|]*)*([/\\\\][^\\s\\\\/:*?<>\"|])?$";
  333. #endif
  334. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(
  335. !ValidateStr(real_path, mode),
  336. ErrorManager::GetInstance().ATCReportErrMessage("E10001", {"parameter", "value", "reason"},
  337. {atc_param, real_path, kPathValidReason});
  338. return false, "Invalid value for %s[%s], %s.", atc_param.c_str(), real_path.c_str(), kPathValidReason);
  339. // The absolute path points to a file that is not readable
  340. if (mmAccess2(real_path.c_str(), M_R_OK) != EN_OK) {
  341. ErrorManager::GetInstance().ATCReportErrMessage("E19003", {"file", "errmsg"}, {file_path.c_str(), strerror(errno)});
  342. GELOGW("Read file[%s] failed, errmsg[%s]", file_path.c_str(), strerror(errno));
  343. return false;
  344. }
  345. return true;
  346. }
  347. FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY bool CheckOutputPathValid(const std::string &file_path,
  348. const std::string &atc_param) {
  349. // The specified path is empty
  350. if (file_path.empty()) {
  351. ErrorManager::GetInstance().ATCReportErrMessage("E10004", {"parameter"}, {atc_param});
  352. GELOGW("Input parameter's value is empty.");
  353. return false;
  354. }
  355. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(strlen(file_path.c_str()) >= MMPA_MAX_PATH,
  356. ErrorManager::GetInstance().ATCReportErrMessage(
  357. "E19002", {"filepath", "size"}, {file_path, std::to_string(MMPA_MAX_PATH)});
  358. return "", "Path[%s] len is too long, it must be less than %d", file_path.c_str(),
  359. MMPA_MAX_PATH);
  360. // A regular matching expression to verify the validity of the input file path
  361. // Path section: Support upper and lower case letters, numbers dots(.) chinese and underscores
  362. // File name section: Support upper and lower case letters, numbers, underscores chinese and dots(.)
  363. #ifdef __GNUC__
  364. std::string mode = "^[\u4e00-\u9fa5A-Za-z0-9./_-]+$";
  365. #else
  366. std::string mode = "^[a-zA-Z]:([\\\\/][^\\s\\\\/:*?<>\"|][^\\\\/:*?<>\"|]*)*([/\\\\][^\\s\\\\/:*?<>\"|])?$";
  367. #endif
  368. GE_CHK_BOOL_TRUE_EXEC_WITH_LOG(
  369. !ValidateStr(file_path, mode),
  370. ErrorManager::GetInstance().ATCReportErrMessage("E10001", {"parameter", "value", "reason"},
  371. {atc_param, file_path, kPathValidReason});
  372. return false, "Invalid value for %s[%s], %s.", atc_param.c_str(), file_path.c_str(), kPathValidReason);
  373. std::string real_path = RealPath(file_path.c_str());
  374. // Can get absolute path (file exists)
  375. if (!real_path.empty()) {
  376. // File is not readable or writable
  377. if (mmAccess2(real_path.c_str(), M_W_OK | M_F_OK) != EN_OK) {
  378. ErrorManager::GetInstance().ATCReportErrMessage("E19004", {"file", "errmsg"}, {real_path, strerror(errno)});
  379. GELOGW("Write file[%s] failed, errmsg[%s]", real_path.c_str(), strerror(errno));
  380. return false;
  381. }
  382. } else {
  383. // Find the last separator
  384. int path_split_pos = static_cast<int>(file_path.size() - 1);
  385. for (; path_split_pos >= 0; path_split_pos--) {
  386. if (file_path[path_split_pos] == '\\' || file_path[path_split_pos] == '/') {
  387. break;
  388. }
  389. }
  390. if (path_split_pos == 0) {
  391. return true;
  392. }
  393. if (path_split_pos != -1) {
  394. std::string prefix_path = std::string(file_path).substr(0, static_cast<size_t>(path_split_pos));
  395. // Determine whether the specified path is valid by creating the path
  396. if (CreateDirectory(prefix_path) != 0) {
  397. ErrorManager::GetInstance().ATCReportErrMessage("E19006", {"path"}, {file_path});
  398. GELOGW("Can not create directory[%s].", file_path.c_str());
  399. return false;
  400. }
  401. }
  402. }
  403. return true;
  404. }
  405. FMK_FUNC_HOST_VISIBILITY bool ValidateStr(const std::string &str, const std::string &mode) {
  406. #ifdef __GNUC__
  407. char ebuff[kMaxBuffSize];
  408. regex_t reg;
  409. int cflags = REG_EXTENDED | REG_NOSUB;
  410. int ret = regcomp(&reg, mode.c_str(), cflags);
  411. if (ret) {
  412. regerror(ret, &reg, ebuff, kMaxBuffSize);
  413. GELOGW("regcomp failed, reason: %s", ebuff);
  414. regfree(&reg);
  415. return true;
  416. }
  417. ret = regexec(&reg, str.c_str(), 0, NULL, 0);
  418. if (ret) {
  419. regerror(ret, &reg, ebuff, kMaxBuffSize);
  420. GELOGE(ge::PARAM_INVALID, "regexec failed, reason: %s", ebuff);
  421. regfree(&reg);
  422. return false;
  423. }
  424. regfree(&reg);
  425. return true;
  426. #else
  427. std::wstring wstr(str.begin(), str.end());
  428. std::wstring wmode(mode.begin(), mode.end());
  429. std::wsmatch match;
  430. bool res = false;
  431. try {
  432. std::wregex reg(wmode, std::regex::icase);
  433. // Matching string part
  434. res = regex_match(wstr, match, reg);
  435. res = regex_search(str, std::regex("[`!@#$%^&*()|{}';',<>?]"));
  436. } catch (std::exception &ex) {
  437. GELOGW("The directory %s is invalid, error: %s.", str.c_str(), ex.what());
  438. return false;
  439. }
  440. return !(res) && (str.size() == match.str().size());
  441. #endif
  442. }
  443. FMK_FUNC_HOST_VISIBILITY bool IsValidFile(const char *file_path) {
  444. if (file_path == nullptr) {
  445. GELOGE(PARAM_INVALID, "Config path is null.");
  446. return false;
  447. }
  448. if (!CheckInputPathValid(file_path)) {
  449. GELOGE(PARAM_INVALID, "Config path is invalid: %s", file_path);
  450. return false;
  451. }
  452. // Normalize the path
  453. std::string resolved_file_path = RealPath(file_path);
  454. if (resolved_file_path.empty()) {
  455. GELOGE(PARAM_INVALID, "Invalid input file path [%s], make sure that the file path is correct.", file_path);
  456. return false;
  457. }
  458. mmStat_t stat = {0};
  459. int32_t ret = mmStatGet(resolved_file_path.c_str(), &stat);
  460. if (ret != EN_OK) {
  461. GELOGE(PARAM_INVALID, "cannot get config file status, which path is %s, maybe not exist, return %d, errcode %d",
  462. resolved_file_path.c_str(), ret, mmGetErrorCode());
  463. return false;
  464. }
  465. if ((stat.st_mode & S_IFMT) != S_IFREG) {
  466. GELOGE(PARAM_INVALID, "config file is not a common file, which path is %s, mode is %u", resolved_file_path.c_str(),
  467. stat.st_mode);
  468. return false;
  469. }
  470. if (stat.st_size > kMaxConfigFileByte) {
  471. GELOGE(PARAM_INVALID, "config file %s size[%ld] is larger than max config file Bytes[%u]",
  472. resolved_file_path.c_str(), stat.st_size, kMaxConfigFileByte);
  473. return false;
  474. }
  475. return true;
  476. }
  477. FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY Status CheckPath(const char *path, size_t length) {
  478. if (path == nullptr) {
  479. GELOGE(PARAM_INVALID, "Config path is invalid.");
  480. return PARAM_INVALID;
  481. }
  482. if (strlen(path) != length) {
  483. GELOGE(PARAM_INVALID, "Path is invalid or length of config path is not equal to given length.");
  484. return PARAM_INVALID;
  485. }
  486. if (length == 0 || length > MMPA_MAX_PATH) {
  487. GELOGE(PARAM_INVALID, "Length of config path is invalid.");
  488. return PARAM_INVALID;
  489. }
  490. INT32 is_dir = mmIsDir(path);
  491. if (is_dir != EN_OK) {
  492. GELOGE(PATH_INVALID, "Open directory %s failed, maybe it is not exit or not a dir", path);
  493. return PATH_INVALID;
  494. }
  495. if (mmAccess2(path, M_R_OK) != EN_OK) {
  496. GELOGE(PATH_INVALID, "Read path[%s] failed, errmsg[%s]", path, strerror(errno));
  497. return PATH_INVALID;
  498. }
  499. return SUCCESS;
  500. }
  501. } // namespace ge

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