Fix app's native image existence checking code. (#376)
[platform/core/dotnet/launcher.git] / NativeLauncher / tool / ni_common.cc
index 5f1487e..7c146b7 100644 (file)
 #endif
 #define LOG_TAG "DOTNET_INSTALLER_PLUGIN"
 
-#ifndef CROSSGEN_PATH
-#error "CROSSGEN_PATH is missed"
-#endif
-
 #define __XSTR(x) #x
 #define __STR(x) __XSTR(x)
 #if defined(__arm__) || defined(__aarch64__)
 static const char* __NATIVE_LIB_DIR = __STR(NATIVE_LIB_DIR);
 #endif
-static const char* __CROSSGEN_PATH = __STR(CROSSGEN_PATH);
 static const char* __DOTNET_DIR = __STR(DOTNET_DIR);
 static const char* __READ_ONLY_APP_UPDATE_DIR = __STR(READ_ONLY_APP_UPDATE_DIR);
 
@@ -72,9 +67,9 @@ static const char* __SYSTEM_BASE_FILE = __STR(SYSTEM_BASE_FILE);
 #undef __STR
 #undef __XSTR
 
-static const char* CORERUN_CMD = "/usr/share/dotnet.tizen/netcoreapp/corerun";
-static const char* CROSSGEN2_PATH = "/usr/share/dotnet.tizen/netcoreapp/crossgen2/crossgen2.dll";
-static const char* CLRJIT_PATH = "/usr/share/dotnet.tizen/netcoreapp/libclrjit.so";
+static std::string CORERUN_CMD = "/usr/share/dotnet.tizen/netcoreapp/corerun";
+static std::string CROSSGEN2_PATH = "/usr/share/dotnet.tizen/netcoreapp/crossgen2/crossgen2.dll";
+static std::string CLRJIT_PATH = "/usr/share/dotnet.tizen/netcoreapp/libclrjit.so";
 static const char* CROSSGEN_OPT_JITPATH = "--jitpath";
 static const char* CROSSGEN_OPT_TARGET_ARCH = "--targetarch";
 static const char* CROSSGEN_OPT_OUT_NEAR_INPUT = "--out-near-input";
@@ -86,46 +81,25 @@ static const char* CROSSGEN_OPT_OPTIMIZE = "-O";
 static const char* CROSSGEN_OPT_INPUTBUBBLE = "--inputbubble";
 static const char* CROSSGEN_OPT_COMPILE_BUBBLE_GENERICS = "--compilebubblegenerics";
 static const char* CROSSGEN_OPT_VERBOSE = "--verbose";
-static const char* CROSSGEN_OPT_TUNING = "--tuning";
 static std::vector<std::string> REF_VECTOR;
+static std::vector<std::string> INPUTBUBBLE_REF_VECTOR;
+static std::vector<std::string> MIBC_VECTOR;
 
 static int __interval = 0;
 static PathManager* __pm = nullptr;
 
-static bool isCoreLibPrepared(DWORD flags)
-{
-       if (flags & NI_FLAGS_ENABLER2R) {
-               return true;
-       }
-
-       std::string coreLibBackup = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll.Backup");
-       if (isFile(coreLibBackup)) {
-               return true;
-       } else {
-               _SERR("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");
-               return false;
-       }
-}
+static NIOption* __ni_option = nullptr;
 
-static bool hasCoreLibNI()
+// singleton
+NIOption* getNIOption()
 {
-       std::string ildasm = concatPath(__pm->getRuntimePath(), "ildasm");
-       std::string coreLib = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll");
-       std::string cmd = ildasm + " " + coreLib + " -noil -stats | grep '.rsrc'";
-
-       FILE *fp;
-       fp = popen(cmd.c_str(), "r");
-       if (fp != NULL) {
-               char buff[1024];
-               if (fgets(buff, sizeof(buff), fp) != NULL) {
-                       pclose(fp);
-                       return false;
+       if (__ni_option == nullptr) {
+               __ni_option = (NIOption*)calloc(sizeof(NIOption), 1);
+               if (__ni_option == nullptr) {
+                       _SERR("Fail to create NIOption");
                }
-               pclose(fp);
        }
-       return true;
+       return __ni_option;
 }
 
 static void waitInterval()
@@ -137,23 +111,6 @@ static void waitInterval()
        }
 }
 
-static std::string getNIFilePath(const std::string& dllPath)
-{
-       size_t index = dllPath.find_last_of(".");
-       if (index == std::string::npos) {
-               _SERR("File doesnot contain extension. fail to get NI file name");
-               return "";
-       }
-       std::string fName = dllPath.substr(0, index);
-       std::string fExt = dllPath.substr(index, dllPath.length());
-
-       // crossgen generate file with lower case extension only
-       std::transform(fExt.begin(), fExt.end(), fExt.begin(), ::tolower);
-       std::string niPath = fName + ".ni" + fExt;
-
-       return niPath;
-}
-
 /**
  * @brief create the directory including parents directory, and
  *        copy ownership and smack labels to the created directory.
@@ -195,7 +152,24 @@ static bool createDirsAndCopyOwnerShip(std::string& target_path, const std::stri
        return true;
 }
 
-static std::string getAppNIFilePath(const std::string& absDllPath, DWORD flags)
+static std::string getNIFilePath(const std::string& dllPath)
+{
+       size_t index = dllPath.find_last_of(".");
+       if (index == std::string::npos) {
+               _SERR("File doesnot contain extension. fail to get NI file name");
+               return "";
+       }
+       std::string fName = dllPath.substr(0, index);
+       std::string fExt = dllPath.substr(index, dllPath.length());
+
+       // crossgen generate file with lower case extension only
+       std::transform(fExt.begin(), fExt.end(), fExt.begin(), ::tolower);
+       std::string niPath = fName + ".ni" + fExt;
+
+       return niPath;
+}
+
+static std::string getAppNIFilePath(const std::string& absDllPath, NIOption* opt)
 {
        std::string niDirPath;
        std::string prevPath;
@@ -203,7 +177,7 @@ static std::string getAppNIFilePath(const std::string& absDllPath, DWORD flags)
        prevPath = getBaseName(absDllPath);
        niDirPath = concatPath(prevPath, APP_NI_SUB_DIR);
 
-       if (flags & NI_FLAGS_APP_UNDER_RO_AREA) {
+       if (opt->flags & NI_FLAGS_APP_UNDER_RO_AREA) {
                niDirPath = replaceAll(niDirPath, getBaseName(__pm->getAppRootPath()), __READ_ONLY_APP_UPDATE_DIR);
                _SERR("App is installed in RO area. Change NI path to RW area(%s).", niDirPath.c_str());
                _ERR("App is installed in RO area. Change NI path to RW area(%s).", niDirPath.c_str());
@@ -233,9 +207,21 @@ static bool checkNIExistence(const std::string& absDllPath)
        // native image of System.Private.CoreLib.dll should have to overwrite
        // original file to support new coreclr
        if (absDllPath.find("System.Private.CoreLib.dll") != std::string::npos) {
-               if (hasCoreLibNI()) {
-                       return true;
-               }
+               return isR2RImage(absDllPath);
+       }
+
+       return false;
+}
+
+static bool checkAppNIExistence(const std::string& absDllPath, NIOption* opt)
+{
+       std::string absNIPath = getAppNIFilePath(absDllPath, opt);
+       if (absNIPath.empty()) {
+               return false;
+       }
+
+       if (isFile(absNIPath)) {
+               return true;
        }
 
        return false;
@@ -259,8 +245,6 @@ static bool checkDllExistInDir(const std::string& path)
  * Get the list of managed files in the specific directory
  * Absolute paths of managed files are stored at the result list.
  * If native image already exist in the same directory, managed file is ignored.
- *
- * Note: System.Private.CoreLib is excluded from the result list.
  */
 static ni_error_e getTargetDllList(const std::string& path, std::vector<std::string>& fileList)
 {
@@ -270,9 +254,7 @@ static ni_error_e getTargetDllList(const std::string& path, std::vector<std::str
 
        auto func = [&fileList](const std::string& f_path, const std::string& f_name) {
                if (isManagedAssembly(f_path) && !checkNIExistence(f_path)) {
-                       if (f_path.find("System.Private.CoreLib") == std::string::npos) {
-                               fileList.push_back(getAbsolutePath(f_path));
-                       }
+                       fileList.push_back(getAbsolutePath(f_path));
                }
        };
 
@@ -281,235 +263,40 @@ static ni_error_e getTargetDllList(const std::string& path, std::vector<std::str
        return NI_ERROR_NONE;
 }
 
-#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()
-{
-       FILE *pFile = fopen(__SYSTEM_BASE_FILE, "r");
-       if (pFile == NULL) {
-               _SERR("Failed to open %s", __SYSTEM_BASE_FILE);
-               return 0;
-       }
-
-       uintptr_t addr = 0;
-       uintptr_t size = 0;
-
-       while (fscanf(pFile, "%" SCNxPTR " %" SCNuPTR "", &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) {
-               _SERR("File %s doesn't exist", absNIPath.c_str());
-               return;
-       }
-
-       // Write new entry to the file
-       FILE *pFile = fopen(__SYSTEM_BASE_FILE, "a");
-       if (pFile == NULL) {
-               _SERR("Failed to open %s", __SYSTEM_BASE_FILE);
-               return;
-       }
-
-       fprintf(pFile, "%" PRIxPTR " %" PRIuPTR "\n", baseAddr, niSize);
-       fclose(pFile);
-}
-
-// check if dll is listed in TPA
-static bool isTPADll(const std::string& dllPath)
+/*
+ * Get the list of managed files in the specific directory of Application
+ * Absolute paths of managed files are stored at the result list.
+ * If native image already exist in the .native_image directory, managed file is ignored.
+ *
+ */
+static ni_error_e getAppTargetDllList(const std::string& path, std::vector<std::string>& fileList, NIOption *opt)
 {
-       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;
-               }
+       if (!isDirectory(path)) {
+               return NI_ERROR_INVALID_PARAMETER;
        }
 
-       return false;
-}
-#endif
-
-// baseAddr should be checked in file before getting here
-static ni_error_e crossgen(const std::string& dllPath, const std::string& appPath, DWORD flags)
-{
-       std::string absDllPath = getAbsolutePath(dllPath);
-       std::string absNIPath;
-
-       bool isAppNI = flags & NI_FLAGS_APPNI;
-       if (isAppNI && strstr(absDllPath.c_str(), __DOTNET_DIR) == NULL) {
-               absNIPath = getAppNIFilePath(absDllPath, flags);
-               if (exist(absNIPath)) {
-                       return NI_ERROR_ALREADY_EXIST;
-               }
-       } else {
-               absNIPath = getNIFilePath(absDllPath);
-               if (checkNIExistence(absDllPath)) {
-                       return NI_ERROR_ALREADY_EXIST;
+       auto func = [&fileList, opt](const std::string& f_path, const std::string& f_name) {
+               if (isManagedAssembly(f_path) && !checkAppNIExistence(f_path, opt)) {
+                       fileList.push_back(getAbsolutePath(f_path));
                }
-       }
-
-       if (absNIPath.empty()) {
-               _SERR("Fail to get ni file name");
-               return NI_ERROR_UNKNOWN;
-       }
-
-#ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
-       uintptr_t baseAddr = 0;
-
-       if (isTPADll(dllPath)) {
-               baseAddr = getNextBaseAddr();
-       }
-#endif
-
-       pid_t pid = fork();
-       if (pid == -1)
-               return NI_ERROR_UNKNOWN;
-
-       if (pid > 0) {
-               int status;
-               waitpid(pid, &status, 0);
-               if (WIFEXITED(status)) {
-                       // 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)) {
-                                               _SERR("Failed to copy a .pdb file");
-                                       } else {
-                                               copySmackAndOwnership(absPdbPath, pdbFilePath);
-                                       }
-                               }
-#ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
-                               if (baseAddr != 0) {
-                                       updateBaseAddrFile(absNIPath, baseAddr);
-                               }
-#endif
-                               return NI_ERROR_NONE;
-                       } else {
-                               _SERR("Fail to create native image for %s", dllPath.c_str());
-                               return NI_ERROR_NO_SUCH_FILE;
-                       }
-               }
-       } else {
-               std::string jitPath = __pm->getRuntimePath() + "/libclrjit.so";
-               std::vector<const char*> argv = {
-                       __CROSSGEN_PATH,
-                       "/nologo",
-                       "/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
-               std::string baseAddrString;
-               if (baseAddr != 0) {
-                       argv.push_back("/BaseAddress");
-                       std::stringstream ss;
-                       ss << "0x" << std::hex << baseAddr;
-                       baseAddrString = ss.str();
-                       argv.push_back(baseAddrString.c_str());
-               }
-#endif
-
-               argv.push_back("/App_Paths");
-               std::string absAppPath;
-               if (!appPath.empty()) {
-                       absAppPath = appPath;
-               } else {
-                       absAppPath = getBaseName(absDllPath);
-               }
-               argv.push_back(absAppPath.c_str());
-
-               argv.push_back("/out");
-               argv.push_back(absNIPath.c_str());
-
-               argv.push_back(absDllPath.c_str());
-               argv.push_back(nullptr);
-
-               _SOUT("+ %s (%s)", absDllPath.c_str(), enableR2R ? "R2R" : "FNV");
+       };
 
-               execv(__CROSSGEN_PATH, const_cast<char* const*>(argv.data()));
-               exit(0);
-       }
+       scanFilesInDirectory(path, func, 0);
 
        return NI_ERROR_NONE;
 }
 
-static void makeArgs(std::vector<const char*>& args, const std::vector<std::string>& refPaths, DWORD flags)
+static void makeArgs(std::vector<const char*>& args, const std::vector<std::string>& refPaths, NIOption* opt)
 {
-       args.push_back(CORERUN_CMD);
-       args.push_back(CROSSGEN2_PATH);
+       args.push_back(CORERUN_CMD.c_str());
+       if (CROSSGEN2_PATH != "") {
+               args.push_back(CROSSGEN2_PATH.c_str());
+       }
        args.push_back(CROSSGEN_OPT_JITPATH);
-       args.push_back(CLRJIT_PATH);
+       args.push_back(CLRJIT_PATH.c_str());
        args.push_back(CROSSGEN_OPT_TARGET_ARCH);
        args.push_back(ARCHITECTURE_IDENTIFIER);
-       if (!(flags & NI_FLAGS_NO_PIPELINE)) {
+       if (!(opt->flags & NI_FLAGS_NO_PIPELINE)) {
                args.push_back(CROSSGEN_OPT_OUT_NEAR_INPUT);
                args.push_back(CROSSGEN_OPT_SINGLE_FILE_COMPILATION);
        }
@@ -519,25 +306,58 @@ static void makeArgs(std::vector<const char*>& args, const std::vector<std::stri
 
        args.push_back(CROSSGEN_OPT_OPTIMIZE);
 
-       if (flags & NI_FLAGS_INPUT_BUBBLE) {
+       if (opt->flags & NI_FLAGS_INPUT_BUBBLE) {
                args.push_back(CROSSGEN_OPT_INPUTBUBBLE);
                args.push_back(CROSSGEN_OPT_COMPILE_BUBBLE_GENERICS);
+
+               if (opt->flags & NI_FLAGS_INPUT_BUBBLE_REF) {
+                       INPUTBUBBLE_REF_VECTOR.clear();
+                       // check inputbubbleref format.
+                       for (const auto &path : opt->inputBubbleRefPath) {
+                               if (checkDllExistInDir(path)) {
+                                       INPUTBUBBLE_REF_VECTOR.push_back("--inputbubbleref:" + path + "/*.dll");
+                               }
+                       }
+                       // add ref path to inputbubble ref
+                       for (const auto &path : refPaths) {
+                               if (checkDllExistInDir(path)) {
+                                       INPUTBUBBLE_REF_VECTOR.push_back("--inputbubbleref:" + path + "/*.dll");
+                               }
+                       }
+                       for (const auto &path : INPUTBUBBLE_REF_VECTOR) {
+                               args.push_back(path.c_str());
+                       }
+               }
        }
 
-       if (flags & NI_FLAGS_VERBOSE) {
-               args.push_back(CROSSGEN_OPT_VERBOSE);
+       if (opt->flags & NI_FLAGS_MIBC) {
+               MIBC_VECTOR.clear();
+               for (const auto &path : opt->mibcPath) {
+                       MIBC_VECTOR.push_back("--mibc:" + path);
+               }
+               for (const auto &path : MIBC_VECTOR) {
+                       args.push_back(path.c_str());
+               }
        }
 
-       if (flags & NI_FLAGS_INSTRUMENT) {
-               args.push_back(CROSSGEN_OPT_TUNING);
+       if (opt->flags & NI_FLAGS_VERBOSE) {
+               args.push_back(CROSSGEN_OPT_VERBOSE);
        }
 
        REF_VECTOR.clear();
 
        // set reference path
-       std::vector<std::string> paths = __pm->getPlatformAssembliesPaths();
-       for (const auto &path : paths) {
-               REF_VECTOR.push_back("-r:" + path + "/*.dll");
+       if (opt->flags & NI_FLAGS_REF) {
+               for (const auto &path : opt->refPath) {
+                       REF_VECTOR.push_back("-r:" + path + "/*.dll");
+               }
+       } else {
+               std::vector<std::string> paths = __pm->getPlatformAssembliesPaths();
+               for (const auto &path : paths) {
+                       if (checkDllExistInDir(path)) {
+                               REF_VECTOR.push_back("-r:" + path + "/*.dll");
+                       }
+               }
        }
 
        for (const auto &path : refPaths) {
@@ -576,7 +396,7 @@ static ni_error_e makePdbSymlinkForNI(std::string dllPath, std::string niPath)
        return NI_ERROR_NONE;
 }
 
-static ni_error_e crossgen2PipeLine(const std::vector<std::string>& dllList, const std::vector<std::string>& refPaths, DWORD flags)
+static ni_error_e crossgen2PipeLine(const std::vector<std::string>& dllList, const std::vector<std::string>& refPaths, NIOption* opt)
 {
        // fork crossgen2
        pid_t pid = fork();
@@ -597,19 +417,21 @@ static ni_error_e crossgen2PipeLine(const std::vector<std::string>& dllList, con
 
                                copySmackAndOwnership(dllPath, niPath);
                                // if AppNI then move ni.dll file to .native_image and copy pdb to .native_image
-                               if (flags & NI_FLAGS_APPNI) {
-                                       std::string appNIPath = getAppNIFilePath(dllPath, flags);
+                               if (opt->flags & NI_FLAGS_APPNI) {
+                                       std::string appNIPath = getAppNIFilePath(dllPath, opt);
                                        moveFile(niPath, appNIPath);
                                        makePdbSymlinkForNI(dllPath, appNIPath);
                                        niPath = appNIPath;
                                }
+
                                _SOUT("Native image %s generated successfully.", niPath.c_str());
                        }
+               } else {
+                       _SERR("Failed. Forked process terminated abnormally");
                }
        } else {
                std::vector<const char*> argv;
-
-               makeArgs(argv, refPaths, flags);
+               makeArgs(argv, refPaths, opt);
 
                // add input files at the end of parameter
                for (const auto &input : dllList) {
@@ -617,12 +439,16 @@ static ni_error_e crossgen2PipeLine(const std::vector<std::string>& dllList, con
                        _SOUT("+ %s", input.c_str());
                }
 
+               // end param
                argv.push_back(nullptr);
 
                // print cmd
-               //for (auto &arg: argv) _SOUT("+ %s", arg);
+               if (opt->flags & NI_FLAGS_PRINT_CMD) {
+                       _SOUT("==================== NI Commands =========================");
+                       for (auto &arg: argv) _SOUT("+ %s", arg);
+               }
 
-               execv(CORERUN_CMD, const_cast<char* const*>(argv.data()));
+               execv(CORERUN_CMD.c_str(), const_cast<char* const*>(argv.data()));
 
                clearArgs(argv);
                exit(0);
@@ -631,12 +457,12 @@ static ni_error_e crossgen2PipeLine(const std::vector<std::string>& dllList, con
        return NI_ERROR_NONE;
 }
 
-static ni_error_e crossgen2NoPipeLine(const std::vector<std::string>& dllList, const std::vector<std::string>& refPaths, DWORD flags)
+static ni_error_e crossgen2NoPipeLine(const std::vector<std::string>& dllList, const std::vector<std::string>& refPaths, NIOption* opt)
 {
        for (auto& dllPath : dllList) {
                std::string niPath;
-               if (flags & NI_FLAGS_APPNI) {
-                       niPath = getAppNIFilePath(dllPath, flags);
+               if (opt->flags & NI_FLAGS_APPNI) {
+                       niPath = getAppNIFilePath(dllPath, opt);
                } else {
                        niPath = getNIFilePath(dllPath);
                }
@@ -656,14 +482,17 @@ static ni_error_e crossgen2NoPipeLine(const std::vector<std::string>& dllList, c
                                }
 
                                copySmackAndOwnership(dllPath, niPath);
-                               if (flags & NI_FLAGS_APPNI) {
+                               if (opt->flags & NI_FLAGS_APPNI) {
                                        makePdbSymlinkForNI(dllPath, niPath);
                                }
+
                                _SOUT("Native image %s generated successfully.", niPath.c_str());
+                       } else {
+                               _SERR("Failed. Forked process terminated abnormally");
                        }
                } else {
                        std::vector<const char*> argv;
-                       makeArgs(argv, refPaths, flags);
+                       makeArgs(argv, refPaths, opt);
 
                        argv.push_back("-o");
                        argv.push_back(niPath.c_str());
@@ -675,9 +504,12 @@ static ni_error_e crossgen2NoPipeLine(const std::vector<std::string>& dllList, c
                        argv.push_back(nullptr);
 
                        // print cmd
-                       //for (auto &arg: argv) _SOUT("+ %s", arg);
+                       if (opt->flags & NI_FLAGS_PRINT_CMD) {
+                               _SOUT("==================== NI Commands =========================");
+                               for (auto &arg: argv) _SOUT("+ %s", arg);
+                       }
 
-                       execv(CORERUN_CMD, const_cast<char* const*>(argv.data()));
+                       execv(CORERUN_CMD.c_str(), const_cast<char* const*>(argv.data()));
 
                        clearArgs(argv);
                        exit(0);
@@ -689,15 +521,47 @@ static ni_error_e crossgen2NoPipeLine(const std::vector<std::string>& dllList, c
        return NI_ERROR_NONE;
 }
 
+static ni_error_e createCoreLibNI(NIOption* opt)
+{
+       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");
+
+       std::vector<std::string> dllList;
+       std::vector<std::string> refPaths;
+       dllList.push_back(getAbsolutePath(coreLib));
+
+       if (!isFile(coreLibBackup) && !isR2RImage(coreLib)) {
+               if (crossgen2NoPipeLine(dllList, refPaths, opt) == NI_ERROR_NONE && exist(niCoreLib)) {
+                       if (rename(coreLib.c_str(), coreLibBackup.c_str())) {
+                               _SERR("Failed to rename System.Private.CoreLib.dll");
+                               return NI_ERROR_CORE_NI_FILE;
+                       }
+                       if (rename(niCoreLib.c_str(), coreLib.c_str())) {
+                               _SERR("Failed to rename System.Private.CoreLib.ni.dll");
+                               return NI_ERROR_CORE_NI_FILE;
+                       }
+               } else {
+                       _SERR("Failed to create native image for %s", coreLib.c_str());
+                       return NI_ERROR_CORE_NI_FILE;
+               }
+       }
+       return NI_ERROR_NONE;
+}
 
-static ni_error_e doAOTList(std::vector<std::string>& dllList, const std::string& refPaths, DWORD flags)
+static ni_error_e doAOTList(std::vector<std::string>& dllList, const std::string& refPaths, NIOption* opt)
 {
+       ni_error_e ret = NI_ERROR_NONE;
+
        if (dllList.empty()) {
                return NI_ERROR_INVALID_PARAMETER;
        }
        // When performing AOT for one Dll, an error is returned when an error occurs.
        // However, when processing multiple dlls at once, only the log for errors is output and skipped.
 
+       std::string coreLib = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll");
+       bool hasSPC = false;
+
        for (auto it = dllList.begin(); it != dllList.end(); it++) {
                std::string f = *it;
                if (!isFile(f)) {
@@ -708,33 +572,46 @@ static ni_error_e doAOTList(std::vector<std::string>& dllList, const std::string
                        _SERR("Input file is not a dll file : %s", f.c_str());
                        dllList.erase(it--);
                }
+               // handle System.Private.CoreLib.dll separately.
+               // dllList and path manager contain absolute path. So, there is no need to change path to absolute path
+               if (f == coreLib) {
+                       hasSPC = true;
+                       dllList.erase(it--);
+               }
        }
 
-       if (!isFile(concatPath(__pm->getRuntimePath(), "crossgen"))) {
-               _SERR("crossgen1 doesnot supported. use crossgen2 forcibily");
-               flags |= NI_FLAGS_USE_CROSSGEN2;
+       // In the case of SPC, post-processing is required to change the name of the native image.
+       // In order to avoid repeatedly checking whether the generated native image is an SPC,
+       // the SPC native image generation is performed separately.
+       if (hasSPC) {
+               ret = createCoreLibNI(opt);
+               if (ret != NI_ERROR_NONE) {
+                       return ret;
+               }
        }
 
-       if (flags & NI_FLAGS_USE_CROSSGEN2) {           // crossgen2
-               std::vector<std::string> paths;
-               splitPath(refPaths, paths);
-
-               if (flags & NI_FLAGS_NO_PIPELINE) {
-                       crossgen2NoPipeLine(dllList, paths, flags);
+       // if there is no proper input after processing dll list
+       if (dllList.empty()) {
+               if (hasSPC) {
+                       return ret;
                } else {
-                       crossgen2PipeLine(dllList, paths, flags);
-               }
-       } else {                                                                        // crossgen1
-               for (auto& dll : dllList) {
-                       crossgen(dll, refPaths, flags);
-                       waitInterval();
+                       return NI_ERROR_INVALID_PARAMETER;
                }
        }
 
-       return NI_ERROR_NONE;
+       std::vector<std::string> paths;
+       splitPath(refPaths, paths);
+
+       if (opt->flags & NI_FLAGS_NO_PIPELINE) {
+               ret = crossgen2NoPipeLine(dllList, paths, opt);
+       } else {
+               ret = crossgen2PipeLine(dllList, paths, opt);
+       }
+
+       return ret;
 }
 
-static ni_error_e doAOTFile(const std::string& dllFile, const std::string& refPaths, DWORD flags)
+static ni_error_e doAOTFile(const std::string& dllFile, const std::string& refPaths, NIOption* opt)
 {
        if (!isFile(dllFile)) {
                _SERR("dll file is not exist : %s", dllFile.c_str());
@@ -746,9 +623,14 @@ static ni_error_e doAOTFile(const std::string& dllFile, const std::string& refPa
                return NI_ERROR_INVALID_PARAMETER;
        }
 
+       if (checkNIExistence(dllFile)) {
+               _SERR("Native image file is already exist : %s", dllFile.c_str());
+               return NI_ERROR_ALREADY_EXIST;
+       }
+
        std::vector<std::string> dllList;
        dllList.push_back(getAbsolutePath(dllFile));
-       return doAOTList(dllList, refPaths, flags);
+       return doAOTList(dllList, refPaths, opt);
 }
 
 // callback function of "pkgmgrinfo_appinfo_metadata_filter_foreach"
@@ -756,7 +638,7 @@ static int appAotCb(pkgmgrinfo_appinfo_h handle, void *userData)
 {
        char *pkgId = NULL;
        int ret = 0;
-       DWORD *pFlags = (DWORD*)userData;
+       NIOption **pOptions = (NIOption**)userData;
 
        ret = pkgmgrinfo_appinfo_get_pkgid(handle, &pkgId);
        if (ret != PMINFO_R_OK) {
@@ -769,7 +651,7 @@ static int appAotCb(pkgmgrinfo_appinfo_h handle, void *userData)
                return -1;
        }
 
-       if (createNIUnderPkgRoot(pkgId, *pFlags) != NI_ERROR_NONE) {
+       if (createNIUnderPkgRoot(pkgId, *pOptions) != NI_ERROR_NONE) {
                _SERR("Failed to generate NI file [%s]", pkgId);
                return -1;
        } else {
@@ -779,33 +661,18 @@ static int appAotCb(pkgmgrinfo_appinfo_h handle, void *userData)
        return 0;
 }
 
-static ni_error_e createCoreLibNI(DWORD flags)
+ni_error_e initNICommon()
 {
-       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 defined(__arm__) || defined(__aarch64__)
 
-       if (!isFile(coreLibBackup) && !hasCoreLibNI()) {
-               if (doAOTFile(coreLib, std::string(), flags) == NI_ERROR_NONE) {
-                       if (rename(coreLib.c_str(), coreLibBackup.c_str())) {
-                               _SERR("Failed to rename System.Private.CoreLib.dll");
-                               return NI_ERROR_CORE_NI_FILE;
-                       }
-                       if (rename(niCoreLib.c_str(), coreLib.c_str())) {
-                               _SERR("Failed to rename System.Private.CoreLib.ni.dll");
-                               return NI_ERROR_CORE_NI_FILE;
-                       }
-               } else {
-                       _SERR("Failed to create native image for %s", coreLib.c_str());
-                       return NI_ERROR_CORE_NI_FILE;
-               }
+       char *env = nullptr;
+       env = getenv("MIC_CROSSGEN2_ENABLED");
+       if (env != nullptr && !strcmp(env, "1")) {
+               CORERUN_CMD = std::string("/opt/usr/dotnet/mic/crossgen2");
+               CROSSGEN2_PATH = "";
+               CLRJIT_PATH = std::string("/opt/usr/dotnet/mic/libclrjit_unix_") + ARCHITECTURE_IDENTIFIER + std::string("_x64.so");
        }
-       return NI_ERROR_NONE;
-}
 
-ni_error_e initNICommon()
-{
-#if defined(__arm__) || defined(__aarch64__)
        // get interval value
        const static std::string intervalFile = concatPath(__NATIVE_LIB_DIR, "crossgen_interval.txt");
        std::ifstream inFile(intervalFile);
@@ -851,32 +718,29 @@ void finalizeNICommon()
 
        delete(__pm);
        __pm = nullptr;
+
+       if (__ni_option) {
+               free(__ni_option);
+               __ni_option = nullptr;
+       }
 }
 
-ni_error_e createNIPlatform(DWORD flags)
+ni_error_e createNIPlatform(NIOption* opt)
 {
-       ni_error_e ret = createCoreLibNI(flags);
+       ni_error_e ret = createNIUnderDirs(__pm->getRuntimePath(), opt);
        if (ret != NI_ERROR_NONE) {
                return ret;
        }
 
-       return createNIUnderDirs(__pm->getRuntimePath() + ":" + __pm->getTizenFXPath(), flags);
+       return createNIUnderDirs(__pm->getTizenFXPath(), opt);
 }
 
-ni_error_e createNIDll(const std::string& dllPath, DWORD flags)
+ni_error_e createNIDll(const std::string& dllPath, NIOption* opt)
 {
-       if (dllPath.find("System.Private.CoreLib.dll") != std::string::npos) {
-               return createCoreLibNI(flags);
-       }
-
-       if (!isCoreLibPrepared(flags)) {
-               return NI_ERROR_CORE_NI_FILE;
-       }
-
-       return doAOTFile(dllPath, std::string(), flags);
+       return doAOTFile(dllPath, std::string(), opt);
 }
 
-ni_error_e createNIUnderTAC(const std::string& targetPath, const std::string& refPaths, DWORD flags)
+ni_error_e createNIUnderTAC(const std::string& targetPath, const std::string& refPaths, NIOption* opt)
 {
        ni_error_e ret;
 
@@ -900,9 +764,9 @@ ni_error_e createNIUnderTAC(const std::string& targetPath, const std::string& re
        if (!needNIList.empty()) {
                // NI fils of TAC-related dlls under /opt/usr/dotnet should not be created under .native_image directory.
                // So, unset NI_FLAGS_APPNI temporally and restore it after running AOT.
-               flags &= ~NI_FLAGS_APPNI;
-               ret = doAOTList(needNIList, refPaths, flags);
-               flags |= NI_FLAGS_APPNI;
+               opt->flags &= ~NI_FLAGS_APPNI;
+               ret = doAOTList(needNIList, refPaths, opt);
+               opt->flags |= NI_FLAGS_APPNI;
                if (ret != NI_ERROR_NONE) {
                        return ret;
                }
@@ -924,12 +788,9 @@ ni_error_e createNIUnderTAC(const std::string& targetPath, const std::string& re
 }
 
 
-ni_error_e createNIUnderDirs(const std::string& rootPaths, DWORD flags)
+ni_error_e createNIUnderDirs(const std::string& rootPaths, NIOption* opt)
 {
        ni_error_e ret = NI_ERROR_NONE;
-       if (!isCoreLibPrepared(flags)) {
-               return NI_ERROR_CORE_NI_FILE;
-       }
 
        std::vector<std::string> fileList;
        std::vector<std::string> paths;
@@ -941,7 +802,12 @@ ni_error_e createNIUnderDirs(const std::string& rootPaths, DWORD flags)
                }
 
                if (path.find(TAC_SYMLINK_SUB_DIR) != std::string::npos) {
-                       ret = createNIUnderTAC(path, rootPaths, flags);
+                       ret = createNIUnderTAC(path, rootPaths, opt);
+                       if (ret != NI_ERROR_NONE) {
+                               return ret;
+                       }
+               } else if (opt->flags & NI_FLAGS_APPNI) {
+                       ret = getAppTargetDllList(path, fileList, opt);
                        if (ret != NI_ERROR_NONE) {
                                return ret;
                        }
@@ -957,10 +823,10 @@ ni_error_e createNIUnderDirs(const std::string& rootPaths, DWORD flags)
                return NI_ERROR_NONE;
        }
 
-       return doAOTList(fileList, rootPaths, flags);
+       return doAOTList(fileList, rootPaths, opt);
 }
 
-ni_error_e createNIUnderPkgRoot(const std::string& pkgId, DWORD flags)
+ni_error_e createNIUnderPkgRoot(const std::string& pkgId, NIOption* opt)
 {
        std::string rootPath = getRootPath(pkgId);
        if (rootPath.empty()) {
@@ -970,19 +836,24 @@ ni_error_e createNIUnderPkgRoot(const std::string& pkgId, DWORD flags)
 
        __pm->setAppRootPath(rootPath);
 
-       flags |= NI_FLAGS_APPNI;
+       char* extraDllPaths = pluginGetExtraDllPath();
+       if (extraDllPaths && extraDllPaths[0] != '\0') {
+               __pm->setExtraDllPaths(extraDllPaths);
+       }
+
+       opt->flags |= NI_FLAGS_APPNI;
 
        if (isReadOnlyArea(rootPath)) {
-               flags |= NI_FLAGS_APP_UNDER_RO_AREA;
-               flags |= NI_FLAGS_NO_PIPELINE;
+               opt->flags |= NI_FLAGS_APP_UNDER_RO_AREA;
+               opt->flags |= NI_FLAGS_NO_PIPELINE;
                _SERR("Only no-pipeline mode supported for RO app. Set no-pipeline option forcibly");
        } else {
-               flags &= ~NI_FLAGS_APP_UNDER_RO_AREA;
+               opt->flags &= ~NI_FLAGS_APP_UNDER_RO_AREA;
        }
 
        // create native image under bin and lib directory
        // tac directory is skipped in the createNIUnderDirs.
-       return createNIUnderDirs(__pm->getAppPaths(), flags);
+       return createNIUnderDirs(__pm->getAppPaths(), opt);
 }
 
 void removeNIPlatform()
@@ -990,7 +861,7 @@ void removeNIPlatform()
        std::string coreLib = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll");
        std::string coreLibBackup = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll.Backup");
 
-       if (hasCoreLibNI()) {
+       if (isR2RImage(coreLib)) {
                if (!isFile(coreLibBackup)) {
                        return;
                }
@@ -1073,12 +944,8 @@ ni_error_e removeNIUnderPkgRoot(const std::string& pkgId)
        return NI_ERROR_NONE;
 }
 
-ni_error_e regenerateAppNI(DWORD flags)
+ni_error_e regenerateAppNI(NIOption* opt)
 {
-       if (!isCoreLibPrepared(flags)) {
-               return NI_ERROR_CORE_NI_FILE;
-       }
-
        int ret = 0;
        pkgmgrinfo_appinfo_metadata_filter_h handle;
 
@@ -1092,7 +959,7 @@ ni_error_e regenerateAppNI(DWORD flags)
                return NI_ERROR_UNKNOWN;
        }
 
-       ret = pkgmgrMDFilterForeach(handle, appAotCb, &flags);
+       ret = pkgmgrMDFilterForeach(handle, appAotCb, &opt);
        if (ret != 0) {
                pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
                return NI_ERROR_UNKNOWN;
@@ -1106,7 +973,7 @@ ni_error_e regenerateAppNI(DWORD flags)
 static int regenTacCb(pkgmgrinfo_appinfo_h handle, void *userData)
 {
        char *pkgId = NULL;
-       DWORD *pFlags = (DWORD*)userData;
+       NIOption **pOpt = (NIOption**)userData;
 
        int ret = pkgmgrinfo_appinfo_get_pkgid(handle, &pkgId);
        if (ret != PMINFO_R_OK || pkgId == NULL) {
@@ -1139,18 +1006,14 @@ static int regenTacCb(pkgmgrinfo_appinfo_h handle, void *userData)
        }
 
        for (auto& nuget : nugets) {
-               createNIUnderTAC(concatPath(__DOTNET_DIR, nuget), nugetPaths, *pFlags);
+               createNIUnderTAC(concatPath(__DOTNET_DIR, nuget), nugetPaths, *pOpt);
        }
 
        return 0;
 }
 
-ni_error_e regenerateTACNI(DWORD flags)
+ni_error_e regenerateTACNI(NIOption* opt)
 {
-       if (!isCoreLibPrepared(flags)) {
-               return NI_ERROR_CORE_NI_FILE;
-       }
-
        removeNIUnderDirs(__DOTNET_DIR);
 
        pkgmgrinfo_appinfo_metadata_filter_h handle;
@@ -1165,7 +1028,7 @@ ni_error_e regenerateTACNI(DWORD flags)
                return NI_ERROR_UNKNOWN;
        }
 
-       ret = pkgmgrMDFilterForeach(handle, regenTacCb, &flags);
+       ret = pkgmgrMDFilterForeach(handle, regenTacCb, &opt);
        if (ret != 0) {
                pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
                return NI_ERROR_UNKNOWN;