Added error handling for failures during the TAC (#262)
[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
33 #include <pwd.h>
34 #include <grp.h>
35 #include <unistd.h>
36 #include <string.h>
37 #include <sqlite3.h>
38
39 #include "ni_common.h"
40 #include "db_manager.h"
41 #include "tac_common.h"
42 #include "path_manager.h"
43 #include "plugin_manager.h"
44
45 #ifdef  LOG_TAG
46 #undef  LOG_TAG
47 #endif
48 #define LOG_TAG "DOTNET_INSTALLER_PLUGIN"
49
50 #ifndef CROSSGEN_PATH
51 #error "CROSSGEN_PATH is missed"
52 #endif
53
54 #define __XSTR(x) #x
55 #define __STR(x) __XSTR(x)
56 static const char* __NATIVE_LIB_DIR = __STR(NATIVE_LIB_DIR);
57 static const char* __CROSSGEN_PATH = __STR(CROSSGEN_PATH);
58 static const char* __DOTNET_DIR = __STR(DOTNET_DIR);
59
60 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
61 static const char* __SYSTEM_BASE_FILE = __STR(SYSTEM_BASE_FILE);
62 #endif
63
64 #undef __STR
65 #undef __XSTR
66
67 static int __interval = 0;
68 static PathManager* __pm = nullptr;
69
70 static void waitInterval()
71 {
72         // by the recommand, ignore small value for performance.
73         if (__interval > 10000) {
74                 fprintf(stdout, "sleep %d usec\n", __interval);
75                 usleep(__interval);
76         }
77 }
78
79 static std::string getNIFilePath(const std::string& dllPath)
80 {
81         size_t index = dllPath.find_last_of(".");
82         if (index == std::string::npos) {
83                 fprintf(stderr, "File doesnot contain extension. fail to get NI file name\n");
84                 return "";
85         }
86         std::string fName = dllPath.substr(0, index);
87         std::string fExt = dllPath.substr(index, dllPath.length());
88
89         // crossgen generate file with lower case extension only
90         std::transform(fExt.begin(), fExt.end(), fExt.begin(), ::tolower);
91         std::string niPath = fName + ".ni" + fExt;
92
93         return niPath;
94 }
95
96 static std::string getAppNIFilePath(const std::string& niPath)
97 {
98         std::string fileName;
99         std::string niDirPath;
100         std::string prevPath;
101
102         size_t index = niPath.find_last_of("/");
103         if (index != std::string::npos) {
104                 prevPath = niPath.substr(0, index);
105                 fileName = niPath.substr(index + 1, niPath.length());
106         } else {
107                 prevPath = ".";
108                 fileName = niPath;
109         }
110
111         niDirPath = concatPath(prevPath, APP_NI_SUB_DIR);
112
113         if (!isFile(niDirPath)) {
114                 if (mkdir(niDirPath.c_str(), 0755) == 0) {
115                         copySmackAndOwnership(prevPath, niDirPath);
116                 } else {
117                         fprintf(stderr, "Fail to create app ni directory (%s)\n", niDirPath.c_str());
118                 }
119         }
120
121         return concatPath(niDirPath, fileName);
122 }
123
124 static bool checkNIExistence(const std::string& path)
125 {
126         std::string f = getNIFilePath(path);
127         if (f.empty()) {
128                 return false;
129         }
130
131         if (isFile(f)) {
132                 return true;
133         }
134
135         // native image of System.Private.CoreLib.dll should have to overwrite
136         // original file to support new coreclr
137         if (path.find("System.Private.CoreLib.dll") != std::string::npos) {
138                 std::string coreLibBackup = path + ".Backup";
139                 if (isFile(coreLibBackup)) {
140                         return true;
141                 }
142         }
143
144         return false;
145 }
146
147 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
148 static uintptr_t getFileSize(const std::string& path)
149 {
150         struct stat sb;
151
152         if (stat(path.c_str(), &sb) == 0) {
153                 return sb.st_size;
154         }
155
156         return 0;
157 }
158
159 // Get next base address to be used for system ni image from file
160 // __SYSTEM_BASE_FILE should be checked for existance before calling this function
161 static uintptr_t getNextBaseAddrFromFile()
162 {
163         FILE *pFile = fopen(__SYSTEM_BASE_FILE, "r");
164         if (pFile == NULL) {
165                 fprintf(stderr, "Failed to open %s\n", __SYSTEM_BASE_FILE);
166                 return 0;
167         }
168
169         uintptr_t addr = 0;
170         uintptr_t size = 0;
171
172         while (fscanf(pFile, "%u %u", &addr, &size) != EOF) {
173         }
174
175         fclose(pFile);
176
177         return addr + size;
178 }
179
180 // Get next base address to be used for system ni image
181 static uintptr_t getNextBaseAddr()
182 {
183         uintptr_t baseAddr = 0;
184
185         if (!isFile(__SYSTEM_BASE_FILE)) {
186                 // This is the starting address for all default base addresses
187                 baseAddr = DEFAULT_BASE_ADDR_START;
188         } else {
189                 baseAddr = getNextBaseAddrFromFile();
190
191                 // Round to a multple of 64K (see ZapImage::CalculateZapBaseAddress in CoreCLR)
192                 uintptr_t BASE_ADDRESS_ALIGNMENT = 0xffff;
193                 baseAddr = (baseAddr + BASE_ADDRESS_ALIGNMENT) & ~BASE_ADDRESS_ALIGNMENT;
194         }
195
196         return baseAddr;
197 }
198
199 // Save base address of system ni image to file
200 static void updateBaseAddrFile(const std::string& absNIPath, uintptr_t baseAddr)
201 {
202         uintptr_t niSize = getFileSize(absNIPath);
203         if (niSize == 0) {
204                 fprintf(stderr, "File %s doesn't exist\n", absNIPath.c_str());
205                 return;
206         }
207
208         // Write new entry to the file
209         FILE *pFile = fopen(__SYSTEM_BASE_FILE, "a");
210         if (pFile == NULL) {
211                 fprintf(stderr, "Failed to open %s\n", __SYSTEM_BASE_FILE);
212                 return;
213         }
214
215         fprintf(pFile, "%u %u\n", baseAddr, niSize);
216         fclose(pFile);
217 }
218
219 // check if dll is listed in TPA
220 static bool isTPADll(const std::string& dllPath)
221 {
222         std::string absPath = getBaseName(getAbsolutePath(dllPath));
223
224         std::vector<std::string> paths = __pm->getPlatformAssembliesPaths();
225         for (unsigned int i = 0; i < paths.size(); i++) {
226                 if (paths[i].find(getBaseName(absPath)) != std::string::npos) {
227                         return true;
228                 }
229         }
230
231         return false;
232 }
233 #endif
234
235 // baseAddr should be checked in file before getting here
236 static ni_error_e crossgen(const std::string& dllPath, const std::string& appPath, DWORD flags)
237 {
238         if (!isFile(dllPath)) {
239                 fprintf(stderr, "dll file is not exist : %s\n", dllPath.c_str());
240                 return NI_ERROR_NO_SUCH_FILE;
241         }
242
243         if (!isManagedAssembly(dllPath)) {
244                 //fprintf(stderr, "Input file is not a dll file : %s\n", dllPath.c_str());
245                 return NI_ERROR_INVALID_PARAMETER;
246         }
247
248         if (checkNIExistence(dllPath)) {
249                 //fprintf(stderr, "Already ni file is exist for %s\n", dllPath.c_str());
250                 return NI_ERROR_ALREADY_EXIST;
251         }
252
253         std::string absDllPath = getAbsolutePath(dllPath);
254         std::string absNIPath = getNIFilePath(dllPath);
255
256         if (absNIPath.empty()) {
257                 fprintf(stderr, "Fail to get ni file name\n");
258                 return NI_ERROR_UNKNOWN;
259         }
260
261         bool isAppNI = flags & NI_FLAGS_APPNI;
262         if (isAppNI && strstr(absNIPath.c_str(), __DOTNET_DIR) == NULL) {
263                 absNIPath = getAppNIFilePath(absNIPath);
264         }
265
266 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
267         uintptr_t baseAddr = 0;
268
269         if (isTPADll(dllPath)) {
270                 baseAddr = getNextBaseAddr();
271         }
272 #endif
273
274         pid_t pid = fork();
275         if (pid == -1)
276                 return NI_ERROR_UNKNOWN;
277
278         if (pid > 0) {
279                 int status;
280                 waitpid(pid, &status, 0);
281                 if (WIFEXITED(status)) {
282                         // Do not use checkNIExistence() function to check whether ni file created or not.
283                         // checkNIExistence() return false for System.Private.Corelib.dll
284                         if (isFile(absNIPath)) {
285                                 copySmackAndOwnership(absDllPath, absNIPath);
286                                 std::string absPdbPath = replaceAll(absDllPath, ".dll", ".pdb");
287                                 std::string pdbFilePath = replaceAll(absNIPath, ".ni.dll", ".pdb");
288                                 if (isFile(absPdbPath) && (absPdbPath != pdbFilePath)) {
289                                         if (!copyFile(absPdbPath, pdbFilePath)) {
290                                                 fprintf(stderr, "Failed to copy a .pdb file\n");
291                                         } else {
292                                                 copySmackAndOwnership(absPdbPath, pdbFilePath);
293                                         }
294                                 }
295 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
296                                 if (baseAddr != 0) {
297                                         updateBaseAddrFile(absNIPath, baseAddr);
298                                 }
299 #endif
300                                 return NI_ERROR_NONE;
301                         } else {
302                                 fprintf(stderr, "Fail to create native image for %s\n", dllPath.c_str());
303                                 return NI_ERROR_NO_SUCH_FILE;
304                         }
305                 }
306         } else {
307                 std::string jitPath = __pm->getRuntimePath() + "/libclrjit.so";
308                 std::vector<const char*> argv = {
309                         __CROSSGEN_PATH,
310                         "/nologo",
311                         "/JITPath", jitPath.c_str()
312                 };
313
314                 bool compat = flags & NI_FLAGS_COMPATIBILITY;
315                 argv.push_back(compat ? "/Platform_Assemblies_Pathes" : "/p");
316                 std::vector<std::string> paths = __pm->getPlatformAssembliesPaths();
317                 std::string platformAssembliesPaths;
318                 for (const auto &path : paths) {
319                         if (!platformAssembliesPaths.empty()) {
320                                 platformAssembliesPaths += ":";
321                         }
322                         platformAssembliesPaths += path;
323                 }
324                 argv.push_back(platformAssembliesPaths.c_str());
325
326                 bool enableR2R = flags & NI_FLAGS_ENABLER2R;
327                 if (!enableR2R) {
328                         argv.push_back("/FragileNonVersionable");
329                 }
330
331                 if (flags & NI_FLAGS_VERBOSE) {
332                         argv.push_back("/verbose");
333                 }
334
335                 if (flags & NI_FLAGS_INSTRUMENT) {
336                         argv.push_back("/Tuning");
337                 }
338
339 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
340                 char baseAddrString[11] = {0};
341                 if (baseAddr != 0) {
342                         argv.push_back("/BaseAddress");
343                         snprintf(baseAddrString, 11, "0x%08x", baseAddr);
344                         argv.push_back(baseAddrString);
345                 }
346 #endif
347
348                 argv.push_back("/App_Paths");
349                 std::string absAppPath;
350                 if (!appPath.empty()) {
351                         absAppPath = appPath;
352                 } else {
353                         absAppPath = getBaseName(absDllPath);
354                 }
355                 argv.push_back(absAppPath.c_str());
356
357                 argv.push_back("/out");
358                 argv.push_back(absNIPath.c_str());
359
360                 argv.push_back(absDllPath.c_str());
361                 argv.push_back(nullptr);
362
363                 fprintf(stdout, "+ %s (%s)\n", absDllPath.c_str(), enableR2R ? "R2R" : "FNV");
364
365                 execv(__CROSSGEN_PATH, const_cast<char* const*>(argv.data()));
366                 exit(0);
367         }
368
369         return NI_ERROR_NONE;
370 }
371
372 // callback function of "pkgmgrinfo_appinfo_metadata_filter_foreach"
373 static int appAotCb(pkgmgrinfo_appinfo_h handle, void *userData)
374 {
375         char *pkgId = NULL;
376         int ret = 0;
377         DWORD *pFlags = (DWORD*)userData;
378
379         ret = pkgmgrinfo_appinfo_get_pkgid(handle, &pkgId);
380         if (ret != PMINFO_R_OK) {
381                 fprintf(stderr, "Failed to get pkgid\n");
382                 return -1;
383         }
384
385         if (removeNIUnderPkgRoot(pkgId) != NI_ERROR_NONE) {
386                 fprintf(stderr, "Failed to remove previous dlls from [%s]\n", pkgId);
387                 return -1;
388         }
389
390         if (createNIUnderPkgRoot(pkgId, *pFlags) != NI_ERROR_NONE) {
391                 fprintf(stderr, "Failed to generate NI file [%s]\n", pkgId);
392                 return -1;
393         } else {
394                 fprintf(stdout, "Complete make application to native image\n");
395         }
396
397         return 0;
398 }
399
400 static bool isCoreLibPrepared(DWORD flags)
401 {
402         if (flags & NI_FLAGS_ENABLER2R) {
403                 return true;
404         }
405
406         std::string coreLibBackup = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll.Backup");
407         if (isFile(coreLibBackup)) {
408                 return true;
409         } else {
410                 fprintf(stderr, "The native image of System.Private.CoreLib does not exist\n"
411                                         "Run the command to create the native image\n"
412                                         "# dotnettool --ni-dll /usr/share/dotnet.tizen/netcoreapp/System.Private.CoreLib.dll\n\n");
413                 return false;
414         }
415 }
416
417 static bool hasCoreLibNI()
418 {
419         FILE *fp;
420         char buff[1024];
421         std::string ildasm = concatPath(__pm->getRuntimePath(), "ildasm");
422         std::string coreLib = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll");
423         std::string cmd = ildasm + " " + coreLib + " | grep '\\.corflags'";
424         fp = popen(cmd.c_str(), "r");
425         if (fp != NULL) {
426                 while (fgets(buff, sizeof(buff), fp) != NULL) {
427                         buff[strlen(buff) - 1] = '\0';
428                 }
429                 std::string corflag = replaceAll(buff, ".corflags", "");
430                 corflag.erase(std::remove(corflag.begin(), corflag.end(), ' '), corflag.end());
431                 // CorFlags.ILLibrary=0x00000004 (.ni.dll)
432                 if (!strcmp(corflag.substr(0, 10).c_str(), "0x00000004")) {
433                         pclose(fp);
434                         return true;
435                 }
436                 pclose(fp);
437         }
438         return false;
439 }
440
441 static ni_error_e createCoreLibNI(DWORD flags)
442 {
443         std::string coreLib = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll");
444         std::string niCoreLib = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.ni.dll");
445         std::string coreLibBackup = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll.Backup");
446
447         if (!isFile(coreLibBackup) && !hasCoreLibNI()) {
448                 if (!crossgen(coreLib, std::string(), flags)) {
449                         if (rename(coreLib.c_str(), coreLibBackup.c_str())) {
450                                 fprintf(stderr, "Failed to rename System.Private.CoreLib.dll\n");
451                                 return NI_ERROR_CORE_NI_FILE;
452                         }
453                         if (rename(niCoreLib.c_str(), coreLib.c_str())) {
454                                 fprintf(stderr, "Failed to rename System.Private.CoreLib.ni.dll\n");
455                                 return NI_ERROR_CORE_NI_FILE;
456                         }
457                 } else {
458                         fprintf(stderr, "Failed to create native image for %s\n", coreLib.c_str());
459                         return NI_ERROR_CORE_NI_FILE;
460                 }
461         }
462         return NI_ERROR_NONE;
463 }
464
465 ni_error_e initNICommon()
466 {
467 #if defined(__arm__) || defined(__aarch64__)
468         // get interval value
469         const static std::string intervalFile = concatPath(__NATIVE_LIB_DIR, "crossgen_interval.txt");
470         std::ifstream inFile(intervalFile);
471         if (inFile) {
472                 fprintf(stdout, "crossgen_interval.txt is found\n");
473                 inFile >> __interval;
474         }
475
476         if (initializePluginManager("normal")) {
477                 fprintf(stderr, "Fail to initialize PluginManager\n");
478                 return NI_ERROR_UNKNOWN;
479         }
480
481         try {
482                 __pm = new PathManager();
483         } catch (const std::exception& e) {
484                 fprintf(stderr, "Failed to create PathManager");
485                 return NI_ERROR_UNKNOWN;
486         }
487
488         char* pluginDllPaths = pluginGetDllPath();
489         if (pluginDllPaths) {
490                 __pm->addPlatformAssembliesPaths(pluginDllPaths);
491         }
492
493         return NI_ERROR_NONE;
494 #else
495         fprintf(stderr, "crossgen supports arm/arm64 architecture only. skip ni file generation\n");
496         return NI_ERROR_NOT_SUPPORTED;
497 #endif
498 }
499
500 void finalizeNICommon()
501 {
502         __interval = 0;
503
504         finalizePluginManager();
505
506         delete(__pm);
507         __pm = nullptr;
508 }
509
510 ni_error_e createNIPlatform(DWORD flags)
511 {
512         if (createCoreLibNI(flags) != NI_ERROR_NONE) {
513                 return NI_ERROR_CORE_NI_FILE;
514         }
515
516         return createNIUnderDirs(__pm->getRuntimePath() + ":" + __pm->getTizenFXPath(), flags);
517 }
518
519 ni_error_e createNIDll(const std::string& dllPath, DWORD flags)
520 {
521         if (dllPath.find("System.Private.CoreLib.dll") != std::string::npos) {
522                 return createCoreLibNI(flags);
523         }
524
525         if (!isCoreLibPrepared(flags)) {
526                 return NI_ERROR_CORE_NI_FILE;
527         }
528
529         return crossgen(dllPath, std::string(), flags);
530 }
531
532 ni_error_e createNIUnderDirs(const std::string& rootPaths, DWORD flags)
533 {
534         if (!isCoreLibPrepared(flags)) {
535                 return NI_ERROR_CORE_NI_FILE;
536         }
537
538         auto convert = [&rootPaths, flags](const std::string& path, const std::string& filename) {
539                 // if path is symlink, donot generate crossgen
540                 if (!crossgen(path, rootPaths.c_str(), flags)) {
541                         waitInterval();
542                 }
543         };
544
545         std::vector<std::string> targetPaths;
546         splitPath(rootPaths, targetPaths);
547         for (const auto &path : targetPaths) {
548                 // TAC directory should be handled specially because that contains symlink of native image file.
549                 if (strstr(path.c_str(), TAC_SYMLINK_SUB_DIR) != NULL) {
550                         if (!isDirectory(path)) {
551                                 continue;
552                         }
553                         // make native image symlink if not exist under tac directory
554                         try {
555                                 for (auto& symlinkAssembly : bf::recursive_directory_iterator(path)) {
556                                         std::string symPath = symlinkAssembly.path().string();
557                                         if (!isManagedAssembly(symPath)) {
558                                                 continue;
559                                         }
560
561                                         // if there is symlink and original file for native image, skip generation
562                                         std::string symNIPath = symPath.substr(0, symPath.rfind(".dll")) + ".ni.dll";
563                                         if (isFile(symNIPath)) {
564                                                 continue;
565                                         }
566
567                                         // if original native image not exist, generate native image
568                                         std::string originPath = bf::read_symlink(symPath).string();
569                                         std::string originNIPath = originPath.substr(0, originPath.rfind(".dll")) + ".ni.dll";
570                                         if (!isFile(originNIPath)) {
571                                                 if (!crossgen(originPath, path.c_str(), flags)) {
572                                                         waitInterval();
573                                                 }
574                                         }
575
576                                         // if no symlink file exist, create symlink
577                                         if (!isFile(symNIPath)) {
578                                                 bf::create_symlink(originNIPath, symNIPath);
579                                                 copySmackAndOwnership(symPath.c_str(), symNIPath.c_str(), true);
580                                                 fprintf(stdout, "%s symbolic link file generated successfully.\n", symNIPath.c_str());
581                                                 _INFO("%s symbolic link file generated successfully.", symNIPath.c_str());
582                                         }
583                                 }
584                         } catch (const bf::filesystem_error& error) {
585                                 fprintf(stderr, "Failed to recursive directory: %s\n", error.what());
586                                 return NI_ERROR_UNKNOWN;
587                         }
588                 } else {
589                         scanFilesInDirectory(path, convert, 0);
590                 }
591         }
592
593         return NI_ERROR_NONE;
594 }
595
596 ni_error_e createNIUnderPkgRoot(const std::string& pkgId, DWORD flags)
597 {
598         std::string rootPath = getRootPath(pkgId);
599         if (rootPath.empty()) {
600                 fprintf(stderr, "Failed to get root path from [%s]\n", pkgId.c_str());
601                 return NI_ERROR_INVALID_PACKAGE;
602         }
603
604         __pm->setAppRootPath(rootPath);
605
606         flags |= NI_FLAGS_APPNI;
607
608         // create native image under bin and lib directory
609         // tac directory is skipped in the createNIUnderDirs.
610         return createNIUnderDirs(__pm->getAppPaths(), flags);
611 }
612
613 void removeNIPlatform()
614 {
615         std::string coreLib = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll");
616         std::string coreLibBackup = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll.Backup");
617
618         if (hasCoreLibNI()) {
619                 if (!isFile(coreLibBackup)) {
620                         return;
621                 }
622
623                 if (remove(coreLib.c_str())) {
624                         fprintf(stderr, "Failed to remove System.Private.CoreLib native image file\n");
625                 }
626                 if (rename(coreLibBackup.c_str(), coreLib.c_str())) {
627                         fprintf(stderr, "Failed to rename System.Private.CoreLib.Backup to origin\n");
628                 }
629         }
630
631 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
632         if (isFile(__SYSTEM_BASE_FILE)) {
633                 if (remove(__SYSTEM_BASE_FILE)) {
634                         fprintf(stderr, "Failed to remove %s\n", __SYSTEM_BASE_FILE);
635                 }
636         }
637 #endif
638
639         removeNIUnderDirs(__pm->getRuntimePath() + ":" + __pm->getTizenFXPath());
640 }
641
642 void removeNIUnderDirs(const std::string& rootPaths)
643 {
644         auto convert = [](const std::string& path, const std::string& filename) {
645                 if (isNativeImage(path)) {
646                         if (remove(path.c_str())) {
647                                 fprintf(stderr, "Failed to remove %s\n", path.c_str());
648                         }
649                 }
650         };
651
652         std::vector<std::string> paths;
653         splitPath(rootPaths, paths);
654         for (const auto &path : paths) {
655                 scanFilesInDirectory(path, convert, -1);
656         }
657 }
658
659 ni_error_e removeNIUnderPkgRoot(const std::string& pkgId)
660 {
661         std::string rootPath = getRootPath(pkgId);
662         if (rootPath.empty()) {
663                 fprintf(stderr, "Failed to get root path from [%s]\n", pkgId.c_str());
664                 return NI_ERROR_INVALID_PACKAGE;
665         }
666
667         __pm->setAppRootPath(rootPath);
668
669         // getAppNIPaths returns bin/.native_image, lib/.native_image and .tac_symlink.
670         std::string appNIPaths = __pm->getAppNIPaths();
671         std::vector<std::string> paths;
672         splitPath(appNIPaths, paths);
673         for (const auto &path : paths) {
674                 // Only the native image inside the TAC should be removed.
675                 if (strstr(path.c_str(), TAC_SYMLINK_SUB_DIR) != NULL) {
676                         removeNIUnderDirs(path);
677                 } else {
678                         if (isDirectory(path)) {
679                                 if (!removeAll(path.c_str())) {
680                                         fprintf(stderr, "Failed to remove app ni dir [%s]\n", path.c_str());
681                                 }
682                         }
683                 }
684         }
685
686         return NI_ERROR_NONE;
687 }
688
689 ni_error_e regenerateAppNI(DWORD flags)
690 {
691         if (!isCoreLibPrepared(flags)) {
692                 return NI_ERROR_CORE_NI_FILE;
693         }
694
695         int ret = 0;
696         pkgmgrinfo_appinfo_metadata_filter_h handle;
697
698         ret = pkgmgrinfo_appinfo_metadata_filter_create(&handle);
699         if (ret != PMINFO_R_OK)
700                 return NI_ERROR_UNKNOWN;
701
702         ret = pkgmgrinfo_appinfo_metadata_filter_add(handle, AOT_METADATA_KEY, METADATA_VALUE);
703         if (ret != PMINFO_R_OK) {
704                 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
705                 return NI_ERROR_UNKNOWN;
706         }
707
708         ret = pkgmgrinfo_appinfo_metadata_filter_foreach(handle, appAotCb, &flags);
709         if (ret != PMINFO_R_OK) {
710                 fprintf(stderr, "Failed pkgmgrinfo_appinfo_metadata_filter_foreach\n");
711                 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
712                 return NI_ERROR_UNKNOWN;
713         }
714
715         fprintf(stdout, "Success pkgmgrinfo_appinfo_metadata_filter_foreach\n");
716
717         pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
718         return NI_ERROR_NONE;
719 }
720
721 // callback function of "pkgmgrinfo_appinfo_metadata_filter_foreach"
722 static int regenTacCb(pkgmgrinfo_appinfo_h handle, void *userData)
723 {
724         char *pkgId = NULL;
725         DWORD *pFlags = (DWORD*)userData;
726
727         int ret = pkgmgrinfo_appinfo_get_pkgid(handle, &pkgId);
728         if (ret != PMINFO_R_OK || pkgId == NULL) {
729                 fprintf(stderr, "Failed to get pkgid\n");
730                 return -1;
731         }
732
733         sqlite3 *tac_db = openDB(TAC_APP_LIST_DB);
734         if (!tac_db) {
735                 fprintf(stderr, "Sqlite open error\n");
736                 return -1;
737         }
738         sqlite3_exec(tac_db, "BEGIN;", NULL, NULL, NULL);
739
740         char *sql = sqlite3_mprintf("SELECT * FROM TAC WHERE PKGID = %Q;", pkgId);
741         std::vector<std::string> nugets = selectDB(tac_db, sql);
742         sqlite3_free(sql);
743
744         if (tac_db) {
745                 closeDB(tac_db);
746                 tac_db = NULL;
747         }
748
749         std::string nugetPaths;
750         for (const auto &nuget : nugets) {
751                 if (!nugetPaths.empty()) {
752                         nugetPaths += ":";
753                 }
754                 nugetPaths += concatPath(__DOTNET_DIR, nuget);
755         }
756
757         auto convert = [&nugetPaths, pFlags](const std::string& path, const std::string& filename) {
758                 if (strstr(path.c_str(), TAC_SHA_256_INFO) != NULL)
759                         return;
760                 if (!crossgen(path, nugetPaths.c_str(), *pFlags)) {
761                         waitInterval();
762                 }
763         };
764
765         for (auto& nuget : nugets) {
766                 scanFilesInDirectory(concatPath(__DOTNET_DIR, nuget), convert, -1);
767         }
768
769         return 0;
770 }
771
772 ni_error_e regenerateTACNI(DWORD flags)
773 {
774         if (!isCoreLibPrepared(flags)) {
775                 return NI_ERROR_CORE_NI_FILE;
776         }
777
778         removeNIUnderDirs(__DOTNET_DIR);
779
780         pkgmgrinfo_appinfo_metadata_filter_h handle;
781         int ret = pkgmgrinfo_appinfo_metadata_filter_create(&handle);
782         if (ret != PMINFO_R_OK) {
783                 return NI_ERROR_UNKNOWN;
784         }
785
786         ret = pkgmgrinfo_appinfo_metadata_filter_add(handle, TAC_METADATA_KEY, METADATA_VALUE);
787         if (ret != PMINFO_R_OK) {
788                 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
789                 return NI_ERROR_UNKNOWN;
790         }
791
792         ret = pkgmgrinfo_appinfo_metadata_filter_foreach(handle, regenTacCb, &flags);
793         if (ret != PMINFO_R_OK) {
794                 fprintf(stderr, "Failed pkgmgrinfo_appinfo_metadata_filter_foreach\n");
795                 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
796                 return NI_ERROR_UNKNOWN;
797         }
798         fprintf(stdout, "Success pkgmgrinfo_appinfo_metadata_filter_foreach\n");
799
800         pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
801
802         return NI_ERROR_NONE;
803 }