Refactoring path manager
[platform/core/dotnet/launcher.git] / NativeLauncher / tool / ni_common.cc
index c6f5695..3f73edb 100644 (file)
 
 #include <algorithm>
 #include <string>
+#include <fstream>
 
 #include <pwd.h>
 #include <grp.h>
-#include <sys/stat.h>
 #include <unistd.h>
 #include <string.h>
-
-#include <fstream>
-#include <sys/smack.h>
+#include <sqlite3.h>
 
 #include "ni_common.h"
+#include "db_manager.h"
+#include "tac_common.h"
 #include "path_manager.h"
 #include "plugin_manager.h"
 
 #ifdef  LOG_TAG
 #undef  LOG_TAG
 #endif
-#define LOG_TAG "NETCORE_INSTALLER_PLUGIN"
+#define LOG_TAG "DOTNET_INSTALLER_PLUGIN"
 
 #ifndef CROSSGEN_PATH
 #error "CROSSGEN_PATH is missed"
 
 #define __XSTR(x) #x
 #define __STR(x) __XSTR(x)
+static const char* __NATIVE_LIB_DIR = __STR(NATIVE_LIB_DIR);
 static const char* __CROSSGEN_PATH = __STR(CROSSGEN_PATH);
+static const char* __DOTNET_DIR = __STR(DOTNET_DIR);
+
+#ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
+static const char* __SYSTEM_BASE_FILE = __STR(SYSTEM_BASE_FILE);
+#endif
+
 #undef __STR
 #undef __XSTR
 
 static int __interval = 0;
-static std::string __tpa;
+static PathManager* __pm = nullptr;
 
 static void waitInterval()
 {
        // by the recommand, ignore small value for performance.
        if (__interval > 10000) {
-               fprintf(stderr, "sleep %d usec\n", __interval);
+               fprintf(stdout, "sleep %d usec\n", __interval);
                usleep(__interval);
        }
 }
 
-static std::string getNiFileName(const std::string& dllPath)
+static std::string getNIFilePath(const std::string& dllPath)
 {
        size_t index = dllPath.find_last_of(".");
        if (index == std::string::npos) {
@@ -86,14 +93,42 @@ static std::string getNiFileName(const std::string& dllPath)
        return niPath;
 }
 
-static bool niExist(const std::string& path)
+static std::string getAppNIFilePath(const std::string& niPath)
+{
+       std::string fileName;
+       std::string niDirPath;
+       std::string prevPath;
+
+       size_t index = niPath.find_last_of("/");
+       if (index != std::string::npos) {
+               prevPath = niPath.substr(0, index);
+               fileName = niPath.substr(index + 1, niPath.length());
+       } else {
+               prevPath = ".";
+               fileName = niPath;
+       }
+
+       niDirPath = concatPath(prevPath, APP_NI_SUB_DIR);
+
+       if (!isFile(niDirPath)) {
+               if (mkdir(niDirPath.c_str(), 0755) == 0) {
+                       copySmackAndOwnership(prevPath, niDirPath);
+               } else {
+                       fprintf(stderr, "Fail to create app ni directory (%s)\n", niDirPath.c_str());
+               }
+       }
+
+       return concatPath(niDirPath, fileName);
+}
+
+static bool checkNIExistence(const std::string& path)
 {
-       std::string f = getNiFileName(path);
+       std::string f = getNIFilePath(path);
        if (f.empty()) {
                return false;
        }
 
-       if (isFileExist(f)) {
+       if (isFile(f)) {
                return true;
        }
 
@@ -101,7 +136,7 @@ static bool niExist(const std::string& path)
        // original file to support new coreclr
        if (path.find("System.Private.CoreLib.dll") != std::string::npos) {
                std::string coreLibBackup = path + ".Backup";
-               if (isFileExist(coreLibBackup)) {
+               if (isFile(coreLibBackup)) {
                        return true;
                }
        }
@@ -109,144 +144,235 @@ static bool niExist(const std::string& path)
        return false;
 }
 
-static void updateNiFileInfo(const std::string& dllPath, const std::string& niPath)
+#ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
+static uintptr_t getFileSize(const std::string& path)
 {
-       char* label = NULL;
+       struct stat sb;
 
-       // change smack label
-       if (smack_getlabel(dllPath.c_str(), &label, SMACK_LABEL_ACCESS) == 0) {
-               if (smack_setlabel(niPath.c_str(), label, SMACK_LABEL_ACCESS) < 0) {
-                       fprintf(stderr, "Fail to set smack label\n");
-               }
-               free(label);
+       if (stat(path.c_str(), &sb) == 0) {
+               return sb.st_size;
+       }
+
+       return 0;
+}
+
+// Get next base address to be used for system ni image from file
+// __SYSTEM_BASE_FILE should be checked for existance before calling this function
+static uintptr_t getNextBaseAddrFromFile()
+{
+       FILE *pFile = fopen(__SYSTEM_BASE_FILE, "r");
+       if (pFile == NULL) {
+               fprintf(stderr, "Failed to open %s\n", __SYSTEM_BASE_FILE);
+               return 0;
+       }
+
+       uintptr_t addr = 0;
+       uintptr_t size = 0;
+
+       while (fscanf(pFile, "%u %u", &addr, &size) != EOF) {
+       }
+
+       fclose(pFile);
+
+       return addr + size;
+}
+
+// Get next base address to be used for system ni image
+static uintptr_t getNextBaseAddr()
+{
+       uintptr_t baseAddr = 0;
+
+       if (!isFile(__SYSTEM_BASE_FILE)) {
+               // This is the starting address for all default base addresses
+               baseAddr = DEFAULT_BASE_ADDR_START;
+       } else {
+               baseAddr = getNextBaseAddrFromFile();
+
+               // Round to a multple of 64K (see ZapImage::CalculateZapBaseAddress in CoreCLR)
+               uintptr_t BASE_ADDRESS_ALIGNMENT = 0xffff;
+               baseAddr = (baseAddr + BASE_ADDRESS_ALIGNMENT) & ~BASE_ADDRESS_ALIGNMENT;
+       }
+
+       return baseAddr;
+}
+
+// Save base address of system ni image to file
+static void updateBaseAddrFile(const std::string& absNIPath, uintptr_t baseAddr)
+{
+       uintptr_t niSize = getFileSize(absNIPath);
+       if (niSize == 0) {
+               fprintf(stderr, "File %s doesn't exist\n", absNIPath.c_str());
+               return;
+       }
+
+       // Write new entry to the file
+       FILE *pFile = fopen(__SYSTEM_BASE_FILE, "a");
+       if (pFile == NULL) {
+               fprintf(stderr, "Failed to open %s\n", __SYSTEM_BASE_FILE);
+               return;
        }
 
-       // change owner and groups for generated ni file.
-       struct stat info;
-       if (!stat(dllPath.c_str(), &info)) {
-               if (chown(niPath.c_str(), info.st_uid, info.st_gid) == -1)
-                       fprintf(stderr, "Failed to change owner and group name\n");
+       fprintf(pFile, "%u %u\n", baseAddr, niSize);
+       fclose(pFile);
+}
+
+// check if dll is listed in TPA
+static bool isTPADll(const std::string& dllPath)
+{
+       std::string absPath = getBaseName(getAbsolutePath(dllPath));
+
+       std::vector<std::string> paths = __pm->getPlatformAssembliesPaths();
+       for (unsigned int i = 0; i < paths.size(); i++) {
+               if (paths[i].find(getBaseName(absPath)) != std::string::npos) {
+                       return true;
+               }
        }
+
+       return false;
 }
+#endif
 
-static int crossgen(const std::string& dllPath, const std::string& appPath, bool enableR2R)
+// baseAddr should be checked in file before getting here
+static ni_error_e crossgen(const std::string& dllPath, const std::string& appPath, DWORD flags)
 {
-       if (!isFileExist(dllPath)) {
+       if (!isFile(dllPath)) {
                fprintf(stderr, "dll file is not exist : %s\n", dllPath.c_str());
-               return -1;
+               return NI_ERROR_NO_SUCH_FILE;
        }
 
        if (!isManagedAssembly(dllPath)) {
-               fprintf(stderr, "Input file is not a dll file : %s\n", dllPath.c_str());
-               return -1;
+               //fprintf(stderr, "Input file is not a dll file : %s\n", dllPath.c_str());
+               return NI_ERROR_INVALID_PARAMETER;
        }
 
-       if (niExist(dllPath)) {
+       if (checkNIExistence(dllPath)) {
                fprintf(stderr, "Already ni file is exist for %s\n", dllPath.c_str());
-               return -1;
+               return NI_ERROR_ALREADY_EXIST;
        }
 
-       std::string absDllPath = absolutePath(dllPath);
-       std::string absNiPath = getNiFileName(dllPath);
-       if (absNiPath.empty()) {
+       std::string absDllPath = getAbsolutePath(dllPath);
+       std::string absNIPath = getNIFilePath(dllPath);
+
+       if (absNIPath.empty()) {
                fprintf(stderr, "Fail to get ni file name\n");
-               return -1;
+               return NI_ERROR_UNKNOWN;
+       }
+
+       bool isAppNI = flags & NI_FLAGS_APPNI;
+       if (isAppNI && strstr(absNIPath.c_str(), __DOTNET_DIR) == NULL) {
+               absNIPath = getAppNIFilePath(absNIPath);
+       }
+
+#ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
+       uintptr_t baseAddr = 0;
+
+       if (isTPADll(dllPath)) {
+               baseAddr = getNextBaseAddr();
        }
+#endif
 
        pid_t pid = fork();
        if (pid == -1)
-               return -1;
+               return NI_ERROR_UNKNOWN;
 
        if (pid > 0) {
                int status;
                waitpid(pid, &status, 0);
                if (WIFEXITED(status)) {
-                       // Do not use niExist() function to check whether ni file created or not.
-                       // niEixst() return false for System.Private.Corelib.dll
-                       if (isFileExist(absNiPath)) {
-                               updateNiFileInfo(absDllPath, absNiPath);
-                               return 0;
+                       // Do not use checkNIExistence() function to check whether ni file created or not.
+                       // checkNIExistence() return false for System.Private.Corelib.dll
+                       if (isFile(absNIPath)) {
+                               copySmackAndOwnership(absDllPath, absNIPath);
+                               std::string absPdbPath = replaceAll(absDllPath, ".dll", ".pdb");
+                               std::string pdbFilePath = replaceAll(absNIPath, ".ni.dll", ".pdb");
+                               if (isFile(absPdbPath) && (absPdbPath != pdbFilePath)) {
+                                       if (!copyFile(absPdbPath, pdbFilePath)) {
+                                               fprintf(stderr, "Failed to copy a .pdb file\n");
+                                       } else {
+                                               copySmackAndOwnership(absPdbPath, pdbFilePath);
+                                       }
+                               }
+#ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
+                               if (baseAddr != 0) {
+                                       updateBaseAddrFile(absNIPath, baseAddr);
+                               }
+#endif
+                               return NI_ERROR_NONE;
                        } else {
                                fprintf(stderr, "Fail to create native image for %s\n", dllPath.c_str());
-                               return -1;
+                               return NI_ERROR_NO_SUCH_FILE;
                        }
                }
        } else {
-               std::string jitPath = getRuntimeDir() + "/libclrjit.so";
+               std::string jitPath = __pm->getRuntimePath() + "/libclrjit.so";
                std::vector<const char*> argv = {
                        __CROSSGEN_PATH,
                        "/nologo",
-                       "/Trusted_Platform_Assemblies", __tpa.c_str(),
                        "/JITPath", jitPath.c_str()
                };
 
+               bool compat = flags & NI_FLAGS_COMPATIBILITY;
+               argv.push_back(compat ? "/Platform_Assemblies_Pathes" : "/p");
+               std::vector<std::string> paths = __pm->getPlatformAssembliesPaths();
+               std::string platformAssembliesPaths;
+               for (const auto &path : paths) {
+                       if (!platformAssembliesPaths.empty()) {
+                               platformAssembliesPaths += ":";
+                       }
+                       platformAssembliesPaths += path;
+               }
+               argv.push_back(platformAssembliesPaths.c_str());
+
+               bool enableR2R = flags & NI_FLAGS_ENABLER2R;
                if (!enableR2R) {
                        argv.push_back("/FragileNonVersionable");
                }
 
+               if (flags & NI_FLAGS_VERBOSE) {
+                       argv.push_back("/verbose");
+               }
+
+               if (flags & NI_FLAGS_INSTRUMENT) {
+                       argv.push_back("/Tuning");
+               }
+
+#ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
+               if (baseAddr != 0) {
+                       argv.push_back("/BaseAddress");
+                       argv.push_back(std::to_string(baseAddr).c_str());
+               }
+#endif
+
                argv.push_back("/App_Paths");
                std::string absAppPath;
                if (!appPath.empty()) {
                        absAppPath = appPath;
                } else {
-                       absAppPath = baseName(absDllPath);
+                       absAppPath = getBaseName(absDllPath);
                }
                argv.push_back(absAppPath.c_str());
 
                argv.push_back("/out");
-               argv.push_back(absNiPath.c_str());
+               argv.push_back(absNIPath.c_str());
 
                argv.push_back(absDllPath.c_str());
                argv.push_back(nullptr);
 
-               fprintf(stderr, "+ %s (%s)\n", absDllPath.c_str(), enableR2R ? "R2R" : "FNV");
+               fprintf(stdout, "+ %s (%s)\n", absDllPath.c_str(), enableR2R ? "R2R" : "FNV");
 
                execv(__CROSSGEN_PATH, const_cast<char* const*>(argv.data()));
                exit(0);
        }
 
-       return 0;
-}
-
-static int getRootPath(std::string pkgId, std::string& rootPath)
-{
-       int ret = 0;
-       char *path = 0;
-
-       uid_t uid = 0;
-
-       if (pkgmgr_installer_info_get_target_uid(&uid) < 0) {
-               _ERR("Failed to get UID");
-               return -1;
-       }
-
-       pkgmgrinfo_pkginfo_h handle;
-       if (uid == 0) {
-               ret = pkgmgrinfo_pkginfo_get_pkginfo(pkgId.c_str(), &handle);
-               if (ret != PMINFO_R_OK)
-                       return -1;
-       } else {
-               ret = pkgmgrinfo_pkginfo_get_usr_pkginfo(pkgId.c_str(), uid, &handle);
-               if (ret != PMINFO_R_OK)
-                       return -1;
-       }
-
-       ret = pkgmgrinfo_pkginfo_get_root_path(handle, &path);
-       if (ret != PMINFO_R_OK) {
-               pkgmgrinfo_pkginfo_destroy_pkginfo(handle);
-               return -1;
-       }
-       rootPath = path;
-       pkgmgrinfo_pkginfo_destroy_pkginfo(handle);
-
-       return 0;
+       return NI_ERROR_NONE;
 }
 
+// callback function of "pkgmgrinfo_appinfo_metadata_filter_foreach"
 static int appAotCb(pkgmgrinfo_appinfo_h handle, void *userData)
 {
        char *pkgId = NULL;
        int ret = 0;
-       bool* enableR2R = (bool*)userData;
+       DWORD *pFlags = (DWORD*)userData;
 
        ret = pkgmgrinfo_appinfo_get_pkgid(handle, &pkgId);
        if (ret != PMINFO_R_OK) {
@@ -254,68 +380,118 @@ static int appAotCb(pkgmgrinfo_appinfo_h handle, void *userData)
                return -1;
        }
 
-       if (removeNiUnderPkgRoot(pkgId) != 0) {
+       if (removeNIUnderPkgRoot(pkgId) != NI_ERROR_NONE) {
                fprintf(stderr, "Failed to remove previous dlls from [%s]\n", pkgId);
                return -1;
        }
 
-       // Regenerate ni files with R2R mode forcibiliy. (there is no way to now which option is used)
-       if (createNiUnderPkgRoot(pkgId, *enableR2R) != 0) {
-               fprintf(stderr, "Failed to get root path from [%s]\n", pkgId);
+       if (createNIUnderPkgRoot(pkgId, *pFlags) != NI_ERROR_NONE) {
+               fprintf(stderr, "Failed to generate NI file [%s]\n", pkgId);
                return -1;
        } else {
-               fprintf(stderr, "Complete make application to native image\n");
+               fprintf(stdout, "Complete make application to native image\n");
        }
 
        return 0;
 }
 
-static void createCoreLibNI(bool enableR2R)
+static bool isCoreLibPrepared(DWORD flags)
 {
-       std::string coreLib = concatPath(getRuntimeDir(), "System.Private.CoreLib.dll");
-       std::string niCoreLib = concatPath(getRuntimeDir(), "System.Private.CoreLib.ni.dll");
-       std::string coreLibBackup = concatPath(getRuntimeDir(), "System.Private.CoreLib.dll.Backup");
+       if (flags & NI_FLAGS_ENABLER2R) {
+               return true;
+       }
+
+       std::string coreLibBackup = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll.Backup");
+       if (isFile(coreLibBackup)) {
+               return true;
+       } else {
+               fprintf(stderr, "The native image of System.Private.CoreLib does not exist\n"
+                                       "Run the command to create the native image\n"
+                                       "# dotnettool --ni-dll /usr/share/dotnet.tizen/netcoreapp/System.Private.CoreLib.dll\n\n");
+               return false;
+       }
+}
 
-       if (!isFileExist(coreLibBackup)) {
-               if (!crossgen(coreLib, std::string(), enableR2R)) {
+static bool hasCoreLibNI()
+{
+       FILE *fp;
+       char buff[1024];
+       std::string ildasm = concatPath(__pm->getRuntimePath(), "ildasm");
+       std::string coreLib = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll");
+       std::string cmd = ildasm + " " + coreLib + " | grep '\\.corflags'";
+       fp = popen(cmd.c_str(), "r");
+       if (fp != NULL) {
+               while (fgets(buff, sizeof(buff), fp) != NULL) {
+                       buff[strlen(buff) - 1] = '\0';
+               }
+               std::string corflag = replaceAll(buff, ".corflags", "");
+               corflag.erase(std::remove(corflag.begin(), corflag.end(), ' '), corflag.end());
+               // CorFlags.ILLibrary=0x00000004 (.ni.dll)
+               if (!strcmp(corflag.substr(0, 10).c_str(), "0x00000004")) {
+                       pclose(fp);
+                       return true;
+               }
+               pclose(fp);
+       }
+       return false;
+}
+
+static ni_error_e createCoreLibNI(DWORD flags)
+{
+       std::string coreLib = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll");
+       std::string niCoreLib = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.ni.dll");
+       std::string coreLibBackup = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll.Backup");
+
+       if (!isFile(coreLibBackup) && !hasCoreLibNI()) {
+               if (!crossgen(coreLib, std::string(), flags)) {
                        if (rename(coreLib.c_str(), coreLibBackup.c_str())) {
                                fprintf(stderr, "Failed to rename System.Private.CoreLib.dll\n");
+                               return NI_ERROR_CORE_NI_FILE;
                        }
                        if (rename(niCoreLib.c_str(), coreLib.c_str())) {
                                fprintf(stderr, "Failed to rename System.Private.CoreLib.ni.dll\n");
+                               return NI_ERROR_CORE_NI_FILE;
                        }
                } else {
                        fprintf(stderr, "Failed to create native image for %s\n", coreLib.c_str());
+                       return NI_ERROR_CORE_NI_FILE;
                }
        }
+       return NI_ERROR_NONE;
 }
 
-int initNICommon(NiCommonOption* option)
+ni_error_e initNICommon()
 {
-#if defined(__arm__)
+#if defined(__arm__) || defined(__aarch64__)
        // get interval value
-       const char* intervalFile = "/usr/share/dotnet.tizen/lib/crossgen_interval.txt";
+       const static std::string intervalFile = concatPath(__NATIVE_LIB_DIR, "crossgen_interval.txt");
        std::ifstream inFile(intervalFile);
        if (inFile) {
-               fprintf(stderr, "crossgen_interval.txt is found\n");
+               fprintf(stdout, "crossgen_interval.txt is found\n");
                inFile >> __interval;
        }
 
        if (initializePluginManager("normal")) {
-               fprintf(stderr, "Fail to initialize plugin manager\n");
-               return -1;
+               fprintf(stderr, "Fail to initialize PluginManager\n");
+               return NI_ERROR_UNKNOWN;
        }
-       if (initializePathManager(option->runtimeDir, option->tizenFXDir, option->extraDirs)) {
-               fprintf(stderr, "Fail to initialize path manager\n");
-               return -1;
+
+       try {
+               __pm = new PathManager();
+       } catch (const std::exception& e) {
+               fprintf(stderr, "Failed to create PathManager");
+               return NI_ERROR_UNKNOWN;
        }
 
-       __tpa = getTPA();
+       char* pluginDllPaths = pluginGetDllPath();
+       if (pluginDllPaths) {
+               __pm->addPlatformAssembliesPaths(pluginDllPaths);
+       }
 
-       return 0;
+       return NI_ERROR_NONE;
 #else
-       fprintf(stderr, "crossgen supports arm architecture only. skip ni file generation\n");
-       return -1;
+       fprintf(stderr, "crossgen supports arm/arm64 architecture only. skip ni file generation\n");
+       return NI_ERROR_NOT_SUPPORTED;
 #endif
 }
 
@@ -324,106 +500,146 @@ void finalizeNICommon()
        __interval = 0;
 
        finalizePluginManager();
-       finalizePathManager();
 
-       __tpa.clear();
+       delete(__pm);
+       __pm = nullptr;
 }
 
-
-void createNiPlatform(bool enableR2R)
+ni_error_e createNIPlatform(DWORD flags)
 {
-       const std::string platformDirs[] = {getRuntimeDir(), getTizenFXDir()};
-       createNiUnderDirs(platformDirs, 2, enableR2R);
+       if (createCoreLibNI(flags) != NI_ERROR_NONE) {
+               return NI_ERROR_CORE_NI_FILE;
+       }
+
+       return createNIUnderDirs(__pm->getRuntimePath() + ":" + __pm->getTizenFXPath(), flags);
 }
 
-int createNiDll(const std::string& dllPath, bool enableR2R)
+ni_error_e createNIDll(const std::string& dllPath, DWORD flags)
 {
-       createCoreLibNI(enableR2R);
-       return crossgen(dllPath, std::string(), enableR2R);
+       if (dllPath.find("System.Private.CoreLib.dll") != std::string::npos) {
+               return createCoreLibNI(flags);
+       }
+
+       if (!isCoreLibPrepared(flags)) {
+               return NI_ERROR_CORE_NI_FILE;
+       }
+
+       return crossgen(dllPath, std::string(), flags);
 }
 
-void createNiUnderDirs(const std::string rootPaths[], int count, bool enableR2R)
+ni_error_e createNIUnderDirs(const std::string rootPaths, DWORD flags)
 {
-       createCoreLibNI(enableR2R);
-
-       std::string appPaths;
-       for (int i = 0; i < count; i++) {
-               appPaths += rootPaths[i];
-               appPaths += ':';
+       if (!isCoreLibPrepared(flags)) {
+               return NI_ERROR_CORE_NI_FILE;
        }
 
-       if (appPaths.back() == ':')
-               appPaths.pop_back();
+       auto convert = [&rootPaths, flags](const std::string& path, const std::string& filename) {
 
-       auto convert = [&appPaths, enableR2R](const std::string& path, const char* name) {
-               if (!crossgen(path, appPaths.c_str(), enableR2R)) {
+               // if path is symlink, donot generate crossgen
+               if (!crossgen(path, rootPaths.c_str(), flags)) {
                        waitInterval();
                }
        };
 
-       for (int i = 0; i < count; i++) {
-               scanFilesInDir(rootPaths[i], convert, 1);
-       }
-}
-
-int createNiUnderPkgRoot(const std::string& pkgName, bool enableR2R)
-{
-       std::string pkgRoot;
-       if (getRootPath(pkgName, pkgRoot) < 0) {
-               fprintf(stderr, "Failed to get root path from [%s]\n", pkgName.c_str());
-               return -1;
+       std::vector<std::string> targetPaths;
+       splitPath(rootPaths, targetPaths);
+       for (const auto &path : targetPaths) {
+               // TAC directory should be handled specially because that contains symlink of native image file.
+               if (strstr(path.c_str(), TAC_SYMLINK_SUB_DIR) != NULL) {
+                       if (!isDirectory(path)) {
+                               continue;
+                       }
+                       // make native image symlink if not exist under tac directory
+                       try {
+                               for (auto& symlinkAssembly : bf::recursive_directory_iterator(path)) {
+                                       std::string symPath = symlinkAssembly.path().string();
+                                       if (!isManagedAssembly(symPath)) {
+                                               continue;
+                                       }
+
+                                       // if there is symlink and original file for native image, skip generation
+                                       std::string symNIPath = symPath.substr(0, symPath.rfind(".dll")) + ".ni.dll";
+                                       if (isFile(symNIPath)) {
+                                               continue;
+                                       }
+
+                                       // if original native image not exist, generate native image
+                                       std::string originPath = bf::read_symlink(symPath).string();
+                                       std::string originNIPath = originPath.substr(0, originPath.rfind(".dll")) + ".ni.dll";
+                                       if (!isFile(originNIPath)) {
+                                               if (!crossgen(originPath, path.c_str(), flags)) {
+                                                       waitInterval();
+                                               }
+                                       }
+
+                                       // if no symlink file exist, create symlink
+                                       if (!isFile(symNIPath)) {
+                                               bf::create_symlink(originNIPath, symNIPath);
+                                               copySmackAndOwnership(symPath.c_str(), symNIPath.c_str(), true);
+                                               fprintf(stdout, "%s symbolic link file generated successfully.\n", symNIPath.c_str());
+                                       }
+                               }
+                       } catch (const bf::filesystem_error& error) {
+                               fprintf(stderr, "Failed to recursive directory: %s\n", error.what());
+                               return NI_ERROR_UNKNOWN;
+                       }
+               } else {
+                       scanFilesInDirectory(path, convert, 0);
+               }
        }
 
-       std::string binDir = concatPath(pkgRoot, "bin");
-       std::string libDir = concatPath(pkgRoot, "lib");
-       std::string appTAC = concatPath(binDir, "TAC.Release");
-       std::string paths[] = {binDir, libDir, appTAC};
-
-       createNiUnderDirs(paths, 3, enableR2R);
-
-       return 0;
+       return NI_ERROR_NONE;
 }
 
-int createNiDllUnderPkgRoot(const std::string& pkgName, const std::string& dllPath, bool enableR2R)
+ni_error_e createNIUnderPkgRoot(const std::string& pkgId, DWORD flags)
 {
-       std::string pkgRoot;
-       if (getRootPath(pkgName, pkgRoot) < 0) {
-               fprintf(stderr, "Failed to get root path from [%s]\n", pkgName.c_str());
-               return -1;
+       std::string rootPath = getRootPath(pkgId);
+       if (rootPath.empty()) {
+               fprintf(stderr, "Failed to get root path from [%s]\n", pkgId.c_str());
+               return NI_ERROR_INVALID_PACKAGE;
        }
 
-       std::string binDir = concatPath(pkgRoot, "bin");
-       std::string libDir = concatPath(pkgRoot, "lib");
-       std::string paths = binDir + ":" + libDir;
+       __pm->setAppRootPath(rootPath);
 
-       return crossgen(dllPath, paths, enableR2R);
+       flags |= NI_FLAGS_APPNI;
+
+       // create native image under bin and lib directory
+       // tac directory is skipped in the createNIUnderDirs.
+       return createNIUnderDirs(__pm->getAppPaths(), flags);
 }
 
-void removeNiPlatform()
+void removeNIPlatform()
 {
-       std::string coreLib = concatPath(getRuntimeDir(), "System.Private.CoreLib.dll");
-       std::string coreLibBackup = concatPath(getRuntimeDir(), "System.Private.CoreLib.dll.Backup");
+       std::string coreLib = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll");
+       std::string coreLibBackup = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll.Backup");
 
-       if (!isFileExist(coreLibBackup)) {
-               return;
-       }
+       if (hasCoreLibNI()) {
+               if (!isFile(coreLibBackup)) {
+                       return;
+               }
 
-       if (remove(coreLib.c_str())) {
-               fprintf(stderr, "Failed to remove System.Private.CoreLib native image file\n");
+               if (remove(coreLib.c_str())) {
+                       fprintf(stderr, "Failed to remove System.Private.CoreLib native image file\n");
+               }
+               if (rename(coreLibBackup.c_str(), coreLib.c_str())) {
+                       fprintf(stderr, "Failed to rename System.Private.CoreLib.Backup to origin\n");
+               }
        }
 
-       if (rename(coreLibBackup.c_str(), coreLib.c_str())) {
-               fprintf(stderr, "Failed to rename System.Private.CoreLib.Backup to origin\n");
+#ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
+       if (isFile(__SYSTEM_BASE_FILE)) {
+               if (remove(__SYSTEM_BASE_FILE)) {
+                       fprintf(stderr, "Failed to remove %s\n", __SYSTEM_BASE_FILE);
+               }
        }
+#endif
 
-       const std::string platformDirs[] = {getRuntimeDir(), getTizenFXDir()};
-
-       removeNiUnderDirs(platformDirs, 2);
+       removeNIUnderDirs(__pm->getRuntimePath() + ":" + __pm->getTizenFXPath());
 }
 
-void removeNiUnderDirs(const std::string rootPaths[], int count)
+void removeNIUnderDirs(const std::string rootPaths)
 {
-       auto convert = [](const std::string& path, std::string name) {
+       auto convert = [](const std::string& path, const std::string& filename) {
                if (isNativeImage(path)) {
                        if (remove(path.c_str())) {
                                fprintf(stderr, "Failed to remove %s\n", path.c_str());
@@ -431,51 +647,154 @@ void removeNiUnderDirs(const std::string rootPaths[], int count)
                }
        };
 
-       for (int i = 0; i < count; i++)
-               scanFilesInDir(rootPaths[i], convert, -1);
+       std::vector<std::string> paths;
+       splitPath(rootPaths, paths);
+       for (const auto &path : paths) {
+               scanFilesInDirectory(path, convert, -1);
+       }
 }
 
-int removeNiUnderPkgRoot(const std::string& pkgName)
+ni_error_e removeNIUnderPkgRoot(const std::string& pkgId)
 {
-       std::string pkgRoot;
-       if (getRootPath(pkgName, pkgRoot) < 0) {
-               fprintf(stderr, "Failed to get root path from [%s]\n", pkgName.c_str());
-               return -1;
+       std::string rootPath = getRootPath(pkgId);
+       if (rootPath.empty()) {
+               fprintf(stderr, "Failed to get root path from [%s]\n", pkgId.c_str());
+               return NI_ERROR_INVALID_PACKAGE;
+       }
+
+       __pm->setAppRootPath(rootPath);
+
+       // getAppNIPaths returns bin/.native_image, lib/.native_image and .tac_symlink.
+       std::string appNIPaths = __pm->getAppNIPaths();
+       std::vector<std::string> paths;
+       splitPath(appNIPaths, paths);
+       for (const auto &path : paths) {
+               // Only the native image inside the TAC should be removed.
+               if (strstr(path.c_str(), TAC_SYMLINK_SUB_DIR) != NULL) {
+                       removeNIUnderDirs(path);
+               } else {
+                       if (isDirectory(path)) {
+                               if (!removeAll(path.c_str())) {
+                                       fprintf(stderr, "Failed to remove app ni dir [%s]\n", path.c_str());
+                               }
+                       }
+               }
        }
 
-       std::string binDir = concatPath(pkgRoot, "bin");
-       std::string libDir = concatPath(pkgRoot, "lib");
-       std::string paths[] = {binDir, libDir};
-
-       removeNiUnderDirs(paths, 2);
-
-       return 0;
+       return NI_ERROR_NONE;
 }
 
-int regenerateAppNI(bool enableR2R)
+ni_error_e regenerateAppNI(DWORD flags)
 {
+       if (!isCoreLibPrepared(flags)) {
+               return NI_ERROR_CORE_NI_FILE;
+       }
+
        int ret = 0;
        pkgmgrinfo_appinfo_metadata_filter_h handle;
 
        ret = pkgmgrinfo_appinfo_metadata_filter_create(&handle);
        if (ret != PMINFO_R_OK)
-               return -1;
+               return NI_ERROR_UNKNOWN;
 
-       ret = pkgmgrinfo_appinfo_metadata_filter_add(handle, "http://tizen.org/metadata/prefer_dotnet_aot", "true");
+       ret = pkgmgrinfo_appinfo_metadata_filter_add(handle, AOT_METADATA_KEY, METADATA_VALUE);
        if (ret != PMINFO_R_OK) {
                pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
-               return -1;
+               return NI_ERROR_UNKNOWN;
        }
 
-       ret = pkgmgrinfo_appinfo_metadata_filter_foreach(handle, appAotCb, &enableR2R);
+       ret = pkgmgrinfo_appinfo_metadata_filter_foreach(handle, appAotCb, &flags);
        if (ret != PMINFO_R_OK) {
                fprintf(stderr, "Failed pkgmgrinfo_appinfo_metadata_filter_foreach\n");
                pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
-               return -1;
+               return NI_ERROR_UNKNOWN;
        }
 
-       fprintf(stderr, "Success pkgmgrinfo_appinfo_metadata_filter_foreach\n");
+       fprintf(stdout, "Success pkgmgrinfo_appinfo_metadata_filter_foreach\n");
 
        pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
+       return NI_ERROR_NONE;
+}
+
+// callback function of "pkgmgrinfo_appinfo_metadata_filter_foreach"
+static int regenTacCb(pkgmgrinfo_appinfo_h handle, void *userData)
+{
+       char *pkgId = NULL;
+       DWORD *pFlags = (DWORD*)userData;
+
+       int ret = pkgmgrinfo_appinfo_get_pkgid(handle, &pkgId);
+       if (ret != PMINFO_R_OK || pkgId == NULL) {
+               fprintf(stderr, "Failed to get pkgid\n");
+               return -1;
+       }
+
+       sqlite3 *tac_db = dbOpen(TAC_APP_LIST_DB);
+       if (!tac_db) {
+               fprintf(stderr, "Sqlite open error\n");
+               return -1;
+       }
+
+       char *sql = sqlite3_mprintf("SELECT * FROM TAC WHERE PKGID = %Q;", pkgId);
+       std::vector<std::string> nugets = dbSelect(tac_db, TAC_APP_LIST_DB, sql);
+       sqlite3_free(sql);
+
+       if (tac_db) {
+               dbClose(tac_db);
+               tac_db = NULL;
+       }
+
+       std::string nugetPaths;
+       for (const auto &nuget : nugets) {
+               if (!nugetPaths.empty()) {
+                       nugetPaths += ":";
+               }
+               nugetPaths += concatPath(__DOTNET_DIR, nuget);
+       }
+
+       auto convert = [&nugetPaths, pFlags](const std::string& path, const std::string& filename) {
+               if (strstr(path.c_str(), TAC_SHA_256_INFO) != NULL)
+                       return;
+               if (!crossgen(path, nugetPaths.c_str(), *pFlags)) {
+                       waitInterval();
+               }
+       };
+
+       for (auto& nuget : nugets) {
+               scanFilesInDirectory(concatPath(__DOTNET_DIR, nuget), convert, -1);
+       }
+
        return 0;
 }
+
+ni_error_e regenerateTACNI(DWORD flags)
+{
+       if (!isCoreLibPrepared(flags)) {
+               return NI_ERROR_CORE_NI_FILE;
+       }
+
+       removeNIUnderDirs(__DOTNET_DIR);
+
+       pkgmgrinfo_appinfo_metadata_filter_h handle;
+       int ret = pkgmgrinfo_appinfo_metadata_filter_create(&handle);
+       if (ret != PMINFO_R_OK) {
+               return NI_ERROR_UNKNOWN;
+       }
+
+       ret = pkgmgrinfo_appinfo_metadata_filter_add(handle, TAC_METADATA_KEY, METADATA_VALUE);
+       if (ret != PMINFO_R_OK) {
+               pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
+               return NI_ERROR_UNKNOWN;
+       }
+
+       ret = pkgmgrinfo_appinfo_metadata_filter_foreach(handle, regenTacCb, &flags);
+       if (ret != PMINFO_R_OK) {
+               fprintf(stderr, "Failed pkgmgrinfo_appinfo_metadata_filter_foreach\n");
+               pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
+               return NI_ERROR_UNKNOWN;
+       }
+       fprintf(stdout, "Success pkgmgrinfo_appinfo_metadata_filter_foreach\n");
+
+       pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
+
+       return NI_ERROR_NONE;
+}