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