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