Refactoring path manager
[platform/core/dotnet/launcher.git] / NativeLauncher / tool / ni_common.cc
index 970bbb2..3f73edb 100644 (file)
@@ -65,7 +65,7 @@ static const char* __SYSTEM_BASE_FILE = __STR(SYSTEM_BASE_FILE);
 #undef __XSTR
 
 static int __interval = 0;
-static std::string __tpa;
+static PathManager* __pm = nullptr;
 
 static void waitInterval()
 {
@@ -93,7 +93,7 @@ static std::string getNIFilePath(const std::string& dllPath)
        return niPath;
 }
 
-static std::string getAppNIPath(const std::string& niPath)
+static std::string getAppNIFilePath(const std::string& niPath)
 {
        std::string fileName;
        std::string niDirPath;
@@ -145,6 +145,17 @@ static bool checkNIExistence(const std::string& path)
 }
 
 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
+static uintptr_t getFileSize(const std::string& path)
+{
+       struct stat sb;
+
+       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()
@@ -186,7 +197,7 @@ static uintptr_t getNextBaseAddr()
 }
 
 // Save base address of system ni image to file
-static void updateBaseAddrFile(const std::string &absNIPath, uintptr_t baseAddr)
+static void updateBaseAddrFile(const std::stringabsNIPath, uintptr_t baseAddr)
 {
        uintptr_t niSize = getFileSize(absNIPath);
        if (niSize == 0) {
@@ -206,12 +217,15 @@ static void updateBaseAddrFile(const std::string &absNIPath, uintptr_t baseAddr)
 }
 
 // check if dll is listed in TPA
-static bool isTPADll(const std::string &dllPath)
+static bool isTPADll(const std::stringdllPath)
 {
-       std::string absDllPath = getAbsolutePath(dllPath);
+       std::string absPath = getBaseName(getAbsolutePath(dllPath));
 
-       if (__tpa.find(absDllPath) != std::string::npos) {
-               return true;
+       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;
@@ -239,7 +253,6 @@ static ni_error_e crossgen(const std::string& dllPath, const std::string& appPat
        std::string absDllPath = getAbsolutePath(dllPath);
        std::string absNIPath = getNIFilePath(dllPath);
 
-
        if (absNIPath.empty()) {
                fprintf(stderr, "Fail to get ni file name\n");
                return NI_ERROR_UNKNOWN;
@@ -247,7 +260,7 @@ static ni_error_e crossgen(const std::string& dllPath, const std::string& appPat
 
        bool isAppNI = flags & NI_FLAGS_APPNI;
        if (isAppNI && strstr(absNIPath.c_str(), __DOTNET_DIR) == NULL) {
-               absNIPath = getAppNIPath(absNIPath);
+               absNIPath = getAppNIFilePath(absNIPath);
        }
 
 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
@@ -291,7 +304,7 @@ static ni_error_e crossgen(const std::string& dllPath, const std::string& appPat
                        }
                }
        } else {
-               std::string jitPath = getRuntimeDir() + "/libclrjit.so";
+               std::string jitPath = __pm->getRuntimePath() + "/libclrjit.so";
                std::vector<const char*> argv = {
                        __CROSSGEN_PATH,
                        "/nologo",
@@ -299,8 +312,16 @@ static ni_error_e crossgen(const std::string& dllPath, const std::string& appPat
                };
 
                bool compat = flags & NI_FLAGS_COMPATIBILITY;
-               argv.push_back(compat ? "/Trusted_Platform_Assemblies" : "/r");
-               argv.push_back(__tpa.c_str());
+               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) {
@@ -364,12 +385,6 @@ static int appAotCb(pkgmgrinfo_appinfo_h handle, void *userData)
                return -1;
        }
 
-       if (resetTACPackage(pkgId) != TAC_ERROR_NONE) {
-               fprintf(stderr, "Failed to remove symlink for given package [%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, *pFlags) != NI_ERROR_NONE) {
                fprintf(stderr, "Failed to generate NI file [%s]\n", pkgId);
                return -1;
@@ -377,13 +392,6 @@ static int appAotCb(pkgmgrinfo_appinfo_h handle, void *userData)
                fprintf(stdout, "Complete make application to native image\n");
        }
 
-       if (createTACPkgRoot(pkgId, *pFlags) != NI_ERROR_NONE) {
-               fprintf(stderr, "Failed to generate symbolic link file [%s]\n", pkgId);
-               return -1;
-       }else {
-               fprintf(stdout, "Complete make symbolic link file to tac\n");
-       }
-
        return 0;
 }
 
@@ -393,7 +401,7 @@ static bool isCoreLibPrepared(DWORD flags)
                return true;
        }
 
-       std::string coreLibBackup = concatPath(getRuntimeDir(), "System.Private.CoreLib.dll.Backup");
+       std::string coreLibBackup = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll.Backup");
        if (isFile(coreLibBackup)) {
                return true;
        } else {
@@ -404,13 +412,37 @@ static bool isCoreLibPrepared(DWORD flags)
        }
 }
 
+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(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");
+       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)) {
+       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");
@@ -428,9 +460,9 @@ static ni_error_e createCoreLibNI(DWORD flags)
        return NI_ERROR_NONE;
 }
 
-ni_error_e initNICommon(NICommonOption* option)
+ni_error_e initNICommon()
 {
-#if defined(__arm__)
+#if defined(__arm__) || defined(__aarch64__)
        // get interval value
        const static std::string intervalFile = concatPath(__NATIVE_LIB_DIR, "crossgen_interval.txt");
        std::ifstream inFile(intervalFile);
@@ -443,16 +475,22 @@ ni_error_e initNICommon(NICommonOption* option)
                fprintf(stderr, "Fail to initialize PluginManager\n");
                return NI_ERROR_UNKNOWN;
        }
-       if (initializePathManager(option->runtimeDir, option->tizenFXDir, option->extraDirs)) {
-               fprintf(stderr, "Fail to initialize PathManager\n");
+
+       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 NI_ERROR_NONE;
 #else
-       fprintf(stderr, "crossgen supports arm architecture only. skip ni file generation\n");
+       fprintf(stderr, "crossgen supports arm/arm64 architecture only. skip ni file generation\n");
        return NI_ERROR_NOT_SUPPORTED;
 #endif
 }
@@ -462,20 +500,18 @@ void finalizeNICommon()
        __interval = 0;
 
        finalizePluginManager();
-       finalizePathManager();
 
-       __tpa.clear();
+       delete(__pm);
+       __pm = nullptr;
 }
 
-
 ni_error_e createNIPlatform(DWORD flags)
 {
        if (createCoreLibNI(flags) != NI_ERROR_NONE) {
                return NI_ERROR_CORE_NI_FILE;
        }
 
-       const std::string platformDirs[] = {getRuntimeDir(), getTizenFXDir()};
-       return createNIUnderDirs(platformDirs, 2, flags);
+       return createNIUnderDirs(__pm->getRuntimePath() + ":" + __pm->getTizenFXPath(), flags);
 }
 
 ni_error_e createNIDll(const std::string& dllPath, DWORD flags)
@@ -491,207 +527,103 @@ ni_error_e createNIDll(const std::string& dllPath, DWORD flags)
        return crossgen(dllPath, std::string(), flags);
 }
 
-void createNIUnderTAC(std::vector<std::string> nugets, DWORD flags)
+ni_error_e createNIUnderDirs(const std::string rootPaths, DWORD flags)
 {
-       std::string appPaths;
-       for (auto& nuget : nugets) {
-               appPaths += concatPath(__DOTNET_DIR, nuget);
-               appPaths += ':';
-       }
-       if (appPaths.back() == ':') {
-               appPaths.pop_back();
+       if (!isCoreLibPrepared(flags)) {
+               return NI_ERROR_CORE_NI_FILE;
        }
 
-       auto convert = [&appPaths, flags](const std::string& path, const std::string& filename) {
-               if (strstr(path.c_str(), TAC_SHA_256_INFO) != NULL)
-                       return;
-               if (!crossgen(path, appPaths.c_str(), flags)) {
+       auto convert = [&rootPaths, flags](const std::string& path, const std::string& filename) {
+
+               // if path is symlink, donot generate crossgen
+               if (!crossgen(path, rootPaths.c_str(), flags)) {
                        waitInterval();
                }
        };
-       for (auto& nuget : nugets) {
-               scanFilesInDirectory(concatPath(__DOTNET_DIR, nuget), convert, -1);
-       }
-}
 
-ni_error_e createTACPkgRoot(const std::string& pkgId, DWORD flags)
-{
-       if (!isCoreLibPrepared(flags)) {
-               return NI_ERROR_CORE_NI_FILE;
-       }
+       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;
+                                       }
 
-       std::string pkgRoot;
-       if (getRootPath(pkgId, pkgRoot) < 0) {
-               fprintf(stderr, "Failed to get root path from [%s]\n", pkgId.c_str());
-               return NI_ERROR_INVALID_PACKAGE;
-       }
+                                       // 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;
+                                       }
 
-       std::string binDir = concatPath(pkgRoot, "bin");
-       std::string libDir = concatPath(pkgRoot, "lib");
-       std::string tacDir = concatPath(binDir, TAC_SYMLINK_SUB_DIR);
-       std::string binNIDir = concatPath(binDir, APP_NI_SUB_DIR);
-       std::string paths = binDir + ":" + libDir + ":" + tacDir;
-       if (bf::exists(tacDir)) {
-               try {
-                       for (auto& symlinkAssembly : bf::recursive_directory_iterator(tacDir)) {
-                               std::string symPath = symlinkAssembly.path().string();
-                               if (bf::is_symlink(symPath)) {
-                                       if (!isNativeImage(symPath)) {
-                                               std::string originPath = bf::read_symlink(symPath).string();
-                                               std::string originNIPath = originPath.substr(0, originPath.rfind(".dll")) + ".ni.dll";
-                                               if (!bf::exists(originNIPath)) {
-                                                       flags |= NI_FLAGS_APPNI;
-                                                       if(crossgen(originPath, paths, flags) != NI_ERROR_NONE) {
-                                                               fprintf(stderr, "Failed to create NI file [%s]\n", originPath.c_str());
-                                                               return NI_ERROR_UNKNOWN;
-                                                       }
-                                               }
-                                               std::string symNIPath = symPath.substr(0, symPath.rfind(".dll")) + ".ni.dll";
-                                               if (!bf::exists(symNIPath)) {
-                                                       bf::create_symlink(originNIPath, symNIPath);
-                                                       fprintf(stdout, "%s symbolic link file generated successfully.\n", symNIPath.c_str());
-                                                       copySmackAndOwnership(tacDir.c_str(), symNIPath.c_str(), true);
-
-                                                       std::string niFileName = symNIPath.substr(symNIPath.rfind('/') + 1);
-                                                       if (!removeFile(concatPath(binNIDir, niFileName))) {
-                                                               fprintf(stderr, "Failed to remove of %s\n", concatPath(binNIDir, niFileName).c_str());
-                                                       }
+                                       // 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();
                                                }
                                        }
-                               }
-                       }
-               } catch (const bf::filesystem_error& error) {
-                       fprintf(stderr, "Failed to recursive directory: %s\n", error.what());
-                       return NI_ERROR_UNKNOWN;
-               }
-       }
-       return NI_ERROR_NONE;
-}
-
-ni_error_e createNIUnderDirs(const std::string rootPaths[], int count, DWORD flags)
-{
-       if (!isCoreLibPrepared(flags)) {
-               return NI_ERROR_CORE_NI_FILE;
-       }
-
-       std::string appPaths;
-       for (int i = 0; i < count; i++) {
-               appPaths += rootPaths[i];
-               appPaths += ':';
-       }
 
-       if (appPaths.back() == ':')
-               appPaths.pop_back();
-
-       std::vector<std::string> tpaAssemblies;
-       splitPath(__tpa, tpaAssemblies);
-
-       auto convert = [&appPaths, flags, tpaAssemblies](const std::string& path, const std::string& filename) {
-               bool isAppNI = flags & NI_FLAGS_APPNI;
-               if (isAppNI) {
-                       for (auto& tpa : tpaAssemblies) {
-                               if (!strcmp(replaceAll(tpa.substr(tpa.rfind('/') + 1), ".ni.dll", ".dll").c_str(), filename.c_str())) {
-                                       fprintf(stderr, "%s present in the TPA list skips generation of NI file.\n", filename.c_str());
-                                       return;
+                                       // 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);
                }
-               if (!crossgen(path, appPaths.c_str(), flags)) {
-                       waitInterval();
-               }
-       };
-
-       for (int i = 0; i < count; i++) {
-               scanFilesInDirectory(rootPaths[i], convert, 0);
        }
 
-       tpaAssemblies.clear();
        return NI_ERROR_NONE;
 }
 
 ni_error_e createNIUnderPkgRoot(const std::string& pkgId, DWORD flags)
 {
-       std::string pkgRoot;
-       if (getRootPath(pkgId, pkgRoot) < 0) {
+       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 tacDir = concatPath(binDir, TAC_SYMLINK_SUB_DIR);
-       std::string paths[] = {binDir, libDir, tacDir};
+       __pm->setAppRootPath(rootPath);
 
        flags |= NI_FLAGS_APPNI;
-       return createNIUnderDirs(paths, 3, flags);
+
+       // create native image under bin and lib directory
+       // tac directory is skipped in the createNIUnderDirs.
+       return createNIUnderDirs(__pm->getAppPaths(), flags);
 }
 
-ni_error_e createNIDllUnderPkgRoot(const std::string& pkgId, const std::string& dllPath, DWORD flags)
+void removeNIPlatform()
 {
-       if (!isCoreLibPrepared(flags)) {
-               return NI_ERROR_CORE_NI_FILE;
-       }
+       std::string coreLib = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll");
+       std::string coreLibBackup = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll.Backup");
 
-       std::string pkgRoot;
-       if (getRootPath(pkgId, pkgRoot) < 0) {
-               fprintf(stderr, "Failed to get root path from [%s]\n", pkgId.c_str());
-               return NI_ERROR_INVALID_PACKAGE;
-       }
+       if (hasCoreLibNI()) {
+               if (!isFile(coreLibBackup)) {
+                       return;
+               }
 
-       std::string binDir = concatPath(pkgRoot, "bin");
-       std::string libDir = concatPath(pkgRoot, "lib");
-       std::string tacDir = concatPath(binDir, TAC_SYMLINK_SUB_DIR);
-       std::string binNIDir = concatPath(binDir, APP_NI_SUB_DIR);
-       std::string paths = binDir + ":" + libDir + ":" + tacDir;
-
-       if (bf::is_symlink(dllPath)) {
-               if (bf::exists(tacDir)) {
-                       if (!isNativeImage(dllPath)) {
-                               std::string originPath = bf::read_symlink(dllPath).string();
-                               std::string originNIPath = originPath.substr(0, originPath.rfind(".dll")) + ".ni.dll";
-                               if (!bf::exists(originNIPath)) {
-                                       flags |= NI_FLAGS_APPNI;
-                                       if(crossgen(originPath, paths, flags) != NI_ERROR_NONE) {
-                                               fprintf(stderr, "Failed to create NI file [%s]\n", originPath.c_str());
-                                               return NI_ERROR_UNKNOWN;
-                                       }
-                               }
-                               std::string setNIPath = dllPath.substr(0, dllPath.rfind(".dll")) + ".ni.dll";
-                               if (!bf::exists(setNIPath)) {
-                                       bf::create_symlink(originNIPath, setNIPath);
-                                       fprintf(stdout, "%s symbolic link file generated successfully.\n", setNIPath.c_str());
-                                       copySmackAndOwnership(tacDir.c_str(), setNIPath.c_str(), true);
-                               }
-                               std::string niFileName = setNIPath.substr(setNIPath.rfind('/') + 1);
-                               if (!removeFile(concatPath(binNIDir, niFileName))) {
-                                       fprintf(stderr, "Failed to remove of %s\n", concatPath(binNIDir, niFileName).c_str());
-                               }
-                       }
+               if (remove(coreLib.c_str())) {
+                       fprintf(stderr, "Failed to remove System.Private.CoreLib native image file\n");
                }
-               return NI_ERROR_NONE;
-       } else {
-               std::string assembly = dllPath.substr(dllPath.rfind('/') + 1);
-               std::vector<std::string> tpaAssemblies;
-               splitPath(__tpa, tpaAssemblies);
-               for (auto& tpa : tpaAssemblies) {
-                       if (!strcmp(replaceAll(tpa.substr(tpa.rfind('/') + 1), ".ni.dll", ".dll").c_str(), assembly.c_str())) {
-                               fprintf(stderr, "%s present in the TPA list skips generation of NI file.\n", assembly.c_str());
-                               return NI_ERROR_NONE;
-                       }
+               if (rename(coreLibBackup.c_str(), coreLib.c_str())) {
+                       fprintf(stderr, "Failed to rename System.Private.CoreLib.Backup to origin\n");
                }
-               tpaAssemblies.clear();
-               flags |= NI_FLAGS_APPNI;
-               return crossgen(dllPath, paths, flags);
-       }
-}
-
-void removeNIPlatform()
-{
-       std::string coreLib = concatPath(getRuntimeDir(), "System.Private.CoreLib.dll");
-       std::string coreLibBackup = concatPath(getRuntimeDir(), "System.Private.CoreLib.dll.Backup");
-
-       if (!isFile(coreLibBackup)) {
-               return;
        }
 
 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
@@ -702,20 +634,10 @@ void removeNIPlatform()
        }
 #endif
 
-       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");
-       }
-
-       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, const std::string& filename) {
                if (isNativeImage(path)) {
@@ -725,36 +647,37 @@ void removeNIUnderDirs(const std::string rootPaths[], int count)
                }
        };
 
-       for (int i = 0; i < count; i++) {
-               scanFilesInDirectory(rootPaths[i], convert, -1);
+       std::vector<std::string> paths;
+       splitPath(rootPaths, paths);
+       for (const auto &path : paths) {
+               scanFilesInDirectory(path, convert, -1);
        }
 }
 
 ni_error_e removeNIUnderPkgRoot(const std::string& pkgId)
 {
-       std::string pkgRoot;
-       if (getRootPath(pkgId, pkgRoot) < 0) {
+       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};
-
-       removeNIUnderDirs(paths, 2);
+       __pm->setAppRootPath(rootPath);
 
-       std::string binNIDir = concatPath(binDir, APP_NI_SUB_DIR);
-       if (isFile(binNIDir)) {
-               if (!removeAll(binNIDir.c_str())) {
-                       fprintf(stderr, "Failed to remove app ni dir [%s]\n", binNIDir.c_str());
-               }
-       }
-
-       std::string libNIDir = concatPath(libDir, APP_NI_SUB_DIR);
-       if (isFile(libNIDir)) {
-               if (!removeAll(libNIDir.c_str())) {
-                       fprintf(stderr, "Failed to remove app ni dir [%s]\n", libNIDir.c_str());
+       // 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());
+                               }
+                       }
                }
        }
 
@@ -800,7 +723,7 @@ static int regenTacCb(pkgmgrinfo_appinfo_h handle, void *userData)
        DWORD *pFlags = (DWORD*)userData;
 
        int ret = pkgmgrinfo_appinfo_get_pkgid(handle, &pkgId);
-       if (ret != PMINFO_R_OK) {
+       if (ret != PMINFO_R_OK || pkgId == NULL) {
                fprintf(stderr, "Failed to get pkgid\n");
                return -1;
        }
@@ -820,7 +743,25 @@ static int regenTacCb(pkgmgrinfo_appinfo_h handle, void *userData)
                tac_db = NULL;
        }
 
-       createNIUnderTAC(nugets, *pFlags);
+       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;
 }
@@ -831,8 +772,7 @@ ni_error_e regenerateTACNI(DWORD flags)
                return NI_ERROR_CORE_NI_FILE;
        }
 
-       const std::string tacDir[] = {__DOTNET_DIR};
-       removeNIUnderDirs(tacDir, 1);
+       removeNIUnderDirs(__DOTNET_DIR);
 
        pkgmgrinfo_appinfo_metadata_filter_h handle;
        int ret = pkgmgrinfo_appinfo_metadata_filter_create(&handle);