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