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