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