Skip app ni regeneration if app ni already exist (#344)
[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                 _SOUT("sleep %d usec", __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                 _SERR("File doesnot contain extension. fail to get NI file name");
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                                         _SERR("Fail to create app ni directory (%s)", 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                                         _SERR("Fail. path is not a dir (%s)", 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_APP_UNDER_RO_AREA) {
152                 niDirPath = replaceAll(niDirPath, getBaseName(__pm->getAppRootPath()), __READ_ONLY_APP_UPDATE_DIR);
153                 _SERR("App is installed in RO area. Change NI path to RW area(%s).", niDirPath.c_str());
154                 _ERR("App is installed in RO area. Change NI path to RW area(%s).", niDirPath.c_str());
155         }
156
157         if (!isDirectory(niDirPath)) {
158                 if (!createDirsAndCopyOwnerShip(niDirPath, prevPath)) {
159                         niDirPath = prevPath;
160                         _SERR("fail to create dir (%s)", niDirPath.c_str());
161                 }
162         }
163
164         return getNIFilePath(concatPath(niDirPath, getFileName(absDllPath)));
165 }
166
167 static bool checkNIExistence(const std::string& absDllPath, const std::string& absNIPath)
168 {
169         if (absNIPath.empty()) {
170                 return false;
171         }
172
173         if (isFile(absNIPath)) {
174                 return true;
175         }
176
177         // native image of System.Private.CoreLib.dll should have to overwrite
178         // original file to support new coreclr
179         if (absDllPath.find("System.Private.CoreLib.dll") != std::string::npos) {
180                 std::string coreLibBackup = absDllPath + ".Backup";
181                 if (isFile(coreLibBackup)) {
182                         return true;
183                 }
184         }
185
186         return false;
187 }
188
189 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
190 static uintptr_t getFileSize(const std::string& path)
191 {
192         struct stat sb;
193
194         if (stat(path.c_str(), &sb) == 0) {
195                 return sb.st_size;
196         }
197
198         return 0;
199 }
200
201 // Get next base address to be used for system ni image from file
202 // __SYSTEM_BASE_FILE should be checked for existance before calling this function
203 static uintptr_t getNextBaseAddrFromFile()
204 {
205         FILE *pFile = fopen(__SYSTEM_BASE_FILE, "r");
206         if (pFile == NULL) {
207                 _SERR("Failed to open %s", __SYSTEM_BASE_FILE);
208                 return 0;
209         }
210
211         uintptr_t addr = 0;
212         uintptr_t size = 0;
213
214         while (fscanf(pFile, "%" SCNxPTR " %" SCNuPTR "", &addr, &size) != EOF) {
215         }
216
217         fclose(pFile);
218
219         return addr + size;
220 }
221
222 // Get next base address to be used for system ni image
223 static uintptr_t getNextBaseAddr()
224 {
225         uintptr_t baseAddr = 0;
226
227         if (!isFile(__SYSTEM_BASE_FILE)) {
228                 // This is the starting address for all default base addresses
229                 baseAddr = DEFAULT_BASE_ADDR_START;
230         } else {
231                 baseAddr = getNextBaseAddrFromFile();
232
233                 // Round to a multple of 64K (see ZapImage::CalculateZapBaseAddress in CoreCLR)
234                 uintptr_t BASE_ADDRESS_ALIGNMENT = 0xffff;
235                 baseAddr = (baseAddr + BASE_ADDRESS_ALIGNMENT) & ~BASE_ADDRESS_ALIGNMENT;
236         }
237
238         return baseAddr;
239 }
240
241 // Save base address of system ni image to file
242 static void updateBaseAddrFile(const std::string& absNIPath, uintptr_t baseAddr)
243 {
244         uintptr_t niSize = getFileSize(absNIPath);
245         if (niSize == 0) {
246                 _SERR("File %s doesn't exist", absNIPath.c_str());
247                 return;
248         }
249
250         // Write new entry to the file
251         FILE *pFile = fopen(__SYSTEM_BASE_FILE, "a");
252         if (pFile == NULL) {
253                 _SERR("Failed to open %s", __SYSTEM_BASE_FILE);
254                 return;
255         }
256
257         fprintf(pFile, "%" PRIxPTR " %" PRIuPTR "\n", baseAddr, niSize);
258         fclose(pFile);
259 }
260
261 // check if dll is listed in TPA
262 static bool isTPADll(const std::string& dllPath)
263 {
264         std::string absPath = getBaseName(getAbsolutePath(dllPath));
265
266         std::vector<std::string> paths = __pm->getPlatformAssembliesPaths();
267         for (unsigned int i = 0; i < paths.size(); i++) {
268                 if (paths[i].find(getBaseName(absPath)) != std::string::npos) {
269                         return true;
270                 }
271         }
272
273         return false;
274 }
275 #endif
276
277 // baseAddr should be checked in file before getting here
278 static ni_error_e crossgen(const std::string& dllPath, const std::string& appPath, DWORD flags)
279 {
280         if (!isFile(dllPath)) {
281                 _SERR("dll file is not exist : %s", dllPath.c_str());
282                 return NI_ERROR_NO_SUCH_FILE;
283         }
284
285         if (!isManagedAssembly(dllPath)) {
286                 //_SERR("Input file is not a dll file : %s", dllPath.c_str());
287                 return NI_ERROR_INVALID_PARAMETER;
288         }
289
290         std::string absDllPath = getAbsolutePath(dllPath);
291         std::string absNIPath;
292
293         bool isAppNI = flags & NI_FLAGS_APPNI;
294         if (isAppNI && strstr(absDllPath.c_str(), __DOTNET_DIR) == NULL) {
295                 absNIPath = getAppNIFilePath(absDllPath, flags);
296         } else {
297                 absNIPath = getNIFilePath(absDllPath);
298         }
299
300         if (absNIPath.empty()) {
301                 _SERR("Fail to get ni file name");
302                 return NI_ERROR_UNKNOWN;
303         }
304
305         if (checkNIExistence(absDllPath, absNIPath)) {
306                 //_SERR("Already ni file is exist for %s", absNIPath.c_str());
307                 return NI_ERROR_ALREADY_EXIST;
308         }
309
310 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
311         uintptr_t baseAddr = 0;
312
313         if (isTPADll(dllPath)) {
314                 baseAddr = getNextBaseAddr();
315         }
316 #endif
317
318         pid_t pid = fork();
319         if (pid == -1)
320                 return NI_ERROR_UNKNOWN;
321
322         if (pid > 0) {
323                 int status;
324                 waitpid(pid, &status, 0);
325                 if (WIFEXITED(status)) {
326                         // Do not use checkNIExistence() function to check whether ni file created or not.
327                         // checkNIExistence() return false for System.Private.Corelib.dll
328                         if (isFile(absNIPath)) {
329                                 copySmackAndOwnership(absDllPath, absNIPath);
330                                 std::string absPdbPath = replaceAll(absDllPath, ".dll", ".pdb");
331                                 std::string pdbFilePath = replaceAll(absNIPath, ".ni.dll", ".pdb");
332                                 if (isFile(absPdbPath) && (absPdbPath != pdbFilePath)) {
333                                         if (!copyFile(absPdbPath, pdbFilePath)) {
334                                                 _SERR("Failed to copy a .pdb file");
335                                         } else {
336                                                 copySmackAndOwnership(absPdbPath, pdbFilePath);
337                                         }
338                                 }
339 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
340                                 if (baseAddr != 0) {
341                                         updateBaseAddrFile(absNIPath, baseAddr);
342                                 }
343 #endif
344                                 return NI_ERROR_NONE;
345                         } else {
346                                 _SERR("Fail to create native image for %s", dllPath.c_str());
347                                 return NI_ERROR_NO_SUCH_FILE;
348                         }
349                 }
350         } else {
351                 std::string jitPath = __pm->getRuntimePath() + "/libclrjit.so";
352                 std::vector<const char*> argv = {
353                         __CROSSGEN_PATH,
354                         "/nologo",
355                         "/JITPath", jitPath.c_str()
356                 };
357
358                 bool compat = flags & NI_FLAGS_COMPATIBILITY;
359                 argv.push_back(compat ? "/Platform_Assemblies_Pathes" : "/p");
360                 std::vector<std::string> paths = __pm->getPlatformAssembliesPaths();
361                 std::string platformAssembliesPaths;
362                 for (const auto &path : paths) {
363                         if (!platformAssembliesPaths.empty()) {
364                                 platformAssembliesPaths += ":";
365                         }
366                         platformAssembliesPaths += path;
367                 }
368                 argv.push_back(platformAssembliesPaths.c_str());
369
370                 bool enableR2R = flags & NI_FLAGS_ENABLER2R;
371                 if (!enableR2R) {
372                         argv.push_back("/FragileNonVersionable");
373                 }
374
375                 if (flags & NI_FLAGS_VERBOSE) {
376                         argv.push_back("/verbose");
377                 }
378
379                 if (flags & NI_FLAGS_INSTRUMENT) {
380                         argv.push_back("/Tuning");
381                 }
382
383 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
384                 std::string baseAddrString;
385                 if (baseAddr != 0) {
386                         argv.push_back("/BaseAddress");
387                         std::stringstream ss;
388                         ss << "0x" << std::hex << baseAddr;
389                         baseAddrString = ss.str();
390                         argv.push_back(baseAddrString.c_str());
391                 }
392 #endif
393
394                 argv.push_back("/App_Paths");
395                 std::string absAppPath;
396                 if (!appPath.empty()) {
397                         absAppPath = appPath;
398                 } else {
399                         absAppPath = getBaseName(absDllPath);
400                 }
401                 argv.push_back(absAppPath.c_str());
402
403                 argv.push_back("/out");
404                 argv.push_back(absNIPath.c_str());
405
406                 argv.push_back(absDllPath.c_str());
407                 argv.push_back(nullptr);
408
409                 _SOUT("+ %s (%s)", absDllPath.c_str(), enableR2R ? "R2R" : "FNV");
410
411                 execv(__CROSSGEN_PATH, const_cast<char* const*>(argv.data()));
412                 exit(0);
413         }
414
415         return NI_ERROR_NONE;
416 }
417
418 // callback function of "pkgmgrinfo_appinfo_metadata_filter_foreach"
419 static int appAotCb(pkgmgrinfo_appinfo_h handle, void *userData)
420 {
421         char *pkgId = NULL;
422         int ret = 0;
423         DWORD *pFlags = (DWORD*)userData;
424
425         ret = pkgmgrinfo_appinfo_get_pkgid(handle, &pkgId);
426         if (ret != PMINFO_R_OK) {
427                 _SERR("Failed to get pkgid");
428                 return -1;
429         }
430
431         if (removeNIUnderPkgRoot(pkgId) != NI_ERROR_NONE) {
432                 _SERR("Failed to remove previous dlls from [%s]", pkgId);
433                 return -1;
434         }
435
436         if (createNIUnderPkgRoot(pkgId, *pFlags) != NI_ERROR_NONE) {
437                 _SERR("Failed to generate NI file [%s]", pkgId);
438                 return -1;
439         } else {
440                 _SOUT("Complete make application to native image");
441         }
442
443         return 0;
444 }
445
446 static bool isCoreLibPrepared(DWORD flags)
447 {
448         if (flags & NI_FLAGS_ENABLER2R) {
449                 return true;
450         }
451
452         std::string coreLibBackup = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll.Backup");
453         if (isFile(coreLibBackup)) {
454                 return true;
455         } else {
456                 _SERR("The native image of System.Private.CoreLib does not exist\n"
457                                         "Run the command to create the native image\n"
458                                         "# dotnettool --ni-dll /usr/share/dotnet.tizen/netcoreapp/System.Private.CoreLib.dll\n");
459                 return false;
460         }
461 }
462
463 static bool hasCoreLibNI()
464 {
465         std::string ildasm = concatPath(__pm->getRuntimePath(), "ildasm");
466         std::string coreLib = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll");
467         std::string cmd = ildasm + " " + coreLib + " -noil -stats | grep '\\.xdata'";
468
469         FILE *fp;
470         fp = popen(cmd.c_str(), "r");
471         if (fp != NULL) {
472                 char buff[1024];
473                 if (fgets(buff, sizeof(buff), fp) != NULL) {
474                         pclose(fp);
475                         return true;
476                 }
477                 pclose(fp);
478         }
479         return false;
480 }
481
482 static ni_error_e createCoreLibNI(DWORD flags)
483 {
484         std::string coreLib = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll");
485         std::string niCoreLib = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.ni.dll");
486         std::string coreLibBackup = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll.Backup");
487
488         if (!isFile(coreLibBackup) && !hasCoreLibNI()) {
489                 if (!crossgen(coreLib, std::string(), flags)) {
490                         if (rename(coreLib.c_str(), coreLibBackup.c_str())) {
491                                 _SERR("Failed to rename System.Private.CoreLib.dll");
492                                 return NI_ERROR_CORE_NI_FILE;
493                         }
494                         if (rename(niCoreLib.c_str(), coreLib.c_str())) {
495                                 _SERR("Failed to rename System.Private.CoreLib.ni.dll");
496                                 return NI_ERROR_CORE_NI_FILE;
497                         }
498                 } else {
499                         _SERR("Failed to create native image for %s", coreLib.c_str());
500                         return NI_ERROR_CORE_NI_FILE;
501                 }
502         }
503         return NI_ERROR_NONE;
504 }
505
506 ni_error_e initNICommon()
507 {
508 #if defined(__arm__) || defined(__aarch64__)
509         // get interval value
510         const static std::string intervalFile = concatPath(__NATIVE_LIB_DIR, "crossgen_interval.txt");
511         std::ifstream inFile(intervalFile);
512         if (inFile) {
513                 _SOUT("crossgen_interval.txt is found");
514                 inFile >> __interval;
515         }
516
517         if (initializePluginManager("normal")) {
518                 _SERR("Fail to initialize PluginManager");
519                 return NI_ERROR_UNKNOWN;
520         }
521
522         try {
523                 __pm = new PathManager();
524         } catch (const std::exception& e) {
525                 _SERR("Failed to create PathManager");
526                 return NI_ERROR_UNKNOWN;
527         }
528
529         char* pluginDllPaths = pluginGetDllPath();
530         if (pluginDllPaths && pluginDllPaths[0] != '\0') {
531                 __pm->addPlatformAssembliesPaths(pluginDllPaths, true);
532         }
533
534         char* pluginNativePaths = pluginGetNativeDllSearchingPath();
535         if (pluginNativePaths && pluginNativePaths[0] != '\0') {
536                 __pm->addNativeDllSearchingPaths(pluginNativePaths, true);
537         }
538
539         return NI_ERROR_NONE;
540 #else
541         _SERR("crossgen supports arm/arm64 architecture only. skip ni file generation");
542         return NI_ERROR_NOT_SUPPORTED;
543 #endif
544 }
545
546 void finalizeNICommon()
547 {
548         __interval = 0;
549
550         finalizePluginManager();
551
552         delete(__pm);
553         __pm = nullptr;
554 }
555
556 ni_error_e createNIPlatform(DWORD flags)
557 {
558         if (createCoreLibNI(flags) != NI_ERROR_NONE) {
559                 return NI_ERROR_CORE_NI_FILE;
560         }
561
562         return createNIUnderDirs(__pm->getRuntimePath() + ":" + __pm->getTizenFXPath(), flags);
563 }
564
565 ni_error_e createNIDll(const std::string& dllPath, DWORD flags)
566 {
567         if (dllPath.find("System.Private.CoreLib.dll") != std::string::npos) {
568                 return createCoreLibNI(flags);
569         }
570
571         if (!isCoreLibPrepared(flags)) {
572                 return NI_ERROR_CORE_NI_FILE;
573         }
574
575         return crossgen(dllPath, std::string(), flags);
576 }
577
578 ni_error_e createNIUnderDirs(const std::string& rootPaths, DWORD flags)
579 {
580         if (!isCoreLibPrepared(flags)) {
581                 return NI_ERROR_CORE_NI_FILE;
582         }
583
584         auto convert = [&rootPaths, flags](const std::string& path, const std::string& filename) {
585                 // if path is symlink, donot generate crossgen
586                 if (!crossgen(path, rootPaths.c_str(), flags)) {
587                         waitInterval();
588                 }
589         };
590
591         std::vector<std::string> targetPaths;
592         splitPath(rootPaths, targetPaths);
593         for (const auto &path : targetPaths) {
594                 // TAC directory should be handled specially because that contains symlink of native image file.
595                 if (strstr(path.c_str(), TAC_SYMLINK_SUB_DIR) != NULL) {
596                         if (!isDirectory(path)) {
597                                 continue;
598                         }
599                         // make native image symlink if not exist under tac directory
600                         try {
601                                 for (auto& symlinkAssembly : bf::recursive_directory_iterator(path)) {
602                                         std::string symPath = symlinkAssembly.path().string();
603                                         if (!isManagedAssembly(symPath)) {
604                                                 continue;
605                                         }
606
607                                         // if there is symlink and original file for native image, skip generation
608                                         std::string symNIPath = changeExtension(symPath, "dll", "ni.dll");
609                                         if (isFile(symNIPath)) {
610                                                 continue;
611                                         }
612
613                                         // if original native image not exist, generate native image
614                                         std::string originPath = bf::read_symlink(symPath).string();
615                                         std::string originNIPath = changeExtension(originPath, "dll", "ni.dll");
616                                         if (!isFile(originNIPath)) {
617                                                 if (!crossgen(originPath, path.c_str(), flags)) {
618                                                         waitInterval();
619                                                 }
620                                         }
621
622                                         // if no symlink file exist, create symlink
623                                         if (!isFile(symNIPath)) {
624                                                 bf::create_symlink(originNIPath, symNIPath);
625                                                 copySmackAndOwnership(symPath.c_str(), symNIPath.c_str(), true);
626                                                 _SOUT("%s symbolic link file generated successfully.", symNIPath.c_str());
627                                                 _INFO("%s symbolic link file generated successfully.", symNIPath.c_str());
628                                         }
629                                 }
630                         } catch (const bf::filesystem_error& error) {
631                                 _SERR("Failed to recursive directory: %s", error.what());
632                                 return NI_ERROR_UNKNOWN;
633                         }
634                 } else {
635                         scanFilesInDirectory(path, convert, 0);
636                 }
637         }
638
639         return NI_ERROR_NONE;
640 }
641
642 ni_error_e createNIUnderPkgRoot(const std::string& pkgId, DWORD flags)
643 {
644         std::string rootPath = getRootPath(pkgId);
645         if (rootPath.empty()) {
646                 _SERR("Failed to get root path from [%s]", pkgId.c_str());
647                 return NI_ERROR_INVALID_PACKAGE;
648         }
649
650         __pm->setAppRootPath(rootPath);
651
652         flags |= NI_FLAGS_APPNI;
653
654         if (isReadOnlyArea(rootPath)) {
655                 flags |= NI_FLAGS_APP_UNDER_RO_AREA;
656         } else {
657                 flags &= ~NI_FLAGS_APP_UNDER_RO_AREA;
658         }
659
660         // create native image under bin and lib directory
661         // tac directory is skipped in the createNIUnderDirs.
662         return createNIUnderDirs(__pm->getAppPaths(), flags);
663 }
664
665 void removeNIPlatform()
666 {
667         std::string coreLib = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll");
668         std::string coreLibBackup = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll.Backup");
669
670         if (hasCoreLibNI()) {
671                 if (!isFile(coreLibBackup)) {
672                         return;
673                 }
674
675                 if (remove(coreLib.c_str())) {
676                         _SERR("Failed to remove System.Private.CoreLib native image file");
677                 }
678                 if (rename(coreLibBackup.c_str(), coreLib.c_str())) {
679                         _SERR("Failed to rename System.Private.CoreLib.Backup to origin");
680                 }
681         }
682
683 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
684         if (isFile(__SYSTEM_BASE_FILE)) {
685                 if (remove(__SYSTEM_BASE_FILE)) {
686                         _SERR("Failed to remove %s", __SYSTEM_BASE_FILE);
687                 }
688         }
689 #endif
690
691         removeNIUnderDirs(__pm->getRuntimePath() + ":" + __pm->getTizenFXPath());
692 }
693
694 void removeNIUnderDirs(const std::string& rootPaths)
695 {
696         auto convert = [](const std::string& path, const std::string& filename) {
697                 if (isNativeImage(path)) {
698                         if (remove(path.c_str())) {
699                                 _SERR("Failed to remove %s", path.c_str());
700                         }
701                 }
702         };
703
704         std::vector<std::string> paths;
705         splitPath(rootPaths, paths);
706         for (const auto &path : paths) {
707                 scanFilesInDirectory(path, convert, -1);
708         }
709 }
710
711 ni_error_e removeNIUnderPkgRoot(const std::string& pkgId)
712 {
713         std::string rootPath = getRootPath(pkgId);
714         if (rootPath.empty()) {
715                 _SERR("Failed to get root path from [%s]", pkgId.c_str());
716                 return NI_ERROR_INVALID_PACKAGE;
717         }
718
719         __pm->setAppRootPath(rootPath);
720
721         // getAppNIPaths returns bin/.native_image, lib/.native_image and .tac_symlink.
722         std::string appNIPaths = __pm->getAppNIPaths();
723         std::vector<std::string> paths;
724         splitPath(appNIPaths, paths);
725         for (const auto &path : paths) {
726                 if (!isReadOnlyArea(path)) {
727                         // Only the native image inside the TAC should be removed.
728                         if (strstr(path.c_str(), TAC_SYMLINK_SUB_DIR) != NULL) {
729                                 removeNIUnderDirs(path);
730                         } else {
731                                 if (isDirectory(path)) {
732                                         if (!removeAll(path.c_str())) {
733                                                 _SERR("Failed to remove app ni dir [%s]", path.c_str());
734                                         }
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                 _SERR("Failed to get pkgid");
781                 return -1;
782         }
783
784         sqlite3 *tac_db = openDB(TAC_APP_LIST_DB);
785         if (!tac_db) {
786                 _SERR("Sqlite open error");
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 }