6fbd70738b2f8eb82f66307cd99e987a97cce0a8
[platform/core/dotnet/launcher.git] / NativeLauncher / tool / ni_common.cc
1 /*
2  * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
3  *
4  * Licensed under the Apache License, Version 2.0 (the License);
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an AS IS BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <pkgmgr-info.h>
18 #include <pkgmgr_installer_info.h>
19 #include <aul.h>
20
21 #include "log.h"
22 #include "utils.h"
23 #include "pkgmgr_parser_plugin_interface.h"
24
25 #include <wait.h>
26 #include <dirent.h>
27 #include <sys/stat.h>
28 #include <sys/time.h>
29 #include <sys/resource.h>
30
31 #include <algorithm>
32 #include <string>
33 #include <fstream>
34 #include <sstream>
35
36 #include <grp.h>
37 #include <unistd.h>
38 #include <string.h>
39 #include <sqlite3.h>
40 #include <inttypes.h>
41 #include <errno.h>
42
43 #include "ni_common.h"
44 #include "db_manager.h"
45 #include "tac_common.h"
46 #include "path_manager.h"
47 #include "plugin_manager.h"
48 #include "r2r_checker.h"
49
50 #ifdef  LOG_TAG
51 #undef  LOG_TAG
52 #endif
53 #define LOG_TAG "DOTNET_INSTALLER_PLUGIN"
54
55 #define __XSTR(x) #x
56 #define __STR(x) __XSTR(x)
57 #if defined(__arm__) || defined(__aarch64__)
58 static const char* __NATIVE_LIB_DIR = __STR(NATIVE_LIB_DIR);
59 #endif
60 static const char* __DOTNET_DIR = __STR(DOTNET_DIR);
61 static const char* __READ_ONLY_APP_UPDATE_DIR = __STR(READ_ONLY_APP_UPDATE_DIR);
62
63 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
64 static const char* __SYSTEM_BASE_FILE = __STR(SYSTEM_BASE_FILE);
65 #endif
66
67 #undef __STR
68 #undef __XSTR
69
70 static std::string CORERUN_CMD = "/usr/share/dotnet.tizen/netcoreapp/corerun";
71 static std::string CROSSGEN2_PATH = "/usr/share/dotnet.tizen/netcoreapp/crossgen2/crossgen2.dll";
72 static std::string CLRJIT_PATH = "/usr/share/dotnet.tizen/netcoreapp/libclrjit.so";
73 static const char* CROSSGEN_OPT_JITPATH = "--jitpath";
74 static const char* CROSSGEN_OPT_TARGET_ARCH = "--targetarch";
75 static const char* CROSSGEN_OPT_OUT_NEAR_INPUT = "--out-near-input";
76 static const char* CROSSGEN_OPT_SINGLE_FILE_COMPILATION = "--single-file-compilation";
77 //static const char* CROSSGEN_OPT_PARALLELISM = "--parallelism";
78 //static const char* CROSSGEN_OPT_PARALLELISM_COUNT = "5";
79 static const char* CROSSGEN_OPT_RESILIENT = "--resilient";
80 //static const char* CROSSGEN_OPT_OPTIMIZE = "-O";
81 static const char* CROSSGEN_OPT_OPTIMIZE_TIME = "--Ot";
82 static const char* CROSSGEN_OPT_INPUTBUBBLE = "--inputbubble";
83 static const char* CROSSGEN_OPT_COMPILE_BUBBLE_GENERICS = "--compilebubblegenerics";
84 static const char* CROSSGEN_OPT_VERBOSE = "--verbose";
85 static std::vector<std::string> REF_VECTOR;
86 static std::vector<std::string> INPUTBUBBLE_REF_VECTOR;
87 static std::vector<std::string> MIBC_VECTOR;
88
89 static int __interval = 0;
90 static PathManager* __pm = nullptr;
91
92 static NIOption* __ni_option = nullptr;
93
94 // singleton
95 NIOption* getNIOption()
96 {
97         if (__ni_option == nullptr) {
98                 __ni_option = (NIOption*)calloc(sizeof(NIOption), 1);
99                 if (__ni_option == nullptr) {
100                         _SERR("Fail to create NIOption");
101                 }
102         }
103         return __ni_option;
104 }
105
106 static void waitInterval()
107 {
108         // by the recommand, ignore small value for performance.
109         if (__interval > 10000) {
110                 _SOUT("sleep %d usec", __interval);
111                 usleep(__interval);
112         }
113 }
114
115 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
116 // Get next base address to be used for system ni image from file
117 // __SYSTEM_BASE_FILE should be checked for existance before calling this function
118 static uintptr_t getNextBaseAddrFromFile()
119 {
120         FILE *pFile = fopen(__SYSTEM_BASE_FILE, "r");
121         if (pFile == NULL) {
122                 _SERR("Failed to open %s", __SYSTEM_BASE_FILE);
123                 return 0;
124         }
125
126         uintptr_t addr = 0;
127         uintptr_t size = 0;
128
129         while (fscanf(pFile, "%" SCNxPTR " %" SCNuPTR "", &addr, &size) != EOF) {
130         }
131
132         fclose(pFile);
133
134         return addr + size;
135 }
136
137 // Get next base address to be used for system ni image
138 static uintptr_t getNextBaseAddr()
139 {
140         uintptr_t baseAddr = 0;
141
142         if (!isFile(__SYSTEM_BASE_FILE)) {
143                 // This is the starting address for all default base addresses
144                 baseAddr = DEFAULT_BASE_ADDR_START;
145         } else {
146                 baseAddr = getNextBaseAddrFromFile();
147
148                 // Round to a multple of 64K (see ZapImage::CalculateZapBaseAddress in CoreCLR)
149                 uintptr_t BASE_ADDRESS_ALIGNMENT = 0xffff;
150                 baseAddr = (baseAddr + BASE_ADDRESS_ALIGNMENT) & ~BASE_ADDRESS_ALIGNMENT;
151         }
152
153         return baseAddr;
154 }
155
156 // Save base address of system ni image to file
157 static void updateBaseAddrFile(const std::string& absNIPath, uintptr_t baseAddr)
158 {
159         uintptr_t niSize = getSizeOfImage(absNIPath);
160         if (niSize == 0) {
161                 _SERR("File %s doesn't exist", absNIPath.c_str());
162                 return;
163         }
164
165         // Write new entry to the file
166         FILE *pFile = fopen(__SYSTEM_BASE_FILE, "a");
167         if (pFile == NULL) {
168                 _SERR("Failed to open %s", __SYSTEM_BASE_FILE);
169                 return;
170         }
171
172         fprintf(pFile, "%" PRIxPTR " %" PRIuPTR "\n", baseAddr, niSize);
173         fclose(pFile);
174 }
175
176 // check if dll is listed in TPA
177 static bool isTPADll(const std::string& dllPath)
178 {
179         std::string absPath = getBaseName(getAbsolutePath(dllPath));
180
181         std::vector<std::string> paths = __pm->getPlatformAssembliesPaths();
182         for (unsigned int i = 0; i < paths.size(); i++) {
183                 if (paths[i].find(getBaseName(absPath)) != std::string::npos) {
184                         return true;
185                 }
186         }
187
188         return false;
189 }
190 #endif
191
192 /**
193  * @brief create the directory including parents directory, and
194  *          copy ownership and smack labels to the created directory.
195  * @param[in] target directory path
196  * @param[in] source directory path to get ownership and smack label
197  * @return if directory created successfully, return true otherwise false
198  */
199 static bool createDirsAndCopyOwnerShip(std::string& target_path, const std::string& source)
200 {
201         struct stat st;
202         mode_t mode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
203
204         for (std::string::iterator iter = target_path.begin(); iter != target_path.end();) {
205                 std::string::iterator newIter = std::find(iter, target_path.end(), '/');
206                 std::string newPath = std::string(target_path.begin(), newIter);
207
208                 if (!newPath.empty()) {
209                         if (stat(newPath.c_str(), &st) != 0) {
210                                 if (mkdir(newPath.c_str(), mode) != 0 && errno != EEXIST) {
211                                         _SERR("Fail to create app ni directory (%s)", newPath.c_str());
212                                         return false;
213                                 }
214                                 if (!source.empty()) {
215                                         copySmackAndOwnership(source, newPath);
216                                 }
217                         } else {
218                                 if (!S_ISDIR(st.st_mode)) {
219                                         _SERR("Fail. path is not a dir (%s)", newPath.c_str());
220                                         return false;
221                                 }
222                         }
223                 }
224                 iter = newIter;
225                 if(newIter != target_path.end()) {
226                         ++iter;
227                 }
228         }
229
230         return true;
231 }
232
233 static std::string getNIFilePath(const std::string& dllPath)
234 {
235         size_t index = dllPath.find_last_of(".");
236         if (index == std::string::npos) {
237                 _SERR("File doesnot contain extension. fail to get NI file name");
238                 return "";
239         }
240         std::string fName = dllPath.substr(0, index);
241         std::string fExt = dllPath.substr(index, dllPath.length());
242
243         // crossgen generate file with lower case extension only
244         std::transform(fExt.begin(), fExt.end(), fExt.begin(), ::tolower);
245         std::string niPath = fName + ".ni" + fExt;
246
247         return niPath;
248 }
249
250 static std::string getAppNIFilePath(const std::string& absDllPath, NIOption* opt)
251 {
252         std::string niDirPath;
253         std::string prevPath;
254
255         prevPath = getBaseName(absDllPath);
256         niDirPath = concatPath(prevPath, APP_NI_SUB_TMP_DIR);
257
258         if (opt->flags & NI_FLAGS_APP_UNDER_RO_AREA) {
259                 niDirPath = replaceAll(niDirPath, getBaseName(__pm->getAppRootPath()), __READ_ONLY_APP_UPDATE_DIR);
260                 _SERR("App is installed in RO area. Change NI path to RW area(%s).", niDirPath.c_str());
261                 _ERR("App is installed in RO area. Change NI path to RW area(%s).", niDirPath.c_str());
262         }
263
264         if (!isDirectory(niDirPath)) {
265                 if (!createDirsAndCopyOwnerShip(niDirPath, prevPath)) {
266                         niDirPath = prevPath;
267                         _SERR("fail to create dir (%s)", niDirPath.c_str());
268                 }
269         }
270
271         return getNIFilePath(concatPath(niDirPath, getFileName(absDllPath)));
272 }
273
274 static bool checkNIExistence(const std::string& absDllPath)
275 {
276         std::string absNIPath = getNIFilePath(absDllPath);
277         if (absNIPath.empty()) {
278                 return false;
279         }
280
281         if (isFile(absNIPath)) {
282                 return true;
283         }
284
285         // native image of System.Private.CoreLib.dll should have to overwrite
286         // original file to support new coreclr
287         if (absDllPath.find("System.Private.CoreLib.dll") != std::string::npos) {
288                 return isR2RImage(absDllPath);
289         }
290
291         return false;
292 }
293
294 static bool checkAppNIExistence(const std::string& absDllPath, NIOption* opt)
295 {
296         std::string absNIPath = getAppNIFilePath(absDllPath, opt);
297         if (absNIPath.empty()) {
298                 return false;
299         }
300
301         if (isFile(absNIPath)) {
302                 return true;
303         }
304
305         return false;
306 }
307
308 static bool checkDllExistInDir(const std::string& path)
309 {
310         bool ret = false;
311         auto func = [&ret](const std::string& f_path, const std::string& f_name) {
312                 if (isManagedAssembly(f_name) || isNativeImage(f_name)) {
313                         ret = true;
314                 }
315         };
316
317         scanFilesInDirectory(path, func, 0);
318
319         return ret;
320 }
321
322 /*
323  * Get the list of managed files in the specific directory
324  * Absolute paths of managed files are stored at the result list.
325  * If native image already exist in the same directory, managed file is ignored.
326  */
327 static ni_error_e getTargetDllList(const std::string& path, std::vector<std::string>& fileList)
328 {
329         if (!isDirectory(path)) {
330                 return NI_ERROR_INVALID_PARAMETER;
331         }
332
333         auto func = [&fileList](const std::string& f_path, const std::string& f_name) {
334                 if (isManagedAssembly(f_path) && !checkNIExistence(f_path)) {
335                         fileList.push_back(getAbsolutePath(f_path));
336                 }
337         };
338
339         scanFilesInDirectory(path, func, 0);
340
341         return NI_ERROR_NONE;
342 }
343
344 /*
345  * Get the list of managed files in the specific directory of Application
346  * Absolute paths of managed files are stored at the result list.
347  * If native image already exist in the .native_image directory, managed file is ignored.
348  *
349  */
350 static ni_error_e getAppTargetDllList(const std::string& path, std::vector<std::string>& fileList, NIOption *opt)
351 {
352         if (!isDirectory(path)) {
353                 return NI_ERROR_INVALID_PARAMETER;
354         }
355
356         auto func = [&fileList, opt](const std::string& f_path, const std::string& f_name) {
357                 if (isManagedAssembly(f_path) && !checkAppNIExistence(f_path, opt)) {
358                         fileList.push_back(getAbsolutePath(f_path));
359                 }
360         };
361
362         scanFilesInDirectory(path, func, 0);
363
364         return NI_ERROR_NONE;
365 }
366
367 static void makeArgs(std::vector<const char*>& args, const std::vector<std::string>& refPaths, NIOption* opt)
368 {
369         args.push_back(CORERUN_CMD.c_str());
370         if (CROSSGEN2_PATH != "") {
371                 args.push_back(CROSSGEN2_PATH.c_str());
372         }
373         args.push_back(CROSSGEN_OPT_JITPATH);
374         args.push_back(CLRJIT_PATH.c_str());
375         args.push_back(CROSSGEN_OPT_TARGET_ARCH);
376         args.push_back(ARCHITECTURE_IDENTIFIER);
377
378         //args.push_back(OPT_PARALLELISM);
379         //args.push_back(OPT_PARALLELISM_COUNT);
380         args.push_back(CROSSGEN_OPT_RESILIENT);
381
382         args.push_back(CROSSGEN_OPT_OPTIMIZE_TIME);
383
384         if (opt->flags & NI_FLAGS_INPUT_BUBBLE) {
385                 args.push_back(CROSSGEN_OPT_INPUTBUBBLE);
386                 args.push_back(CROSSGEN_OPT_COMPILE_BUBBLE_GENERICS);
387
388                 INPUTBUBBLE_REF_VECTOR.clear();
389                 for (const auto &path : opt->inputBubbleRefFiles) {
390                         INPUTBUBBLE_REF_VECTOR.push_back("--inputbubbleref:" + path);
391                 }
392                 for (const auto &path : INPUTBUBBLE_REF_VECTOR) {
393                         if (find(args.begin(), args.end(), path) == args.end()) {
394                                 args.push_back(path.c_str());
395                         }
396                 }
397         }
398
399         if (opt->flags & NI_FLAGS_MIBC) {
400                 MIBC_VECTOR.clear();
401                 for (const auto &path : opt->mibcPath) {
402                         MIBC_VECTOR.push_back("--mibc:" + path);
403                 }
404                 for (const auto &path : MIBC_VECTOR) {
405                         if (find(args.begin(), args.end(), path) == args.end()) {
406                                 args.push_back(path.c_str());
407                         }
408                 }
409         }
410
411         if (opt->flags & NI_FLAGS_VERBOSE) {
412                 args.push_back(CROSSGEN_OPT_VERBOSE);
413         }
414
415         REF_VECTOR.clear();
416
417         // set reference path
418         for (const auto &path : opt->refFiles) {
419                 REF_VECTOR.push_back("-r:" + path);
420         }
421
422         std::vector<std::string> paths = __pm->getPlatformAssembliesPaths();
423         for (const auto &path : paths) {
424                 if (checkDllExistInDir(path)) {
425                         REF_VECTOR.push_back("-r:" + path + "/*.dll");
426                 }
427         }
428
429         if (opt->flags & NI_FLAGS_EXTRA_REF) {
430                 for (const auto &erPath : opt->extraRefPath) {
431                         std::string path = getAbsolutePath(erPath);
432                         if (checkDllExistInDir(path)) {
433                                 REF_VECTOR.push_back("-r:" + path + "/*.dll");
434                         }
435                 }
436         }
437
438         for (const auto &path : refPaths) {
439                 if (checkDllExistInDir(path)) {
440                         REF_VECTOR.push_back("-r:" + path + "/*.dll");
441                 }
442         }
443
444         for (const auto &path : REF_VECTOR) {
445                 if (find(args.begin(), args.end(), path) == args.end()) {
446                         args.push_back(path.c_str());
447                 }
448         }
449 }
450
451 static void clearArgs(std::vector<const char*>& args)
452 {
453         REF_VECTOR.clear();
454         args.clear();
455 }
456
457 static ni_error_e makePdbSymlinkForNI(std::string dllPath, std::string niPath)
458 {
459         std::string pdbPath = changeExtension(dllPath, ".dll", ".pdb");
460         try {
461                 if (exist(pdbPath)) {
462                         std::string targetPDBPath = changeExtension(niPath, ".ni.dll", ".pdb");
463                         if (!exist(targetPDBPath)) {
464                                 bf::create_symlink(pdbPath, targetPDBPath);
465                                 copySmackAndOwnership(pdbPath, targetPDBPath, true);
466                         }
467                 }
468         } catch (const bf::filesystem_error& error) {
469                 _SERR("Fail to create symlink for %s", pdbPath.c_str());
470                 return NI_ERROR_UNKNOWN;
471         }
472
473         return NI_ERROR_NONE;
474 }
475
476 static ni_error_e crossgen2PostAction(const std::string& dllPath, const std::string& niPath, NIOption* opt) {
477         std::string outFile = niPath;
478         if (!exist(outFile)) {
479                 return NI_ERROR_NO_SUCH_FILE;
480         }
481         copySmackAndOwnership(dllPath, outFile);
482
483         // if AppNI then move ni.dll file to .native_image and copy pdb to .native_image
484         if (opt->flags & NI_FLAGS_APPNI) {
485                 outFile = getAppNIFilePath(dllPath, opt);
486                 makePdbSymlinkForNI(dllPath, outFile);
487
488                 if (opt->flags & NI_FLAGS_INPUT_BUBBLE && opt->flags & NI_FLAGS_NO_PIPELINE) {
489                         outFile = outFile + ".tmp";
490                 }
491
492                 if (niPath != outFile) {
493                         moveFile(niPath, outFile);
494                 }
495         }
496
497         if (opt->flags & NI_FLAGS_RM_ORIGIN_AFTER_NI) {
498                 if (!removeFile(dllPath)) {
499                         _SERR("Fail to remove original file : %s", dllPath.c_str());
500                 }
501         }
502
503         if (!(opt->flags & NI_FLAGS_INPUT_BUBBLE && opt->flags & NI_FLAGS_NO_PIPELINE)) {
504                 _SOUT("Native image %s generated successfully.", outFile.c_str());
505         }
506
507         return NI_ERROR_NONE;
508 }
509
510 void setPriority(NIOption* opt)
511 {
512         pid_t pid = getpid();
513         if (setpriority(PRIO_PROCESS, pid, opt->priority) == 0) {
514                 std::string str = " ";
515                 if (opt->priority <= -20) {
516                         str = " highest ";
517                 } else if (opt->priority >= 19) {
518                         str = " lowest ";
519                 }
520                 _SOUT("Success to set the%spriority of the process. pid : [%d], priority : [%d]", str.c_str(), pid, getpriority(PRIO_PROCESS, pid));
521         } else {
522                 _SERR("Failed to set the priority of the process. pid : [%d], priority : [%d]", pid, getpriority(PRIO_PROCESS, pid));
523         }
524 }
525
526 static ni_error_e crossgen2PipeLine(const std::vector<std::string>& dllList, const std::vector<std::string>& refPaths, NIOption* opt)
527 {
528         // fork crossgen2
529         pid_t pid = fork();
530         if (pid == -1)
531                 return NI_ERROR_UNKNOWN;
532
533         if (pid > 0) {
534                 int status;
535                 waitpid(pid, &status, 0);
536                 if (WIFEXITED(status)) {
537                         for (auto& dllPath: dllList) {
538                                 ni_error_e ret = crossgen2PostAction(dllPath, changeExtension(dllPath, ".dll", ".ni.dll"), opt);
539                                 if (ret != NI_ERROR_NONE) {
540                                         return ret;
541                                 }
542                         }
543                 } else {
544                         _SERR("Failed. Forked process terminated abnormally");
545                         return NI_ERROR_ABNORMAL_PROCESS_TERMINATION;
546                 }
547         } else {
548                 if (opt->flags & NI_FLAGS_SET_PRIORITY) {
549                         setPriority(opt);
550                 }
551                 std::vector<const char*> argv;
552                 makeArgs(argv, refPaths, opt);
553                 argv.push_back(CROSSGEN_OPT_OUT_NEAR_INPUT);
554                 argv.push_back(CROSSGEN_OPT_SINGLE_FILE_COMPILATION);
555
556                 // add input files at the end of parameter
557                 for (const auto &input : dllList) {
558                         argv.push_back(input.c_str());
559                         _SOUT("+ %s", input.c_str());
560                 }
561
562                 // end param
563                 argv.push_back(nullptr);
564
565                 // print cmd
566                 if (opt->flags & NI_FLAGS_PRINT_CMD) {
567                         _SOUT("==================== NI Commands =========================");
568                         for (auto &arg: argv) _SOUT("+ %s", arg);
569                 }
570
571                 execv(CORERUN_CMD.c_str(), const_cast<char* const*>(argv.data()));
572
573                 clearArgs(argv);
574                 exit(0);
575         }
576
577         return NI_ERROR_NONE;
578 }
579
580 static ni_error_e crossgen2NoPipeLine(const std::vector<std::string>& dllList, const std::vector<std::string>& refPaths, NIOption* opt)
581 {
582         for (auto& dllPath : dllList) {
583                 std::string niPath;
584                 if (opt->flags & NI_FLAGS_APPNI) {
585                         niPath = getAppNIFilePath(dllPath, opt);
586                 } else {
587                         niPath = getNIFilePath(dllPath);
588                 }
589 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
590                 uintptr_t baseAddr = 0;
591                 if (isTPADll(dllPath)) {
592                         baseAddr = getNextBaseAddr();
593                 }
594 #endif
595                 if (opt->flags & NI_FLAGS_INPUT_BUBBLE) {
596                         niPath += ".tmp";
597                 }
598
599                 // fork crossgen2
600                 pid_t pid = fork();
601                 if (pid == -1)
602                         return NI_ERROR_UNKNOWN;
603
604                 if (pid > 0) {
605                         int status;
606                         waitpid(pid, &status, 0);
607                         if (WIFEXITED(status)) {
608                                 ni_error_e ret = crossgen2PostAction(dllPath, niPath, opt);
609                                 if (ret != NI_ERROR_NONE) {
610                                         return ret;
611                                 }
612 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
613                                 if (baseAddr != 0) {
614                                         updateBaseAddrFile(niPath, baseAddr);
615                                 }
616 #endif
617                         } else {
618                                 _SERR("Failed. Forked process terminated abnormally");
619                                 _SERR("Crossgen2 was terminated by the OOM killer. Please check the system.");
620                                 removeFile(changeExtension(niPath, ".ni.dll", ".ni.dll.tmp"));
621                                 return NI_ERROR_ABNORMAL_PROCESS_TERMINATION;
622                         }
623                 } else {
624                         if (opt->flags & NI_FLAGS_SET_PRIORITY) {
625                                 setPriority(opt);
626                         }
627                         std::vector<const char*> argv;
628                         makeArgs(argv, refPaths, opt);
629
630 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
631                         std::string baseAddrString;
632                         if (baseAddr != 0) {
633                                 argv.push_back("--imagebase");
634                                 std::stringstream ss;
635                                 ss << "0x" << std::hex << baseAddr;
636                                 baseAddrString = ss.str();
637                                 argv.push_back(baseAddrString.c_str());
638                         }
639 #endif
640                         argv.push_back("-o");
641                         argv.push_back(niPath.c_str());
642
643                         argv.push_back(dllPath.c_str());
644                         _SOUT("+ %s", dllPath.c_str());
645
646                         // end param
647                         argv.push_back(nullptr);
648
649                         // print cmd
650                         if (opt->flags & NI_FLAGS_PRINT_CMD) {
651                                 _SOUT("==================== NI Commands =========================");
652                                 for (auto &arg: argv) _SOUT("+ %s", arg);
653                         }
654
655                         execv(CORERUN_CMD.c_str(), const_cast<char* const*>(argv.data()));
656
657                         clearArgs(argv);
658                         exit(0);
659                 }
660
661                 waitInterval();
662         }
663
664         return NI_ERROR_NONE;
665 }
666
667 static ni_error_e createCoreLibNI(NIOption* opt)
668 {
669         std::string coreLib = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll");
670         std::string niCoreLib = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.ni.dll");
671         std::string niTmpCoreLib = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.ni.dll.tmp");
672         std::string coreLibBackup = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll.Backup");
673
674         std::vector<std::string> dllList;
675         std::vector<std::string> refPaths;
676         dllList.push_back(getAbsolutePath(coreLib));
677
678         if (!isFile(coreLibBackup) && !isR2RImage(coreLib)) {
679                 if (crossgen2NoPipeLine(dllList, refPaths, opt) == NI_ERROR_NONE) {
680                         if (opt->flags & NI_FLAGS_RM_ORIGIN_AFTER_NI) {
681                                 std::ofstream output(coreLibBackup);
682                                 if (!exist(coreLibBackup)) {
683                                         _SERR("Failed to create System.Private.CoreLib.dll.Backup");
684                                         return NI_ERROR_CORE_NI_FILE;
685                                 }
686                                 copySmackAndOwnership(__pm->getRuntimePath(), coreLibBackup, false);
687                                 output.close();
688                         } else if (rename(coreLib.c_str(), coreLibBackup.c_str())) {
689                                 _SERR("Failed to rename from System.Private.CoreLib.dll to System.Private.CoreLib.dll.Backup");
690                                 return NI_ERROR_CORE_NI_FILE;
691                         }
692                         if (opt->flags & NI_FLAGS_INPUT_BUBBLE) {
693                                 if (rename(niTmpCoreLib.c_str(), coreLib.c_str())) {
694                                         _SERR("Failed to rename from System.Private.CoreLib.ni.dll.tmp to Private.CoreLib.dll");
695                                         return NI_ERROR_CORE_NI_FILE;
696                                 }
697                         } else {
698                                 if (rename(niCoreLib.c_str(), coreLib.c_str())) {
699                                         _SERR("Failed to rename from System.Private.CoreLib.ni.dll to Private.CoreLib.dll");
700                                         return NI_ERROR_CORE_NI_FILE;
701                                 }
702                         }
703                 } else {
704                         _SERR("Failed to create native image for %s", coreLib.c_str());
705                         return NI_ERROR_CORE_NI_FILE;
706                 }
707         }
708         return NI_ERROR_NONE;
709 }
710
711 static void renameAppNITmpPath(NIOption* opt)
712 {
713         std::string niTmpPath = __pm->getAppRootPath() + "/bin/" + APP_NI_SUB_TMP_DIR;
714         std::string niPath = __pm->getAppRootPath() + "/bin/" + APP_NI_SUB_DIR;
715
716         if (opt->flags & NI_FLAGS_APP_UNDER_RO_AREA) {
717                 niTmpPath = replaceAll(niTmpPath, getBaseName(__pm->getAppRootPath()), __READ_ONLY_APP_UPDATE_DIR);
718                 niPath = replaceAll(niPath, getBaseName(__pm->getAppRootPath()), __READ_ONLY_APP_UPDATE_DIR);
719         }
720
721         if (isDirectory(niTmpPath)) {
722                 if (rename(niTmpPath.c_str(), niPath.c_str())) {
723                         _SERR("Fail to rename from .native_image_tmp to .native_image");
724                 }
725         }
726 }
727
728 static ni_error_e doAOTList(std::vector<std::string>& dllList, const std::string& refPaths, NIOption* opt)
729 {
730         ni_error_e ret = NI_ERROR_NONE;
731
732         if (dllList.empty()) {
733                 return NI_ERROR_INVALID_PARAMETER;
734         }
735         // When performing AOT for one Dll, an error is returned when an error occurs.
736         // However, when processing multiple dlls at once, only the log for errors is output and skipped.
737
738         std::string coreLib = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll");
739         bool hasSPC = false;
740
741         for (auto it = dllList.begin(); it != dllList.end(); it++) {
742                 std::string f = *it;
743                 if (!isFile(f)) {
744                         _SERR("dll file is not exist : %s", f.c_str());
745                         dllList.erase(it--);
746                 }
747                 else if (!isManagedAssembly(f)) {
748                         _SERR("Input file is not a dll file : %s", f.c_str());
749                         dllList.erase(it--);
750                 }
751                 // handle System.Private.CoreLib.dll separately.
752                 // dllList and path manager contain absolute path. So, there is no need to change path to absolute path
753                 else if (f == coreLib) {
754                         hasSPC = true;
755                         dllList.erase(it--);
756                 }
757         }
758
759         // Error : Multiple input files matching same simple name
760         // So, Remove dulicate files from dll list
761         dllList.erase(unique(dllList.begin(), dllList.end()), dllList.end());
762
763         // In the case of SPC, post-processing is required to change the name of the native image.
764         // In order to avoid repeatedly checking whether the generated native image is an SPC,
765         // the SPC native image generation is performed separately.
766         if (hasSPC) {
767                 ret = createCoreLibNI(opt);
768                 if (ret != NI_ERROR_NONE) {
769                         return ret;
770                 }
771         }
772
773         // if there is no proper input after processing dll list
774         if (dllList.empty()) {
775                 if (hasSPC) {
776                         return ret;
777                 } else {
778                         return NI_ERROR_INVALID_PARAMETER;
779                 }
780         }
781
782         std::vector<std::string> paths;
783         splitPath(refPaths, paths);
784
785         if (opt->flags & NI_FLAGS_NO_PIPELINE) {
786                 ret = crossgen2NoPipeLine(dllList, paths, opt);
787         } else {
788                 std::vector<std::string> notCompiled;
789                 ret = crossgen2PipeLine(dllList, paths, opt);
790                 if (ret != NI_ERROR_NONE) {
791                         _SERR("Crossgen2 is abnormally terminated. Regenerate native images that failed while running crossgen2.");
792                         for (auto &dll : dllList) {
793                                 std::string tFile = changeExtension(dll, ".dll", ".ni.dll");
794                                 if (opt->flags & NI_FLAGS_INPUT_BUBBLE) {
795                                         tFile += ".tmp";
796                                 }
797                                 if (!exist(tFile)) {
798                                         notCompiled.push_back(dll);
799                                 }
800                         }
801                         _SERR("Retry running crossgen2 with --no-pipeline mode to avoid termination by OOM.");
802                         ret = crossgen2NoPipeLine(notCompiled, paths, opt);
803                 }
804         }
805
806         if (ret == NI_ERROR_NONE) {
807                 if (opt->flags & NI_FLAGS_INPUT_BUBBLE) {
808                         for (auto &dll : dllList) {
809                                 std::string tmpFile;
810                                 std::string niFile;
811                                 if (opt->flags & NI_FLAGS_APPNI) {
812                                         niFile = getAppNIFilePath(dll, opt);
813                                 } else {
814                                         niFile = getNIFilePath(dll);
815                                 }
816                                 tmpFile = niFile + ".tmp";
817
818                                 if (exist(tmpFile)) {
819                                         moveFile(tmpFile, niFile);
820                                         _SOUT("Native image %s generated successfully.", niFile.c_str());
821                                 }
822                         }
823                 }
824                 if (opt->flags & NI_FLAGS_APPNI) {
825                         renameAppNITmpPath(opt);
826                 }
827         }
828
829         return ret;
830 }
831
832 static ni_error_e doAOTFile(const std::string& dllFile, const std::string& refPaths, NIOption* opt)
833 {
834         if (!isFile(dllFile)) {
835                 _SERR("dll file is not exist : %s", dllFile.c_str());
836                 return NI_ERROR_NO_SUCH_FILE;
837         }
838
839         if (!isManagedAssembly(dllFile)) {
840                 _SERR("Failed. Input parameter is not managed dll (%s)\n", dllFile.c_str());
841                 return NI_ERROR_INVALID_PARAMETER;
842         }
843
844         if (checkNIExistence(dllFile)) {
845                 _SERR("Native image file is already exist : %s", dllFile.c_str());
846                 return NI_ERROR_ALREADY_EXIST;
847         }
848
849         std::vector<std::string> dllList;
850         dllList.push_back(getAbsolutePath(dllFile));
851         return doAOTList(dllList, refPaths, opt);
852 }
853
854 // callback function of "pkgmgrinfo_appinfo_metadata_filter_foreach"
855 static int appAotCb(pkgmgrinfo_appinfo_h handle, void *userData)
856 {
857         char *pkgId = NULL;
858         int ret = 0;
859         NIOption **pOptions = (NIOption**)userData;
860
861         if ((*pOptions)->flags & NI_FLAGS_SKIP_RO_APP) {
862                 bool isSystem = false;
863                 int ret = pkgmgrinfo_appinfo_is_system(handle, &isSystem);
864                 if (ret != PMINFO_R_OK) {
865                         _SERR("Failed to check that app is System or not\n");
866                         return -1;
867                 }
868                 if (isSystem) {
869                         return 0;
870                 }
871         }
872
873         ret = pkgmgrinfo_appinfo_get_pkgid(handle, &pkgId);
874         if (ret != PMINFO_R_OK) {
875                 _SERR("Failed to get pkgid");
876                 return -1;
877         }
878
879         if (removeNIUnderPkgRoot(pkgId) != NI_ERROR_NONE) {
880                 _SERR("Failed to remove previous dlls from [%s]", pkgId);
881                 return -1;
882         }
883
884         if (createNIUnderPkgRoot(pkgId, *pOptions) != NI_ERROR_NONE) {
885                 _SERR("Failed to generate NI file [%s]", pkgId);
886                 return -1;
887         } else {
888                 _SOUT("Complete make application to native image");
889         }
890
891         return 0;
892 }
893
894 ni_error_e initNICommon()
895 {
896 #if defined(__arm__) || defined(__aarch64__)
897
898         char *env = nullptr;
899         env = getenv("MIC_CROSSGEN2_ENABLED");
900         if (env != nullptr && !strcmp(env, "1")) {
901                 CORERUN_CMD = std::string("/opt/usr/dotnet/mic/crossgen2");
902                 CROSSGEN2_PATH = "";
903                 CLRJIT_PATH = std::string("/opt/usr/dotnet/mic/libclrjit_unix_") + ARCHITECTURE_IDENTIFIER + std::string("_x64.so");
904         }
905
906         // get interval value
907         const static std::string intervalFile = concatPath(__NATIVE_LIB_DIR, "crossgen_interval.txt");
908         std::ifstream inFile(intervalFile);
909         if (inFile) {
910                 _SOUT("crossgen_interval.txt is found");
911                 inFile >> __interval;
912         }
913
914         if (initializePluginManager("normal")) {
915                 _SERR("Fail to initialize PluginManager");
916                 return NI_ERROR_UNKNOWN;
917         }
918
919         try {
920                 __pm = new PathManager();
921         } catch (const std::exception& e) {
922                 _SERR("Failed to create PathManager");
923                 return NI_ERROR_UNKNOWN;
924         }
925
926         char* pluginDllPaths = pluginGetDllPath();
927         if (pluginDllPaths && pluginDllPaths[0] != '\0') {
928                 __pm->addPlatformAssembliesPaths(pluginDllPaths, true);
929         }
930
931         char* pluginNativePaths = pluginGetNativeDllSearchingPath();
932         if (pluginNativePaths && pluginNativePaths[0] != '\0') {
933                 __pm->addNativeDllSearchingPaths(pluginNativePaths, true);
934         }
935
936         return NI_ERROR_NONE;
937 #else
938         _SERR("crossgen supports arm/arm64 architecture only. skip ni file generation");
939         return NI_ERROR_NOT_SUPPORTED;
940 #endif
941 }
942
943 void finalizeNICommon()
944 {
945         __interval = 0;
946
947         finalizePluginManager();
948
949         delete(__pm);
950         __pm = nullptr;
951
952         if (__ni_option) {
953                 free(__ni_option);
954                 __ni_option = nullptr;
955         }
956 }
957
958 ni_error_e createNIPlatform(std::string& extraInputs, NIOption* opt)
959 {
960         extraInputs += ":" + __pm->getRuntimePath();
961         extraInputs += ":" + __pm->getTizenFXPath();
962
963         return createNIUnderDirs(extraInputs, opt);
964 }
965
966 ni_error_e createNIDll(const std::string& dllPath, NIOption* opt)
967 {
968         return doAOTFile(dllPath, std::string(), opt);
969 }
970
971 ni_error_e createNIUnderTAC(const std::string& targetPath, const std::string& refPaths, NIOption* opt)
972 {
973         ni_error_e ret;
974
975         bool isAppNI = false;
976         if (opt->flags & NI_FLAGS_APPNI) {
977                 isAppNI = true;
978         }
979
980         if (opt->flags & NI_FLAGS_INPUT_BUBBLE) {
981                 std::vector<std::string> refs;
982                 splitPath(refPaths, refs);
983                 for (auto &p: refs) {
984                         if (isDirectory(p) && checkDllExistInDir(p)) {
985                                 opt->inputBubbleRefFiles.push_back(p + "/*.dll");
986                         }
987                 }
988         }
989
990         // get managed file list from targetPath
991         std::vector<std::string> dllList;
992         ret = getTargetDllList(targetPath, dllList);
993         if (ret != NI_ERROR_NONE) {
994                 return ret;
995         }
996
997         std::vector<std::string> needNIList;
998         std::vector<std::string> niList;
999
1000         for (auto &dll : dllList) {
1001                 if (!checkNIExistence(dll)) {
1002                         needNIList.push_back(dll);
1003                 }
1004                 niList.push_back(getNIFilePath(dll));
1005         }
1006
1007         if (!needNIList.empty()) {
1008                 // NI fils of TAC-related dlls under /opt/usr/dotnet should not be created under .native_image directory.
1009                 // So, unset NI_FLAGS_APPNI temporally and restore it after running AOT.
1010                 opt->flags &= ~NI_FLAGS_APPNI;
1011                 ret = doAOTList(needNIList, refPaths, opt);
1012                 if (isAppNI) {
1013                         opt->flags |= NI_FLAGS_APPNI;
1014                 }
1015                 if (ret != NI_ERROR_NONE) {
1016                         return ret;
1017                 }
1018         }
1019
1020         if (isAppNI) {
1021                 for (auto &niPath : niList) {
1022                         if (exist(niPath)) {
1023                                 std::string symNIPath = concatPath(targetPath, getFileName(niPath));
1024                                 if (!exist(symNIPath)) {
1025                                         bf::create_symlink(niPath, symNIPath);
1026                                         copySmackAndOwnership(targetPath.c_str(), symNIPath.c_str(), true);
1027                                         _SOUT("%s symbolic link file generated successfully.", symNIPath.c_str());
1028                                         _INFO("%s symbolic link file generated successfully.", symNIPath.c_str());
1029                                 }
1030                         }
1031                 }
1032         }
1033
1034         return NI_ERROR_NONE;
1035 }
1036
1037
1038 ni_error_e createNIUnderDirs(const std::string& rootPaths, NIOption* opt)
1039 {
1040         ni_error_e ret = NI_ERROR_NONE;
1041
1042         std::vector<std::string> fileList;
1043         std::vector<std::string> paths;
1044         splitPath(rootPaths, paths);
1045
1046         if (opt->flags & NI_FLAGS_INPUT_BUBBLE) {
1047                 for (auto &p: paths) {
1048                         if (isDirectory(p) && checkDllExistInDir(p)) {
1049                                 opt->inputBubbleRefFiles.push_back(p + "/*.dll");
1050                         }
1051                 }
1052         }
1053
1054         for (const auto &path : paths) {
1055                 if (!exist(path)) {
1056                         continue;
1057                 }
1058
1059                 if (path.find(TAC_SYMLINK_SUB_DIR) != std::string::npos) {
1060                         ret = createNIUnderTAC(path, rootPaths, opt);
1061                         if (ret != NI_ERROR_NONE) {
1062                                 return ret;
1063                         }
1064                 } else if (opt->flags & NI_FLAGS_APPNI) {
1065                         ret = getAppTargetDllList(path, fileList, opt);
1066                         if (ret != NI_ERROR_NONE) {
1067                                 return ret;
1068                         }
1069                 } else {
1070                         ret = getTargetDllList(path, fileList);
1071                         if (ret != NI_ERROR_NONE) {
1072                                 return ret;
1073                         }
1074                 }
1075         }
1076
1077         if (fileList.empty()) {
1078                 return NI_ERROR_NONE;
1079         }
1080
1081         return doAOTList(fileList, rootPaths, opt);
1082 }
1083
1084 ni_error_e createNIUnderPkgRoot(const std::string& pkgId, NIOption* opt)
1085 {
1086         if (!isR2RImage(concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll"))) {
1087                 _SERR("The native image of System.Private.CoreLib does not exist.\n"
1088                                 "Run the command to create the native image\n"
1089                                 "# dotnettool --ni-dll /usr/share/dotnet.tizen/netcoreapp/System.Private.CoreLib.dll");
1090                 return NI_ERROR_CORE_NI_FILE;
1091         }
1092
1093         std::string rootPath = getRootPath(pkgId);
1094         if (rootPath.empty()) {
1095                 _SERR("Failed to get root path from [%s]", pkgId.c_str());
1096                 return NI_ERROR_INVALID_PACKAGE;
1097         }
1098
1099         __pm->setAppRootPath(rootPath);
1100
1101         char* extraDllPaths = pluginGetExtraDllPath();
1102         if (extraDllPaths && extraDllPaths[0] != '\0') {
1103                 opt->flags |= NI_FLAGS_EXTRA_REF;
1104                 splitPath(extraDllPaths, opt->extraRefPath);
1105         }
1106
1107         opt->flags |= NI_FLAGS_APPNI;
1108
1109         if (isReadOnlyArea(rootPath)) {
1110                 opt->flags |= NI_FLAGS_APP_UNDER_RO_AREA;
1111                 opt->flags |= NI_FLAGS_NO_PIPELINE;
1112                 _SERR("Only no-pipeline mode supported for RO app. Set no-pipeline option forcibly");
1113         } else {
1114                 opt->flags &= ~NI_FLAGS_APP_UNDER_RO_AREA;
1115         }
1116
1117         // create native image under bin and lib directory
1118         // tac directory is skipped in the createNIUnderDirs.
1119         return createNIUnderDirs(__pm->getAppPaths(), opt);
1120 }
1121
1122 void removeNIPlatform()
1123 {
1124         std::string coreLib = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll");
1125         std::string coreLibBackup = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll.Backup");
1126
1127         if (isR2RImage(coreLib)) {
1128                 if (!isFile(coreLibBackup)) {
1129                         return;
1130                 }
1131
1132                 if (remove(coreLib.c_str())) {
1133                         _SERR("Failed to remove System.Private.CoreLib native image file");
1134                 }
1135                 if (rename(coreLibBackup.c_str(), coreLib.c_str())) {
1136                         _SERR("Failed to rename System.Private.CoreLib.Backup to origin");
1137                 }
1138         }
1139
1140 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
1141         if (isFile(__SYSTEM_BASE_FILE)) {
1142                 if (remove(__SYSTEM_BASE_FILE)) {
1143                         _SERR("Failed to remove %s", __SYSTEM_BASE_FILE);
1144                 }
1145         }
1146 #endif
1147
1148         removeNIUnderDirs(__pm->getRuntimePath() + ":" + __pm->getTizenFXPath());
1149 }
1150
1151 void removeNIUnderDirs(const std::string& rootPaths)
1152 {
1153         auto convert = [](const std::string& path, const std::string& filename) {
1154                 if (isNativeImage(path)) {
1155                         std::string assemblyPath = changeExtension(path, ".ni.dll", ".dll");
1156                         if (exist(assemblyPath)) {
1157                                 if (remove(path.c_str())) {
1158                                         _SERR("Failed to remove %s", path.c_str());
1159                                 }
1160                         } else {
1161                                 _SOUT("%s cannot be removed because there is no %s", path.c_str(), assemblyPath.c_str());
1162                         }
1163                 }
1164         };
1165
1166         std::vector<std::string> paths;
1167         splitPath(rootPaths, paths);
1168         for (const auto &path : paths) {
1169                 scanFilesInDirectory(path, convert, -1);
1170         }
1171 }
1172
1173 ni_error_e removeNIUnderPkgRoot(const std::string& pkgId)
1174 {
1175         std::string rootPath = getRootPath(pkgId);
1176         if (rootPath.empty()) {
1177                 _SERR("Failed to get root path from [%s]", pkgId.c_str());
1178                 return NI_ERROR_INVALID_PACKAGE;
1179         }
1180
1181         __pm->setAppRootPath(rootPath);
1182
1183         // getAppNIPaths returns bin/.native_image, lib/.native_image and .tac_symlink.
1184         std::string appNIPaths = __pm->getAppNIPaths();
1185         std::vector<std::string> paths;
1186         splitPath(appNIPaths, paths);
1187         for (const auto &path : paths) {
1188                 if (!isReadOnlyArea(path)) {
1189                         // Only the native image inside the TAC should be removed.
1190                         if (strstr(path.c_str(), TAC_SYMLINK_SUB_DIR) != NULL) {
1191                                 removeNIUnderDirs(path);
1192                         } else {
1193                                 if (isDirectory(path)) {
1194                                         if (!removeAll(path.c_str())) {
1195                                                 _SERR("Failed to remove app ni dir [%s]", path.c_str());
1196                                         }
1197                                 }
1198                         }
1199                 }
1200         }
1201
1202         // In special cases, the ni file may exist in the dll location.
1203         // The code below is to avoid this exceptional case.
1204         std::string appPaths = __pm->getAppPaths();
1205         splitPath(appPaths, paths);
1206         for (const auto &path : paths) {
1207                 if (isDirectory(path)) {
1208                         removeNIUnderDirs(path);
1209                 }
1210         }
1211
1212         return NI_ERROR_NONE;
1213 }
1214
1215 ni_error_e regenerateAppNI(NIOption* opt)
1216 {
1217         int ret = 0;
1218         pkgmgrinfo_appinfo_metadata_filter_h handle;
1219
1220         ret = pkgmgrinfo_appinfo_metadata_filter_create(&handle);
1221         if (ret != PMINFO_R_OK)
1222                 return NI_ERROR_UNKNOWN;
1223
1224         ret = pkgmgrinfo_appinfo_metadata_filter_add(handle, AOT_METADATA_KEY, METADATA_VALUE_TRUE);
1225         if (ret != PMINFO_R_OK) {
1226                 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
1227                 return NI_ERROR_UNKNOWN;
1228         }
1229
1230         ret = pkgmgrMDFilterForeach(handle, appAotCb, &opt);
1231         if (ret != 0) {
1232                 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
1233                 return NI_ERROR_UNKNOWN;
1234         }
1235
1236         pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
1237         return NI_ERROR_NONE;
1238 }
1239
1240 // callback function of "pkgmgrinfo_appinfo_metadata_filter_foreach"
1241 static int regenTacCb(pkgmgrinfo_appinfo_h handle, void *userData)
1242 {
1243         char *pkgId = NULL;
1244         char *root = NULL;
1245         NIOption **pOpt = (NIOption**)userData;
1246
1247         int ret = pkgmgrinfo_appinfo_get_pkgid(handle, &pkgId);
1248         if (ret != PMINFO_R_OK || pkgId == NULL) {
1249                 _SERR("Failed to get pkgid");
1250                 return -1;
1251         }
1252
1253         ret = pkgmgrinfo_appinfo_get_root_path(handle, &root);
1254         if (ret != PMINFO_R_OK) {
1255                 _SERR("Failed to get root path");
1256                 return -1;
1257         }
1258
1259         std::string binPath = concatPath(std::string(root), "bin");
1260         if (exist(concatPath(binPath, PRE_COMPILED_PACKAGE_FILE))) {
1261                 _INFO("The %s is a Pre-Compiled package. So, skip the TAC", pkgId);
1262                 return 0;
1263         }
1264
1265         sqlite3 *tac_db = openDB(TAC_APP_LIST_DB);
1266         if (!tac_db) {
1267                 _SERR("Sqlite open error");
1268                 return -1;
1269         }
1270         sqlite3_exec(tac_db, "BEGIN;", NULL, NULL, NULL);
1271
1272         char *sql = sqlite3_mprintf("SELECT * FROM TAC WHERE PKGID = %Q;", pkgId);
1273         std::vector<std::string> nugets = selectDB(tac_db, sql);
1274         sqlite3_free(sql);
1275
1276         if (tac_db) {
1277                 closeDB(tac_db);
1278                 tac_db = NULL;
1279         }
1280
1281         std::string nugetPaths;
1282         for (const auto &nuget : nugets) {
1283                 if (!nugetPaths.empty()) {
1284                         nugetPaths += ":";
1285                 }
1286                 nugetPaths += concatPath(__DOTNET_DIR, nuget);
1287         }
1288
1289         for (auto& nuget : nugets) {
1290                 createNIUnderTAC(concatPath(__DOTNET_DIR, nuget), nugetPaths, *pOpt);
1291         }
1292
1293         return 0;
1294 }
1295
1296 ni_error_e regenerateTACNI(NIOption* opt)
1297 {
1298         removeNIUnderDirs(__DOTNET_DIR);
1299
1300         pkgmgrinfo_appinfo_metadata_filter_h handle;
1301         int ret = pkgmgrinfo_appinfo_metadata_filter_create(&handle);
1302         if (ret != PMINFO_R_OK) {
1303                 return NI_ERROR_UNKNOWN;
1304         }
1305
1306         ret = pkgmgrinfo_appinfo_metadata_filter_add(handle, TAC_METADATA_KEY, METADATA_VALUE_TRUE);
1307         if (ret != PMINFO_R_OK) {
1308                 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
1309                 return NI_ERROR_UNKNOWN;
1310         }
1311
1312         ret = pkgmgrMDFilterForeach(handle, regenTacCb, &opt);
1313         if (ret != 0) {
1314                 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
1315                 return NI_ERROR_UNKNOWN;
1316         }
1317
1318         pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
1319
1320         return NI_ERROR_NONE;
1321 }
1322