Change the name of the define directory(/opt/usr/dotnet)
[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* __DOTNET_DIR = __STR(DOTNET_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(stdout, "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                         copySmackAndOwnership(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
242
243         if (absNiPath.empty()) {
244                 fprintf(stderr, "Fail to get ni file name\n");
245                 return NI_ERROR_UNKNOWN;
246         }
247
248         bool isAppNI = flags & NI_FLAGS_APPNI;
249         if (isAppNI && strstr(absNiPath.c_str(), __DOTNET_DIR) == NULL) {
250                 absNiPath = getAppNIPath(absNiPath);
251         }
252
253 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
254         uintptr_t baseAddr = 0;
255
256         if (isTPADll(dllPath)) {
257                 baseAddr = getNextBaseAddr();
258         }
259 #endif
260
261         pid_t pid = fork();
262         if (pid == -1)
263                 return NI_ERROR_UNKNOWN;
264
265         if (pid > 0) {
266                 int status;
267                 waitpid(pid, &status, 0);
268                 if (WIFEXITED(status)) {
269                         // Do not use niExist() function to check whether ni file created or not.
270                         // niEixst() return false for System.Private.Corelib.dll
271                         if (isFileExist(absNiPath)) {
272                                 copySmackAndOwnership(absDllPath, absNiPath);
273                                 std::string absPdbPath = replaceAll(absDllPath, ".dll", ".pdb");
274                                 std::string pdbFilePath = replaceAll(absNiPath, ".ni.dll", ".pdb");
275                                 if (isFileExist(absPdbPath) && (absPdbPath != pdbFilePath)) {
276                                         if (!copyFile(absPdbPath, pdbFilePath)) {
277                                                 fprintf(stderr, "Failed to copy a .pdb file\n");
278                                         }
279                                 }
280 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
281                                 if (baseAddr != 0) {
282                                         updateBaseAddrFile(absNiPath, baseAddr);
283                                 }
284 #endif
285                                 return NI_ERROR_NONE;
286                         } else {
287                                 fprintf(stderr, "Fail to create native image for %s\n", dllPath.c_str());
288                                 return NI_ERROR_NO_SUCH_FILE;
289                         }
290                 }
291         } else {
292                 std::string jitPath = getRuntimeDir() + "/libclrjit.so";
293                 std::vector<const char*> argv = {
294                         __CROSSGEN_PATH,
295                         "/nologo",
296                         "/JITPath", jitPath.c_str()
297                 };
298
299                 bool compat = flags & NI_FLAGS_COMPATIBILITY;
300                 argv.push_back(compat ? "/Trusted_Platform_Assemblies" : "/r");
301                 argv.push_back(__tpa.c_str());
302
303                 bool enableR2R = flags & NI_FLAGS_ENABLER2R;
304                 if (!enableR2R) {
305                         argv.push_back("/FragileNonVersionable");
306                 }
307
308                 if (flags & NI_FLAGS_VERBOSE) {
309                         argv.push_back("/verbose");
310                 }
311
312                 if (flags & NI_FLAGS_INSTRUMENT) {
313                         argv.push_back("/Tuning");
314                 }
315
316 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
317                 if (baseAddr != 0) {
318                         argv.push_back("/BaseAddress");
319                         argv.push_back(std::to_string(baseAddr).c_str());
320                 }
321 #endif
322
323                 argv.push_back("/App_Paths");
324                 std::string absAppPath;
325                 if (!appPath.empty()) {
326                         absAppPath = appPath;
327                 } else {
328                         absAppPath = baseName(absDllPath);
329                 }
330                 argv.push_back(absAppPath.c_str());
331
332                 argv.push_back("/out");
333                 argv.push_back(absNiPath.c_str());
334
335                 argv.push_back(absDllPath.c_str());
336                 argv.push_back(nullptr);
337
338                 fprintf(stdout, "+ %s (%s)\n", absDllPath.c_str(), enableR2R ? "R2R" : "FNV");
339
340                 execv(__CROSSGEN_PATH, const_cast<char* const*>(argv.data()));
341                 exit(0);
342         }
343
344         return NI_ERROR_NONE;
345 }
346
347 // callback function of "pkgmgrinfo_appinfo_metadata_filter_foreach"
348 static int appAotCb(pkgmgrinfo_appinfo_h handle, void *userData)
349 {
350         char *pkgId = NULL;
351         int ret = 0;
352         DWORD *pFlags = (DWORD*)userData;
353
354         ret = pkgmgrinfo_appinfo_get_pkgid(handle, &pkgId);
355         if (ret != PMINFO_R_OK) {
356                 fprintf(stderr, "Failed to get pkgid\n");
357                 return -1;
358         }
359
360         if (removeNiUnderPkgRoot(pkgId) != NI_ERROR_NONE) {
361                 fprintf(stderr, "Failed to remove previous dlls from [%s]\n", pkgId);
362                 return -1;
363         }
364
365         if (resetTACPackage(pkgId) != TAC_ERROR_NONE) {
366                 fprintf(stderr, "Failed to remove symlink for given package [%s]\n", pkgId);
367                 return -1;
368         }
369
370         // Regenerate ni files with R2R mode forcibiliy. (there is no way to now which option is used)
371         if (createNiUnderPkgRoot(pkgId, *pFlags) != NI_ERROR_NONE) {
372                 fprintf(stderr, "Failed to generate NI file [%s]\n", pkgId);
373                 return -1;
374         } else {
375                 fprintf(stdout, "Complete make application to native image\n");
376         }
377
378         if (createTACPkgRoot(pkgId, *pFlags) != NI_ERROR_NONE) {
379                 fprintf(stderr, "Failed to generate symbolic link file [%s]\n", pkgId);
380                 return -1;
381         }else {
382                 fprintf(stdout, "Complete make symbolic link file to tac\n");
383         }
384
385         return 0;
386 }
387
388 static void createCoreLibNI(DWORD flags)
389 {
390         std::string coreLib = concatPath(getRuntimeDir(), "System.Private.CoreLib.dll");
391         std::string niCoreLib = concatPath(getRuntimeDir(), "System.Private.CoreLib.ni.dll");
392         std::string coreLibBackup = concatPath(getRuntimeDir(), "System.Private.CoreLib.dll.Backup");
393
394         if (!isFileExist(coreLibBackup)) {
395
396                 if (!crossgen(coreLib, std::string(), flags)) {
397                         if (rename(coreLib.c_str(), coreLibBackup.c_str())) {
398                                 fprintf(stderr, "Failed to rename System.Private.CoreLib.dll\n");
399                         }
400                         if (rename(niCoreLib.c_str(), coreLib.c_str())) {
401                                 fprintf(stderr, "Failed to rename System.Private.CoreLib.ni.dll\n");
402                         }
403                 } else {
404                         fprintf(stderr, "Failed to create native image for %s\n", coreLib.c_str());
405                 }
406         }
407 }
408
409 ni_error_e initNICommon(NiCommonOption* option)
410 {
411 #if defined(__arm__)
412         // get interval value
413         const static std::string intervalFile = concatPath(__NATIVE_LIB_DIR, "crossgen_interval.txt");
414         std::ifstream inFile(intervalFile);
415         if (inFile) {
416                 fprintf(stdout, "crossgen_interval.txt is found\n");
417                 inFile >> __interval;
418         }
419
420         if (initializePluginManager("normal")) {
421                 fprintf(stderr, "Fail to initialize PluginManager\n");
422                 return NI_ERROR_UNKNOWN;
423         }
424         if (initializePathManager(option->runtimeDir, option->tizenFXDir, option->extraDirs)) {
425                 fprintf(stderr, "Fail to initialize PathManager\n");
426                 return NI_ERROR_UNKNOWN;
427         }
428
429         __tpa = getTPA();
430
431         return NI_ERROR_NONE;
432 #else
433         fprintf(stderr, "crossgen supports arm architecture only. skip ni file generation\n");
434         return NI_ERROR_NOT_SUPPORTED;
435 #endif
436 }
437
438 void finalizeNICommon()
439 {
440         __interval = 0;
441
442         finalizePluginManager();
443         finalizePathManager();
444
445         __tpa.clear();
446 }
447
448
449 void createNiPlatform(DWORD flags)
450 {
451         const std::string platformDirs[] = {getRuntimeDir(), getTizenFXDir()};
452         createNiUnderDirs(platformDirs, 2, flags);
453 }
454
455 ni_error_e createNiDll(const std::string& dllPath, DWORD flags)
456 {
457         createCoreLibNI(flags);
458         // System.Private.CoreLib.dll is generated in the createCoreLibNI function.
459         // Skip if input dll is System.Private.CoreLib.dll
460         if (dllPath.find("System.Private.CoreLib.dll") != std::string::npos) {
461                 return NI_ERROR_NONE;
462         }
463
464         return crossgen(dllPath, std::string(), flags);
465 }
466
467 void createNiUnderTAC(std::vector<std::string> nugets, DWORD flags)
468 {
469         std::string appPaths;
470         for (auto& nuget : nugets) {
471                 appPaths += concatPath(__DOTNET_DIR, nuget);
472                 appPaths += ':';
473         }
474         if (appPaths.back() == ':') {
475                 appPaths.pop_back();
476         }
477
478         auto convert = [&appPaths, flags](const std::string& path, const char* name) {
479                 if (strstr(path.c_str(), TAC_SHA_256_INFO) != NULL)
480                         return;
481                 if (!crossgen(path, appPaths.c_str(), flags)) {
482                         waitInterval();
483                 }
484         };
485         for (auto& nuget : nugets) {
486                 scanFilesInDir(concatPath(__DOTNET_DIR, nuget), convert, -1);
487         }
488 }
489
490 ni_error_e createTACPkgRoot(const std::string& pkgId, DWORD flags)
491 {
492         std::string pkgRoot;
493         if (getRootPath(pkgId, pkgRoot) < 0) {
494                 return NI_ERROR_INVALID_PACKAGE;
495         }
496
497         std::string binDir = concatPath(pkgRoot, "bin");
498         std::string libDir = concatPath(pkgRoot, "lib");
499         std::string tacDir = concatPath(binDir, TAC_SYMLINK_SUB_DIR);
500         std::string binNIDir = concatPath(binDir, APP_NI_SUB_DIR);
501         std::string paths = binDir + ":" + libDir + ":" + tacDir;
502         if (bf::exists(tacDir)) {
503                 try {
504                         for (auto& symlinkAssembly : bf::recursive_directory_iterator(tacDir)) {
505                                 std::string symPath = symlinkAssembly.path().string();
506                                 if (bf::is_symlink(symPath)) {
507                                         if (!isNativeImage(symPath)) {
508                                                 std::string originPath = bf::read_symlink(symPath).string();
509                                                 std::string originNiPath = originPath.substr(0, originPath.rfind(".dll")) + ".ni.dll";
510                                                 if (!bf::exists(originNiPath)) {
511                                                         flags |= NI_FLAGS_APPNI;
512                                                         if(crossgen(originPath, paths, flags) != NI_ERROR_NONE) {
513                                                                 fprintf(stderr, "Failed to create NI file [%s]\n", originPath.c_str());
514                                                                 return NI_ERROR_UNKNOWN;
515                                                         }
516                                                 }
517                                                 std::string symNIPath = symPath.substr(0, symPath.rfind(".dll")) + ".ni.dll";
518                                                 if (!bf::exists(symNIPath)) {
519                                                         bf::create_symlink(originNiPath, symNIPath);
520                                                         fprintf(stdout, "%s symbolic link file generated successfully.\n", symNIPath.c_str());
521                                                         copySmackAndOwnership(tacDir.c_str(), symNIPath.c_str(), true);
522
523                                                         std::string niFileName = symNIPath.substr(symNIPath.rfind('/') + 1);
524                                                         if (!removeFile(concatPath(binNIDir, niFileName))) {
525                                                                 fprintf(stderr, "Failed to remove of %s\n", concatPath(binNIDir, niFileName).c_str());
526                                                         }
527                                                 }
528                                         }
529                                 }
530                         }
531                 } catch (const bf::filesystem_error& error) {
532                         fprintf(stderr, "Failed to recursive directory: %s\n", error.what());
533                         return NI_ERROR_UNKNOWN;
534                 }
535         }
536         return NI_ERROR_NONE;
537 }
538
539 void createNiUnderDirs(const std::string rootPaths[], int count, DWORD flags)
540 {
541         createCoreLibNI(flags);
542
543         std::string appPaths;
544         for (int i = 0; i < count; i++) {
545                 appPaths += rootPaths[i];
546                 appPaths += ':';
547         }
548
549         if (appPaths.back() == ':')
550                 appPaths.pop_back();
551
552         std::vector<std::string> tpaAssemblies;
553         splitPath(__tpa, tpaAssemblies);
554
555         auto convert = [&appPaths, flags, tpaAssemblies](const std::string& path, const char* name) {
556                 bool isAppNI = flags & NI_FLAGS_APPNI;
557                 if (isAppNI) {
558                         for (auto& tpa : tpaAssemblies) {
559                                 if (!strcmp(replaceAll(tpa.substr(tpa.rfind('/') + 1), ".ni.dll", ".dll").c_str(), name)) {
560                                         fprintf(stderr, "%s present in the TPA list skips generation of NI file.\n", name);
561                                         return;
562                                 }
563                         }
564                 }
565                 if (!crossgen(path, appPaths.c_str(), flags)) {
566                         waitInterval();
567                 }
568         };
569
570         for (int i = 0; i < count; i++) {
571                 scanFilesInDir(rootPaths[i], convert, 1);
572         }
573
574         tpaAssemblies.clear();
575 }
576
577 ni_error_e createNiUnderPkgRoot(const std::string& pkgId, DWORD flags)
578 {
579         std::string pkgRoot;
580         if (getRootPath(pkgId, pkgRoot) < 0) {
581                 return NI_ERROR_INVALID_PACKAGE;
582         }
583
584         std::string binDir = concatPath(pkgRoot, "bin");
585         std::string libDir = concatPath(pkgRoot, "lib");
586         std::string tacDir = concatPath(binDir, TAC_SYMLINK_SUB_DIR);
587         std::string paths[] = {binDir, libDir, tacDir};
588
589         flags |= NI_FLAGS_APPNI;
590         createNiUnderDirs(paths, 3, flags);
591
592         return NI_ERROR_NONE;
593 }
594
595 ni_error_e createNiDllUnderPkgRoot(const std::string& pkgId, const std::string& dllPath, DWORD flags)
596 {
597         std::string pkgRoot;
598         if (getRootPath(pkgId, pkgRoot) < 0) {
599                 return NI_ERROR_INVALID_PACKAGE;
600         }
601
602         std::string binDir = concatPath(pkgRoot, "bin");
603         std::string libDir = concatPath(pkgRoot, "lib");
604         std::string tacDir = concatPath(binDir, TAC_SYMLINK_SUB_DIR);
605         std::string binNIDir = concatPath(binDir, APP_NI_SUB_DIR);
606         std::string paths = binDir + ":" + libDir + ":" + tacDir;
607
608         if (bf::is_symlink(dllPath)) {
609                 if (bf::exists(tacDir)) {
610                         if (!isNativeImage(dllPath)) {
611                                 std::string originPath = bf::read_symlink(dllPath).string();
612                                 std::string originNiPath = originPath.substr(0, originPath.rfind(".dll")) + ".ni.dll";
613                                 if (!bf::exists(originNiPath)) {
614                                         flags |= NI_FLAGS_APPNI;
615                                         if(crossgen(originPath, paths, flags) != NI_ERROR_NONE) {
616                                                 fprintf(stderr, "Failed to create NI file [%s]\n", originPath.c_str());
617                                                 return NI_ERROR_UNKNOWN;
618                                         }
619                                 }
620                                 std::string setNiPath = dllPath.substr(0, dllPath.rfind(".dll")) + ".ni.dll";
621                                 if (!bf::exists(setNiPath)) {
622                                         bf::create_symlink(originNiPath, setNiPath);
623                                         fprintf(stdout, "%s symbolic link file generated successfully.\n", setNiPath.c_str());
624                                         copySmackAndOwnership(tacDir.c_str(), setNiPath.c_str(), true);
625                                 }
626                                 std::string niFileName = setNiPath.substr(setNiPath.rfind('/') + 1);
627                                 if (!removeFile(concatPath(binNIDir, niFileName))) {
628                                         fprintf(stderr, "Failed to remove of %s\n", concatPath(binNIDir, niFileName).c_str());
629                                 }
630                         }
631                 }
632                 return NI_ERROR_NONE;
633         } else {
634                 std::string assembly = dllPath.substr(dllPath.rfind('/') + 1);
635                 std::vector<std::string> tpaAssemblies;
636                 splitPath(__tpa, tpaAssemblies);
637                 for (auto& tpa : tpaAssemblies) {
638                         if (!strcmp(replaceAll(tpa.substr(tpa.rfind('/') + 1), ".ni.dll", ".dll").c_str(), assembly.c_str())) {
639                                 fprintf(stderr, "%s present in the TPA list skips generation of NI file.\n", assembly.c_str());
640                                 return NI_ERROR_NONE;
641                         }
642                 }
643                 tpaAssemblies.clear();
644                 flags |= NI_FLAGS_APPNI;
645                 return crossgen(dllPath, paths, flags);
646         }
647 }
648
649 void removeNiPlatform()
650 {
651         std::string coreLib = concatPath(getRuntimeDir(), "System.Private.CoreLib.dll");
652         std::string coreLibBackup = concatPath(getRuntimeDir(), "System.Private.CoreLib.dll.Backup");
653
654         if (!isFileExist(coreLibBackup)) {
655                 return;
656         }
657
658 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
659         if (isFileExist(__SYSTEM_BASE_FILE)) {
660                 if (remove(__SYSTEM_BASE_FILE)) {
661                         fprintf(stderr, "Failed to remove %s\n", __SYSTEM_BASE_FILE);
662                 }
663         }
664 #endif
665
666         if (remove(coreLib.c_str())) {
667                 fprintf(stderr, "Failed to remove System.Private.CoreLib native image file\n");
668         }
669
670         if (rename(coreLibBackup.c_str(), coreLib.c_str())) {
671                 fprintf(stderr, "Failed to rename System.Private.CoreLib.Backup to origin\n");
672         }
673
674         const std::string platformDirs[] = {getRuntimeDir(), getTizenFXDir()};
675
676         removeNiUnderDirs(platformDirs, 2);
677 }
678
679 void removeNiUnderDirs(const std::string rootPaths[], int count)
680 {
681         auto convert = [](const std::string& path, std::string name) {
682                 if (isNativeImage(path)) {
683                         if (remove(path.c_str())) {
684                                 fprintf(stderr, "Failed to remove %s\n", path.c_str());
685                         }
686                 }
687         };
688
689         for (int i = 0; i < count; i++) {
690                 scanFilesInDir(rootPaths[i], convert, -1);
691         }
692 }
693
694 ni_error_e removeNiUnderPkgRoot(const std::string& pkgId)
695 {
696         std::string pkgRoot;
697         if (getRootPath(pkgId, pkgRoot) < 0) {
698                 return NI_ERROR_INVALID_PACKAGE;
699         }
700
701         std::string binDir = concatPath(pkgRoot, "bin");
702         std::string libDir = concatPath(pkgRoot, "lib");
703         std::string paths[] = {binDir, libDir};
704
705         removeNiUnderDirs(paths, 2);
706
707         std::string binNIDir = concatPath(binDir, APP_NI_SUB_DIR);
708         if (isFileExist(binNIDir)) {
709                 if (!removeAll(binNIDir.c_str())) {
710                         fprintf(stderr, "Failed to remove app ni dir [%s]\n", binNIDir.c_str());
711                 }
712         }
713
714         std::string libNIDir = concatPath(libDir, APP_NI_SUB_DIR);
715         if (isFileExist(libNIDir)) {
716                 if (!removeAll(libNIDir.c_str())) {
717                         fprintf(stderr, "Failed to remove app ni dir [%s]\n", libNIDir.c_str());
718                 }
719         }
720
721         return NI_ERROR_NONE;
722 }
723
724 ni_error_e regenerateAppNI(DWORD flags)
725 {
726         int ret = 0;
727         pkgmgrinfo_appinfo_metadata_filter_h handle;
728
729         ret = pkgmgrinfo_appinfo_metadata_filter_create(&handle);
730         if (ret != PMINFO_R_OK)
731                 return NI_ERROR_UNKNOWN;
732
733         ret = pkgmgrinfo_appinfo_metadata_filter_add(handle, AOT_METADATA_KEY, METADATA_VALUE);
734         if (ret != PMINFO_R_OK) {
735                 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
736                 return NI_ERROR_UNKNOWN;
737         }
738
739         ret = pkgmgrinfo_appinfo_metadata_filter_foreach(handle, appAotCb, &flags);
740         if (ret != PMINFO_R_OK) {
741                 fprintf(stderr, "Failed pkgmgrinfo_appinfo_metadata_filter_foreach\n");
742                 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
743                 return NI_ERROR_UNKNOWN;
744         }
745
746         fprintf(stdout, "Success pkgmgrinfo_appinfo_metadata_filter_foreach\n");
747
748         pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
749         return NI_ERROR_NONE;
750 }
751
752 // callback function of "pkgmgrinfo_appinfo_metadata_filter_foreach"
753 static int regenTacCb(pkgmgrinfo_appinfo_h handle, void *userData)
754 {
755         char *pkgId = NULL;
756         DWORD *pFlags = (DWORD*)userData;
757
758         int ret = pkgmgrinfo_appinfo_get_pkgid(handle, &pkgId);
759         if (ret != PMINFO_R_OK) {
760                 fprintf(stderr, "Failed to get pkgid\n");
761                 return -1;
762         }
763
764         sqlite3 *tac_db = dbOpen(TAC_APP_LIST_DB);
765         if (!tac_db) {
766                 fprintf(stderr, "Sqlite open error\n");
767                 return -1;
768         }
769
770         char *sql = sqlite3_mprintf("SELECT * FROM TAC WHERE PKGID = %Q;", pkgId);
771         std::vector<std::string> nugets = dbSelect(tac_db, TAC_APP_LIST_DB, sql);
772         sqlite3_free(sql);
773
774         if (tac_db) {
775                 dbClose(tac_db);
776                 tac_db = NULL;
777         }
778
779         createNiUnderTAC(nugets, *pFlags);
780
781         return 0;
782 }
783
784 ni_error_e regenerateTACNI(DWORD flags)
785 {
786         const std::string tacDir[] = {__DOTNET_DIR};
787         removeNiUnderDirs(tacDir, 1);
788
789         pkgmgrinfo_appinfo_metadata_filter_h handle;
790         int ret = pkgmgrinfo_appinfo_metadata_filter_create(&handle);
791         if (ret != PMINFO_R_OK) {
792                 return NI_ERROR_UNKNOWN;
793         }
794
795         ret = pkgmgrinfo_appinfo_metadata_filter_add(handle, TAC_METADATA_KEY, METADATA_VALUE);
796         if (ret != PMINFO_R_OK) {
797                 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
798                 return NI_ERROR_UNKNOWN;
799         }
800
801         ret = pkgmgrinfo_appinfo_metadata_filter_foreach(handle, regenTacCb, &flags);
802         if (ret != PMINFO_R_OK) {
803                 fprintf(stderr, "Failed pkgmgrinfo_appinfo_metadata_filter_foreach\n");
804                 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
805                 return NI_ERROR_UNKNOWN;
806         }
807         fprintf(stdout, "Success pkgmgrinfo_appinfo_metadata_filter_foreach\n");
808
809         pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
810
811         return NI_ERROR_NONE;
812 }