Code cleanup and Add missing flag (#257)
[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                 if (baseAddr != 0) {
341                         argv.push_back("/BaseAddress");
342                         argv.push_back(std::to_string(baseAddr).c_str());
343                 }
344 #endif
345
346                 argv.push_back("/App_Paths");
347                 std::string absAppPath;
348                 if (!appPath.empty()) {
349                         absAppPath = appPath;
350                 } else {
351                         absAppPath = getBaseName(absDllPath);
352                 }
353                 argv.push_back(absAppPath.c_str());
354
355                 argv.push_back("/out");
356                 argv.push_back(absNIPath.c_str());
357
358                 argv.push_back(absDllPath.c_str());
359                 argv.push_back(nullptr);
360
361                 fprintf(stdout, "+ %s (%s)\n", absDllPath.c_str(), enableR2R ? "R2R" : "FNV");
362
363                 execv(__CROSSGEN_PATH, const_cast<char* const*>(argv.data()));
364                 exit(0);
365         }
366
367         return NI_ERROR_NONE;
368 }
369
370 // callback function of "pkgmgrinfo_appinfo_metadata_filter_foreach"
371 static int appAotCb(pkgmgrinfo_appinfo_h handle, void *userData)
372 {
373         char *pkgId = NULL;
374         int ret = 0;
375         DWORD *pFlags = (DWORD*)userData;
376
377         ret = pkgmgrinfo_appinfo_get_pkgid(handle, &pkgId);
378         if (ret != PMINFO_R_OK) {
379                 fprintf(stderr, "Failed to get pkgid\n");
380                 return -1;
381         }
382
383         if (removeNIUnderPkgRoot(pkgId) != NI_ERROR_NONE) {
384                 fprintf(stderr, "Failed to remove previous dlls from [%s]\n", pkgId);
385                 return -1;
386         }
387
388         if (createNIUnderPkgRoot(pkgId, *pFlags) != NI_ERROR_NONE) {
389                 fprintf(stderr, "Failed to generate NI file [%s]\n", pkgId);
390                 return -1;
391         } else {
392                 fprintf(stdout, "Complete make application to native image\n");
393         }
394
395         return 0;
396 }
397
398 static bool isCoreLibPrepared(DWORD flags)
399 {
400         if (flags & NI_FLAGS_ENABLER2R) {
401                 return true;
402         }
403
404         std::string coreLibBackup = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll.Backup");
405         if (isFile(coreLibBackup)) {
406                 return true;
407         } else {
408                 fprintf(stderr, "The native image of System.Private.CoreLib does not exist\n"
409                                         "Run the command to create the native image\n"
410                                         "# dotnettool --ni-dll /usr/share/dotnet.tizen/netcoreapp/System.Private.CoreLib.dll\n\n");
411                 return false;
412         }
413 }
414
415 static bool hasCoreLibNI()
416 {
417         FILE *fp;
418         char buff[1024];
419         std::string ildasm = concatPath(__pm->getRuntimePath(), "ildasm");
420         std::string coreLib = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll");
421         std::string cmd = ildasm + " " + coreLib + " | grep '\\.corflags'";
422         fp = popen(cmd.c_str(), "r");
423         if (fp != NULL) {
424                 while (fgets(buff, sizeof(buff), fp) != NULL) {
425                         buff[strlen(buff) - 1] = '\0';
426                 }
427                 std::string corflag = replaceAll(buff, ".corflags", "");
428                 corflag.erase(std::remove(corflag.begin(), corflag.end(), ' '), corflag.end());
429                 // CorFlags.ILLibrary=0x00000004 (.ni.dll)
430                 if (!strcmp(corflag.substr(0, 10).c_str(), "0x00000004")) {
431                         pclose(fp);
432                         return true;
433                 }
434                 pclose(fp);
435         }
436         return false;
437 }
438
439 static ni_error_e createCoreLibNI(DWORD flags)
440 {
441         std::string coreLib = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll");
442         std::string niCoreLib = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.ni.dll");
443         std::string coreLibBackup = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll.Backup");
444
445         if (!isFile(coreLibBackup) && !hasCoreLibNI()) {
446                 if (!crossgen(coreLib, std::string(), flags)) {
447                         if (rename(coreLib.c_str(), coreLibBackup.c_str())) {
448                                 fprintf(stderr, "Failed to rename System.Private.CoreLib.dll\n");
449                                 return NI_ERROR_CORE_NI_FILE;
450                         }
451                         if (rename(niCoreLib.c_str(), coreLib.c_str())) {
452                                 fprintf(stderr, "Failed to rename System.Private.CoreLib.ni.dll\n");
453                                 return NI_ERROR_CORE_NI_FILE;
454                         }
455                 } else {
456                         fprintf(stderr, "Failed to create native image for %s\n", coreLib.c_str());
457                         return NI_ERROR_CORE_NI_FILE;
458                 }
459         }
460         return NI_ERROR_NONE;
461 }
462
463 ni_error_e initNICommon()
464 {
465 #if defined(__arm__) || defined(__aarch64__)
466         // get interval value
467         const static std::string intervalFile = concatPath(__NATIVE_LIB_DIR, "crossgen_interval.txt");
468         std::ifstream inFile(intervalFile);
469         if (inFile) {
470                 fprintf(stdout, "crossgen_interval.txt is found\n");
471                 inFile >> __interval;
472         }
473
474         if (initializePluginManager("normal")) {
475                 fprintf(stderr, "Fail to initialize PluginManager\n");
476                 return NI_ERROR_UNKNOWN;
477         }
478
479         try {
480                 __pm = new PathManager();
481         } catch (const std::exception& e) {
482                 fprintf(stderr, "Failed to create PathManager");
483                 return NI_ERROR_UNKNOWN;
484         }
485
486         char* pluginDllPaths = pluginGetDllPath();
487         if (pluginDllPaths) {
488                 __pm->addPlatformAssembliesPaths(pluginDllPaths);
489         }
490
491         return NI_ERROR_NONE;
492 #else
493         fprintf(stderr, "crossgen supports arm/arm64 architecture only. skip ni file generation\n");
494         return NI_ERROR_NOT_SUPPORTED;
495 #endif
496 }
497
498 void finalizeNICommon()
499 {
500         __interval = 0;
501
502         finalizePluginManager();
503
504         delete(__pm);
505         __pm = nullptr;
506 }
507
508 ni_error_e createNIPlatform(DWORD flags)
509 {
510         if (createCoreLibNI(flags) != NI_ERROR_NONE) {
511                 return NI_ERROR_CORE_NI_FILE;
512         }
513
514         return createNIUnderDirs(__pm->getRuntimePath() + ":" + __pm->getTizenFXPath(), flags);
515 }
516
517 ni_error_e createNIDll(const std::string& dllPath, DWORD flags)
518 {
519         if (dllPath.find("System.Private.CoreLib.dll") != std::string::npos) {
520                 return createCoreLibNI(flags);
521         }
522
523         if (!isCoreLibPrepared(flags)) {
524                 return NI_ERROR_CORE_NI_FILE;
525         }
526
527         return crossgen(dllPath, std::string(), flags);
528 }
529
530 ni_error_e createNIUnderDirs(const std::string rootPaths, DWORD flags)
531 {
532         if (!isCoreLibPrepared(flags)) {
533                 return NI_ERROR_CORE_NI_FILE;
534         }
535
536         auto convert = [&rootPaths, flags](const std::string& path, const std::string& filename) {
537                 // if path is symlink, donot generate crossgen
538                 if (!crossgen(path, rootPaths.c_str(), flags)) {
539                         waitInterval();
540                 }
541         };
542
543         std::vector<std::string> targetPaths;
544         splitPath(rootPaths, targetPaths);
545         for (const auto &path : targetPaths) {
546                 // TAC directory should be handled specially because that contains symlink of native image file.
547                 if (strstr(path.c_str(), TAC_SYMLINK_SUB_DIR) != NULL) {
548                         if (!isDirectory(path)) {
549                                 continue;
550                         }
551                         // make native image symlink if not exist under tac directory
552                         try {
553                                 for (auto& symlinkAssembly : bf::recursive_directory_iterator(path)) {
554                                         std::string symPath = symlinkAssembly.path().string();
555                                         if (!isManagedAssembly(symPath)) {
556                                                 continue;
557                                         }
558
559                                         // if there is symlink and original file for native image, skip generation
560                                         std::string symNIPath = symPath.substr(0, symPath.rfind(".dll")) + ".ni.dll";
561                                         if (isFile(symNIPath)) {
562                                                 continue;
563                                         }
564
565                                         // if original native image not exist, generate native image
566                                         std::string originPath = bf::read_symlink(symPath).string();
567                                         std::string originNIPath = originPath.substr(0, originPath.rfind(".dll")) + ".ni.dll";
568                                         if (!isFile(originNIPath)) {
569                                                 if (!crossgen(originPath, path.c_str(), flags)) {
570                                                         waitInterval();
571                                                 }
572                                         }
573
574                                         // if no symlink file exist, create symlink
575                                         if (!isFile(symNIPath)) {
576                                                 bf::create_symlink(originNIPath, symNIPath);
577                                                 copySmackAndOwnership(symPath.c_str(), symNIPath.c_str(), true);
578                                                 fprintf(stdout, "%s symbolic link file generated successfully.\n", symNIPath.c_str());
579                                                 _INFO("%s symbolic link file generated successfully.", symNIPath.c_str());
580                                         }
581                                 }
582                         } catch (const bf::filesystem_error& error) {
583                                 fprintf(stderr, "Failed to recursive directory: %s\n", error.what());
584                                 return NI_ERROR_UNKNOWN;
585                         }
586                 } else {
587                         scanFilesInDirectory(path, convert, 0);
588                 }
589         }
590
591         return NI_ERROR_NONE;
592 }
593
594 ni_error_e createNIUnderPkgRoot(const std::string& pkgId, DWORD flags)
595 {
596         std::string rootPath = getRootPath(pkgId);
597         if (rootPath.empty()) {
598                 fprintf(stderr, "Failed to get root path from [%s]\n", pkgId.c_str());
599                 return NI_ERROR_INVALID_PACKAGE;
600         }
601
602         __pm->setAppRootPath(rootPath);
603
604         flags |= NI_FLAGS_APPNI;
605
606         // create native image under bin and lib directory
607         // tac directory is skipped in the createNIUnderDirs.
608         return createNIUnderDirs(__pm->getAppPaths(), flags);
609 }
610
611 void removeNIPlatform()
612 {
613         std::string coreLib = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll");
614         std::string coreLibBackup = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll.Backup");
615
616         if (hasCoreLibNI()) {
617                 if (!isFile(coreLibBackup)) {
618                         return;
619                 }
620
621                 if (remove(coreLib.c_str())) {
622                         fprintf(stderr, "Failed to remove System.Private.CoreLib native image file\n");
623                 }
624                 if (rename(coreLibBackup.c_str(), coreLib.c_str())) {
625                         fprintf(stderr, "Failed to rename System.Private.CoreLib.Backup to origin\n");
626                 }
627         }
628
629 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
630         if (isFile(__SYSTEM_BASE_FILE)) {
631                 if (remove(__SYSTEM_BASE_FILE)) {
632                         fprintf(stderr, "Failed to remove %s\n", __SYSTEM_BASE_FILE);
633                 }
634         }
635 #endif
636
637         removeNIUnderDirs(__pm->getRuntimePath() + ":" + __pm->getTizenFXPath());
638 }
639
640 void removeNIUnderDirs(const std::string rootPaths)
641 {
642         auto convert = [](const std::string& path, const std::string& filename) {
643                 if (isNativeImage(path)) {
644                         if (remove(path.c_str())) {
645                                 fprintf(stderr, "Failed to remove %s\n", path.c_str());
646                         }
647                 }
648         };
649
650         std::vector<std::string> paths;
651         splitPath(rootPaths, paths);
652         for (const auto &path : paths) {
653                 scanFilesInDirectory(path, convert, -1);
654         }
655 }
656
657 ni_error_e removeNIUnderPkgRoot(const std::string& pkgId)
658 {
659         std::string rootPath = getRootPath(pkgId);
660         if (rootPath.empty()) {
661                 fprintf(stderr, "Failed to get root path from [%s]\n", pkgId.c_str());
662                 return NI_ERROR_INVALID_PACKAGE;
663         }
664
665         __pm->setAppRootPath(rootPath);
666
667         // getAppNIPaths returns bin/.native_image, lib/.native_image and .tac_symlink.
668         std::string appNIPaths = __pm->getAppNIPaths();
669         std::vector<std::string> paths;
670         splitPath(appNIPaths, paths);
671         for (const auto &path : paths) {
672                 // Only the native image inside the TAC should be removed.
673                 if (strstr(path.c_str(), TAC_SYMLINK_SUB_DIR) != NULL) {
674                         removeNIUnderDirs(path);
675                 } else {
676                         if (isDirectory(path)) {
677                                 if (!removeAll(path.c_str())) {
678                                         fprintf(stderr, "Failed to remove app ni dir [%s]\n", path.c_str());
679                                 }
680                         }
681                 }
682         }
683
684         return NI_ERROR_NONE;
685 }
686
687 ni_error_e regenerateAppNI(DWORD flags)
688 {
689         if (!isCoreLibPrepared(flags)) {
690                 return NI_ERROR_CORE_NI_FILE;
691         }
692
693         int ret = 0;
694         pkgmgrinfo_appinfo_metadata_filter_h handle;
695
696         ret = pkgmgrinfo_appinfo_metadata_filter_create(&handle);
697         if (ret != PMINFO_R_OK)
698                 return NI_ERROR_UNKNOWN;
699
700         ret = pkgmgrinfo_appinfo_metadata_filter_add(handle, AOT_METADATA_KEY, METADATA_VALUE);
701         if (ret != PMINFO_R_OK) {
702                 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
703                 return NI_ERROR_UNKNOWN;
704         }
705
706         ret = pkgmgrinfo_appinfo_metadata_filter_foreach(handle, appAotCb, &flags);
707         if (ret != PMINFO_R_OK) {
708                 fprintf(stderr, "Failed pkgmgrinfo_appinfo_metadata_filter_foreach\n");
709                 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
710                 return NI_ERROR_UNKNOWN;
711         }
712
713         fprintf(stdout, "Success pkgmgrinfo_appinfo_metadata_filter_foreach\n");
714
715         pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
716         return NI_ERROR_NONE;
717 }
718
719 // callback function of "pkgmgrinfo_appinfo_metadata_filter_foreach"
720 static int regenTacCb(pkgmgrinfo_appinfo_h handle, void *userData)
721 {
722         char *pkgId = NULL;
723         DWORD *pFlags = (DWORD*)userData;
724
725         int ret = pkgmgrinfo_appinfo_get_pkgid(handle, &pkgId);
726         if (ret != PMINFO_R_OK || pkgId == NULL) {
727                 fprintf(stderr, "Failed to get pkgid\n");
728                 return -1;
729         }
730
731         sqlite3 *tac_db = dbOpen(TAC_APP_LIST_DB);
732         if (!tac_db) {
733                 fprintf(stderr, "Sqlite open error\n");
734                 return -1;
735         }
736
737         char *sql = sqlite3_mprintf("SELECT * FROM TAC WHERE PKGID = %Q;", pkgId);
738         std::vector<std::string> nugets = dbSelect(tac_db, TAC_APP_LIST_DB, sql);
739         sqlite3_free(sql);
740
741         if (tac_db) {
742                 dbClose(tac_db);
743                 tac_db = NULL;
744         }
745
746         std::string nugetPaths;
747         for (const auto &nuget : nugets) {
748                 if (!nugetPaths.empty()) {
749                         nugetPaths += ":";
750                 }
751                 nugetPaths += concatPath(__DOTNET_DIR, nuget);
752         }
753
754         auto convert = [&nugetPaths, pFlags](const std::string& path, const std::string& filename) {
755                 if (strstr(path.c_str(), TAC_SHA_256_INFO) != NULL)
756                         return;
757                 if (!crossgen(path, nugetPaths.c_str(), *pFlags)) {
758                         waitInterval();
759                 }
760         };
761
762         for (auto& nuget : nugets) {
763                 scanFilesInDirectory(concatPath(__DOTNET_DIR, nuget), convert, -1);
764         }
765
766         return 0;
767 }
768
769 ni_error_e regenerateTACNI(DWORD flags)
770 {
771         if (!isCoreLibPrepared(flags)) {
772                 return NI_ERROR_CORE_NI_FILE;
773         }
774
775         removeNIUnderDirs(__DOTNET_DIR);
776
777         pkgmgrinfo_appinfo_metadata_filter_h handle;
778         int ret = pkgmgrinfo_appinfo_metadata_filter_create(&handle);
779         if (ret != PMINFO_R_OK) {
780                 return NI_ERROR_UNKNOWN;
781         }
782
783         ret = pkgmgrinfo_appinfo_metadata_filter_add(handle, TAC_METADATA_KEY, METADATA_VALUE);
784         if (ret != PMINFO_R_OK) {
785                 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
786                 return NI_ERROR_UNKNOWN;
787         }
788
789         ret = pkgmgrinfo_appinfo_metadata_filter_foreach(handle, regenTacCb, &flags);
790         if (ret != PMINFO_R_OK) {
791                 fprintf(stderr, "Failed pkgmgrinfo_appinfo_metadata_filter_foreach\n");
792                 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
793                 return NI_ERROR_UNKNOWN;
794         }
795         fprintf(stdout, "Success pkgmgrinfo_appinfo_metadata_filter_foreach\n");
796
797         pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
798
799         return NI_ERROR_NONE;
800 }