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

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