Code cleanup
[platform/core/dotnet/launcher.git] / NativeLauncher / tool / ni_common.cc
1 /*
2  * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
3  *
4  * Licensed under the Apache License, Version 2.0 (the License);
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an AS IS BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <pkgmgr-info.h>
18 #include <pkgmgr_installer_info.h>
19 #include <aul.h>
20
21 #include "log.h"
22 #include "utils.h"
23 #include "pkgmgr_parser_plugin_interface.h"
24
25 #include <wait.h>
26 #include <dirent.h>
27 #include <sys/stat.h>
28
29 #include <algorithm>
30 #include <string>
31 #include <fstream>
32
33 #include <pwd.h>
34 #include <grp.h>
35 #include <unistd.h>
36 #include <string.h>
37 #include <sqlite3.h>
38
39 #include "ni_common.h"
40 #include "db_manager.h"
41 #include "tac_common.h"
42 #include "path_manager.h"
43 #include "plugin_manager.h"
44
45 #ifdef  LOG_TAG
46 #undef  LOG_TAG
47 #endif
48 #define LOG_TAG "DOTNET_INSTALLER_PLUGIN"
49
50 #ifndef CROSSGEN_PATH
51 #error "CROSSGEN_PATH is missed"
52 #endif
53
54 #define __XSTR(x) #x
55 #define __STR(x) __XSTR(x)
56 static const char* __NATIVE_LIB_DIR = __STR(NATIVE_LIB_DIR);
57 static const char* __CROSSGEN_PATH = __STR(CROSSGEN_PATH);
58 static const char* __TAC_DIR = __STR(TAC_DIR);
59
60 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
61 static const char* __SYSTEM_BASE_FILE = __STR(SYSTEM_BASE_FILE);
62 #endif
63
64 #undef __STR
65 #undef __XSTR
66
67 static int __interval = 0;
68 static std::string __tpa;
69
70 static void waitInterval()
71 {
72         // by the recommand, ignore small value for performance.
73         if (__interval > 10000) {
74                 fprintf(stderr, "sleep %d usec\n", __interval);
75                 usleep(__interval);
76         }
77 }
78
79 static std::string getNiFilePath(const std::string& dllPath)
80 {
81         size_t index = dllPath.find_last_of(".");
82         if (index == std::string::npos) {
83                 fprintf(stderr, "File doesnot contain extension. fail to get NI file name\n");
84                 return "";
85         }
86         std::string fName = dllPath.substr(0, index);
87         std::string fExt = dllPath.substr(index, dllPath.length());
88
89         // crossgen generate file with lower case extension only
90         std::transform(fExt.begin(), fExt.end(), fExt.begin(), ::tolower);
91         std::string niPath = fName + ".ni" + fExt;
92
93         return niPath;
94 }
95
96 static std::string getAppNIPath(const std::string& niPath)
97 {
98         std::string fileName;
99         std::string niDirPath;
100         std::string prevPath;
101
102         size_t index = niPath.find_last_of("/");
103         if (index != std::string::npos) {
104                 prevPath = niPath.substr(0, index);
105                 fileName = niPath.substr(index + 1, niPath.length());
106         } else {
107                 prevPath = ".";
108                 fileName = niPath;
109         }
110
111         niDirPath = concatPath(prevPath, APP_NI_SUB_DIR);
112
113         if (!isFileExist(niDirPath)) {
114                 if (mkdir(niDirPath.c_str(), 0755) == 0) {
115                         updateAssemblyInfo(prevPath, niDirPath);
116                 } else {
117                         fprintf(stderr, "Fail to create app ni directory (%s)\n", niDirPath.c_str());
118                 }
119         }
120
121         return concatPath(niDirPath, fileName);
122 }
123
124 static bool niExist(const std::string& path)
125 {
126         std::string f = getNiFilePath(path);
127         if (f.empty()) {
128                 return false;
129         }
130
131         if (isFileExist(f)) {
132                 return true;
133         }
134
135         // native image of System.Private.CoreLib.dll should have to overwrite
136         // original file to support new coreclr
137         if (path.find("System.Private.CoreLib.dll") != std::string::npos) {
138                 std::string coreLibBackup = path + ".Backup";
139                 if (isFileExist(coreLibBackup)) {
140                         return true;
141                 }
142         }
143
144         return false;
145 }
146
147 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
148 // Get next base address to be used for system ni image from file
149 // __SYSTEM_BASE_FILE should be checked for existance before calling this function
150 static uintptr_t getNextBaseAddrFromFile()
151 {
152         FILE *pFile = fopen(__SYSTEM_BASE_FILE, "r");
153         if (pFile == NULL) {
154                 fprintf(stderr, "Failed to open %s\n", __SYSTEM_BASE_FILE);
155                 return 0;
156         }
157
158         uintptr_t addr = 0;
159         uintptr_t size = 0;
160
161         while (fscanf(pFile, "%u %u", &addr, &size) != EOF) {
162         }
163
164         fclose(pFile);
165
166         return addr + size;
167 }
168
169 // Get next base address to be used for system ni image
170 static uintptr_t getNextBaseAddr()
171 {
172         uintptr_t baseAddr = 0;
173
174         if (!isFileExist(__SYSTEM_BASE_FILE)) {
175                 // This is the starting address for all default base addresses
176                 baseAddr = DEFAULT_BASE_ADDR_START;
177         } else {
178                 baseAddr = getNextBaseAddrFromFile();
179
180                 // Round to a multple of 64K (see ZapImage::CalculateZapBaseAddress in CoreCLR)
181                 uintptr_t BASE_ADDRESS_ALIGNMENT = 0xffff;
182                 baseAddr = (baseAddr + BASE_ADDRESS_ALIGNMENT) & ~BASE_ADDRESS_ALIGNMENT;
183         }
184
185         return baseAddr;
186 }
187
188 // Save base address of system ni image to file
189 static void updateBaseAddrFile(const std::string &absNiPath, uintptr_t baseAddr)
190 {
191         uintptr_t niSize = getFileSize(absNiPath);
192         if (niSize == 0) {
193                 fprintf(stderr, "File %s doesn't exist\n", absNiPath.c_str());
194                 return;
195         }
196
197         // Write new entry to the file
198         FILE *pFile = fopen(__SYSTEM_BASE_FILE, "a");
199         if (pFile == NULL) {
200                 fprintf(stderr, "Failed to open %s\n", __SYSTEM_BASE_FILE);
201                 return;
202         }
203
204         fprintf(pFile, "%u %u\n", baseAddr, niSize);
205         fclose(pFile);
206 }
207
208 // check if dll is listed in TPA
209 static bool isTPADll(const std::string &dllPath)
210 {
211         std::string absDllPath = absolutePath(dllPath);
212
213         if (__tpa.find(absDllPath) != std::string::npos) {
214                 return true;
215         }
216
217         return false;
218 }
219 #endif
220
221 // baseAddr should be checked in file before getting here
222 static ni_error_e crossgen(const std::string& dllPath, const std::string& appPath, DWORD flags)
223 {
224         if (!isFileExist(dllPath)) {
225                 fprintf(stderr, "dll file is not exist : %s\n", dllPath.c_str());
226                 return NI_ERROR_NO_SUCH_FILE;
227         }
228
229         if (!isManagedAssembly(dllPath)) {
230                 fprintf(stderr, "Input file is not a dll file : %s\n", dllPath.c_str());
231                 return NI_ERROR_INVALID_PARAMETER;
232         }
233
234         if (niExist(dllPath)) {
235                 fprintf(stderr, "Already ni file is exist for %s\n", dllPath.c_str());
236                 return NI_ERROR_ALREADY_EXIST;
237         }
238
239         std::string absDllPath = absolutePath(dllPath);
240         std::string absNiPath = getNiFilePath(dllPath);
241         if (absNiPath.empty()) {
242                 fprintf(stderr, "Fail to get ni file name\n");
243                 return NI_ERROR_UNKNOWN;
244         }
245
246         bool isAppNI = flags & NI_FLAGS_APPNI;
247         if (isAppNI && strstr(absNiPath.c_str(), __TAC_DIR) == NULL) {
248                 absNiPath = getAppNIPath(absNiPath);
249         }
250
251 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
252         uintptr_t baseAddr = 0;
253
254         if (isTPADll(dllPath)) {
255                 baseAddr = getNextBaseAddr();
256         }
257 #endif
258
259         pid_t pid = fork();
260         if (pid == -1)
261                 return NI_ERROR_UNKNOWN;
262
263         if (pid > 0) {
264                 int status;
265                 waitpid(pid, &status, 0);
266                 if (WIFEXITED(status)) {
267                         // Do not use niExist() function to check whether ni file created or not.
268                         // niEixst() return false for System.Private.Corelib.dll
269                         if (isFileExist(absNiPath)) {
270                                 updateAssemblyInfo(absDllPath, absNiPath);
271 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
272                                 if (baseAddr != 0) {
273                                         updateBaseAddrFile(absNiPath, baseAddr);
274                                 }
275 #endif
276                                 return NI_ERROR_NONE;
277                         } else {
278                                 fprintf(stderr, "Fail to create native image for %s\n", dllPath.c_str());
279                                 return NI_ERROR_NO_SUCH_FILE;
280                         }
281                 }
282         } else {
283                 std::string jitPath = getRuntimeDir() + "/libclrjit.so";
284                 std::vector<const char*> argv = {
285                         __CROSSGEN_PATH,
286                         "/nologo",
287                         "/JITPath", jitPath.c_str()
288                 };
289
290                 bool compat = flags & NI_FLAGS_COMPATIBILITY;
291                 argv.push_back(compat ? "/Trusted_Platform_Assemblies" : "/r");
292                 argv.push_back(__tpa.c_str());
293
294                 bool enableR2R = flags & NI_FLAGS_ENABLER2R;
295                 if (!enableR2R) {
296                         argv.push_back("/FragileNonVersionable");
297                 }
298
299                 if (flags & NI_FLAGS_VERBOSE) {
300                         argv.push_back("/verbose");
301                 }
302
303                 if (flags & NI_FLAGS_INSTRUMENT) {
304                         argv.push_back("/Tuning");
305                 }
306
307 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
308                 if (baseAddr != 0) {
309                         argv.push_back("/BaseAddress");
310                         argv.push_back(std::to_string(baseAddr).c_str());
311                 }
312 #endif
313
314                 argv.push_back("/App_Paths");
315                 std::string absAppPath;
316                 if (!appPath.empty()) {
317                         absAppPath = appPath;
318                 } else {
319                         absAppPath = baseName(absDllPath);
320                 }
321                 argv.push_back(absAppPath.c_str());
322
323                 argv.push_back("/out");
324                 argv.push_back(absNiPath.c_str());
325
326                 argv.push_back(absDllPath.c_str());
327                 argv.push_back(nullptr);
328
329                 fprintf(stderr, "+ %s (%s)\n", absDllPath.c_str(), enableR2R ? "R2R" : "FNV");
330
331                 execv(__CROSSGEN_PATH, const_cast<char* const*>(argv.data()));
332                 exit(0);
333         }
334
335         return NI_ERROR_NONE;
336 }
337
338 // callback function of "pkgmgrinfo_appinfo_metadata_filter_foreach"
339 static int appAotCb(pkgmgrinfo_appinfo_h handle, void *userData)
340 {
341         char *pkgId = NULL;
342         int ret = 0;
343         DWORD *pFlags = (DWORD*)userData;
344
345         ret = pkgmgrinfo_appinfo_get_pkgid(handle, &pkgId);
346         if (ret != PMINFO_R_OK) {
347                 fprintf(stderr, "Failed to get pkgid\n");
348                 return -1;
349         }
350
351         if (removeNiUnderPkgRoot(pkgId) != NI_ERROR_NONE) {
352                 fprintf(stderr, "Failed to remove previous dlls from [%s]\n", pkgId);
353                 return -1;
354         }
355
356         if (resetTACPackage(pkgId) != TAC_ERROR_NONE) {
357                 fprintf(stderr, "Failed to remove symlink for given package [%s]\n", pkgId);
358                 return -1;
359         }
360
361         // Regenerate ni files with R2R mode forcibiliy. (there is no way to now which option is used)
362         if (createNiUnderPkgRoot(pkgId, *pFlags) != NI_ERROR_NONE) {
363                 fprintf(stderr, "Failed to generate NI file [%s]\n", pkgId);
364                 return -1;
365         } else {
366                 fprintf(stderr, "Complete make application to native image\n");
367         }
368
369         if (createTACPkgRoot(pkgId, *pFlags) != NI_ERROR_NONE) {
370                 fprintf(stderr, "Failed to generate symbolic link file [%s]\n", pkgId);
371                 return -1;
372         }else {
373                 fprintf(stderr, "Complete make symbolic link file to tac\n");
374         }
375
376         return 0;
377 }
378
379 static void createCoreLibNI(DWORD flags)
380 {
381         std::string coreLib = concatPath(getRuntimeDir(), "System.Private.CoreLib.dll");
382         std::string niCoreLib = concatPath(getRuntimeDir(), "System.Private.CoreLib.ni.dll");
383         std::string coreLibBackup = concatPath(getRuntimeDir(), "System.Private.CoreLib.dll.Backup");
384
385         if (!isFileExist(coreLibBackup)) {
386
387                 if (!crossgen(coreLib, std::string(), flags)) {
388                         if (rename(coreLib.c_str(), coreLibBackup.c_str())) {
389                                 fprintf(stderr, "Failed to rename System.Private.CoreLib.dll\n");
390                         }
391                         if (rename(niCoreLib.c_str(), coreLib.c_str())) {
392                                 fprintf(stderr, "Failed to rename System.Private.CoreLib.ni.dll\n");
393                         }
394                 } else {
395                         fprintf(stderr, "Failed to create native image for %s\n", coreLib.c_str());
396                 }
397         }
398 }
399
400 ni_error_e initNICommon(NiCommonOption* option)
401 {
402 #if defined(__arm__)
403         // get interval value
404         const static std::string intervalFile = concatPath(__NATIVE_LIB_DIR, "crossgen_interval.txt");
405         std::ifstream inFile(intervalFile);
406         if (inFile) {
407                 fprintf(stderr, "crossgen_interval.txt is found\n");
408                 inFile >> __interval;
409         }
410
411         if (initializePluginManager("normal")) {
412                 fprintf(stderr, "Fail to initialize PluginManager\n");
413                 return NI_ERROR_UNKNOWN;
414         }
415         if (initializePathManager(option->runtimeDir, option->tizenFXDir, option->extraDirs)) {
416                 fprintf(stderr, "Fail to initialize PathManager\n");
417                 return NI_ERROR_UNKNOWN;
418         }
419
420         __tpa = getTPA();
421
422         return NI_ERROR_NONE;
423 #else
424         fprintf(stderr, "crossgen supports arm architecture only. skip ni file generation\n");
425         return NI_ERROR_NOT_SUPPORTED;
426 #endif
427 }
428
429 void finalizeNICommon()
430 {
431         __interval = 0;
432
433         finalizePluginManager();
434         finalizePathManager();
435
436         __tpa.clear();
437 }
438
439
440 void createNiPlatform(DWORD flags)
441 {
442         const std::string platformDirs[] = {getRuntimeDir(), getTizenFXDir()};
443         createNiUnderDirs(platformDirs, 2, flags);
444 }
445
446 ni_error_e createNiDll(const std::string& dllPath, DWORD flags)
447 {
448         createCoreLibNI(flags);
449         // System.Private.CoreLib.dll is generated in the createCoreLibNI function.
450         // Skip if input dll is System.Private.CoreLib.dll
451         if (dllPath.find("System.Private.CoreLib.dll") != std::string::npos) {
452                 return NI_ERROR_NONE;
453         }
454
455         ni_error_e status = crossgen(dllPath, std::string(), flags);
456
457         return status;
458 }
459
460 void createNiUnderTAC(std::vector<std::string> nugets, DWORD flags)
461 {
462         std::string appPaths;
463         for (auto& nuget : nugets) {
464                 appPaths += concatPath(__TAC_DIR, nuget);
465                 appPaths += ':';
466         }
467         if (appPaths.back() == ':') {
468                 appPaths.pop_back();
469         }
470
471         auto convert = [&appPaths, flags](const std::string& path, const char* name) {
472                 if (strstr(path.c_str(), TAC_SHA_256_INFO) != NULL)
473                         return;
474                 if (!crossgen(path, appPaths.c_str(), flags)) {
475                         waitInterval();
476                 }
477         };
478         for (auto& nuget : nugets) {
479                 scanFilesInDir(concatPath(__TAC_DIR, nuget), convert, -1);
480         }
481 }
482
483 ni_error_e createTACPkgRoot(const std::string& pkgId, DWORD flags)
484 {
485         std::string pkgRoot;
486         if (getRootPath(pkgId, pkgRoot) < 0) {
487                 return NI_ERROR_INVALID_PACKAGE;
488         }
489
490         std::string binDir = concatPath(pkgRoot, "bin");
491         std::string tacDir = concatPath(binDir, TAC_SYMLINK_SUB_DIR);
492         std::string binNIDir = concatPath(binDir, APP_NI_SUB_DIR);
493         if (bf::exists(tacDir)) {
494                 try {
495                         for (auto& symlinkAssembly : bf::recursive_directory_iterator(tacDir)) {
496                                 std::string symPath = symlinkAssembly.path().string();
497                                 if (bf::is_symlink(symPath)) {
498                                         if (!isNativeImage(symPath)) {
499                                                 std::string originPath = bf::read_symlink(symPath).string();
500                                                 std::string originNiPath = originPath.substr(0, originPath.rfind(".dll")) + ".ni.dll";
501                                                 if (!bf::exists(originNiPath)) {
502                                                         if(createNiDll(originPath, flags) != NI_ERROR_NONE) {
503                                                                 fprintf(stderr, "Failed to create NI file [%s]\n", originPath.c_str());
504                                                                 return NI_ERROR_UNKNOWN;
505                                                         }
506                                                 }
507                                                 std::string symNIPath = symPath.substr(0, symPath.rfind(".dll")) + ".ni.dll";
508                                                 if (!bf::exists(symNIPath)) {
509                                                         bf::create_symlink(originNiPath, symNIPath);
510                                                         fprintf(stderr, "%s symbolic link file generated successfully.\n", symNIPath.c_str());
511                                                         updateAssemblyInfo(tacDir.c_str(), symNIPath.c_str(), true);
512
513                                                         std::string NIFileName = symNIPath.substr(symNIPath.rfind('/') + 1);
514                                                         if (!removeFile(concatPath(binNIDir, NIFileName))) {
515                                                                 fprintf(stderr, "Failed to remove of %s\n", concatPath(binNIDir, NIFileName).c_str());
516                                                                 return NI_ERROR_UNKNOWN;
517                                                         }
518                                                 }
519                                         }
520                                 }
521                         }
522                 } catch (const bf::filesystem_error& error) {
523                         fprintf(stderr, "Failed to recursive directory: %s\n", error.what());
524                         return NI_ERROR_UNKNOWN;
525                 }
526         }
527         return NI_ERROR_NONE;
528 }
529
530 void createNiUnderDirs(const std::string rootPaths[], int count, DWORD flags)
531 {
532         createCoreLibNI(flags);
533
534         std::string appPaths;
535         for (int i = 0; i < count; i++) {
536                 appPaths += rootPaths[i];
537                 appPaths += ':';
538         }
539
540         if (appPaths.back() == ':')
541                 appPaths.pop_back();
542
543         std::vector<std::string> tpaAssemblies;
544         splitPath(__tpa, tpaAssemblies);
545
546         auto convert = [&appPaths, flags, tpaAssemblies](const std::string& path, const char* name) {
547                 bool isAppNI = flags & NI_FLAGS_APPNI;
548                 if (isAppNI) {
549                         std::string assembly = path.substr(path.rfind('/') + 1);
550                         bool isExist = false;
551                         for (auto& tpa : tpaAssemblies) {
552                                 if (!strcmp(replaceAll(tpa, ".ni.dll", ".dll").c_str(), assembly.c_str())) {
553                                         isExist = true;
554                                         break;
555                                 }
556                         }
557                         if (isExist) {
558                                 fprintf(stderr, "%s present in the TPA list skips generation of NI file.\n", path.c_str());
559                                 return;
560                         }
561                 }
562                 if (!crossgen(path, appPaths.c_str(), flags)) {
563                         waitInterval();
564                 }
565         };
566
567         for (int i = 0; i < count; i++) {
568                 scanFilesInDir(rootPaths[i], convert, 1);
569         }
570
571         tpaAssemblies.clear();
572 }
573
574 ni_error_e createNiUnderPkgRoot(const std::string& pkgId, DWORD flags)
575 {
576         std::string pkgRoot;
577         if (getRootPath(pkgId, pkgRoot) < 0) {
578                 return NI_ERROR_INVALID_PACKAGE;
579         }
580
581         std::string binDir = concatPath(pkgRoot, "bin");
582         std::string libDir = concatPath(pkgRoot, "lib");
583         std::string tacDir = concatPath(binDir, TAC_SYMLINK_SUB_DIR);
584         std::string paths[] = {binDir, libDir, tacDir};
585
586         flags |= NI_FLAGS_APPNI;
587         createNiUnderDirs(paths, 3, flags);
588
589         return NI_ERROR_NONE;
590 }
591
592 ni_error_e createNiDllUnderPkgRoot(const std::string& pkgId, const std::string& dllPath, DWORD flags)
593 {
594         std::string pkgRoot;
595         if (getRootPath(pkgId, pkgRoot) < 0) {
596                 return NI_ERROR_INVALID_PACKAGE;
597         }
598
599         std::string binDir = concatPath(pkgRoot, "bin");
600         std::string libDir = concatPath(pkgRoot, "lib");
601         std::string tacDir = concatPath(binDir, TAC_SYMLINK_SUB_DIR);
602         std::string paths = binDir + ":" + libDir + ":" + tacDir;
603
604         if (bf::is_symlink(dllPath)) {
605                 if (bf::exists(tacDir)) {
606                         if (!isNativeImage(dllPath)) {
607                                 std::string originPath = bf::read_symlink(dllPath).string();
608                                 std::string originNiPath = originPath.substr(0, originPath.rfind(".dll")) + ".ni.dll";
609                                 if (!bf::exists(originNiPath)) {
610                                         if(createNiDll(originPath, flags) != NI_ERROR_NONE) {
611                                                 fprintf(stderr, "Failed to create NI file [%s]\n", originPath.c_str());
612                                                 return NI_ERROR_UNKNOWN;
613                                         }
614                                 }
615                                 std::string setNiPath = dllPath.substr(0, dllPath.rfind(".dll")) + ".ni.dll";
616                                 if (!bf::exists(setNiPath)) {
617                                         bf::create_symlink(originNiPath, setNiPath);
618                                         fprintf(stderr, "%s symbolic link file generated successfully.\n", setNiPath.c_str());
619                                         updateAssemblyInfo(tacDir.c_str(), setNiPath.c_str(), true);
620                                 }
621                         }
622                 }
623                 return NI_ERROR_NONE;
624         } else {
625                 std::string assembly = dllPath.substr(dllPath.rfind('/') + 1);
626                 std::vector<std::string> tpaAssemblies;
627                 splitPath(__tpa, tpaAssemblies);
628                 bool isExist = false;
629                 for (auto& tpa : tpaAssemblies) {
630                         if (!strcmp(replaceAll(tpa, ".ni.dll", ".dll").c_str(), assembly.c_str())) {
631                                 isExist = true;
632                                 break;
633                         }
634                 }
635                 tpaAssemblies.clear();
636                 if (isExist) {
637                         fprintf(stderr, "%s present in the TPA list skips generation of NI file.\n", dllPath.c_str());
638                         return NI_ERROR_NONE;
639                 } else {
640                         flags |= NI_FLAGS_APPNI;
641                         return crossgen(dllPath, paths, flags);
642                 }
643         }
644 }
645
646 void removeNiPlatform()
647 {
648         std::string coreLib = concatPath(getRuntimeDir(), "System.Private.CoreLib.dll");
649         std::string coreLibBackup = concatPath(getRuntimeDir(), "System.Private.CoreLib.dll.Backup");
650
651         if (!isFileExist(coreLibBackup)) {
652                 return;
653         }
654
655 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
656         if (isFileExist(__SYSTEM_BASE_FILE)) {
657                 if (remove(__SYSTEM_BASE_FILE)) {
658                         fprintf(stderr, "Failed to remove %s\n", __SYSTEM_BASE_FILE);
659                 }
660         }
661 #endif
662
663         if (remove(coreLib.c_str())) {
664                 fprintf(stderr, "Failed to remove System.Private.CoreLib native image file\n");
665         }
666
667         if (rename(coreLibBackup.c_str(), coreLib.c_str())) {
668                 fprintf(stderr, "Failed to rename System.Private.CoreLib.Backup to origin\n");
669         }
670
671         const std::string platformDirs[] = {getRuntimeDir(), getTizenFXDir()};
672
673         removeNiUnderDirs(platformDirs, 2);
674 }
675
676 void removeNiUnderDirs(const std::string rootPaths[], int count)
677 {
678         auto convert = [](const std::string& path, std::string name) {
679                 if (isNativeImage(path)) {
680                         if (remove(path.c_str())) {
681                                 fprintf(stderr, "Failed to remove %s\n", path.c_str());
682                         }
683                 }
684         };
685
686         for (int i = 0; i < count; i++) {
687                 scanFilesInDir(rootPaths[i], convert, -1);
688         }
689 }
690
691 ni_error_e removeNiUnderPkgRoot(const std::string& pkgId)
692 {
693         std::string pkgRoot;
694         if (getRootPath(pkgId, pkgRoot) < 0) {
695                 return NI_ERROR_INVALID_PACKAGE;
696         }
697
698         std::string binDir = concatPath(pkgRoot, "bin");
699         std::string libDir = concatPath(pkgRoot, "lib");
700         std::string paths[] = {binDir, libDir};
701
702         removeNiUnderDirs(paths, 2);
703
704         std::string binNIDir = concatPath(binDir, APP_NI_SUB_DIR);
705         if (isFileExist(binNIDir)) {
706                 if (rmdir(binNIDir.c_str()) != 0) {
707                         fprintf(stderr, "Failed to remove app ni dir [%s]\n", binNIDir.c_str());
708                 }
709         }
710
711         std::string libNIDir = concatPath(libDir, APP_NI_SUB_DIR);
712         if (isFileExist(libNIDir)) {
713                 if (rmdir(libNIDir.c_str()) != 0) {
714                         fprintf(stderr, "Failed to remove app ni dir [%s]\n", libNIDir.c_str());
715                 }
716         }
717
718         return NI_ERROR_NONE;
719 }
720
721 ni_error_e regenerateAppNI(DWORD flags)
722 {
723         int ret = 0;
724         pkgmgrinfo_appinfo_metadata_filter_h handle;
725
726         ret = pkgmgrinfo_appinfo_metadata_filter_create(&handle);
727         if (ret != PMINFO_R_OK)
728                 return NI_ERROR_UNKNOWN;
729
730         ret = pkgmgrinfo_appinfo_metadata_filter_add(handle, AOT_METADATA_KEY, METADATA_VALUE);
731         if (ret != PMINFO_R_OK) {
732                 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
733                 return NI_ERROR_UNKNOWN;
734         }
735
736         ret = pkgmgrinfo_appinfo_metadata_filter_foreach(handle, appAotCb, &flags);
737         if (ret != PMINFO_R_OK) {
738                 fprintf(stderr, "Failed pkgmgrinfo_appinfo_metadata_filter_foreach\n");
739                 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
740                 return NI_ERROR_UNKNOWN;
741         }
742
743         fprintf(stderr, "Success pkgmgrinfo_appinfo_metadata_filter_foreach\n");
744
745         pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
746         return NI_ERROR_NONE;
747 }
748
749 // callback function of "pkgmgrinfo_appinfo_metadata_filter_foreach"
750 static int regenTacCb(pkgmgrinfo_appinfo_h handle, void *userData)
751 {
752         char *pkgId = NULL;
753         DWORD *pFlags = (DWORD*)userData;
754
755         int ret = pkgmgrinfo_appinfo_get_pkgid(handle, &pkgId);
756         if (ret != PMINFO_R_OK) {
757                 fprintf(stderr, "Failed to get pkgid\n");
758                 return -1;
759         }
760
761         sqlite3 *tac_db = dbOpen(TAC_APP_LIST_DB);
762         if (!tac_db) {
763                 fprintf(stderr, "Sqlite open error\n");
764                 return -1;
765         }
766
767         char *sql = sqlite3_mprintf("SELECT * FROM TAC WHERE PKGID = %Q;", pkgId);
768         std::vector<std::string> nugets = dbSelect(tac_db, TAC_APP_LIST_DB, sql);
769         sqlite3_free(sql);
770
771         if (tac_db) {
772                 dbClose(tac_db);
773                 tac_db = NULL;
774         }
775
776         createNiUnderTAC(nugets, *pFlags);
777
778         return 0;
779 }
780
781 ni_error_e regenerateTACNI(DWORD flags)
782 {
783         const std::string tacDir[] = {__TAC_DIR};
784         removeNiUnderDirs(tacDir, 1);
785
786         pkgmgrinfo_appinfo_metadata_filter_h handle;
787         int ret = pkgmgrinfo_appinfo_metadata_filter_create(&handle);
788         if (ret != PMINFO_R_OK) {
789                 return NI_ERROR_UNKNOWN;
790         }
791
792         ret = pkgmgrinfo_appinfo_metadata_filter_add(handle, TAC_METADATA_KEY, METADATA_VALUE);
793         if (ret != PMINFO_R_OK) {
794                 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
795                 return NI_ERROR_UNKNOWN;
796         }
797
798         ret = pkgmgrinfo_appinfo_metadata_filter_foreach(handle, regenTacCb, &flags);
799         if (ret != PMINFO_R_OK) {
800                 fprintf(stderr, "Failed pkgmgrinfo_appinfo_metadata_filter_foreach\n");
801                 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
802                 return NI_ERROR_UNKNOWN;
803         }
804         fprintf(stderr, "Success pkgmgrinfo_appinfo_metadata_filter_foreach\n");
805
806         pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
807
808         return NI_ERROR_NONE;
809 }