2 * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #include <pkgmgr-info.h>
18 #include <pkgmgr_installer_info.h>
23 #include "pkgmgr_parser_plugin_interface.h"
29 #include <sys/resource.h>
43 #include "ni_common.h"
44 #include "db_manager.h"
45 #include "tac_common.h"
46 #include "path_manager.h"
47 #include "plugin_manager.h"
48 #include "r2r_checker.h"
53 #define LOG_TAG "DOTNET_INSTALLER_PLUGIN"
56 #define __STR(x) __XSTR(x)
57 #if defined(__arm__) || defined(__aarch64__)
58 static const char* __NATIVE_LIB_DIR = __STR(NATIVE_LIB_DIR);
60 static const char* __DOTNET_DIR = __STR(DOTNET_DIR);
61 static const char* __READ_ONLY_APP_UPDATE_DIR = __STR(READ_ONLY_APP_UPDATE_DIR);
63 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
64 static const char* __SYSTEM_BASE_FILE = __STR(SYSTEM_BASE_FILE);
70 static std::string CORERUN_CMD = "/usr/share/dotnet.tizen/netcoreapp/corerun";
71 static std::string CROSSGEN2_PATH = "/usr/share/dotnet.tizen/netcoreapp/crossgen2/crossgen2.dll";
72 static std::string CLRJIT_PATH = "/usr/share/dotnet.tizen/netcoreapp/libclrjit.so";
73 static const char* CROSSGEN_OPT_JITPATH = "--jitpath";
74 static const char* CROSSGEN_OPT_TARGET_ARCH = "--targetarch";
75 static const char* CROSSGEN_OPT_OUT_NEAR_INPUT = "--out-near-input";
76 static const char* CROSSGEN_OPT_SINGLE_FILE_COMPILATION = "--single-file-compilation";
77 //static const char* CROSSGEN_OPT_PARALLELISM = "--parallelism";
78 //static const char* CROSSGEN_OPT_PARALLELISM_COUNT = "5";
79 static const char* CROSSGEN_OPT_RESILIENT = "--resilient";
80 //static const char* CROSSGEN_OPT_OPTIMIZE = "-O";
81 static const char* CROSSGEN_OPT_OPTIMIZE_TIME = "--Ot";
82 static const char* CROSSGEN_OPT_INPUTBUBBLE = "--inputbubble";
83 static const char* CROSSGEN_OPT_COMPILE_BUBBLE_GENERICS = "--compilebubblegenerics";
84 static const char* CROSSGEN_OPT_VERBOSE = "--verbose";
85 static std::vector<std::string> REF_VECTOR;
86 static std::vector<std::string> INPUTBUBBLE_REF_VECTOR;
87 static std::vector<std::string> MIBC_VECTOR;
89 static int __interval = 0;
90 static PathManager* __pm = nullptr;
92 static NIOption* __ni_option = nullptr;
95 NIOption* getNIOption()
97 if (__ni_option == nullptr) {
98 __ni_option = (NIOption*)calloc(sizeof(NIOption), 1);
99 if (__ni_option == nullptr) {
100 _SERR("Fail to create NIOption");
106 static void waitInterval()
108 // by the recommand, ignore small value for performance.
109 if (__interval > 10000) {
110 _SOUT("sleep %d usec", __interval);
115 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
116 // Get next base address to be used for system ni image from file
117 // __SYSTEM_BASE_FILE should be checked for existance before calling this function
118 static uintptr_t getNextBaseAddrFromFile()
120 FILE *pFile = fopen(__SYSTEM_BASE_FILE, "r");
122 _SERR("Failed to open %s", __SYSTEM_BASE_FILE);
129 while (fscanf(pFile, "%" SCNxPTR " %" SCNuPTR "", &addr, &size) != EOF) {
137 // Get next base address to be used for system ni image
138 static uintptr_t getNextBaseAddr()
140 uintptr_t baseAddr = 0;
142 if (!isFile(__SYSTEM_BASE_FILE)) {
143 // This is the starting address for all default base addresses
144 baseAddr = DEFAULT_BASE_ADDR_START;
146 baseAddr = getNextBaseAddrFromFile();
148 // Round to a multple of 64K (see ZapImage::CalculateZapBaseAddress in CoreCLR)
149 uintptr_t BASE_ADDRESS_ALIGNMENT = 0xffff;
150 baseAddr = (baseAddr + BASE_ADDRESS_ALIGNMENT) & ~BASE_ADDRESS_ALIGNMENT;
156 // Save base address of system ni image to file
157 static void updateBaseAddrFile(const std::string& absNIPath, uintptr_t baseAddr)
159 uintptr_t niSize = getSizeOfImage(absNIPath);
161 _SERR("File %s doesn't exist", absNIPath.c_str());
165 // Write new entry to the file
166 FILE *pFile = fopen(__SYSTEM_BASE_FILE, "a");
168 _SERR("Failed to open %s", __SYSTEM_BASE_FILE);
172 fprintf(pFile, "%" PRIxPTR " %" PRIuPTR "\n", baseAddr, niSize);
176 // check if dll is listed in TPA
177 static bool isTPADll(const std::string& dllPath)
179 std::string absPath = getBaseName(getAbsolutePath(dllPath));
181 std::vector<std::string> paths = __pm->getPlatformAssembliesPaths();
182 for (unsigned int i = 0; i < paths.size(); i++) {
183 if (paths[i].find(getBaseName(absPath)) != std::string::npos) {
193 * @brief create the directory including parents directory, and
194 * copy ownership and smack labels to the created directory.
195 * @param[in] target directory path
196 * @param[in] source directory path to get ownership and smack label
197 * @return if directory created successfully, return true otherwise false
199 static bool createDirsAndCopyOwnerShip(std::string& target_path, const std::string& source)
202 mode_t mode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
204 for (std::string::iterator iter = target_path.begin(); iter != target_path.end();) {
205 std::string::iterator newIter = std::find(iter, target_path.end(), '/');
206 std::string newPath = std::string(target_path.begin(), newIter);
208 if (!newPath.empty()) {
209 if (stat(newPath.c_str(), &st) != 0) {
210 if (mkdir(newPath.c_str(), mode) != 0 && errno != EEXIST) {
211 _SERR("Fail to create app ni directory (%s)", newPath.c_str());
214 if (!source.empty()) {
215 copySmackAndOwnership(source, newPath);
218 if (!S_ISDIR(st.st_mode)) {
219 _SERR("Fail. path is not a dir (%s)", newPath.c_str());
225 if(newIter != target_path.end()) {
233 static std::string getNIFilePath(const std::string& absDllPath, NIOption* opt)
235 std::string dllPath = absDllPath;
236 if (opt->flags & NI_FLAGS_APPNI) {
237 std::string niDirPath;
238 std::string niTmpDirPath;
239 std::string prevPath;
241 prevPath = getBaseName(absDllPath);
242 niDirPath = concatPath(prevPath, APP_NI_SUB_DIR);
243 niTmpDirPath = concatPath(prevPath, APP_NI_SUB_TMP_DIR);
245 if (opt->flags & NI_FLAGS_APP_UNDER_RO_AREA) {
246 niTmpDirPath = replaceAll(niTmpDirPath, getBaseName(__pm->getAppRootPath()), __READ_ONLY_APP_UPDATE_DIR);
247 niDirPath = replaceAll(niDirPath, getBaseName(__pm->getAppRootPath()), __READ_ONLY_APP_UPDATE_DIR);
248 _INFO("App is installed in RO area. Change NI path to RW area(%s).", niTmpDirPath.c_str());
251 if (!isDirectory(niDirPath)) {
252 if (!createDirsAndCopyOwnerShip(niTmpDirPath, prevPath)) {
253 niTmpDirPath = prevPath;
254 _SERR("fail to create dir (%s)", niTmpDirPath.c_str());
256 dllPath = concatPath(niTmpDirPath, getFileName(absDllPath));
258 dllPath = concatPath(niDirPath, getFileName(absDllPath));
262 size_t index = dllPath.find_last_of(".");
263 if (index == std::string::npos) {
264 _SERR("File doesnot contain extension. fail to get NI file name");
267 std::string fName = dllPath.substr(0, index);
268 std::string fExt = dllPath.substr(index, dllPath.length());
270 // crossgen generate file with lower case extension only
271 std::transform(fExt.begin(), fExt.end(), fExt.begin(), ::tolower);
272 std::string niPath = fName + ".ni" + fExt;
277 static bool checkNIExistence(const std::string& absDllPath, NIOption* opt)
279 std::string absNIPath = getNIFilePath(absDllPath, opt);
280 if (absNIPath.empty()) {
284 if (isFile(absNIPath)) {
288 // native image of System.Private.CoreLib.dll should have to overwrite
289 // original file to support new coreclr
290 if (absDllPath.find("System.Private.CoreLib.dll") != std::string::npos) {
291 return isR2RImage(absDllPath);
297 static bool checkDllExistInDir(const std::string& path)
300 auto func = [&ret](const std::string& f_path, const std::string& f_name) {
301 if (isManagedAssembly(f_name) || isR2RImage(f_name)) {
306 scanFilesInDirectory(path, func, 0);
312 * Get the list of managed files in the specific directory (of Application)
313 * Absolute paths of managed files are stored at the result list.
314 * If native image already exist in the (same / .native_image) directory, managed file is ignored.
316 static ni_error_e getTargetDllList(const std::string& path, std::vector<std::string>& fileList, NIOption *opt)
318 if (!isDirectory(path)) {
319 return NI_ERROR_INVALID_PARAMETER;
322 auto func = [&fileList, opt](const std::string& f_path, const std::string& f_name) {
323 if (isManagedAssembly(f_path) && !checkNIExistence(f_path, opt)) {
324 fileList.push_back(getAbsolutePath(f_path));
328 scanFilesInDirectory(path, func, 0);
330 return NI_ERROR_NONE;
333 static void makeArgs(std::vector<const char*>& args, const std::vector<std::string>& refPaths, NIOption* opt)
335 args.push_back(CORERUN_CMD.c_str());
336 if (CROSSGEN2_PATH != "") {
337 args.push_back(CROSSGEN2_PATH.c_str());
339 args.push_back(CROSSGEN_OPT_JITPATH);
340 args.push_back(CLRJIT_PATH.c_str());
341 args.push_back(CROSSGEN_OPT_TARGET_ARCH);
342 args.push_back(ARCHITECTURE_IDENTIFIER);
344 //args.push_back(OPT_PARALLELISM);
345 //args.push_back(OPT_PARALLELISM_COUNT);
346 args.push_back(CROSSGEN_OPT_RESILIENT);
348 args.push_back(CROSSGEN_OPT_OPTIMIZE_TIME);
350 if (opt->flags & NI_FLAGS_INPUT_BUBBLE) {
351 args.push_back(CROSSGEN_OPT_INPUTBUBBLE);
352 args.push_back(CROSSGEN_OPT_COMPILE_BUBBLE_GENERICS);
354 INPUTBUBBLE_REF_VECTOR.clear();
355 for (const auto &path : opt->inputBubbleRefFiles) {
356 INPUTBUBBLE_REF_VECTOR.push_back("--inputbubbleref:" + path);
358 for (const auto &path : INPUTBUBBLE_REF_VECTOR) {
359 if (find(args.begin(), args.end(), path) == args.end()) {
360 args.push_back(path.c_str());
365 if (opt->flags & NI_FLAGS_MIBC) {
367 for (const auto &path : opt->mibcPath) {
368 MIBC_VECTOR.push_back("--mibc:" + path);
370 for (const auto &path : MIBC_VECTOR) {
371 if (find(args.begin(), args.end(), path) == args.end()) {
372 args.push_back(path.c_str());
377 if (opt->flags & NI_FLAGS_VERBOSE) {
378 args.push_back(CROSSGEN_OPT_VERBOSE);
383 // set reference path
384 for (const auto &path : opt->refFiles) {
385 REF_VECTOR.push_back("-r:" + path);
388 std::vector<std::string> paths = __pm->getPlatformAssembliesPaths();
389 for (const auto &path : paths) {
390 if (checkDllExistInDir(path)) {
391 REF_VECTOR.push_back("-r:" + path + "/*.dll");
395 if (opt->flags & NI_FLAGS_EXTRA_REF) {
396 for (const auto &erPath : opt->extraRefPath) {
397 std::string path = getAbsolutePath(erPath);
398 if (checkDllExistInDir(path)) {
399 REF_VECTOR.push_back("-r:" + path + "/*.dll");
404 for (const auto &path : refPaths) {
405 if (checkDllExistInDir(path)) {
406 REF_VECTOR.push_back("-r:" + path + "/*.dll");
410 for (const auto &path : REF_VECTOR) {
411 if (find(args.begin(), args.end(), path) == args.end()) {
412 args.push_back(path.c_str());
417 static void clearArgs(std::vector<const char*>& args)
423 static ni_error_e makePdbSymlinkForNI(std::string dllPath, std::string niPath)
425 std::string pdbPath = changeExtension(dllPath, ".dll", ".pdb");
427 if (exist(pdbPath)) {
428 std::string targetPDBPath = changeExtension(niPath, ".ni.dll", ".pdb");
429 if (!exist(targetPDBPath)) {
430 bf::create_symlink(pdbPath, targetPDBPath);
431 copySmackAndOwnership(pdbPath, targetPDBPath, true);
434 } catch (const bf::filesystem_error& error) {
435 _SERR("Fail to create symlink for %s", pdbPath.c_str());
436 return NI_ERROR_UNKNOWN;
439 return NI_ERROR_NONE;
442 static ni_error_e crossgen2PostAction(const std::string& dllPath, const std::string& niPath, NIOption* opt) {
443 std::string outFile = niPath;
444 if (!exist(outFile)) {
445 return NI_ERROR_NO_SUCH_FILE;
447 copySmackAndOwnership(dllPath, outFile);
449 // if AppNI then move ni.dll file to .native_image and copy pdb to .native_image
450 if (opt->flags & NI_FLAGS_APPNI) {
451 outFile = getNIFilePath(dllPath, opt);
452 makePdbSymlinkForNI(dllPath, outFile);
454 if (opt->flags & NI_FLAGS_INPUT_BUBBLE && opt->flags & NI_FLAGS_NO_PIPELINE) {
455 outFile = outFile + ".tmp";
458 if (niPath != outFile) {
459 moveFile(niPath, outFile);
463 if (opt->flags & NI_FLAGS_RM_ORIGIN_AFTER_NI) {
464 if (!removeFile(dllPath)) {
465 _SERR("Fail to remove original file : %s", dllPath.c_str());
469 if (!(opt->flags & NI_FLAGS_INPUT_BUBBLE && opt->flags & NI_FLAGS_NO_PIPELINE)) {
470 _SOUT("Native image %s generated successfully.", outFile.c_str());
473 return NI_ERROR_NONE;
476 void setPriority(NIOption* opt)
478 pid_t pid = getpid();
479 if (setpriority(PRIO_PROCESS, pid, opt->priority) == 0) {
480 std::string str = " ";
481 if (opt->priority <= -20) {
483 } else if (opt->priority >= 19) {
486 _SOUT("Success to set the%spriority of the process. pid : [%d], priority : [%d]", str.c_str(), pid, getpriority(PRIO_PROCESS, pid));
488 _SERR("Failed to set the priority of the process. pid : [%d], priority : [%d]", pid, getpriority(PRIO_PROCESS, pid));
492 static ni_error_e crossgen2PipeLine(const std::vector<std::string>& dllList, const std::vector<std::string>& refPaths, NIOption* opt)
497 return NI_ERROR_UNKNOWN;
501 waitpid(pid, &status, 0);
502 if (WIFEXITED(status)) {
503 for (auto& dllPath: dllList) {
504 ni_error_e ret = crossgen2PostAction(dllPath, changeExtension(dllPath, ".dll", ".ni.dll"), opt);
505 if (ret != NI_ERROR_NONE) {
510 _SERR("Failed. Forked process terminated abnormally");
511 return NI_ERROR_ABNORMAL_PROCESS_TERMINATION;
514 if (opt->flags & NI_FLAGS_SET_PRIORITY) {
517 std::vector<const char*> argv;
518 makeArgs(argv, refPaths, opt);
519 argv.push_back(CROSSGEN_OPT_OUT_NEAR_INPUT);
520 argv.push_back(CROSSGEN_OPT_SINGLE_FILE_COMPILATION);
522 // add input files at the end of parameter
523 for (const auto &input : dllList) {
524 argv.push_back(input.c_str());
525 _SOUT("+ %s", input.c_str());
529 argv.push_back(nullptr);
532 if (opt->flags & NI_FLAGS_PRINT_CMD) {
533 _SOUT("==================== NI Commands =========================");
534 for (auto &arg: argv) _SOUT("+ %s", arg);
537 execv(CORERUN_CMD.c_str(), const_cast<char* const*>(argv.data()));
543 return NI_ERROR_NONE;
546 static ni_error_e crossgen2NoPipeLine(const std::vector<std::string>& dllList, const std::vector<std::string>& refPaths, NIOption* opt)
548 for (auto& dllPath : dllList) {
550 niPath = getNIFilePath(dllPath, opt);
552 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
553 uintptr_t baseAddr = 0;
554 if (isTPADll(dllPath)) {
555 baseAddr = getNextBaseAddr();
558 if (opt->flags & NI_FLAGS_INPUT_BUBBLE) {
565 return NI_ERROR_UNKNOWN;
569 waitpid(pid, &status, 0);
570 if (WIFEXITED(status)) {
571 ni_error_e ret = crossgen2PostAction(dllPath, niPath, opt);
572 if (ret != NI_ERROR_NONE) {
575 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
577 updateBaseAddrFile(niPath, baseAddr);
581 _SERR("Failed. Forked process terminated abnormally");
582 _SERR("Crossgen2 was terminated by the OOM killer. Please check the system.");
583 removeFile(changeExtension(niPath, ".ni.dll", ".ni.dll.tmp"));
584 return NI_ERROR_ABNORMAL_PROCESS_TERMINATION;
587 if (opt->flags & NI_FLAGS_SET_PRIORITY) {
590 std::vector<const char*> argv;
591 makeArgs(argv, refPaths, opt);
593 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
594 std::string baseAddrString;
596 argv.push_back("--imagebase");
597 std::stringstream ss;
598 ss << "0x" << std::hex << baseAddr;
599 baseAddrString = ss.str();
600 argv.push_back(baseAddrString.c_str());
603 argv.push_back("-o");
604 argv.push_back(niPath.c_str());
606 argv.push_back(dllPath.c_str());
607 _SOUT("+ %s", dllPath.c_str());
610 argv.push_back(nullptr);
613 if (opt->flags & NI_FLAGS_PRINT_CMD) {
614 _SOUT("==================== NI Commands =========================");
615 for (auto &arg: argv) _SOUT("+ %s", arg);
618 execv(CORERUN_CMD.c_str(), const_cast<char* const*>(argv.data()));
627 return NI_ERROR_NONE;
630 static ni_error_e createCoreLibNI(NIOption* opt)
632 std::string coreLib = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll");
633 std::string niCoreLib = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.ni.dll");
634 std::string niTmpCoreLib = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.ni.dll.tmp");
635 std::string coreLibBackup = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll.Backup");
637 std::vector<std::string> dllList;
638 std::vector<std::string> refPaths;
639 dllList.push_back(getAbsolutePath(coreLib));
641 if (!isFile(coreLibBackup) && !isR2RImage(coreLib)) {
642 if (crossgen2NoPipeLine(dllList, refPaths, opt) == NI_ERROR_NONE) {
643 if (opt->flags & NI_FLAGS_RM_ORIGIN_AFTER_NI) {
644 std::ofstream output(coreLibBackup);
645 if (!exist(coreLibBackup)) {
646 _SERR("Failed to create System.Private.CoreLib.dll.Backup");
647 return NI_ERROR_CORE_NI_FILE;
649 copySmackAndOwnership(__pm->getRuntimePath(), coreLibBackup, false);
651 } else if (rename(coreLib.c_str(), coreLibBackup.c_str())) {
652 _SERR("Failed to rename from System.Private.CoreLib.dll to System.Private.CoreLib.dll.Backup");
653 return NI_ERROR_CORE_NI_FILE;
655 if (opt->flags & NI_FLAGS_INPUT_BUBBLE) {
656 if (rename(niTmpCoreLib.c_str(), coreLib.c_str())) {
657 _SERR("Failed to rename from System.Private.CoreLib.ni.dll.tmp to Private.CoreLib.dll");
658 return NI_ERROR_CORE_NI_FILE;
661 if (rename(niCoreLib.c_str(), coreLib.c_str())) {
662 _SERR("Failed to rename from System.Private.CoreLib.ni.dll to Private.CoreLib.dll");
663 return NI_ERROR_CORE_NI_FILE;
667 _SERR("Failed to create native image for %s", coreLib.c_str());
668 return NI_ERROR_CORE_NI_FILE;
671 return NI_ERROR_NONE;
674 static void renameAppNITmpPath(NIOption* opt)
676 std::string niTmpPath = __pm->getAppRootPath() + "/bin/" + APP_NI_SUB_TMP_DIR;
677 std::string niPath = __pm->getAppRootPath() + "/bin/" + APP_NI_SUB_DIR;
679 if (opt->flags & NI_FLAGS_APP_UNDER_RO_AREA) {
680 niTmpPath = replaceAll(niTmpPath, getBaseName(__pm->getAppRootPath()), __READ_ONLY_APP_UPDATE_DIR);
681 niPath = replaceAll(niPath, getBaseName(__pm->getAppRootPath()), __READ_ONLY_APP_UPDATE_DIR);
684 if (isDirectory(niTmpPath)) {
685 if (rename(niTmpPath.c_str(), niPath.c_str())) {
686 _SERR("Fail to rename from .native_image_tmp to .native_image");
688 _SOUT("Success to rename from %s to %s", niTmpPath.c_str(), niPath.c_str());
693 static ni_error_e doAOTList(std::vector<std::string>& dllList, const std::string& refPaths, NIOption* opt)
695 ni_error_e ret = NI_ERROR_NONE;
697 if (dllList.empty()) {
698 return NI_ERROR_INVALID_PARAMETER;
700 // When performing AOT for one Dll, an error is returned when an error occurs.
701 // However, when processing multiple dlls at once, only the log for errors is output and skipped.
703 std::string coreLib = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll");
706 for (auto it = dllList.begin(); it != dllList.end(); it++) {
709 _SERR("dll file is not exist : %s", f.c_str());
712 else if (!isManagedAssembly(f)) {
713 _SERR("Input file is not a dll file : %s", f.c_str());
716 // handle System.Private.CoreLib.dll separately.
717 // dllList and path manager contain absolute path. So, there is no need to change path to absolute path
718 else if (f == coreLib) {
724 // Error : Multiple input files matching same simple name
725 // So, Remove dulicate files from dll list
726 std::sort(dllList.begin(), dllList.end());
727 dllList.erase(unique(dllList.begin(), dllList.end()), dllList.end());
729 // In the case of SPC, post-processing is required to change the name of the native image.
730 // In order to avoid repeatedly checking whether the generated native image is an SPC,
731 // the SPC native image generation is performed separately.
733 ret = createCoreLibNI(opt);
734 if (ret != NI_ERROR_NONE) {
739 // if there is no proper input after processing dll list
740 if (dllList.empty()) {
744 return NI_ERROR_INVALID_PARAMETER;
748 std::vector<std::string> paths;
749 splitPath(refPaths, paths);
751 if (opt->flags & NI_FLAGS_NO_PIPELINE) {
752 ret = crossgen2NoPipeLine(dllList, paths, opt);
754 std::vector<std::string> notCompiled;
755 ret = crossgen2PipeLine(dllList, paths, opt);
756 if (ret != NI_ERROR_NONE) {
757 _SERR("Crossgen2 is abnormally terminated. Regenerate native images that failed while running crossgen2.");
758 for (auto &dll : dllList) {
759 std::string tFile = changeExtension(dll, ".dll", ".ni.dll");
760 if (opt->flags & NI_FLAGS_INPUT_BUBBLE) {
764 notCompiled.push_back(dll);
767 _SERR("Retry running crossgen2 with --no-pipeline mode to avoid termination by OOM.");
768 ret = crossgen2NoPipeLine(notCompiled, paths, opt);
772 if (ret == NI_ERROR_NONE) {
773 if (opt->flags & NI_FLAGS_INPUT_BUBBLE) {
774 for (auto &dll : dllList) {
776 std::string niFile = getNIFilePath(dll, opt);
777 tmpFile = niFile + ".tmp";
779 if (exist(tmpFile)) {
780 moveFile(tmpFile, niFile);
781 _SOUT("Native image %s generated successfully.", niFile.c_str());
785 if (opt->flags & NI_FLAGS_APPNI) {
786 renameAppNITmpPath(opt);
793 static ni_error_e doAOTFile(const std::string& dllFile, const std::string& refPaths, NIOption* opt)
795 if (!isFile(dllFile)) {
796 _SERR("dll file is not exist : %s", dllFile.c_str());
797 return NI_ERROR_NO_SUCH_FILE;
800 if (checkNIExistence(dllFile, opt)) {
801 _SERR("Native image file is already exist : %s", dllFile.c_str());
802 return NI_ERROR_ALREADY_EXIST;
805 if (!isManagedAssembly(dllFile)) {
806 _SERR("Failed. Input parameter is not managed dll (%s)\n", dllFile.c_str());
807 return NI_ERROR_INVALID_PARAMETER;
810 std::vector<std::string> dllList;
811 dllList.push_back(getAbsolutePath(dllFile));
812 return doAOTList(dllList, refPaths, opt);
815 // callback function of "pkgmgrinfo_appinfo_metadata_filter_foreach"
816 static int getPkgIdCb(pkgmgrinfo_appinfo_h handle, void *userData)
821 ret = pkgmgrinfo_appinfo_get_pkgid(handle, &pkgId);
822 if (ret != PMINFO_R_OK) {
823 _SERR("Failed to get pkgid");
827 std::vector<std::string> *pkgList = (std::vector<std::string> *)userData;
828 pkgList->push_back(pkgId);
833 static bool isReadOnlyPkg(std::string pkgId)
836 bool readonly = false;
837 pkgmgrinfo_pkginfo_h handle;
839 ret = pkgmgrinfo_pkginfo_get_pkginfo(pkgId.c_str(), &handle);
840 if (ret != PMINFO_R_OK) {
841 _ERR("Fail to get pkginfo");
845 ret = pkgmgrinfo_pkginfo_is_readonly(handle, &readonly);
846 if (ret != PMINFO_R_OK) {
847 _ERR("Fail to get is_readonly");
848 pkgmgrinfo_pkginfo_destroy_pkginfo(handle);
852 pkgmgrinfo_pkginfo_destroy_pkginfo(handle);
856 ni_error_e initNICommon()
858 #if defined(__arm__) || defined(__aarch64__)
861 env = getenv("MIC_CROSSGEN2_ENABLED");
862 if (env != nullptr && !strcmp(env, "1")) {
863 CORERUN_CMD = std::string("/opt/usr/dotnet/mic/crossgen2");
865 CLRJIT_PATH = std::string("/opt/usr/dotnet/mic/libclrjit_unix_") + ARCHITECTURE_IDENTIFIER + std::string("_x64.so");
868 // get interval value
869 const static std::string intervalFile = concatPath(__NATIVE_LIB_DIR, "crossgen_interval.txt");
870 std::ifstream inFile(intervalFile);
872 _SOUT("crossgen_interval.txt is found");
873 inFile >> __interval;
876 if (initializePluginManager("normal")) {
877 _SERR("Fail to initialize PluginManager");
878 return NI_ERROR_UNKNOWN;
882 __pm = new PathManager();
883 } catch (const std::exception& e) {
884 _SERR("Failed to create PathManager");
885 return NI_ERROR_UNKNOWN;
888 char* pluginDllPaths = pluginGetDllPath();
889 if (pluginDllPaths && pluginDllPaths[0] != '\0') {
890 __pm->addPlatformAssembliesPaths(pluginDllPaths, true);
893 char* pluginNativePaths = pluginGetNativeDllSearchingPath();
894 if (pluginNativePaths && pluginNativePaths[0] != '\0') {
895 __pm->addNativeDllSearchingPaths(pluginNativePaths, true);
898 return NI_ERROR_NONE;
900 _SERR("crossgen supports arm/arm64 architecture only. skip ni file generation");
901 return NI_ERROR_NOT_SUPPORTED;
905 void finalizeNICommon()
909 finalizePluginManager();
916 __ni_option = nullptr;
920 ni_error_e createNIPlatform(std::string& extraInputs, NIOption* opt)
922 extraInputs += ":" + __pm->getRuntimePath();
923 extraInputs += ":" + __pm->getTizenFXPath();
925 return createNIUnderDirs(extraInputs, opt);
928 ni_error_e createNIDll(const std::string& dllPath, NIOption* opt)
930 return doAOTFile(dllPath, std::string(), opt);
933 ni_error_e createNIUnderTAC(const std::string& targetPath, const std::string& refPaths, NIOption* opt)
937 bool isAppNI = false;
938 if (opt->flags & NI_FLAGS_APPNI) {
942 if (opt->flags & NI_FLAGS_INPUT_BUBBLE) {
943 std::vector<std::string> refs;
944 splitPath(refPaths, refs);
945 for (auto &p: refs) {
946 if (isDirectory(p) && checkDllExistInDir(p)) {
947 opt->inputBubbleRefFiles.push_back(p + "/*.dll");
952 // get managed file list from targetPath
953 std::vector<std::string> dllList;
954 ret = getTargetDllList(targetPath, dllList, opt);
955 if (ret != NI_ERROR_NONE) {
959 std::vector<std::string> needNIList;
960 std::vector<std::string> niList;
962 for (auto &dll : dllList) {
963 if (!checkNIExistence(dll, opt)) {
964 needNIList.push_back(dll);
966 niList.push_back(getNIFilePath(dll, opt));
969 if (!needNIList.empty()) {
970 // NI fils of TAC-related dlls under /opt/usr/dotnet should not be created under .native_image directory.
971 // So, unset NI_FLAGS_APPNI temporally and restore it after running AOT.
972 opt->flags &= ~NI_FLAGS_APPNI;
973 ret = doAOTList(needNIList, refPaths, opt);
975 opt->flags |= NI_FLAGS_APPNI;
977 if (ret != NI_ERROR_NONE) {
983 for (auto &niPath : niList) {
985 std::string symNIPath = concatPath(targetPath, getFileName(niPath));
986 if (!exist(symNIPath)) {
987 bf::create_symlink(niPath, symNIPath);
988 copySmackAndOwnership(targetPath.c_str(), symNIPath.c_str(), true);
989 _SOUT("%s symbolic link file generated successfully.", symNIPath.c_str());
990 _INFO("%s symbolic link file generated successfully.", symNIPath.c_str());
996 return NI_ERROR_NONE;
1000 ni_error_e createNIUnderDirs(const std::string& rootPaths, NIOption* opt)
1002 ni_error_e ret = NI_ERROR_NONE;
1004 std::vector<std::string> fileList;
1005 std::vector<std::string> paths;
1006 splitPath(rootPaths, paths);
1008 if (opt->flags & NI_FLAGS_INPUT_BUBBLE) {
1009 for (auto &p: paths) {
1010 if (isDirectory(p) && checkDllExistInDir(p)) {
1011 opt->inputBubbleRefFiles.push_back(p + "/*.dll");
1016 for (const auto &path : paths) {
1021 if (path.find(TAC_SYMLINK_SUB_DIR) != std::string::npos) {
1022 ret = createNIUnderTAC(path, rootPaths, opt);
1023 if (ret != NI_ERROR_NONE) {
1027 ret = getTargetDllList(path, fileList, opt);
1028 if (ret != NI_ERROR_NONE) {
1034 if (fileList.empty()) {
1035 return NI_ERROR_NONE;
1038 return doAOTList(fileList, rootPaths, opt);
1041 ni_error_e createNIUnderPkgRoot(const std::string& pkgId, NIOption* opt)
1043 if (!isR2RImage(concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll"))) {
1044 _SERR("The native image of System.Private.CoreLib does not exist.\n"
1045 "Run the command to create the native image\n"
1046 "# dotnettool --ni-dll /usr/share/dotnet.tizen/netcoreapp/System.Private.CoreLib.dll");
1047 return NI_ERROR_CORE_NI_FILE;
1050 std::string rootPath = getRootPath(pkgId);
1051 if (rootPath.empty()) {
1052 _SERR("Failed to get root path from [%s]", pkgId.c_str());
1053 return NI_ERROR_INVALID_PACKAGE;
1056 __pm->setAppRootPath(rootPath);
1058 char* extraDllPaths = pluginGetExtraDllPath();
1059 if (extraDllPaths && extraDllPaths[0] != '\0') {
1060 opt->flags |= NI_FLAGS_EXTRA_REF;
1061 splitPath(extraDllPaths, opt->extraRefPath);
1064 opt->flags |= NI_FLAGS_APPNI;
1066 if (isReadOnlyArea(rootPath)) {
1067 opt->flags |= NI_FLAGS_APP_UNDER_RO_AREA;
1068 opt->flags |= NI_FLAGS_NO_PIPELINE;
1069 _SERR("Only no-pipeline mode supported for RO app. Set no-pipeline option forcibly");
1071 opt->flags &= ~NI_FLAGS_APP_UNDER_RO_AREA;
1074 // create native image under bin and lib directory
1075 // tac directory is skipped in the createNIUnderDirs.
1076 return createNIUnderDirs(__pm->getAppPaths(), opt);
1079 void removeNIPlatform()
1081 std::string coreLib = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll");
1082 std::string coreLibBackup = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll.Backup");
1084 if (isR2RImage(coreLib)) {
1085 if (!isFile(coreLibBackup)) {
1089 if (remove(coreLib.c_str())) {
1090 _SERR("Failed to remove System.Private.CoreLib native image file");
1092 if (rename(coreLibBackup.c_str(), coreLib.c_str())) {
1093 _SERR("Failed to rename System.Private.CoreLib.Backup to origin");
1097 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
1098 if (isFile(__SYSTEM_BASE_FILE)) {
1099 if (remove(__SYSTEM_BASE_FILE)) {
1100 _SERR("Failed to remove %s", __SYSTEM_BASE_FILE);
1105 removeNIUnderDirs(__pm->getRuntimePath() + ":" + __pm->getTizenFXPath());
1108 void removeNIUnderDirs(const std::string& rootPaths)
1110 auto convert = [](const std::string& path, const std::string& filename) {
1111 if (isR2RImage(path)) {
1112 std::string assemblyPath = changeExtension(path, ".ni.dll", ".dll");
1113 if (exist(assemblyPath)) {
1114 if (remove(path.c_str())) {
1115 _SERR("Failed to remove %s", path.c_str());
1118 _SOUT("%s cannot be removed because there is no %s", path.c_str(), assemblyPath.c_str());
1123 std::vector<std::string> paths;
1124 splitPath(rootPaths, paths);
1125 for (const auto &path : paths) {
1126 scanFilesInDirectory(path, convert, -1);
1130 ni_error_e removeNIUnderPkgRoot(const std::string& pkgId)
1132 std::string rootPath = getRootPath(pkgId);
1133 if (rootPath.empty()) {
1134 _SERR("Failed to get root path from [%s]", pkgId.c_str());
1135 return NI_ERROR_INVALID_PACKAGE;
1138 __pm->setAppRootPath(rootPath);
1140 // getAppNIPaths returns bin/.native_image, lib/.native_image and .tac_symlink.
1141 std::string appNIPaths = __pm->getAppNIPaths();
1142 std::vector<std::string> paths;
1143 splitPath(appNIPaths, paths);
1144 for (const auto &path : paths) {
1145 if (!isReadOnlyArea(path)) {
1146 // Only the native image inside the TAC should be removed.
1147 if (strstr(path.c_str(), TAC_SYMLINK_SUB_DIR) != NULL) {
1148 removeNIUnderDirs(path);
1150 if (isDirectory(path)) {
1151 if (!removeAll(path.c_str())) {
1152 _SERR("Failed to remove app ni dir [%s]", path.c_str());
1159 // In special cases, the ni file may exist in the dll location.
1160 // The code below is to avoid this exceptional case.
1161 std::string appPaths = __pm->getAppPaths();
1162 splitPath(appPaths, paths);
1163 for (const auto &path : paths) {
1164 if (isDirectory(path)) {
1165 removeNIUnderDirs(path);
1169 return NI_ERROR_NONE;
1172 ni_error_e regenerateAppNI(NIOption* opt)
1175 pkgmgrinfo_appinfo_metadata_filter_h handle;
1176 std::vector<std::string> pkgList;
1178 ret = pkgmgrinfo_appinfo_metadata_filter_create(&handle);
1179 if (ret != PMINFO_R_OK)
1180 return NI_ERROR_UNKNOWN;
1182 ret = pkgmgrinfo_appinfo_metadata_filter_add(handle, AOT_METADATA_KEY, METADATA_VALUE_TRUE);
1183 if (ret != PMINFO_R_OK) {
1184 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
1185 return NI_ERROR_UNKNOWN;
1188 ret = pkgmgrMDFilterForeach(handle, getPkgIdCb, &pkgList);
1190 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
1191 return NI_ERROR_UNKNOWN;
1194 // remove duplicated pkg in the list.
1195 // If one package has multiple apps, there can be duplicate values.
1196 std::sort(pkgList.begin(), pkgList.end());
1197 pkgList.erase(unique(pkgList.begin(), pkgList.end()), pkgList.end());
1199 for (auto pkg : pkgList) {
1200 if (isReadOnlyPkg(pkg) && opt->flags & NI_FLAGS_SKIP_RO_APP) {
1204 if (removeNIUnderPkgRoot(pkg) != NI_ERROR_NONE) {
1205 _SERR("Failed to remove previous dlls from [%s]", pkg.c_str());
1206 return NI_ERROR_UNKNOWN;
1209 if (createNIUnderPkgRoot(pkg, opt) != NI_ERROR_NONE) {
1210 _SERR("Failed to generate NI file [%s]", pkg.c_str());
1211 return NI_ERROR_UNKNOWN;
1213 _SOUT("Complete make application to native image");
1217 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
1218 return NI_ERROR_NONE;
1221 // callback function of "pkgmgrinfo_appinfo_metadata_filter_foreach"
1222 static int regenTacCb(pkgmgrinfo_appinfo_h handle, void *userData)
1226 NIOption **pOpt = (NIOption**)userData;
1228 int ret = pkgmgrinfo_appinfo_get_pkgid(handle, &pkgId);
1229 if (ret != PMINFO_R_OK || pkgId == NULL) {
1230 _SERR("Failed to get pkgid");
1234 ret = pkgmgrinfo_appinfo_get_root_path(handle, &root);
1235 if (ret != PMINFO_R_OK) {
1236 _SERR("Failed to get root path");
1240 std::string binPath = concatPath(std::string(root), "bin");
1241 if (exist(concatPath(binPath, PRE_COMPILED_PACKAGE_FILE))) {
1242 _INFO("The %s is a Pre-Compiled package. So, skip the TAC", pkgId);
1246 sqlite3 *tac_db = openDB(TAC_APP_LIST_DB);
1248 _SERR("Sqlite open error");
1251 sqlite3_exec(tac_db, "BEGIN;", NULL, NULL, NULL);
1253 char *sql = sqlite3_mprintf("SELECT * FROM TAC WHERE PKGID = %Q;", pkgId);
1254 std::vector<std::string> nugets = selectDB(tac_db, sql);
1262 std::string nugetPaths;
1263 for (const auto &nuget : nugets) {
1264 if (!nugetPaths.empty()) {
1267 nugetPaths += concatPath(__DOTNET_DIR, nuget);
1270 for (auto& nuget : nugets) {
1271 createNIUnderTAC(concatPath(__DOTNET_DIR, nuget), nugetPaths, *pOpt);
1277 ni_error_e regenerateTACNI(NIOption* opt)
1279 removeNIUnderDirs(__DOTNET_DIR);
1281 pkgmgrinfo_appinfo_metadata_filter_h handle;
1282 int ret = pkgmgrinfo_appinfo_metadata_filter_create(&handle);
1283 if (ret != PMINFO_R_OK) {
1284 return NI_ERROR_UNKNOWN;
1287 ret = pkgmgrinfo_appinfo_metadata_filter_add(handle, TAC_METADATA_KEY, METADATA_VALUE_TRUE);
1288 if (ret != PMINFO_R_OK) {
1289 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
1290 return NI_ERROR_UNKNOWN;
1293 ret = pkgmgrMDFilterForeach(handle, regenTacCb, &opt);
1295 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
1296 return NI_ERROR_UNKNOWN;
1299 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
1301 return NI_ERROR_NONE;