Change implementation of regeneratePkgNI
[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& absDllPath, NIOption* opt)
234 {
235         std::string dllPath = absDllPath;
236         if (opt->flags & NI_FLAGS_APPNI) {
237                 std::string niDirPath;
238                 std::string niTmpDirPath;
239                 std::string prevPath;
240
241                 prevPath = getBaseName(absDllPath);
242                 niDirPath = concatPath(prevPath, APP_NI_SUB_DIR);
243                 niTmpDirPath = concatPath(prevPath, APP_NI_SUB_TMP_DIR);
244
245                 if (opt->flags & NI_FLAGS_APP_UNDER_RO_AREA) {
246                         niTmpDirPath = replaceAll(niTmpDirPath, getBaseName(__pm->getAppRootPath()), __READ_ONLY_APP_UPDATE_DIR);
247                         niDirPath = replaceAll(niDirPath, getBaseName(__pm->getAppRootPath()), __READ_ONLY_APP_UPDATE_DIR);
248                         _INFO("App is installed in RO area. Change NI path to RW area(%s).", niTmpDirPath.c_str());
249                 }
250
251                 if (!isDirectory(niDirPath)) {
252                         if (!createDirsAndCopyOwnerShip(niTmpDirPath, prevPath)) {
253                                 niTmpDirPath = prevPath;
254                                 _SERR("fail to create dir (%s)", niTmpDirPath.c_str());
255                         }
256                         dllPath = concatPath(niTmpDirPath, getFileName(absDllPath));
257                 } else {
258                         dllPath = concatPath(niDirPath, getFileName(absDllPath));
259                 }
260         }
261
262         size_t index = dllPath.find_last_of(".");
263         if (index == std::string::npos) {
264                 _SERR("File doesnot contain extension. fail to get NI file name");
265                 return "";
266         }
267         std::string fName = dllPath.substr(0, index);
268         std::string fExt = dllPath.substr(index, dllPath.length());
269
270         // crossgen generate file with lower case extension only
271         std::transform(fExt.begin(), fExt.end(), fExt.begin(), ::tolower);
272         std::string niPath = fName + ".ni" + fExt;
273
274         return niPath;
275 }
276
277 static bool checkNIExistence(const std::string& absDllPath, NIOption* opt)
278 {
279         std::string absNIPath = getNIFilePath(absDllPath, opt);
280         if (absNIPath.empty()) {
281                 return false;
282         }
283
284         if (isFile(absNIPath)) {
285                 return true;
286         }
287
288         // native image of System.Private.CoreLib.dll should have to overwrite
289         // original file to support new coreclr
290         if (absDllPath.find("System.Private.CoreLib.dll") != std::string::npos) {
291                 return isR2RImage(absDllPath);
292         }
293
294         return false;
295 }
296
297 static bool checkDllExistInDir(const std::string& path)
298 {
299         bool ret = false;
300         auto func = [&ret](const std::string& f_path, const std::string& f_name) {
301                 if (isManagedAssembly(f_name) || isR2RImage(f_name)) {
302                         ret = true;
303                 }
304         };
305
306         scanFilesInDirectory(path, func, 0);
307
308         return ret;
309 }
310
311 /*
312  * Get the list of managed files in the specific directory (of Application)
313  * Absolute paths of managed files are stored at the result list.
314  * If native image already exist in the (same / .native_image) directory, managed file is ignored.
315  */
316 static ni_error_e getTargetDllList(const std::string& path, std::vector<std::string>& fileList, NIOption *opt)
317 {
318         if (!isDirectory(path)) {
319                 return NI_ERROR_INVALID_PARAMETER;
320         }
321
322         auto func = [&fileList, opt](const std::string& f_path, const std::string& f_name) {
323                 if (isManagedAssembly(f_path) && !checkNIExistence(f_path, opt)) {
324                         fileList.push_back(getAbsolutePath(f_path));
325                 }
326         };
327
328         scanFilesInDirectory(path, func, 0);
329
330         return NI_ERROR_NONE;
331 }
332
333 static void makeArgs(std::vector<const char*>& args, const std::vector<std::string>& refPaths, NIOption* opt)
334 {
335         args.push_back(CORERUN_CMD.c_str());
336         if (CROSSGEN2_PATH != "") {
337                 args.push_back(CROSSGEN2_PATH.c_str());
338         }
339         args.push_back(CROSSGEN_OPT_JITPATH);
340         args.push_back(CLRJIT_PATH.c_str());
341         args.push_back(CROSSGEN_OPT_TARGET_ARCH);
342         args.push_back(ARCHITECTURE_IDENTIFIER);
343
344         //args.push_back(OPT_PARALLELISM);
345         //args.push_back(OPT_PARALLELISM_COUNT);
346         args.push_back(CROSSGEN_OPT_RESILIENT);
347
348         args.push_back(CROSSGEN_OPT_OPTIMIZE_TIME);
349
350         if (opt->flags & NI_FLAGS_INPUT_BUBBLE) {
351                 args.push_back(CROSSGEN_OPT_INPUTBUBBLE);
352                 args.push_back(CROSSGEN_OPT_COMPILE_BUBBLE_GENERICS);
353
354                 INPUTBUBBLE_REF_VECTOR.clear();
355                 for (const auto &path : opt->inputBubbleRefFiles) {
356                         INPUTBUBBLE_REF_VECTOR.push_back("--inputbubbleref:" + path);
357                 }
358                 for (const auto &path : INPUTBUBBLE_REF_VECTOR) {
359                         if (find(args.begin(), args.end(), path) == args.end()) {
360                                 args.push_back(path.c_str());
361                         }
362                 }
363         }
364
365         if (opt->flags & NI_FLAGS_MIBC) {
366                 MIBC_VECTOR.clear();
367                 for (const auto &path : opt->mibcPath) {
368                         MIBC_VECTOR.push_back("--mibc:" + path);
369                 }
370                 for (const auto &path : MIBC_VECTOR) {
371                         if (find(args.begin(), args.end(), path) == args.end()) {
372                                 args.push_back(path.c_str());
373                         }
374                 }
375         }
376
377         if (opt->flags & NI_FLAGS_VERBOSE) {
378                 args.push_back(CROSSGEN_OPT_VERBOSE);
379         }
380
381         REF_VECTOR.clear();
382
383         // set reference path
384         for (const auto &path : opt->refFiles) {
385                 REF_VECTOR.push_back("-r:" + path);
386         }
387
388         std::vector<std::string> paths = __pm->getPlatformAssembliesPaths();
389         for (const auto &path : paths) {
390                 if (checkDllExistInDir(path)) {
391                         REF_VECTOR.push_back("-r:" + path + "/*.dll");
392                 }
393         }
394
395         if (opt->flags & NI_FLAGS_EXTRA_REF) {
396                 for (const auto &erPath : opt->extraRefPath) {
397                         std::string path = getAbsolutePath(erPath);
398                         if (checkDllExistInDir(path)) {
399                                 REF_VECTOR.push_back("-r:" + path + "/*.dll");
400                         }
401                 }
402         }
403
404         for (const auto &path : refPaths) {
405                 if (checkDllExistInDir(path)) {
406                         REF_VECTOR.push_back("-r:" + path + "/*.dll");
407                 }
408         }
409
410         for (const auto &path : REF_VECTOR) {
411                 if (find(args.begin(), args.end(), path) == args.end()) {
412                         args.push_back(path.c_str());
413                 }
414         }
415 }
416
417 static void clearArgs(std::vector<const char*>& args)
418 {
419         REF_VECTOR.clear();
420         args.clear();
421 }
422
423 static ni_error_e makePdbSymlinkForNI(std::string dllPath, std::string niPath)
424 {
425         std::string pdbPath = changeExtension(dllPath, ".dll", ".pdb");
426         try {
427                 if (exist(pdbPath)) {
428                         std::string targetPDBPath = changeExtension(niPath, ".ni.dll", ".pdb");
429                         if (!exist(targetPDBPath)) {
430                                 bf::create_symlink(pdbPath, targetPDBPath);
431                                 copySmackAndOwnership(pdbPath, targetPDBPath, true);
432                         }
433                 }
434         } catch (const bf::filesystem_error& error) {
435                 _SERR("Fail to create symlink for %s", pdbPath.c_str());
436                 return NI_ERROR_UNKNOWN;
437         }
438
439         return NI_ERROR_NONE;
440 }
441
442 static ni_error_e crossgen2PostAction(const std::string& dllPath, const std::string& niPath, NIOption* opt) {
443         std::string outFile = niPath;
444         if (!exist(outFile)) {
445                 return NI_ERROR_NO_SUCH_FILE;
446         }
447         copySmackAndOwnership(dllPath, outFile);
448
449         // if AppNI then move ni.dll file to .native_image and copy pdb to .native_image
450         if (opt->flags & NI_FLAGS_APPNI) {
451                 outFile = getNIFilePath(dllPath, opt);
452                 makePdbSymlinkForNI(dllPath, outFile);
453
454                 if (opt->flags & NI_FLAGS_INPUT_BUBBLE && opt->flags & NI_FLAGS_NO_PIPELINE) {
455                         outFile = outFile + ".tmp";
456                 }
457
458                 if (niPath != outFile) {
459                         moveFile(niPath, outFile);
460                 }
461         }
462
463         if (opt->flags & NI_FLAGS_RM_ORIGIN_AFTER_NI) {
464                 if (!removeFile(dllPath)) {
465                         _SERR("Fail to remove original file : %s", dllPath.c_str());
466                 }
467         }
468
469         if (!(opt->flags & NI_FLAGS_INPUT_BUBBLE && opt->flags & NI_FLAGS_NO_PIPELINE)) {
470                 _SOUT("Native image %s generated successfully.", outFile.c_str());
471         }
472
473         return NI_ERROR_NONE;
474 }
475
476 void setPriority(NIOption* opt)
477 {
478         pid_t pid = getpid();
479         if (setpriority(PRIO_PROCESS, pid, opt->priority) == 0) {
480                 std::string str = " ";
481                 if (opt->priority <= -20) {
482                         str = " highest ";
483                 } else if (opt->priority >= 19) {
484                         str = " lowest ";
485                 }
486                 _SOUT("Success to set the%spriority of the process. pid : [%d], priority : [%d]", str.c_str(), pid, getpriority(PRIO_PROCESS, pid));
487         } else {
488                 _SERR("Failed to set the priority of the process. pid : [%d], priority : [%d]", pid, getpriority(PRIO_PROCESS, pid));
489         }
490 }
491
492 static ni_error_e crossgen2PipeLine(const std::vector<std::string>& dllList, const std::vector<std::string>& refPaths, NIOption* opt)
493 {
494         // fork crossgen2
495         pid_t pid = fork();
496         if (pid == -1)
497                 return NI_ERROR_UNKNOWN;
498
499         if (pid > 0) {
500                 int status;
501                 waitpid(pid, &status, 0);
502                 if (WIFEXITED(status)) {
503                         for (auto& dllPath: dllList) {
504                                 ni_error_e ret = crossgen2PostAction(dllPath, changeExtension(dllPath, ".dll", ".ni.dll"), opt);
505                                 if (ret != NI_ERROR_NONE) {
506                                         return ret;
507                                 }
508                         }
509                 } else {
510                         _SERR("Failed. Forked process terminated abnormally");
511                         return NI_ERROR_ABNORMAL_PROCESS_TERMINATION;
512                 }
513         } else {
514                 if (opt->flags & NI_FLAGS_SET_PRIORITY) {
515                         setPriority(opt);
516                 }
517                 std::vector<const char*> argv;
518                 makeArgs(argv, refPaths, opt);
519                 argv.push_back(CROSSGEN_OPT_OUT_NEAR_INPUT);
520                 argv.push_back(CROSSGEN_OPT_SINGLE_FILE_COMPILATION);
521
522                 // add input files at the end of parameter
523                 for (const auto &input : dllList) {
524                         argv.push_back(input.c_str());
525                         _SOUT("+ %s", input.c_str());
526                 }
527
528                 // end param
529                 argv.push_back(nullptr);
530
531                 // print cmd
532                 if (opt->flags & NI_FLAGS_PRINT_CMD) {
533                         _SOUT("==================== NI Commands =========================");
534                         for (auto &arg: argv) _SOUT("+ %s", arg);
535                 }
536
537                 execv(CORERUN_CMD.c_str(), const_cast<char* const*>(argv.data()));
538
539                 clearArgs(argv);
540                 exit(0);
541         }
542
543         return NI_ERROR_NONE;
544 }
545
546 static ni_error_e crossgen2NoPipeLine(const std::vector<std::string>& dllList, const std::vector<std::string>& refPaths, NIOption* opt)
547 {
548         for (auto& dllPath : dllList) {
549                 std::string niPath;
550                 niPath = getNIFilePath(dllPath, opt);
551
552 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
553                 uintptr_t baseAddr = 0;
554                 if (isTPADll(dllPath)) {
555                         baseAddr = getNextBaseAddr();
556                 }
557 #endif
558                 if (opt->flags & NI_FLAGS_INPUT_BUBBLE) {
559                         niPath += ".tmp";
560                 }
561
562                 // fork crossgen2
563                 pid_t pid = fork();
564                 if (pid == -1)
565                         return NI_ERROR_UNKNOWN;
566
567                 if (pid > 0) {
568                         int status;
569                         waitpid(pid, &status, 0);
570                         if (WIFEXITED(status)) {
571                                 ni_error_e ret = crossgen2PostAction(dllPath, niPath, opt);
572                                 if (ret != NI_ERROR_NONE) {
573                                         return ret;
574                                 }
575 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
576                                 if (baseAddr != 0) {
577                                         updateBaseAddrFile(niPath, baseAddr);
578                                 }
579 #endif
580                         } else {
581                                 _SERR("Failed. Forked process terminated abnormally");
582                                 _SERR("Crossgen2 was terminated by the OOM killer. Please check the system.");
583                                 removeFile(changeExtension(niPath, ".ni.dll", ".ni.dll.tmp"));
584                                 return NI_ERROR_ABNORMAL_PROCESS_TERMINATION;
585                         }
586                 } else {
587                         if (opt->flags & NI_FLAGS_SET_PRIORITY) {
588                                 setPriority(opt);
589                         }
590                         std::vector<const char*> argv;
591                         makeArgs(argv, refPaths, opt);
592
593 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
594                         std::string baseAddrString;
595                         if (baseAddr != 0) {
596                                 argv.push_back("--imagebase");
597                                 std::stringstream ss;
598                                 ss << "0x" << std::hex << baseAddr;
599                                 baseAddrString = ss.str();
600                                 argv.push_back(baseAddrString.c_str());
601                         }
602 #endif
603                         argv.push_back("-o");
604                         argv.push_back(niPath.c_str());
605
606                         argv.push_back(dllPath.c_str());
607                         _SOUT("+ %s", dllPath.c_str());
608
609                         // end param
610                         argv.push_back(nullptr);
611
612                         // print cmd
613                         if (opt->flags & NI_FLAGS_PRINT_CMD) {
614                                 _SOUT("==================== NI Commands =========================");
615                                 for (auto &arg: argv) _SOUT("+ %s", arg);
616                         }
617
618                         execv(CORERUN_CMD.c_str(), const_cast<char* const*>(argv.data()));
619
620                         clearArgs(argv);
621                         exit(0);
622                 }
623
624                 waitInterval();
625         }
626
627         return NI_ERROR_NONE;
628 }
629
630 static ni_error_e createCoreLibNI(NIOption* opt)
631 {
632         std::string coreLib = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll");
633         std::string niCoreLib = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.ni.dll");
634         std::string niTmpCoreLib = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.ni.dll.tmp");
635         std::string coreLibBackup = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll.Backup");
636
637         std::vector<std::string> dllList;
638         std::vector<std::string> refPaths;
639         dllList.push_back(getAbsolutePath(coreLib));
640
641         if (!isFile(coreLibBackup) && !isR2RImage(coreLib)) {
642                 if (crossgen2NoPipeLine(dllList, refPaths, opt) == NI_ERROR_NONE) {
643                         if (opt->flags & NI_FLAGS_RM_ORIGIN_AFTER_NI) {
644                                 std::ofstream output(coreLibBackup);
645                                 if (!exist(coreLibBackup)) {
646                                         _SERR("Failed to create System.Private.CoreLib.dll.Backup");
647                                         return NI_ERROR_CORE_NI_FILE;
648                                 }
649                                 copySmackAndOwnership(__pm->getRuntimePath(), coreLibBackup, false);
650                                 output.close();
651                         } else if (rename(coreLib.c_str(), coreLibBackup.c_str())) {
652                                 _SERR("Failed to rename from System.Private.CoreLib.dll to System.Private.CoreLib.dll.Backup");
653                                 return NI_ERROR_CORE_NI_FILE;
654                         }
655                         if (opt->flags & NI_FLAGS_INPUT_BUBBLE) {
656                                 if (rename(niTmpCoreLib.c_str(), coreLib.c_str())) {
657                                         _SERR("Failed to rename from System.Private.CoreLib.ni.dll.tmp to Private.CoreLib.dll");
658                                         return NI_ERROR_CORE_NI_FILE;
659                                 }
660                         } else {
661                                 if (rename(niCoreLib.c_str(), coreLib.c_str())) {
662                                         _SERR("Failed to rename from System.Private.CoreLib.ni.dll to Private.CoreLib.dll");
663                                         return NI_ERROR_CORE_NI_FILE;
664                                 }
665                         }
666                 } else {
667                         _SERR("Failed to create native image for %s", coreLib.c_str());
668                         return NI_ERROR_CORE_NI_FILE;
669                 }
670         }
671         return NI_ERROR_NONE;
672 }
673
674 static void renameAppNITmpPath(NIOption* opt)
675 {
676         std::string niTmpPath = __pm->getAppRootPath() + "/bin/" + APP_NI_SUB_TMP_DIR;
677         std::string niPath = __pm->getAppRootPath() + "/bin/" + APP_NI_SUB_DIR;
678
679         if (opt->flags & NI_FLAGS_APP_UNDER_RO_AREA) {
680                 niTmpPath = replaceAll(niTmpPath, getBaseName(__pm->getAppRootPath()), __READ_ONLY_APP_UPDATE_DIR);
681                 niPath = replaceAll(niPath, getBaseName(__pm->getAppRootPath()), __READ_ONLY_APP_UPDATE_DIR);
682         }
683
684         if (isDirectory(niTmpPath)) {
685                 if (rename(niTmpPath.c_str(), niPath.c_str())) {
686                         _SERR("Fail to rename from .native_image_tmp to .native_image");
687                 } else {
688                         _SOUT("Success to rename from %s to %s", niTmpPath.c_str(), niPath.c_str());
689                 }
690         }
691 }
692
693 static ni_error_e doAOTList(std::vector<std::string>& dllList, const std::string& refPaths, NIOption* opt)
694 {
695         ni_error_e ret = NI_ERROR_NONE;
696
697         if (dllList.empty()) {
698                 return NI_ERROR_INVALID_PARAMETER;
699         }
700         // When performing AOT for one Dll, an error is returned when an error occurs.
701         // However, when processing multiple dlls at once, only the log for errors is output and skipped.
702
703         std::string coreLib = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll");
704         bool hasSPC = false;
705
706         for (auto it = dllList.begin(); it != dllList.end(); it++) {
707                 std::string f = *it;
708                 if (!isFile(f)) {
709                         _SERR("dll file is not exist : %s", f.c_str());
710                         dllList.erase(it--);
711                 }
712                 else if (!isManagedAssembly(f)) {
713                         _SERR("Input file is not a dll file : %s", f.c_str());
714                         dllList.erase(it--);
715                 }
716                 // handle System.Private.CoreLib.dll separately.
717                 // dllList and path manager contain absolute path. So, there is no need to change path to absolute path
718                 else if (f == coreLib) {
719                         hasSPC = true;
720                         dllList.erase(it--);
721                 }
722         }
723
724         // Error : Multiple input files matching same simple name
725         // So, Remove dulicate files from dll list
726         std::sort(dllList.begin(), dllList.end());
727         dllList.erase(unique(dllList.begin(), dllList.end()), dllList.end());
728
729         // In the case of SPC, post-processing is required to change the name of the native image.
730         // In order to avoid repeatedly checking whether the generated native image is an SPC,
731         // the SPC native image generation is performed separately.
732         if (hasSPC) {
733                 ret = createCoreLibNI(opt);
734                 if (ret != NI_ERROR_NONE) {
735                         return ret;
736                 }
737         }
738
739         // if there is no proper input after processing dll list
740         if (dllList.empty()) {
741                 if (hasSPC) {
742                         return ret;
743                 } else {
744                         return NI_ERROR_INVALID_PARAMETER;
745                 }
746         }
747
748         std::vector<std::string> paths;
749         splitPath(refPaths, paths);
750
751         if (opt->flags & NI_FLAGS_NO_PIPELINE) {
752                 ret = crossgen2NoPipeLine(dllList, paths, opt);
753         } else {
754                 std::vector<std::string> notCompiled;
755                 ret = crossgen2PipeLine(dllList, paths, opt);
756                 if (ret != NI_ERROR_NONE) {
757                         _SERR("Crossgen2 is abnormally terminated. Regenerate native images that failed while running crossgen2.");
758                         for (auto &dll : dllList) {
759                                 std::string tFile = changeExtension(dll, ".dll", ".ni.dll");
760                                 if (opt->flags & NI_FLAGS_INPUT_BUBBLE) {
761                                         tFile += ".tmp";
762                                 }
763                                 if (!exist(tFile)) {
764                                         notCompiled.push_back(dll);
765                                 }
766                         }
767                         _SERR("Retry running crossgen2 with --no-pipeline mode to avoid termination by OOM.");
768                         ret = crossgen2NoPipeLine(notCompiled, paths, opt);
769                 }
770         }
771
772         if (ret == NI_ERROR_NONE) {
773                 if (opt->flags & NI_FLAGS_INPUT_BUBBLE) {
774                         for (auto &dll : dllList) {
775                                 std::string tmpFile;
776                                 std::string niFile = getNIFilePath(dll, opt);
777                                 tmpFile = niFile + ".tmp";
778
779                                 if (exist(tmpFile)) {
780                                         moveFile(tmpFile, niFile);
781                                         _SOUT("Native image %s generated successfully.", niFile.c_str());
782                                 }
783                         }
784                 }
785                 if (opt->flags & NI_FLAGS_APPNI) {
786                         renameAppNITmpPath(opt);
787                 }
788         }
789
790         return ret;
791 }
792
793 static ni_error_e doAOTFile(const std::string& dllFile, const std::string& refPaths, NIOption* opt)
794 {
795         if (!isFile(dllFile)) {
796                 _SERR("dll file is not exist : %s", dllFile.c_str());
797                 return NI_ERROR_NO_SUCH_FILE;
798         }
799
800         if (checkNIExistence(dllFile, opt)) {
801                 _SERR("Native image file is already exist : %s", dllFile.c_str());
802                 return NI_ERROR_ALREADY_EXIST;
803         }
804
805         if (!isManagedAssembly(dllFile)) {
806                 _SERR("Failed. Input parameter is not managed dll (%s)\n", dllFile.c_str());
807                 return NI_ERROR_INVALID_PARAMETER;
808         }
809
810         std::vector<std::string> dllList;
811         dllList.push_back(getAbsolutePath(dllFile));
812         return doAOTList(dllList, refPaths, opt);
813 }
814
815 static ni_error_e removeAndCreateNI(const char* pkgId, NIOption* pOptions)
816 {
817         if (removeNIUnderPkgRoot(pkgId) != NI_ERROR_NONE) {
818                 _SERR("Failed to remove previous dlls from [%s]", pkgId);
819                 return NI_ERROR_UNKNOWN;
820         }
821
822         if (createNIUnderPkgRoot(pkgId, pOptions) != NI_ERROR_NONE) {
823                 _SERR("Failed to generate NI file [%s]", pkgId);
824                 return NI_ERROR_UNKNOWN;
825         }
826
827         _SOUT("Complete make native image for pkg (%s)", pkgId);
828         return NI_ERROR_NONE;   
829 }
830
831 static bool isReadOnlyPkg(std::string pkgId)
832 {
833         int ret = 0;
834         bool readonly = false;
835         pkgmgrinfo_pkginfo_h handle;
836
837         ret = pkgmgrinfo_pkginfo_get_pkginfo(pkgId.c_str(), &handle);
838         if (ret != PMINFO_R_OK) {
839                 _ERR("Fail to get pkginfo");
840                 return false;
841         }
842
843         ret = pkgmgrinfo_pkginfo_is_readonly(handle, &readonly);
844         if (ret != PMINFO_R_OK) {
845                 _ERR("Fail to get is_readonly");
846                 pkgmgrinfo_pkginfo_destroy_pkginfo(handle);
847                 return false;
848         }
849
850         pkgmgrinfo_pkginfo_destroy_pkginfo(handle);
851         return readonly;
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 = pkgmgrinfo_appinfo_get_pkgid(handle, &pkgId);
859         if (ret != PMINFO_R_OK) {
860                 _SERR("Failed to get pkgid");
861                 return -1;
862         }
863
864         std::vector<std::string> *pkgList = (std::vector<std::string> *)userData;
865         pkgList->push_back(pkgId);
866
867         return 0;
868 }
869
870 // callback function of "pkgmgrinfo_pkginfo_metadata_filter_foreach"
871 static int pkgAotCb(pkgmgrinfo_pkginfo_h handle, void *userData)
872 {
873         char *pkgId = NULL;
874         int ret = pkgmgrinfo_pkginfo_get_pkgid(handle, &pkgId);
875         if (ret != PMINFO_R_OK) {
876                 _SERR("Failed to get pkgid");
877                 return -1;
878         }
879
880         std::vector<std::string> *pkgList = (std::vector<std::string> *)userData;
881         pkgList->push_back(pkgId);
882
883         return 0;
884 }
885
886 ni_error_e initNICommon()
887 {
888 #if defined(__arm__) || defined(__aarch64__)
889
890         char *env = nullptr;
891         env = getenv("MIC_CROSSGEN2_ENABLED");
892         if (env != nullptr && !strcmp(env, "1")) {
893                 CORERUN_CMD = std::string("/opt/usr/dotnet/mic/crossgen2");
894                 CROSSGEN2_PATH = "";
895                 CLRJIT_PATH = std::string("/opt/usr/dotnet/mic/libclrjit_unix_") + ARCHITECTURE_IDENTIFIER + std::string("_x64.so");
896         }
897
898         // get interval value
899         const static std::string intervalFile = concatPath(__NATIVE_LIB_DIR, "crossgen_interval.txt");
900         std::ifstream inFile(intervalFile);
901         if (inFile) {
902                 _SOUT("crossgen_interval.txt is found");
903                 inFile >> __interval;
904         }
905
906         if (initializePluginManager("normal")) {
907                 _SERR("Fail to initialize PluginManager");
908                 return NI_ERROR_UNKNOWN;
909         }
910
911         try {
912                 __pm = new PathManager();
913         } catch (const std::exception& e) {
914                 _SERR("Failed to create PathManager");
915                 return NI_ERROR_UNKNOWN;
916         }
917
918         char* pluginDllPaths = pluginGetDllPath();
919         if (pluginDllPaths && pluginDllPaths[0] != '\0') {
920                 __pm->addPlatformAssembliesPaths(pluginDllPaths, true);
921         }
922
923         char* pluginNativePaths = pluginGetNativeDllSearchingPath();
924         if (pluginNativePaths && pluginNativePaths[0] != '\0') {
925                 __pm->addNativeDllSearchingPaths(pluginNativePaths, true);
926         }
927
928         return NI_ERROR_NONE;
929 #else
930         _SERR("crossgen supports arm/arm64 architecture only. skip ni file generation");
931         return NI_ERROR_NOT_SUPPORTED;
932 #endif
933 }
934
935 void finalizeNICommon()
936 {
937         __interval = 0;
938
939         finalizePluginManager();
940
941         delete(__pm);
942         __pm = nullptr;
943
944         if (__ni_option) {
945                 free(__ni_option);
946                 __ni_option = nullptr;
947         }
948 }
949
950 ni_error_e createNIPlatform(std::string& extraInputs, NIOption* opt)
951 {
952         extraInputs += ":" + __pm->getRuntimePath();
953         extraInputs += ":" + __pm->getTizenFXPath();
954
955         return createNIUnderDirs(extraInputs, opt);
956 }
957
958 ni_error_e createNIDll(const std::string& dllPath, NIOption* opt)
959 {
960         return doAOTFile(dllPath, std::string(), opt);
961 }
962
963 ni_error_e createNIUnderTAC(const std::string& targetPath, const std::string& refPaths, NIOption* opt)
964 {
965         ni_error_e ret;
966
967         bool isAppNI = false;
968         if (opt->flags & NI_FLAGS_APPNI) {
969                 isAppNI = true;
970         }
971
972         if (opt->flags & NI_FLAGS_INPUT_BUBBLE) {
973                 std::vector<std::string> refs;
974                 splitPath(refPaths, refs);
975                 for (auto &p: refs) {
976                         if (isDirectory(p) && checkDllExistInDir(p)) {
977                                 opt->inputBubbleRefFiles.push_back(p + "/*.dll");
978                         }
979                 }
980         }
981
982         // get managed file list from targetPath
983         std::vector<std::string> dllList;
984         ret = getTargetDllList(targetPath, dllList, opt);
985         if (ret != NI_ERROR_NONE) {
986                 return ret;
987         }
988
989         std::vector<std::string> needNIList;
990         std::vector<std::string> niList;
991
992         for (auto &dll : dllList) {
993                 if (!checkNIExistence(dll, opt)) {
994                         needNIList.push_back(dll);
995                 }
996                 niList.push_back(getNIFilePath(dll, opt));
997         }
998
999         if (!needNIList.empty()) {
1000                 // NI fils of TAC-related dlls under /opt/usr/dotnet should not be created under .native_image directory.
1001                 // So, unset NI_FLAGS_APPNI temporally and restore it after running AOT.
1002                 opt->flags &= ~NI_FLAGS_APPNI;
1003                 ret = doAOTList(needNIList, refPaths, opt);
1004                 if (isAppNI) {
1005                         opt->flags |= NI_FLAGS_APPNI;
1006                 }
1007                 if (ret != NI_ERROR_NONE) {
1008                         return ret;
1009                 }
1010         }
1011
1012         if (isAppNI) {
1013                 for (auto &niPath : niList) {
1014                         if (exist(niPath)) {
1015                                 std::string symNIPath = concatPath(targetPath, getFileName(niPath));
1016                                 if (!exist(symNIPath)) {
1017                                         bf::create_symlink(niPath, symNIPath);
1018                                         copySmackAndOwnership(targetPath.c_str(), symNIPath.c_str(), true);
1019                                         _SOUT("%s symbolic link file generated successfully.", symNIPath.c_str());
1020                                         _INFO("%s symbolic link file generated successfully.", symNIPath.c_str());
1021                                 }
1022                         }
1023                 }
1024         }
1025
1026         return NI_ERROR_NONE;
1027 }
1028
1029
1030 ni_error_e createNIUnderDirs(const std::string& rootPaths, NIOption* opt)
1031 {
1032         ni_error_e ret = NI_ERROR_NONE;
1033
1034         std::vector<std::string> fileList;
1035         std::vector<std::string> paths;
1036         splitPath(rootPaths, paths);
1037
1038         if (opt->flags & NI_FLAGS_INPUT_BUBBLE) {
1039                 for (auto &p: paths) {
1040                         if (isDirectory(p) && checkDllExistInDir(p)) {
1041                                 opt->inputBubbleRefFiles.push_back(p + "/*.dll");
1042                         }
1043                 }
1044         }
1045
1046         for (const auto &path : paths) {
1047                 if (!exist(path)) {
1048                         continue;
1049                 }
1050
1051                 if (path.find(TAC_SYMLINK_SUB_DIR) != std::string::npos) {
1052                         ret = createNIUnderTAC(path, rootPaths, opt);
1053                         if (ret != NI_ERROR_NONE) {
1054                                 return ret;
1055                         }
1056                 } else {
1057                         ret = getTargetDllList(path, fileList, opt);
1058                         if (ret != NI_ERROR_NONE) {
1059                                 return ret;
1060                         }
1061                 }
1062         }
1063
1064         if (fileList.empty()) {
1065                 return NI_ERROR_NONE;
1066         }
1067
1068         return doAOTList(fileList, rootPaths, opt);
1069 }
1070
1071 ni_error_e createNIUnderPkgRoot(const std::string& pkgId, NIOption* opt)
1072 {
1073         if (!isR2RImage(concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll"))) {
1074                 _SERR("The native image of System.Private.CoreLib does not exist.\n"
1075                                 "Run the command to create the native image\n"
1076                                 "# dotnettool --ni-dll /usr/share/dotnet.tizen/netcoreapp/System.Private.CoreLib.dll");
1077                 return NI_ERROR_CORE_NI_FILE;
1078         }
1079
1080         std::string rootPath = getRootPath(pkgId);
1081         if (rootPath.empty()) {
1082                 _SERR("Failed to get root path from [%s]", pkgId.c_str());
1083                 return NI_ERROR_INVALID_PACKAGE;
1084         }
1085
1086         char* extraDllPaths = pluginGetExtraDllPath();
1087         if (extraDllPaths && extraDllPaths[0] != '\0') {
1088                 opt->flags |= NI_FLAGS_EXTRA_REF;
1089                 splitPath(extraDllPaths, opt->extraRefPath);
1090         }
1091
1092         std::string targetDirs;
1093         if (isRPK(pkgId)) {
1094                 opt->flags &= ~NI_FLAGS_APPNI;
1095                 std::string paths = getResourcePaths(rootPath);
1096                 if (paths.empty()) {
1097                         _SERR("Failed to get rpk paths from [%s]", pkgId.c_str());
1098                         return NI_ERROR_UNKNOWN;
1099                 }
1100                 targetDirs = paths;
1101         } else {
1102                 __pm->setAppRootPath(rootPath);
1103
1104                 opt->flags |= NI_FLAGS_APPNI;
1105
1106                 if (isReadOnlyArea(rootPath)) {
1107                         opt->flags |= NI_FLAGS_APP_UNDER_RO_AREA;
1108                         opt->flags |= NI_FLAGS_NO_PIPELINE;
1109                         _SERR("Only no-pipeline mode supported for RO app. Set no-pipeline option forcibly");
1110                 } else {
1111                         opt->flags &= ~NI_FLAGS_APP_UNDER_RO_AREA;
1112                 }
1113
1114                 targetDirs = __pm->getAppPaths();
1115         }
1116
1117         return createNIUnderDirs(targetDirs, opt);
1118 }
1119
1120 void removeNIPlatform()
1121 {
1122         std::string coreLib = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll");
1123         std::string coreLibBackup = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll.Backup");
1124
1125         if (isR2RImage(coreLib)) {
1126                 if (!isFile(coreLibBackup)) {
1127                         return;
1128                 }
1129
1130                 if (remove(coreLib.c_str())) {
1131                         _SERR("Failed to remove System.Private.CoreLib native image file");
1132                 }
1133                 if (rename(coreLibBackup.c_str(), coreLib.c_str())) {
1134                         _SERR("Failed to rename System.Private.CoreLib.Backup to origin");
1135                 }
1136         }
1137
1138 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
1139         if (isFile(__SYSTEM_BASE_FILE)) {
1140                 if (remove(__SYSTEM_BASE_FILE)) {
1141                         _SERR("Failed to remove %s", __SYSTEM_BASE_FILE);
1142                 }
1143         }
1144 #endif
1145
1146         removeNIUnderDirs(__pm->getRuntimePath() + ":" + __pm->getTizenFXPath());
1147 }
1148
1149 void removeNIUnderDirs(const std::string& rootPaths)
1150 {
1151         auto convert = [](const std::string& path, const std::string& filename) {
1152                 if (isR2RImage(path)) {
1153                         std::string assemblyPath = changeExtension(path, ".ni.dll", ".dll");
1154                         if (exist(assemblyPath)) {
1155                                 if (remove(path.c_str())) {
1156                                         _SERR("Failed to remove %s", path.c_str());
1157                                 }
1158                         } else {
1159                                 _SOUT("%s cannot be removed because there is no %s", path.c_str(), assemblyPath.c_str());
1160                         }
1161                 }
1162         };
1163
1164         std::vector<std::string> paths;
1165         splitPath(rootPaths, paths);
1166         for (const auto &path : paths) {
1167                 scanFilesInDirectory(path, convert, -1);
1168         }
1169 }
1170
1171 ni_error_e removeNIUnderPkgRoot(const std::string& pkgId)
1172 {
1173         std::vector<std::string> paths;
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         if (isRPK(pkgId)) {
1182                 std::string rpkPaths = getResourcePaths(rootPath);
1183                 if (rpkPaths.empty()) {
1184                         _SERR("Failed to get rpk path from [%s]", pkgId.c_str());
1185                         return NI_ERROR_UNKNOWN;
1186                 }
1187                 splitPath(rpkPaths, paths);
1188                 for (const auto &path : paths) {
1189                         if (isDirectory(path)) {
1190                                 removeNIUnderDirs(path);
1191                         }
1192                 }               
1193         } else {
1194                 __pm->setAppRootPath(rootPath);
1195
1196                 // getAppNIPaths returns bin/.native_image, lib/.native_image and .tac_symlink.
1197                 std::string appNIPaths = __pm->getAppNIPaths();
1198                 splitPath(appNIPaths, paths);
1199                 for (const auto &path : paths) {
1200                         if (!isReadOnlyArea(path)) {
1201                                 // Only the native image inside the TAC should be removed.
1202                                 if (strstr(path.c_str(), TAC_SYMLINK_SUB_DIR) != NULL) {
1203                                         removeNIUnderDirs(path);
1204                                 } else {
1205                                         if (isDirectory(path)) {
1206                                                 if (!removeAll(path.c_str())) {
1207                                                         _SERR("Failed to remove app ni dir [%s]", path.c_str());
1208                                                 }
1209                                         }
1210                                 }
1211                         }
1212                 }
1213
1214                 // In special cases, the ni file may exist in the dll location.
1215                 // The code below is to avoid this exceptional case.
1216                 std::string appPaths = __pm->getAppPaths();
1217                 splitPath(appPaths, paths);
1218                 for (const auto &path : paths) {
1219                         if (isDirectory(path)) {
1220                                 removeNIUnderDirs(path);
1221                         }
1222                 }
1223         }
1224
1225         return NI_ERROR_NONE;
1226 }
1227
1228 ni_error_e regeneratePkgNI(NIOption* opt)
1229 {
1230         std::vector<std::string> pkgList;
1231         ni_error_e ret = NI_ERROR_NONE;
1232
1233         // iterates for Packages's metadata (RPK)
1234         pkgmgrinfo_pkginfo_metadata_filter_h pkgHandle;
1235         if (pkgmgrinfo_pkginfo_metadata_filter_create(&pkgHandle) == PMINFO_R_OK) {
1236                 if (pkgmgrinfo_pkginfo_metadata_filter_add(pkgHandle, AOT_METADATA_KEY, METADATA_VALUE_TRUE) == PMINFO_R_OK) {
1237                         if (pkgmgrPkgMDFilterForeach(pkgHandle, pkgAotCb, &pkgList) != 0) {
1238                                 ret = NI_ERROR_UNKNOWN;
1239                                 _ERR("pkgmgrPkgMDFilterForeach failed");
1240                         }
1241                 } else {
1242                         ret = NI_ERROR_UNKNOWN;
1243                         _ERR("pkgmgrinfo_pkginfo_metadata_filter_add failed");
1244                 }
1245                 pkgmgrinfo_pkginfo_metadata_filter_destroy(pkgHandle);
1246         } else {
1247                 ret = NI_ERROR_UNKNOWN;
1248                 _ERR("pkgmgrinfo_pkginfo_metadata_filter_create failed");
1249         }
1250
1251         // iterate for App's metadata
1252         pkgmgrinfo_appinfo_metadata_filter_h appHandle;
1253         if (pkgmgrinfo_appinfo_metadata_filter_create(&appHandle) == PMINFO_R_OK) {
1254                 if (pkgmgrinfo_appinfo_metadata_filter_add(appHandle, AOT_METADATA_KEY, METADATA_VALUE_TRUE) == PMINFO_R_OK) {
1255                         if (pkgmgrAppMDFilterForeach(appHandle, appAotCb, &pkgList) != 0) {
1256                                 ret = NI_ERROR_UNKNOWN;
1257                                 _ERR("pkgmgrAppMDFilterForeach failed");
1258                         }
1259                 } else {
1260                         ret = NI_ERROR_UNKNOWN;
1261                         _ERR("pkgmgrinfo_appinfo_metadata_filter_add failed");
1262                 }
1263                 pkgmgrinfo_appinfo_metadata_filter_destroy(appHandle);
1264         } else {
1265                 ret = NI_ERROR_UNKNOWN;
1266                 _ERR("pkgmgrinfo_appinfo_metadata_filter_create failed");
1267         }
1268
1269         // remove duplicated pkg in the list.
1270         // If one package has multiple apps, there can be duplicate values.
1271         std::sort(pkgList.begin(), pkgList.end());
1272         pkgList.erase(unique(pkgList.begin(), pkgList.end()), pkgList.end());
1273
1274         for (auto pkg : pkgList) {
1275                 if (isReadOnlyPkg(pkg) && opt->flags & NI_FLAGS_SKIP_RO_APP) {
1276                         continue;
1277                 }
1278
1279                 if (removeAndCreateNI(pkg.c_str(), opt) != NI_ERROR_NONE) {
1280                         _SERR("Failed to remove previous dlls from [%s]", pkg.c_str());
1281                         ret = NI_ERROR_UNKNOWN;
1282                 } else {
1283                         _SOUT("Complete make application to native image");
1284                 }
1285         }
1286
1287         return ret;
1288 }
1289
1290 // callback function of "pkgmgrinfo_appinfo_metadata_filter_foreach"
1291 static int regenTacCb(pkgmgrinfo_appinfo_h handle, void *userData)
1292 {
1293         char *pkgId = NULL;
1294         char *root = NULL;
1295         NIOption **pOpt = (NIOption**)userData;
1296
1297         int ret = pkgmgrinfo_appinfo_get_pkgid(handle, &pkgId);
1298         if (ret != PMINFO_R_OK || pkgId == NULL) {
1299                 _SERR("Failed to get pkgid");
1300                 return -1;
1301         }
1302
1303         ret = pkgmgrinfo_appinfo_get_root_path(handle, &root);
1304         if (ret != PMINFO_R_OK) {
1305                 _SERR("Failed to get root path");
1306                 return -1;
1307         }
1308
1309         std::string binPath = concatPath(std::string(root), "bin");
1310         if (exist(concatPath(binPath, PRE_COMPILED_PACKAGE_FILE))) {
1311                 _INFO("The %s is a Pre-Compiled package. So, skip the TAC", pkgId);
1312                 return 0;
1313         }
1314
1315         sqlite3 *tac_db = openDB(TAC_APP_LIST_DB);
1316         if (!tac_db) {
1317                 _SERR("Sqlite open error");
1318                 return -1;
1319         }
1320         sqlite3_exec(tac_db, "BEGIN;", NULL, NULL, NULL);
1321
1322         char *sql = sqlite3_mprintf("SELECT * FROM TAC WHERE PKGID = %Q;", pkgId);
1323         std::vector<std::string> nugets = selectDB(tac_db, sql);
1324         sqlite3_free(sql);
1325
1326         if (tac_db) {
1327                 closeDB(tac_db);
1328                 tac_db = NULL;
1329         }
1330
1331         std::string nugetPaths;
1332         for (const auto &nuget : nugets) {
1333                 if (!nugetPaths.empty()) {
1334                         nugetPaths += ":";
1335                 }
1336                 nugetPaths += concatPath(__DOTNET_DIR, nuget);
1337         }
1338
1339         for (auto& nuget : nugets) {
1340                 createNIUnderTAC(concatPath(__DOTNET_DIR, nuget), nugetPaths, *pOpt);
1341         }
1342
1343         return 0;
1344 }
1345
1346 ni_error_e regenerateTACNI(NIOption* opt)
1347 {
1348         removeNIUnderDirs(__DOTNET_DIR);
1349
1350         pkgmgrinfo_appinfo_metadata_filter_h handle;
1351         int ret = pkgmgrinfo_appinfo_metadata_filter_create(&handle);
1352         if (ret != PMINFO_R_OK) {
1353                 return NI_ERROR_UNKNOWN;
1354         }
1355
1356         ret = pkgmgrinfo_appinfo_metadata_filter_add(handle, TAC_METADATA_KEY, METADATA_VALUE_TRUE);
1357         if (ret != PMINFO_R_OK) {
1358                 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
1359                 return NI_ERROR_UNKNOWN;
1360         }
1361
1362         ret = pkgmgrAppMDFilterForeach(handle, regenTacCb, &opt);
1363         if (ret != 0) {
1364                 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
1365                 return NI_ERROR_UNKNOWN;
1366         }
1367
1368         pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
1369
1370         return NI_ERROR_NONE;
1371 }
1372