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