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