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>
20 #include <tzplatform_config.h>
24 #include "pkgmgr_parser_plugin_interface.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_INPUTBUBBLE = "--inputbubble";
82 static const char* CROSSGEN_OPT_COMPILE_BUBBLE_GENERICS = "--compilebubblegenerics";
83 static const char* CROSSGEN_OPT_VERBOSE = "--verbose";
84 static std::vector<std::string> REF_VECTOR;
85 static std::vector<std::string> INPUTBUBBLE_REF_VECTOR;
86 static std::vector<std::string> MIBC_VECTOR;
88 static int __interval = 0;
89 static PathManager* __pm = nullptr;
91 static NIOption* __ni_option = nullptr;
94 NIOption* getNIOption()
96 if (__ni_option == nullptr) {
97 __ni_option = (NIOption*)calloc(sizeof(NIOption), 1);
98 if (__ni_option == nullptr) {
99 _SERR("Fail to create NIOption");
105 static void waitInterval()
107 // by the recommand, ignore small value for performance.
108 if (__interval > 10000) {
109 _SOUT("sleep %d usec", __interval);
114 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
115 static uintptr_t getFileSize(const std::string& path)
119 if (stat(path.c_str(), &sb) == 0) {
126 // Get next base address to be used for system ni image from file
127 // __SYSTEM_BASE_FILE should be checked for existance before calling this function
128 static uintptr_t getNextBaseAddrFromFile()
130 FILE *pFile = fopen(__SYSTEM_BASE_FILE, "r");
132 _SERR("Failed to open %s", __SYSTEM_BASE_FILE);
139 while (fscanf(pFile, "%" SCNxPTR " %" SCNuPTR "", &addr, &size) != EOF) {
147 // Get next base address to be used for system ni image
148 static uintptr_t getNextBaseAddr()
150 uintptr_t baseAddr = 0;
152 if (!isFile(__SYSTEM_BASE_FILE)) {
153 // This is the starting address for all default base addresses
154 baseAddr = DEFAULT_BASE_ADDR_START;
156 baseAddr = getNextBaseAddrFromFile();
158 // Round to a multple of 64K (see ZapImage::CalculateZapBaseAddress in CoreCLR)
159 uintptr_t BASE_ADDRESS_ALIGNMENT = 0xffff;
160 baseAddr = (baseAddr + BASE_ADDRESS_ALIGNMENT) & ~BASE_ADDRESS_ALIGNMENT;
166 // Save base address of system ni image to file
167 static void updateBaseAddrFile(const std::string& absNIPath, uintptr_t baseAddr)
169 uintptr_t niSize = getFileSize(absNIPath);
171 _SERR("File %s doesn't exist", absNIPath.c_str());
175 // Write new entry to the file
176 FILE *pFile = fopen(__SYSTEM_BASE_FILE, "a");
178 _SERR("Failed to open %s", __SYSTEM_BASE_FILE);
182 fprintf(pFile, "%" PRIxPTR " %" PRIuPTR "\n", baseAddr, niSize);
186 // check if dll is listed in TPA
187 static bool isTPADll(const std::string& dllPath)
189 std::string absPath = getBaseName(getAbsolutePath(dllPath));
191 std::vector<std::string> paths = __pm->getPlatformAssembliesPaths();
192 for (unsigned int i = 0; i < paths.size(); i++) {
193 if (paths[i].find(getBaseName(absPath)) != std::string::npos) {
203 * @brief create the directory including parents directory, and
204 * copy ownership and smack labels to the created directory.
205 * @param[in] target directory path
206 * @param[in] source directory path to get ownership and smack label
207 * @return if directory created successfully, return true otherwise false
209 static bool createDirsAndCopyOwnerShip(std::string& target_path, const std::string& source)
212 mode_t mode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
214 for (std::string::iterator iter = target_path.begin(); iter != target_path.end();) {
215 std::string::iterator newIter = std::find(iter, target_path.end(), '/');
216 std::string newPath = std::string(target_path.begin(), newIter);
218 if (!newPath.empty()) {
219 if (stat(newPath.c_str(), &st) != 0) {
220 if (mkdir(newPath.c_str(), mode) != 0 && errno != EEXIST) {
221 _SERR("Fail to create app ni directory (%s)", newPath.c_str());
224 if (!source.empty()) {
225 copySmackAndOwnership(source, newPath);
228 if (!S_ISDIR(st.st_mode)) {
229 _SERR("Fail. path is not a dir (%s)", newPath.c_str());
235 if(newIter != target_path.end()) {
243 static std::string getNIFilePath(const std::string& dllPath)
245 size_t index = dllPath.find_last_of(".");
246 if (index == std::string::npos) {
247 _SERR("File doesnot contain extension. fail to get NI file name");
250 std::string fName = dllPath.substr(0, index);
251 std::string fExt = dllPath.substr(index, dllPath.length());
253 // crossgen generate file with lower case extension only
254 std::transform(fExt.begin(), fExt.end(), fExt.begin(), ::tolower);
255 std::string niPath = fName + ".ni" + fExt;
260 static std::string getAppNIFilePath(const std::string& absDllPath, NIOption* opt)
262 std::string niDirPath;
263 std::string prevPath;
265 prevPath = getBaseName(absDllPath);
266 niDirPath = concatPath(prevPath, APP_NI_SUB_DIR);
268 if (opt->flags & NI_FLAGS_APP_UNDER_RO_AREA) {
269 niDirPath = replaceAll(niDirPath, getBaseName(__pm->getAppRootPath()), __READ_ONLY_APP_UPDATE_DIR);
270 _SERR("App is installed in RO area. Change NI path to RW area(%s).", niDirPath.c_str());
271 _ERR("App is installed in RO area. Change NI path to RW area(%s).", niDirPath.c_str());
274 if (!isDirectory(niDirPath)) {
275 if (!createDirsAndCopyOwnerShip(niDirPath, prevPath)) {
276 niDirPath = prevPath;
277 _SERR("fail to create dir (%s)", niDirPath.c_str());
281 return getNIFilePath(concatPath(niDirPath, getFileName(absDllPath)));
284 static bool checkNIExistence(const std::string& absDllPath)
286 std::string absNIPath = getNIFilePath(absDllPath);
287 if (absNIPath.empty()) {
291 if (isFile(absNIPath)) {
295 // native image of System.Private.CoreLib.dll should have to overwrite
296 // original file to support new coreclr
297 if (absDllPath.find("System.Private.CoreLib.dll") != std::string::npos) {
298 return isR2RImage(absDllPath);
304 static bool checkAppNIExistence(const std::string& absDllPath, NIOption* opt)
306 std::string absNIPath = getAppNIFilePath(absDllPath, opt);
307 if (absNIPath.empty()) {
311 if (isFile(absNIPath)) {
318 static bool checkDllExistInDir(const std::string& path)
321 auto func = [&ret](const std::string& f_path, const std::string& f_name) {
322 if (isManagedAssembly(f_name) || isNativeImage(f_name)) {
327 scanFilesInDirectory(path, func, 0);
333 * Get the list of managed files in the specific directory
334 * Absolute paths of managed files are stored at the result list.
335 * If native image already exist in the same directory, managed file is ignored.
337 static ni_error_e getTargetDllList(const std::string& path, std::vector<std::string>& fileList)
339 if (!isDirectory(path)) {
340 return NI_ERROR_INVALID_PARAMETER;
343 auto func = [&fileList](const std::string& f_path, const std::string& f_name) {
344 if (isManagedAssembly(f_path) && !checkNIExistence(f_path)) {
345 fileList.push_back(getAbsolutePath(f_path));
349 scanFilesInDirectory(path, func, 0);
351 return NI_ERROR_NONE;
355 * Get the list of managed files in the specific directory of Application
356 * Absolute paths of managed files are stored at the result list.
357 * If native image already exist in the .native_image directory, managed file is ignored.
360 static ni_error_e getAppTargetDllList(const std::string& path, std::vector<std::string>& fileList, NIOption *opt)
362 if (!isDirectory(path)) {
363 return NI_ERROR_INVALID_PARAMETER;
366 auto func = [&fileList, opt](const std::string& f_path, const std::string& f_name) {
367 if (isManagedAssembly(f_path) && !checkAppNIExistence(f_path, opt)) {
368 fileList.push_back(getAbsolutePath(f_path));
372 scanFilesInDirectory(path, func, 0);
374 return NI_ERROR_NONE;
377 static void makeArgs(std::vector<const char*>& args, const std::vector<std::string>& refPaths, NIOption* opt)
379 args.push_back(CORERUN_CMD.c_str());
380 if (CROSSGEN2_PATH != "") {
381 args.push_back(CROSSGEN2_PATH.c_str());
383 args.push_back(CROSSGEN_OPT_JITPATH);
384 args.push_back(CLRJIT_PATH.c_str());
385 args.push_back(CROSSGEN_OPT_TARGET_ARCH);
386 args.push_back(ARCHITECTURE_IDENTIFIER);
387 if (!(opt->flags & NI_FLAGS_NO_PIPELINE)) {
388 args.push_back(CROSSGEN_OPT_OUT_NEAR_INPUT);
389 args.push_back(CROSSGEN_OPT_SINGLE_FILE_COMPILATION);
391 //args.push_back(OPT_PARALLELISM);
392 //args.push_back(OPT_PARALLELISM_COUNT);
393 args.push_back(CROSSGEN_OPT_RESILIENT);
395 args.push_back(CROSSGEN_OPT_OPTIMIZE);
397 if (opt->flags & NI_FLAGS_INPUT_BUBBLE) {
398 args.push_back(CROSSGEN_OPT_INPUTBUBBLE);
399 args.push_back(CROSSGEN_OPT_COMPILE_BUBBLE_GENERICS);
401 if (opt->flags & NI_FLAGS_INPUT_BUBBLE_REF) {
402 INPUTBUBBLE_REF_VECTOR.clear();
403 // check inputbubbleref format.
404 for (const auto &path : opt->inputBubbleRefPath) {
405 if (checkDllExistInDir(path)) {
406 INPUTBUBBLE_REF_VECTOR.push_back("--inputbubbleref:" + path + "/*.dll");
409 // add ref path to inputbubble ref
410 for (const auto &path : refPaths) {
411 if (checkDllExistInDir(path)) {
412 INPUTBUBBLE_REF_VECTOR.push_back("--inputbubbleref:" + path + "/*.dll");
415 for (const auto &path : INPUTBUBBLE_REF_VECTOR) {
416 args.push_back(path.c_str());
421 if (opt->flags & NI_FLAGS_MIBC) {
423 for (const auto &path : opt->mibcPath) {
424 MIBC_VECTOR.push_back("--mibc:" + path);
426 for (const auto &path : MIBC_VECTOR) {
427 args.push_back(path.c_str());
431 if (opt->flags & NI_FLAGS_VERBOSE) {
432 args.push_back(CROSSGEN_OPT_VERBOSE);
437 // set reference path
438 if (opt->flags & NI_FLAGS_REF) {
439 for (const auto &path : opt->refPath) {
440 REF_VECTOR.push_back("-r:" + path + "/*.dll");
443 std::vector<std::string> paths = __pm->getPlatformAssembliesPaths();
444 for (const auto &path : paths) {
445 if (checkDllExistInDir(path)) {
446 REF_VECTOR.push_back("-r:" + path + "/*.dll");
451 if (opt->flags & NI_FLAGS_EXTRA_REF) {
452 for (const auto &erPath : opt->extraRefPath) {
453 std::string path = getAbsolutePath(erPath);
454 if (checkDllExistInDir(path)) {
455 REF_VECTOR.push_back("-r:" + path + "/*.dll");
460 for (const auto &path : refPaths) {
461 if (checkDllExistInDir(path)) {
462 REF_VECTOR.push_back("-r:" + path + "/*.dll");
466 for (const auto &path : REF_VECTOR) {
467 args.push_back(path.c_str());
471 static void clearArgs(std::vector<const char*>& args)
477 static ni_error_e makePdbSymlinkForNI(std::string dllPath, std::string niPath)
479 std::string pdbPath = changeExtension(dllPath, ".dll", ".pdb");
481 if (exist(pdbPath)) {
482 std::string targetPDBPath = changeExtension(niPath, ".ni.dll", ".pdb");
483 if (!exist(targetPDBPath)) {
484 bf::create_symlink(pdbPath, targetPDBPath);
485 copySmackAndOwnership(pdbPath, targetPDBPath, true);
488 } catch (const bf::filesystem_error& error) {
489 _SERR("Fail to create symlink for %s", pdbPath.c_str());
490 return NI_ERROR_UNKNOWN;
493 return NI_ERROR_NONE;
496 static ni_error_e crossgen2PostAction(const std::string& dllPath, const std::string& niPath, NIOption* opt) {
497 if (!exist(niPath)) {
498 removeFile(changeExtension(niPath, ".ni.dll", ".ni.dll.tmp"));
499 _SERR("Fail to create native image for %s", dllPath.c_str());
500 return NI_ERROR_NO_SUCH_FILE;
502 copySmackAndOwnership(dllPath, niPath);
503 // if AppNI then move ni.dll file to .native_image and copy pdb to .native_image
504 if (opt->flags & NI_FLAGS_APPNI) {
505 std::string appNIPath = getAppNIFilePath(dllPath, opt);
506 moveFile(niPath, appNIPath);
507 makePdbSymlinkForNI(dllPath, appNIPath);
508 _SOUT("Native image %s generated successfully.", appNIPath.c_str());
510 _SOUT("Native image %s generated successfully.", niPath.c_str());
512 return NI_ERROR_NONE;
515 static ni_error_e crossgen2PipeLine(const std::vector<std::string>& dllList, const std::vector<std::string>& refPaths, NIOption* opt)
520 return NI_ERROR_UNKNOWN;
524 waitpid(pid, &status, 0);
525 if (WIFEXITED(status)) {
526 for (auto& dllPath: dllList) {
527 ni_error_e ret = crossgen2PostAction(dllPath, changeExtension(dllPath, ".dll", ".ni.dll"), opt);
528 if (ret != NI_ERROR_NONE) {
533 _SERR("Failed. Forked process terminated abnormally");
534 return NI_ERROR_ABNORMAL_PROCESS_TERMINATION;
537 std::vector<const char*> argv;
538 makeArgs(argv, refPaths, opt);
540 // add input files at the end of parameter
541 for (const auto &input : dllList) {
542 argv.push_back(input.c_str());
543 _SOUT("+ %s", input.c_str());
547 argv.push_back(nullptr);
550 if (opt->flags & NI_FLAGS_PRINT_CMD) {
551 _SOUT("==================== NI Commands =========================");
552 for (auto &arg: argv) _SOUT("+ %s", arg);
555 execv(CORERUN_CMD.c_str(), const_cast<char* const*>(argv.data()));
561 return NI_ERROR_NONE;
564 static ni_error_e crossgen2NoPipeLine(const std::vector<std::string>& dllList, const std::vector<std::string>& refPaths, NIOption* opt)
566 for (auto& dllPath : dllList) {
568 if (opt->flags & NI_FLAGS_APPNI) {
569 niPath = getAppNIFilePath(dllPath, opt);
571 niPath = getNIFilePath(dllPath);
574 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
575 uintptr_t baseAddr = 0;
576 if (isTPADll(dllPath)) {
577 baseAddr = getNextBaseAddr();
584 return NI_ERROR_UNKNOWN;
588 waitpid(pid, &status, 0);
589 if (WIFEXITED(status)) {
590 ni_error_e ret = crossgen2PostAction(dllPath, niPath, opt);
591 if (ret != NI_ERROR_NONE) {
594 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
596 updateBaseAddrFile(niPath, baseAddr);
600 _SERR("Failed. Forked process terminated abnormally");
601 _SERR("Crossgen2 was terminated by the OOM killer. Please check the system.");
602 removeFile(changeExtension(niPath, ".ni.dll", ".ni.dll.tmp"));
603 return NI_ERROR_ABNORMAL_PROCESS_TERMINATION;
606 std::vector<const char*> argv;
607 makeArgs(argv, refPaths, opt);
609 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
610 std::string baseAddrString;
612 argv.push_back("--imagebase");
613 std::stringstream ss;
614 ss << "0x" << std::hex << baseAddr;
615 baseAddrString = ss.str();
616 argv.push_back(baseAddrString.c_str());
619 argv.push_back("-o");
620 argv.push_back(niPath.c_str());
622 argv.push_back(dllPath.c_str());
623 _SOUT("+ %s", dllPath.c_str());
626 argv.push_back(nullptr);
629 if (opt->flags & NI_FLAGS_PRINT_CMD) {
630 _SOUT("==================== NI Commands =========================");
631 for (auto &arg: argv) _SOUT("+ %s", arg);
634 execv(CORERUN_CMD.c_str(), const_cast<char* const*>(argv.data()));
643 return NI_ERROR_NONE;
646 static ni_error_e createCoreLibNI(NIOption* opt)
648 std::string coreLib = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll");
649 std::string niCoreLib = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.ni.dll");
650 std::string coreLibBackup = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll.Backup");
652 std::vector<std::string> dllList;
653 std::vector<std::string> refPaths;
654 dllList.push_back(getAbsolutePath(coreLib));
656 if (!isFile(coreLibBackup) && !isR2RImage(coreLib)) {
657 if (crossgen2NoPipeLine(dllList, refPaths, opt) == NI_ERROR_NONE && exist(niCoreLib)) {
658 if (rename(coreLib.c_str(), coreLibBackup.c_str())) {
659 _SERR("Failed to rename System.Private.CoreLib.dll");
660 return NI_ERROR_CORE_NI_FILE;
662 if (rename(niCoreLib.c_str(), coreLib.c_str())) {
663 _SERR("Failed to rename System.Private.CoreLib.ni.dll");
664 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 ni_error_e doAOTList(std::vector<std::string>& dllList, const std::string& refPaths, NIOption* opt)
676 ni_error_e ret = NI_ERROR_NONE;
678 if (dllList.empty()) {
679 return NI_ERROR_INVALID_PARAMETER;
681 // When performing AOT for one Dll, an error is returned when an error occurs.
682 // However, when processing multiple dlls at once, only the log for errors is output and skipped.
684 std::string coreLib = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll");
687 std::vector<std::string> niList;
688 for (auto it = dllList.begin(); it != dllList.end(); it++) {
691 _SERR("dll file is not exist : %s", f.c_str());
694 if (!isManagedAssembly(f)) {
695 _SERR("Input file is not a dll file : %s", f.c_str());
698 // handle System.Private.CoreLib.dll separately.
699 // dllList and path manager contain absolute path. So, there is no need to change path to absolute path
704 niList.push_back(changeExtension(f, ".dll", ".ni.dll"));
708 // In the case of SPC, post-processing is required to change the name of the native image.
709 // In order to avoid repeatedly checking whether the generated native image is an SPC,
710 // the SPC native image generation is performed separately.
712 ret = createCoreLibNI(opt);
713 if (ret != NI_ERROR_NONE) {
718 // if there is no proper input after processing dll list
719 if (dllList.empty()) {
723 return NI_ERROR_INVALID_PARAMETER;
727 std::vector<std::string> paths;
728 splitPath(refPaths, paths);
730 if (opt->flags & NI_FLAGS_NO_PIPELINE) {
731 ret = crossgen2NoPipeLine(dllList, paths, opt);
733 // When the forked process in the pipeline state is terminated(WIFSIGNALED(status)),
734 // retry the generation of the native image
735 // if the number of .dll files and the number of .ni.dll files are different.
736 for (int callCnt = 0; callCnt < 2; callCnt++) {
737 // If an error occurs, perform it twice with the same option.
738 ret = crossgen2PipeLine(dllList, paths, opt);
739 if (ret != NI_ERROR_NONE) {
740 _SERR("Crossgen2 is abnormally terminated. Regenerate native images that failed while running crossgen2.");
742 for (auto it = niList.begin(); it != niList.end(); it++) {
743 std::string niPath = *it;
744 std::string dllPath = changeExtension(niPath, ".ni.dll", ".dll");
745 if (crossgen2PostAction(dllPath, niPath, opt) != NI_ERROR_NONE) {
746 dllList.push_back(dllPath);
755 // If an error occurs after two crossgen2PipeLine() attempts,
756 // try crossgen2NoPipeLine() for the last time.
757 if (ret != NI_ERROR_NONE) {
758 _SERR("Retry running crossgen2 with --no-pipeline mode to avoid termination by OOM.");
759 ret = crossgen2NoPipeLine(dllList, paths, opt);
766 static ni_error_e doAOTFile(const std::string& dllFile, const std::string& refPaths, NIOption* opt)
768 if (!isFile(dllFile)) {
769 _SERR("dll file is not exist : %s", dllFile.c_str());
770 return NI_ERROR_NO_SUCH_FILE;
773 if (!isManagedAssembly(dllFile)) {
774 _SERR("Failed. Input parameter is not managed dll (%s)\n", dllFile.c_str());
775 return NI_ERROR_INVALID_PARAMETER;
778 if (checkNIExistence(dllFile)) {
779 _SERR("Native image file is already exist : %s", dllFile.c_str());
780 return NI_ERROR_ALREADY_EXIST;
783 std::vector<std::string> dllList;
784 dllList.push_back(getAbsolutePath(dllFile));
785 return doAOTList(dllList, refPaths, opt);
788 // callback function of "pkgmgrinfo_appinfo_metadata_filter_foreach"
789 static int appAotCb(pkgmgrinfo_appinfo_h handle, void *userData)
793 NIOption **pOptions = (NIOption**)userData;
795 if ((*pOptions)->flags & NI_FLAGS_SKIP_RO_APP) {
796 bool isSystem = false;
797 int ret = pkgmgrinfo_appinfo_is_system(handle, &isSystem);
798 if (ret != PMINFO_R_OK) {
799 _SERR("Failed to check that app is System or not\n");
807 ret = pkgmgrinfo_appinfo_get_pkgid(handle, &pkgId);
808 if (ret != PMINFO_R_OK) {
809 _SERR("Failed to get pkgid");
813 if (removeNIUnderPkgRoot(pkgId) != NI_ERROR_NONE) {
814 _SERR("Failed to remove previous dlls from [%s]", pkgId);
818 if (createNIUnderPkgRoot(pkgId, *pOptions) != NI_ERROR_NONE) {
819 _SERR("Failed to generate NI file [%s]", pkgId);
822 _SOUT("Complete make application to native image");
828 ni_error_e initNICommon()
830 #if defined(__arm__) || defined(__aarch64__)
833 env = getenv("MIC_CROSSGEN2_ENABLED");
834 if (env != nullptr && !strcmp(env, "1")) {
835 CORERUN_CMD = std::string("/opt/usr/dotnet/mic/crossgen2");
837 CLRJIT_PATH = std::string("/opt/usr/dotnet/mic/libclrjit_unix_") + ARCHITECTURE_IDENTIFIER + std::string("_x64.so");
840 // get interval value
841 const static std::string intervalFile = concatPath(__NATIVE_LIB_DIR, "crossgen_interval.txt");
842 std::ifstream inFile(intervalFile);
844 _SOUT("crossgen_interval.txt is found");
845 inFile >> __interval;
848 if (initializePluginManager("normal")) {
849 _SERR("Fail to initialize PluginManager");
850 return NI_ERROR_UNKNOWN;
854 __pm = new PathManager();
855 } catch (const std::exception& e) {
856 _SERR("Failed to create PathManager");
857 return NI_ERROR_UNKNOWN;
860 char* pluginDllPaths = pluginGetDllPath();
861 if (pluginDllPaths && pluginDllPaths[0] != '\0') {
862 __pm->addPlatformAssembliesPaths(pluginDllPaths, true);
865 char* pluginNativePaths = pluginGetNativeDllSearchingPath();
866 if (pluginNativePaths && pluginNativePaths[0] != '\0') {
867 __pm->addNativeDllSearchingPaths(pluginNativePaths, true);
870 return NI_ERROR_NONE;
872 _SERR("crossgen supports arm/arm64 architecture only. skip ni file generation");
873 return NI_ERROR_NOT_SUPPORTED;
877 void finalizeNICommon()
881 finalizePluginManager();
888 __ni_option = nullptr;
892 ni_error_e createNIPlatform(NIOption* opt)
894 ni_error_e ret = createNIUnderDirs(__pm->getRuntimePath(), opt);
895 if (ret != NI_ERROR_NONE) {
899 return createNIUnderDirs(__pm->getTizenFXPath(), opt);
902 ni_error_e createNIDll(const std::string& dllPath, NIOption* opt)
904 return doAOTFile(dllPath, std::string(), opt);
907 ni_error_e createNIUnderTAC(const std::string& targetPath, const std::string& refPaths, NIOption* opt)
911 // get managed file list from targetPath
912 std::vector<std::string> dllList;
913 ret = getTargetDllList(targetPath, dllList);
914 if (ret != NI_ERROR_NONE) {
918 std::vector<std::string> needNIList;
919 std::vector<std::string> niList;
921 for (auto &dll : dllList) {
922 if (!checkNIExistence(dll)) {
923 needNIList.push_back(dll);
925 niList.push_back(getNIFilePath(dll));
928 if (!needNIList.empty()) {
929 // NI fils of TAC-related dlls under /opt/usr/dotnet should not be created under .native_image directory.
930 // So, unset NI_FLAGS_APPNI temporally and restore it after running AOT.
931 opt->flags &= ~NI_FLAGS_APPNI;
932 ret = doAOTList(needNIList, refPaths, opt);
933 opt->flags |= NI_FLAGS_APPNI;
934 if (ret != NI_ERROR_NONE) {
939 for (auto &niPath : niList) {
941 std::string symNIPath = concatPath(targetPath, getFileName(niPath));
942 if (!exist(symNIPath)) {
943 bf::create_symlink(niPath, symNIPath);
944 copySmackAndOwnership(targetPath.c_str(), symNIPath.c_str(), true);
945 _SOUT("%s symbolic link file generated successfully.", symNIPath.c_str());
946 _INFO("%s symbolic link file generated successfully.", symNIPath.c_str());
951 return NI_ERROR_NONE;
955 ni_error_e createNIUnderDirs(const std::string& rootPaths, NIOption* opt)
957 ni_error_e ret = NI_ERROR_NONE;
959 std::vector<std::string> fileList;
960 std::vector<std::string> paths;
961 splitPath(rootPaths, paths);
963 for (const auto &path : paths) {
968 if (path.find(TAC_SYMLINK_SUB_DIR) != std::string::npos) {
969 ret = createNIUnderTAC(path, rootPaths, opt);
970 if (ret != NI_ERROR_NONE) {
973 } else if (opt->flags & NI_FLAGS_APPNI) {
974 ret = getAppTargetDllList(path, fileList, opt);
975 if (ret != NI_ERROR_NONE) {
979 ret = getTargetDllList(path, fileList);
980 if (ret != NI_ERROR_NONE) {
986 if (fileList.empty()) {
987 return NI_ERROR_NONE;
990 return doAOTList(fileList, rootPaths, opt);
993 ni_error_e createNIUnderPkgRoot(const std::string& pkgId, NIOption* opt)
995 if (!isR2RImage(concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll"))) {
996 _SERR("The native image of System.Private.CoreLib does not exist.\n"
997 "Run the command to create the native image\n"
998 "# dotnettool --ni-dll /usr/share/dotnet.tizen/netcoreapp/System.Private.CoreLib.dll");
999 return NI_ERROR_CORE_NI_FILE;
1002 std::string rootPath = getRootPath(pkgId);
1003 if (rootPath.empty()) {
1004 _SERR("Failed to get root path from [%s]", pkgId.c_str());
1005 return NI_ERROR_INVALID_PACKAGE;
1008 __pm->setAppRootPath(rootPath);
1010 char* extraDllPaths = pluginGetExtraDllPath();
1011 if (extraDllPaths && extraDllPaths[0] != '\0') {
1012 opt->flags |= NI_FLAGS_EXTRA_REF;
1013 splitPath(extraDllPaths, opt->extraRefPath);
1016 opt->flags |= NI_FLAGS_APPNI;
1018 if (isReadOnlyArea(rootPath)) {
1019 opt->flags |= NI_FLAGS_APP_UNDER_RO_AREA;
1020 opt->flags |= NI_FLAGS_NO_PIPELINE;
1021 _SERR("Only no-pipeline mode supported for RO app. Set no-pipeline option forcibly");
1023 opt->flags &= ~NI_FLAGS_APP_UNDER_RO_AREA;
1026 // create native image under bin and lib directory
1027 // tac directory is skipped in the createNIUnderDirs.
1028 return createNIUnderDirs(__pm->getAppPaths(), opt);
1031 void removeNIPlatform()
1033 std::string coreLib = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll");
1034 std::string coreLibBackup = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll.Backup");
1036 if (isR2RImage(coreLib)) {
1037 if (!isFile(coreLibBackup)) {
1041 if (remove(coreLib.c_str())) {
1042 _SERR("Failed to remove System.Private.CoreLib native image file");
1044 if (rename(coreLibBackup.c_str(), coreLib.c_str())) {
1045 _SERR("Failed to rename System.Private.CoreLib.Backup to origin");
1049 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
1050 if (isFile(__SYSTEM_BASE_FILE)) {
1051 if (remove(__SYSTEM_BASE_FILE)) {
1052 _SERR("Failed to remove %s", __SYSTEM_BASE_FILE);
1057 removeNIUnderDirs(__pm->getRuntimePath() + ":" + __pm->getTizenFXPath());
1060 void removeNIUnderDirs(const std::string& rootPaths)
1062 auto convert = [](const std::string& path, const std::string& filename) {
1063 if (isNativeImage(path)) {
1064 if (remove(path.c_str())) {
1065 _SERR("Failed to remove %s", path.c_str());
1070 std::vector<std::string> paths;
1071 splitPath(rootPaths, paths);
1072 for (const auto &path : paths) {
1073 scanFilesInDirectory(path, convert, -1);
1077 ni_error_e removeNIUnderPkgRoot(const std::string& pkgId)
1079 std::string rootPath = getRootPath(pkgId);
1080 if (rootPath.empty()) {
1081 _SERR("Failed to get root path from [%s]", pkgId.c_str());
1082 return NI_ERROR_INVALID_PACKAGE;
1085 __pm->setAppRootPath(rootPath);
1087 // getAppNIPaths returns bin/.native_image, lib/.native_image and .tac_symlink.
1088 std::string appNIPaths = __pm->getAppNIPaths();
1089 std::vector<std::string> paths;
1090 splitPath(appNIPaths, paths);
1091 for (const auto &path : paths) {
1092 if (!isReadOnlyArea(path)) {
1093 // Only the native image inside the TAC should be removed.
1094 if (strstr(path.c_str(), TAC_SYMLINK_SUB_DIR) != NULL) {
1095 removeNIUnderDirs(path);
1097 if (isDirectory(path)) {
1098 if (!removeAll(path.c_str())) {
1099 _SERR("Failed to remove app ni dir [%s]", path.c_str());
1106 // In special cases, the ni file may exist in the dll location.
1107 // The code below is to avoid this exceptional case.
1108 std::string appPaths = __pm->getAppPaths();
1109 splitPath(appPaths, paths);
1110 for (const auto &path : paths) {
1111 if (isDirectory(path)) {
1112 removeNIUnderDirs(path);
1116 return NI_ERROR_NONE;
1119 ni_error_e regenerateAppNI(NIOption* opt)
1122 pkgmgrinfo_appinfo_metadata_filter_h handle;
1124 ret = pkgmgrinfo_appinfo_metadata_filter_create(&handle);
1125 if (ret != PMINFO_R_OK)
1126 return NI_ERROR_UNKNOWN;
1128 ret = pkgmgrinfo_appinfo_metadata_filter_add(handle, AOT_METADATA_KEY, METADATA_VALUE);
1129 if (ret != PMINFO_R_OK) {
1130 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
1131 return NI_ERROR_UNKNOWN;
1134 ret = pkgmgrMDFilterForeach(handle, appAotCb, &opt);
1136 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
1137 return NI_ERROR_UNKNOWN;
1140 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
1141 return NI_ERROR_NONE;
1144 // callback function of "pkgmgrinfo_appinfo_metadata_filter_foreach"
1145 static int regenTacCb(pkgmgrinfo_appinfo_h handle, void *userData)
1148 NIOption **pOpt = (NIOption**)userData;
1150 int ret = pkgmgrinfo_appinfo_get_pkgid(handle, &pkgId);
1151 if (ret != PMINFO_R_OK || pkgId == NULL) {
1152 _SERR("Failed to get pkgid");
1156 sqlite3 *tac_db = openDB(TAC_APP_LIST_DB);
1158 _SERR("Sqlite open error");
1161 sqlite3_exec(tac_db, "BEGIN;", NULL, NULL, NULL);
1163 char *sql = sqlite3_mprintf("SELECT * FROM TAC WHERE PKGID = %Q;", pkgId);
1164 std::vector<std::string> nugets = selectDB(tac_db, sql);
1172 std::string nugetPaths;
1173 for (const auto &nuget : nugets) {
1174 if (!nugetPaths.empty()) {
1177 nugetPaths += concatPath(__DOTNET_DIR, nuget);
1180 for (auto& nuget : nugets) {
1181 createNIUnderTAC(concatPath(__DOTNET_DIR, nuget), nugetPaths, *pOpt);
1187 ni_error_e regenerateTACNI(NIOption* opt)
1189 removeNIUnderDirs(__DOTNET_DIR);
1191 pkgmgrinfo_appinfo_metadata_filter_h handle;
1192 int ret = pkgmgrinfo_appinfo_metadata_filter_create(&handle);
1193 if (ret != PMINFO_R_OK) {
1194 return NI_ERROR_UNKNOWN;
1197 ret = pkgmgrinfo_appinfo_metadata_filter_add(handle, TAC_METADATA_KEY, METADATA_VALUE);
1198 if (ret != PMINFO_R_OK) {
1199 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
1200 return NI_ERROR_UNKNOWN;
1203 ret = pkgmgrMDFilterForeach(handle, regenTacCb, &opt);
1205 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
1206 return NI_ERROR_UNKNOWN;
1209 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
1211 return NI_ERROR_NONE;
1214 static std::vector<uid_t> getUserIds()
1216 std::vector<uid_t> list;
1219 errno = 0; // so we can distinguish errors from no more entries
1220 passwd* entry = getpwent();
1223 _SERR("Error while getting userIDs");
1229 list.push_back(entry->pw_uid);
1236 static std::string getAppDataPath(const std::string& pkgId, uid_t uid)
1238 std::string pDataFile;
1240 tzplatform_set_user(uid);
1242 const char* tzUserApp = tzplatform_getenv(TZ_USER_APP);
1243 if (tzUserApp != NULL) {
1244 pDataFile = std::string(tzUserApp) + "/" + pkgId + "/data/";
1247 tzplatform_reset_user();
1252 ni_error_e removeAppProfileData(const std::string& pkgId)
1254 if (pkgId.empty()) {
1255 return NI_ERROR_INVALID_PARAMETER;
1258 std::vector<uid_t> uidList = getUserIds();
1259 for (auto& uid : uidList) {
1260 // get data path from pkgid
1261 std::string dataPath = getAppDataPath(pkgId, uid);
1262 if (!dataPath.empty() && exist(dataPath)) {
1263 std::string pDataFile = dataPath + PROFILE_BASENAME;
1265 if (exist(pDataFile)) {
1266 if (!removeFile(pDataFile)) {
1267 _SERR("Fail to remove profile data file (%s).", pDataFile.c_str());
1268 return NI_ERROR_UNKNOWN;
1270 _SOUT("Profile data (%s) is removed successfully", pDataFile.c_str());
1275 return NI_ERROR_NONE;
1278 static int appTypeListCb(pkgmgrinfo_appinfo_h handle, void *user_data)
1281 int ret = pkgmgrinfo_appinfo_get_pkgid(handle, &pkgId);
1282 if (ret != PMINFO_R_OK || pkgId == NULL) {
1283 _SERR("Fail to get pkgid");
1287 if (removeAppProfileData(pkgId) != NI_ERROR_NONE) {
1288 _SERR("Fail to remove profile data for (%s)", pkgId);
1294 static ni_error_e removeAppProfileByAppType(const char* type)
1298 pkgmgrinfo_appinfo_filter_h filter;
1300 ret = pkgmgrinfo_appinfo_filter_create(&filter);
1301 if (ret != PMINFO_R_OK) {
1302 _SERR("Fail to create appinfo filter");
1303 return NI_ERROR_UNKNOWN;
1306 ret = pkgmgrinfo_appinfo_filter_add_string(filter, PMINFO_APPINFO_PROP_APP_TYPE, type);
1307 if (ret != PMINFO_R_OK) {
1308 pkgmgrinfo_appinfo_filter_destroy(filter);
1309 _SERR("Fail to add appinfo filter (%s)", type);
1310 return NI_ERROR_UNKNOWN;
1313 ret = pkgmgrinfo_appinfo_filter_foreach_appinfo(filter, appTypeListCb, NULL);
1314 if (ret != PMINFO_R_OK) {
1315 _SERR("Fail to pkgmgrinfo_pkginfo_filter_foreach_pkginfo");
1316 pkgmgrinfo_appinfo_filter_destroy(filter);
1317 return NI_ERROR_UNKNOWN;
1320 pkgmgrinfo_appinfo_filter_destroy(filter);
1322 return NI_ERROR_NONE;
1325 void removeAllAppProfileData()
1327 std::vector<const char*> appTypeList = {"dotnet", "dotnet-nui", "dotnet-inhouse"};
1329 for (auto& type : appTypeList) {
1330 if (removeAppProfileByAppType(type) != NI_ERROR_NONE) {
1331 _SERR("Fail to removeAppProfileByAppType for type (%s)", type);