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