Fix app's native image existence checking code. (#376)
[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 #include <tzplatform_config.h>
21
22 #include "log.h"
23 #include "utils.h"
24 #include "pkgmgr_parser_plugin_interface.h"
25
26 #include <wait.h>
27 #include <dirent.h>
28 #include <sys/stat.h>
29
30 #include <algorithm>
31 #include <string>
32 #include <fstream>
33 #include <sstream>
34
35 #include <pwd.h>
36 #include <grp.h>
37 #include <unistd.h>
38 #include <string.h>
39 #include <sqlite3.h>
40 #include <inttypes.h>
41 #include <errno.h>
42
43 #include "ni_common.h"
44 #include "db_manager.h"
45 #include "tac_common.h"
46 #include "path_manager.h"
47 #include "plugin_manager.h"
48 #include "r2r_checker.h"
49
50 #ifdef  LOG_TAG
51 #undef  LOG_TAG
52 #endif
53 #define LOG_TAG "DOTNET_INSTALLER_PLUGIN"
54
55 #define __XSTR(x) #x
56 #define __STR(x) __XSTR(x)
57 #if defined(__arm__) || defined(__aarch64__)
58 static const char* __NATIVE_LIB_DIR = __STR(NATIVE_LIB_DIR);
59 #endif
60 static const char* __DOTNET_DIR = __STR(DOTNET_DIR);
61 static const char* __READ_ONLY_APP_UPDATE_DIR = __STR(READ_ONLY_APP_UPDATE_DIR);
62
63 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
64 static const char* __SYSTEM_BASE_FILE = __STR(SYSTEM_BASE_FILE);
65 #endif
66
67 #undef __STR
68 #undef __XSTR
69
70 static std::string CORERUN_CMD = "/usr/share/dotnet.tizen/netcoreapp/corerun";
71 static std::string CROSSGEN2_PATH = "/usr/share/dotnet.tizen/netcoreapp/crossgen2/crossgen2.dll";
72 static std::string CLRJIT_PATH = "/usr/share/dotnet.tizen/netcoreapp/libclrjit.so";
73 static const char* CROSSGEN_OPT_JITPATH = "--jitpath";
74 static const char* CROSSGEN_OPT_TARGET_ARCH = "--targetarch";
75 static const char* CROSSGEN_OPT_OUT_NEAR_INPUT = "--out-near-input";
76 static const char* CROSSGEN_OPT_SINGLE_FILE_COMPILATION = "--single-file-compilation";
77 //static const char* CROSSGEN_OPT_PARALLELISM = "--parallelism";
78 //static const char* CROSSGEN_OPT_PARALLELISM_COUNT = "5";
79 static const char* CROSSGEN_OPT_RESILIENT = "--resilient";
80 static const char* CROSSGEN_OPT_OPTIMIZE = "-O";
81 static const char* CROSSGEN_OPT_INPUTBUBBLE = "--inputbubble";
82 static const char* CROSSGEN_OPT_COMPILE_BUBBLE_GENERICS = "--compilebubblegenerics";
83 static const char* CROSSGEN_OPT_VERBOSE = "--verbose";
84 static std::vector<std::string> REF_VECTOR;
85 static std::vector<std::string> INPUTBUBBLE_REF_VECTOR;
86 static std::vector<std::string> MIBC_VECTOR;
87
88 static int __interval = 0;
89 static PathManager* __pm = nullptr;
90
91 static NIOption* __ni_option = nullptr;
92
93 // singleton
94 NIOption* getNIOption()
95 {
96         if (__ni_option == nullptr) {
97                 __ni_option = (NIOption*)calloc(sizeof(NIOption), 1);
98                 if (__ni_option == nullptr) {
99                         _SERR("Fail to create NIOption");
100                 }
101         }
102         return __ni_option;
103 }
104
105 static void waitInterval()
106 {
107         // by the recommand, ignore small value for performance.
108         if (__interval > 10000) {
109                 _SOUT("sleep %d usec", __interval);
110                 usleep(__interval);
111         }
112 }
113
114 /**
115  * @brief create the directory including parents directory, and
116  *        copy ownership and smack labels to the created directory.
117  * @param[in] target directory path
118  * @param[in] source directory path to get ownership and smack label
119  * @return if directory created successfully, return true otherwise false
120  */
121 static bool createDirsAndCopyOwnerShip(std::string& target_path, const std::string& source)
122 {
123         struct stat st;
124         mode_t mode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
125
126         for (std::string::iterator iter = target_path.begin(); iter != target_path.end();) {
127                 std::string::iterator newIter = std::find(iter, target_path.end(), '/');
128                 std::string newPath = std::string(target_path.begin(), newIter);
129
130                 if (!newPath.empty()) {
131                         if (stat(newPath.c_str(), &st) != 0) {
132                                 if (mkdir(newPath.c_str(), mode) != 0 && errno != EEXIST) {
133                                         _SERR("Fail to create app ni directory (%s)", newPath.c_str());
134                                         return false;
135                                 }
136                                 if (!source.empty()) {
137                                         copySmackAndOwnership(source, newPath);
138                                 }
139                         } else {
140                                 if (!S_ISDIR(st.st_mode)) {
141                                         _SERR("Fail. path is not a dir (%s)", newPath.c_str());
142                                         return false;
143                                 }
144                         }
145                 }
146                 iter = newIter;
147                 if(newIter != target_path.end()) {
148                         ++iter;
149                 }
150         }
151
152         return true;
153 }
154
155 static std::string getNIFilePath(const std::string& dllPath)
156 {
157         size_t index = dllPath.find_last_of(".");
158         if (index == std::string::npos) {
159                 _SERR("File doesnot contain extension. fail to get NI file name");
160                 return "";
161         }
162         std::string fName = dllPath.substr(0, index);
163         std::string fExt = dllPath.substr(index, dllPath.length());
164
165         // crossgen generate file with lower case extension only
166         std::transform(fExt.begin(), fExt.end(), fExt.begin(), ::tolower);
167         std::string niPath = fName + ".ni" + fExt;
168
169         return niPath;
170 }
171
172 static std::string getAppNIFilePath(const std::string& absDllPath, NIOption* opt)
173 {
174         std::string niDirPath;
175         std::string prevPath;
176
177         prevPath = getBaseName(absDllPath);
178         niDirPath = concatPath(prevPath, APP_NI_SUB_DIR);
179
180         if (opt->flags & NI_FLAGS_APP_UNDER_RO_AREA) {
181                 niDirPath = replaceAll(niDirPath, getBaseName(__pm->getAppRootPath()), __READ_ONLY_APP_UPDATE_DIR);
182                 _SERR("App is installed in RO area. Change NI path to RW area(%s).", niDirPath.c_str());
183                 _ERR("App is installed in RO area. Change NI path to RW area(%s).", niDirPath.c_str());
184         }
185
186         if (!isDirectory(niDirPath)) {
187                 if (!createDirsAndCopyOwnerShip(niDirPath, prevPath)) {
188                         niDirPath = prevPath;
189                         _SERR("fail to create dir (%s)", niDirPath.c_str());
190                 }
191         }
192
193         return getNIFilePath(concatPath(niDirPath, getFileName(absDllPath)));
194 }
195
196 static bool checkNIExistence(const std::string& absDllPath)
197 {
198         std::string absNIPath = getNIFilePath(absDllPath);
199         if (absNIPath.empty()) {
200                 return false;
201         }
202
203         if (isFile(absNIPath)) {
204                 return true;
205         }
206
207         // native image of System.Private.CoreLib.dll should have to overwrite
208         // original file to support new coreclr
209         if (absDllPath.find("System.Private.CoreLib.dll") != std::string::npos) {
210                 return isR2RImage(absDllPath);
211         }
212
213         return false;
214 }
215
216 static bool checkAppNIExistence(const std::string& absDllPath, NIOption* opt)
217 {
218         std::string absNIPath = getAppNIFilePath(absDllPath, opt);
219         if (absNIPath.empty()) {
220                 return false;
221         }
222
223         if (isFile(absNIPath)) {
224                 return true;
225         }
226
227         return false;
228 }
229
230 static bool checkDllExistInDir(const std::string& path)
231 {
232         bool ret = false;
233         auto func = [&ret](const std::string& f_path, const std::string& f_name) {
234                 if (isManagedAssembly(f_name) || isNativeImage(f_name)) {
235                         ret = true;
236                 }
237         };
238
239         scanFilesInDirectory(path, func, 0);
240
241         return ret;
242 }
243
244 /*
245  * Get the list of managed files in the specific directory
246  * Absolute paths of managed files are stored at the result list.
247  * If native image already exist in the same directory, managed file is ignored.
248  */
249 static ni_error_e getTargetDllList(const std::string& path, std::vector<std::string>& fileList)
250 {
251         if (!isDirectory(path)) {
252                 return NI_ERROR_INVALID_PARAMETER;
253         }
254
255         auto func = [&fileList](const std::string& f_path, const std::string& f_name) {
256                 if (isManagedAssembly(f_path) && !checkNIExistence(f_path)) {
257                         fileList.push_back(getAbsolutePath(f_path));
258                 }
259         };
260
261         scanFilesInDirectory(path, func, 0);
262
263         return NI_ERROR_NONE;
264 }
265
266 /*
267  * Get the list of managed files in the specific directory of Application
268  * Absolute paths of managed files are stored at the result list.
269  * If native image already exist in the .native_image directory, managed file is ignored.
270  *
271  */
272 static ni_error_e getAppTargetDllList(const std::string& path, std::vector<std::string>& fileList, NIOption *opt)
273 {
274         if (!isDirectory(path)) {
275                 return NI_ERROR_INVALID_PARAMETER;
276         }
277
278         auto func = [&fileList, opt](const std::string& f_path, const std::string& f_name) {
279                 if (isManagedAssembly(f_path) && !checkAppNIExistence(f_path, opt)) {
280                         fileList.push_back(getAbsolutePath(f_path));
281                 }
282         };
283
284         scanFilesInDirectory(path, func, 0);
285
286         return NI_ERROR_NONE;
287 }
288
289 static void makeArgs(std::vector<const char*>& args, const std::vector<std::string>& refPaths, NIOption* opt)
290 {
291         args.push_back(CORERUN_CMD.c_str());
292         if (CROSSGEN2_PATH != "") {
293                 args.push_back(CROSSGEN2_PATH.c_str());
294         }
295         args.push_back(CROSSGEN_OPT_JITPATH);
296         args.push_back(CLRJIT_PATH.c_str());
297         args.push_back(CROSSGEN_OPT_TARGET_ARCH);
298         args.push_back(ARCHITECTURE_IDENTIFIER);
299         if (!(opt->flags & NI_FLAGS_NO_PIPELINE)) {
300                 args.push_back(CROSSGEN_OPT_OUT_NEAR_INPUT);
301                 args.push_back(CROSSGEN_OPT_SINGLE_FILE_COMPILATION);
302         }
303         //args.push_back(OPT_PARALLELISM);
304         //args.push_back(OPT_PARALLELISM_COUNT);
305         args.push_back(CROSSGEN_OPT_RESILIENT);
306
307         args.push_back(CROSSGEN_OPT_OPTIMIZE);
308
309         if (opt->flags & NI_FLAGS_INPUT_BUBBLE) {
310                 args.push_back(CROSSGEN_OPT_INPUTBUBBLE);
311                 args.push_back(CROSSGEN_OPT_COMPILE_BUBBLE_GENERICS);
312
313                 if (opt->flags & NI_FLAGS_INPUT_BUBBLE_REF) {
314                         INPUTBUBBLE_REF_VECTOR.clear();
315                         // check inputbubbleref format.
316                         for (const auto &path : opt->inputBubbleRefPath) {
317                                 if (checkDllExistInDir(path)) {
318                                         INPUTBUBBLE_REF_VECTOR.push_back("--inputbubbleref:" + path + "/*.dll");
319                                 }
320                         }
321                         // add ref path to inputbubble ref
322                         for (const auto &path : refPaths) {
323                                 if (checkDllExistInDir(path)) {
324                                         INPUTBUBBLE_REF_VECTOR.push_back("--inputbubbleref:" + path + "/*.dll");
325                                 }
326                         }
327                         for (const auto &path : INPUTBUBBLE_REF_VECTOR) {
328                                 args.push_back(path.c_str());
329                         }
330                 }
331         }
332
333         if (opt->flags & NI_FLAGS_MIBC) {
334                 MIBC_VECTOR.clear();
335                 for (const auto &path : opt->mibcPath) {
336                         MIBC_VECTOR.push_back("--mibc:" + path);
337                 }
338                 for (const auto &path : MIBC_VECTOR) {
339                         args.push_back(path.c_str());
340                 }
341         }
342
343         if (opt->flags & NI_FLAGS_VERBOSE) {
344                 args.push_back(CROSSGEN_OPT_VERBOSE);
345         }
346
347         REF_VECTOR.clear();
348
349         // set reference path
350         if (opt->flags & NI_FLAGS_REF) {
351                 for (const auto &path : opt->refPath) {
352                         REF_VECTOR.push_back("-r:" + path + "/*.dll");
353                 }
354         } else {
355                 std::vector<std::string> paths = __pm->getPlatformAssembliesPaths();
356                 for (const auto &path : paths) {
357                         if (checkDllExistInDir(path)) {
358                                 REF_VECTOR.push_back("-r:" + path + "/*.dll");
359                         }
360                 }
361         }
362
363         for (const auto &path : refPaths) {
364                 if (checkDllExistInDir(path)) {
365                         REF_VECTOR.push_back("-r:" + path + "/*.dll");
366                 }
367         }
368
369         for (const auto &path : REF_VECTOR) {
370                 args.push_back(path.c_str());
371         }
372 }
373
374 static void clearArgs(std::vector<const char*>& args)
375 {
376         REF_VECTOR.clear();
377         args.clear();
378 }
379
380 static ni_error_e makePdbSymlinkForNI(std::string dllPath, std::string niPath)
381 {
382         std::string pdbPath = changeExtension(dllPath, ".dll", ".pdb");
383         try {
384                 if (exist(pdbPath)) {
385                         std::string targetPDBPath = changeExtension(niPath, ".ni.dll", ".pdb");
386                         if (!exist(targetPDBPath)) {
387                                 bf::create_symlink(pdbPath, targetPDBPath);
388                                 copySmackAndOwnership(pdbPath, targetPDBPath, true);
389                         }
390                 }
391         } catch (const bf::filesystem_error& error) {
392                 _SERR("Fail to create symlink for %s", pdbPath.c_str());
393                 return NI_ERROR_UNKNOWN;
394         }
395
396         return NI_ERROR_NONE;
397 }
398
399 static ni_error_e crossgen2PipeLine(const std::vector<std::string>& dllList, const std::vector<std::string>& refPaths, NIOption* opt)
400 {
401         // fork crossgen2
402         pid_t pid = fork();
403         if (pid == -1)
404                 return NI_ERROR_UNKNOWN;
405
406         if (pid > 0) {
407                 int status;
408                 waitpid(pid, &status, 0);
409                 if (WIFEXITED(status)) {
410                         for (auto& dllPath: dllList) {
411                                 std::string niPath = changeExtension(dllPath, ".dll", ".ni.dll");
412
413                                 if (!exist(niPath)) {
414                                         _SERR("Fail to create native image for %s", dllPath.c_str());
415                                         return NI_ERROR_NO_SUCH_FILE;
416                                 }
417
418                                 copySmackAndOwnership(dllPath, niPath);
419                                 // if AppNI then move ni.dll file to .native_image and copy pdb to .native_image
420                                 if (opt->flags & NI_FLAGS_APPNI) {
421                                         std::string appNIPath = getAppNIFilePath(dllPath, opt);
422                                         moveFile(niPath, appNIPath);
423                                         makePdbSymlinkForNI(dllPath, appNIPath);
424                                         niPath = appNIPath;
425                                 }
426
427                                 _SOUT("Native image %s generated successfully.", niPath.c_str());
428                         }
429                 } else {
430                         _SERR("Failed. Forked process terminated abnormally");
431                 }
432         } else {
433                 std::vector<const char*> argv;
434                 makeArgs(argv, refPaths, opt);
435
436                 // add input files at the end of parameter
437                 for (const auto &input : dllList) {
438                         argv.push_back(input.c_str());
439                         _SOUT("+ %s", input.c_str());
440                 }
441
442                 // end param
443                 argv.push_back(nullptr);
444
445                 // print cmd
446                 if (opt->flags & NI_FLAGS_PRINT_CMD) {
447                         _SOUT("==================== NI Commands =========================");
448                         for (auto &arg: argv) _SOUT("+ %s", arg);
449                 }
450
451                 execv(CORERUN_CMD.c_str(), const_cast<char* const*>(argv.data()));
452
453                 clearArgs(argv);
454                 exit(0);
455         }
456
457         return NI_ERROR_NONE;
458 }
459
460 static ni_error_e crossgen2NoPipeLine(const std::vector<std::string>& dllList, const std::vector<std::string>& refPaths, NIOption* opt)
461 {
462         for (auto& dllPath : dllList) {
463                 std::string niPath;
464                 if (opt->flags & NI_FLAGS_APPNI) {
465                         niPath = getAppNIFilePath(dllPath, opt);
466                 } else {
467                         niPath = getNIFilePath(dllPath);
468                 }
469
470                 // fork crossgen2
471                 pid_t pid = fork();
472                 if (pid == -1)
473                         return NI_ERROR_UNKNOWN;
474
475                 if (pid > 0) {
476                         int status;
477                         waitpid(pid, &status, 0);
478                         if (WIFEXITED(status)) {
479                                 if (!exist(niPath)) {
480                                         _SERR("Fail to create native image for %s", dllPath.c_str());
481                                         return NI_ERROR_NO_SUCH_FILE;
482                                 }
483
484                                 copySmackAndOwnership(dllPath, niPath);
485                                 if (opt->flags & NI_FLAGS_APPNI) {
486                                         makePdbSymlinkForNI(dllPath, niPath);
487                                 }
488
489                                 _SOUT("Native image %s generated successfully.", niPath.c_str());
490                         } else {
491                                 _SERR("Failed. Forked process terminated abnormally");
492                         }
493                 } else {
494                         std::vector<const char*> argv;
495                         makeArgs(argv, refPaths, opt);
496
497                         argv.push_back("-o");
498                         argv.push_back(niPath.c_str());
499
500                         argv.push_back(dllPath.c_str());
501                         _SOUT("+ %s", dllPath.c_str());
502
503                         // end param
504                         argv.push_back(nullptr);
505
506                         // print cmd
507                         if (opt->flags & NI_FLAGS_PRINT_CMD) {
508                                 _SOUT("==================== NI Commands =========================");
509                                 for (auto &arg: argv) _SOUT("+ %s", arg);
510                         }
511
512                         execv(CORERUN_CMD.c_str(), const_cast<char* const*>(argv.data()));
513
514                         clearArgs(argv);
515                         exit(0);
516                 }
517
518                 waitInterval();
519         }
520
521         return NI_ERROR_NONE;
522 }
523
524 static ni_error_e createCoreLibNI(NIOption* opt)
525 {
526         std::string coreLib = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll");
527         std::string niCoreLib = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.ni.dll");
528         std::string coreLibBackup = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll.Backup");
529
530         std::vector<std::string> dllList;
531         std::vector<std::string> refPaths;
532         dllList.push_back(getAbsolutePath(coreLib));
533
534         if (!isFile(coreLibBackup) && !isR2RImage(coreLib)) {
535                 if (crossgen2NoPipeLine(dllList, refPaths, opt) == NI_ERROR_NONE && exist(niCoreLib)) {
536                         if (rename(coreLib.c_str(), coreLibBackup.c_str())) {
537                                 _SERR("Failed to rename System.Private.CoreLib.dll");
538                                 return NI_ERROR_CORE_NI_FILE;
539                         }
540                         if (rename(niCoreLib.c_str(), coreLib.c_str())) {
541                                 _SERR("Failed to rename System.Private.CoreLib.ni.dll");
542                                 return NI_ERROR_CORE_NI_FILE;
543                         }
544                 } else {
545                         _SERR("Failed to create native image for %s", coreLib.c_str());
546                         return NI_ERROR_CORE_NI_FILE;
547                 }
548         }
549         return NI_ERROR_NONE;
550 }
551
552 static ni_error_e doAOTList(std::vector<std::string>& dllList, const std::string& refPaths, NIOption* opt)
553 {
554         ni_error_e ret = NI_ERROR_NONE;
555
556         if (dllList.empty()) {
557                 return NI_ERROR_INVALID_PARAMETER;
558         }
559         // When performing AOT for one Dll, an error is returned when an error occurs.
560         // However, when processing multiple dlls at once, only the log for errors is output and skipped.
561
562         std::string coreLib = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll");
563         bool hasSPC = false;
564
565         for (auto it = dllList.begin(); it != dllList.end(); it++) {
566                 std::string f = *it;
567                 if (!isFile(f)) {
568                         _SERR("dll file is not exist : %s", f.c_str());
569                         dllList.erase(it--);
570                 }
571                 if (!isManagedAssembly(f)) {
572                         _SERR("Input file is not a dll file : %s", f.c_str());
573                         dllList.erase(it--);
574                 }
575                 // handle System.Private.CoreLib.dll separately.
576                 // dllList and path manager contain absolute path. So, there is no need to change path to absolute path
577                 if (f == coreLib) {
578                         hasSPC = true;
579                         dllList.erase(it--);
580                 }
581         }
582
583         // In the case of SPC, post-processing is required to change the name of the native image.
584         // In order to avoid repeatedly checking whether the generated native image is an SPC,
585         // the SPC native image generation is performed separately.
586         if (hasSPC) {
587                 ret = createCoreLibNI(opt);
588                 if (ret != NI_ERROR_NONE) {
589                         return ret;
590                 }
591         }
592
593         // if there is no proper input after processing dll list
594         if (dllList.empty()) {
595                 if (hasSPC) {
596                         return ret;
597                 } else {
598                         return NI_ERROR_INVALID_PARAMETER;
599                 }
600         }
601
602         std::vector<std::string> paths;
603         splitPath(refPaths, paths);
604
605         if (opt->flags & NI_FLAGS_NO_PIPELINE) {
606                 ret = crossgen2NoPipeLine(dllList, paths, opt);
607         } else {
608                 ret = crossgen2PipeLine(dllList, paths, opt);
609         }
610
611         return ret;
612 }
613
614 static ni_error_e doAOTFile(const std::string& dllFile, const std::string& refPaths, NIOption* opt)
615 {
616         if (!isFile(dllFile)) {
617                 _SERR("dll file is not exist : %s", dllFile.c_str());
618                 return NI_ERROR_NO_SUCH_FILE;
619         }
620
621         if (!isManagedAssembly(dllFile)) {
622                 _SERR("Failed. Input parameter is not managed dll (%s)\n", dllFile.c_str());
623                 return NI_ERROR_INVALID_PARAMETER;
624         }
625
626         if (checkNIExistence(dllFile)) {
627                 _SERR("Native image file is already exist : %s", dllFile.c_str());
628                 return NI_ERROR_ALREADY_EXIST;
629         }
630
631         std::vector<std::string> dllList;
632         dllList.push_back(getAbsolutePath(dllFile));
633         return doAOTList(dllList, refPaths, opt);
634 }
635
636 // callback function of "pkgmgrinfo_appinfo_metadata_filter_foreach"
637 static int appAotCb(pkgmgrinfo_appinfo_h handle, void *userData)
638 {
639         char *pkgId = NULL;
640         int ret = 0;
641         NIOption **pOptions = (NIOption**)userData;
642
643         ret = pkgmgrinfo_appinfo_get_pkgid(handle, &pkgId);
644         if (ret != PMINFO_R_OK) {
645                 _SERR("Failed to get pkgid");
646                 return -1;
647         }
648
649         if (removeNIUnderPkgRoot(pkgId) != NI_ERROR_NONE) {
650                 _SERR("Failed to remove previous dlls from [%s]", pkgId);
651                 return -1;
652         }
653
654         if (createNIUnderPkgRoot(pkgId, *pOptions) != NI_ERROR_NONE) {
655                 _SERR("Failed to generate NI file [%s]", pkgId);
656                 return -1;
657         } else {
658                 _SOUT("Complete make application to native image");
659         }
660
661         return 0;
662 }
663
664 ni_error_e initNICommon()
665 {
666 #if defined(__arm__) || defined(__aarch64__)
667
668         char *env = nullptr;
669         env = getenv("MIC_CROSSGEN2_ENABLED");
670         if (env != nullptr && !strcmp(env, "1")) {
671                 CORERUN_CMD = std::string("/opt/usr/dotnet/mic/crossgen2");
672                 CROSSGEN2_PATH = "";
673                 CLRJIT_PATH = std::string("/opt/usr/dotnet/mic/libclrjit_unix_") + ARCHITECTURE_IDENTIFIER + std::string("_x64.so");
674         }
675
676         // get interval value
677         const static std::string intervalFile = concatPath(__NATIVE_LIB_DIR, "crossgen_interval.txt");
678         std::ifstream inFile(intervalFile);
679         if (inFile) {
680                 _SOUT("crossgen_interval.txt is found");
681                 inFile >> __interval;
682         }
683
684         if (initializePluginManager("normal")) {
685                 _SERR("Fail to initialize PluginManager");
686                 return NI_ERROR_UNKNOWN;
687         }
688
689         try {
690                 __pm = new PathManager();
691         } catch (const std::exception& e) {
692                 _SERR("Failed to create PathManager");
693                 return NI_ERROR_UNKNOWN;
694         }
695
696         char* pluginDllPaths = pluginGetDllPath();
697         if (pluginDllPaths && pluginDllPaths[0] != '\0') {
698                 __pm->addPlatformAssembliesPaths(pluginDllPaths, true);
699         }
700
701         char* pluginNativePaths = pluginGetNativeDllSearchingPath();
702         if (pluginNativePaths && pluginNativePaths[0] != '\0') {
703                 __pm->addNativeDllSearchingPaths(pluginNativePaths, true);
704         }
705
706         return NI_ERROR_NONE;
707 #else
708         _SERR("crossgen supports arm/arm64 architecture only. skip ni file generation");
709         return NI_ERROR_NOT_SUPPORTED;
710 #endif
711 }
712
713 void finalizeNICommon()
714 {
715         __interval = 0;
716
717         finalizePluginManager();
718
719         delete(__pm);
720         __pm = nullptr;
721
722         if (__ni_option) {
723                 free(__ni_option);
724                 __ni_option = nullptr;
725         }
726 }
727
728 ni_error_e createNIPlatform(NIOption* opt)
729 {
730         ni_error_e ret = createNIUnderDirs(__pm->getRuntimePath(), opt);
731         if (ret != NI_ERROR_NONE) {
732                 return ret;
733         }
734
735         return createNIUnderDirs(__pm->getTizenFXPath(), opt);
736 }
737
738 ni_error_e createNIDll(const std::string& dllPath, NIOption* opt)
739 {
740         return doAOTFile(dllPath, std::string(), opt);
741 }
742
743 ni_error_e createNIUnderTAC(const std::string& targetPath, const std::string& refPaths, NIOption* opt)
744 {
745         ni_error_e ret;
746
747         // get managed file list from targetPath
748         std::vector<std::string> dllList;
749         ret = getTargetDllList(targetPath, dllList);
750         if (ret != NI_ERROR_NONE) {
751                 return ret;
752         }
753
754         std::vector<std::string> needNIList;
755         std::vector<std::string> niList;
756
757         for (auto &dll : dllList) {
758                 if (!checkNIExistence(dll)) {
759                         needNIList.push_back(dll);
760                 }
761                 niList.push_back(getNIFilePath(dll));
762         }
763
764         if (!needNIList.empty()) {
765                 // NI fils of TAC-related dlls under /opt/usr/dotnet should not be created under .native_image directory.
766                 // So, unset NI_FLAGS_APPNI temporally and restore it after running AOT.
767                 opt->flags &= ~NI_FLAGS_APPNI;
768                 ret = doAOTList(needNIList, refPaths, opt);
769                 opt->flags |= NI_FLAGS_APPNI;
770                 if (ret != NI_ERROR_NONE) {
771                         return ret;
772                 }
773         }
774
775         for (auto &niPath : niList) {
776                 if (exist(niPath)) {
777                         std::string symNIPath = concatPath(targetPath, getFileName(niPath));
778                         if (!exist(symNIPath)) {
779                                 bf::create_symlink(niPath, symNIPath);
780                                 copySmackAndOwnership(targetPath.c_str(), symNIPath.c_str(), true);
781                                 _SOUT("%s symbolic link file generated successfully.", symNIPath.c_str());
782                                 _INFO("%s symbolic link file generated successfully.", symNIPath.c_str());
783                         }
784                 }
785         }
786
787         return NI_ERROR_NONE;
788 }
789
790
791 ni_error_e createNIUnderDirs(const std::string& rootPaths, NIOption* opt)
792 {
793         ni_error_e ret = NI_ERROR_NONE;
794
795         std::vector<std::string> fileList;
796         std::vector<std::string> paths;
797         splitPath(rootPaths, paths);
798
799         for (const auto &path : paths) {
800                 if (!exist(path)) {
801                         continue;
802                 }
803
804                 if (path.find(TAC_SYMLINK_SUB_DIR) != std::string::npos) {
805                         ret = createNIUnderTAC(path, rootPaths, opt);
806                         if (ret != NI_ERROR_NONE) {
807                                 return ret;
808                         }
809                 } else if (opt->flags & NI_FLAGS_APPNI) {
810                         ret = getAppTargetDllList(path, fileList, opt);
811                         if (ret != NI_ERROR_NONE) {
812                                 return ret;
813                         }
814                 } else {
815                         ret = getTargetDllList(path, fileList);
816                         if (ret != NI_ERROR_NONE) {
817                                 return ret;
818                         }
819                 }
820         }
821
822         if (fileList.empty()) {
823                 return NI_ERROR_NONE;
824         }
825
826         return doAOTList(fileList, rootPaths, opt);
827 }
828
829 ni_error_e createNIUnderPkgRoot(const std::string& pkgId, NIOption* opt)
830 {
831         std::string rootPath = getRootPath(pkgId);
832         if (rootPath.empty()) {
833                 _SERR("Failed to get root path from [%s]", pkgId.c_str());
834                 return NI_ERROR_INVALID_PACKAGE;
835         }
836
837         __pm->setAppRootPath(rootPath);
838
839         char* extraDllPaths = pluginGetExtraDllPath();
840         if (extraDllPaths && extraDllPaths[0] != '\0') {
841                 __pm->setExtraDllPaths(extraDllPaths);
842         }
843
844         opt->flags |= NI_FLAGS_APPNI;
845
846         if (isReadOnlyArea(rootPath)) {
847                 opt->flags |= NI_FLAGS_APP_UNDER_RO_AREA;
848                 opt->flags |= NI_FLAGS_NO_PIPELINE;
849                 _SERR("Only no-pipeline mode supported for RO app. Set no-pipeline option forcibly");
850         } else {
851                 opt->flags &= ~NI_FLAGS_APP_UNDER_RO_AREA;
852         }
853
854         // create native image under bin and lib directory
855         // tac directory is skipped in the createNIUnderDirs.
856         return createNIUnderDirs(__pm->getAppPaths(), opt);
857 }
858
859 void removeNIPlatform()
860 {
861         std::string coreLib = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll");
862         std::string coreLibBackup = concatPath(__pm->getRuntimePath(), "System.Private.CoreLib.dll.Backup");
863
864         if (isR2RImage(coreLib)) {
865                 if (!isFile(coreLibBackup)) {
866                         return;
867                 }
868
869                 if (remove(coreLib.c_str())) {
870                         _SERR("Failed to remove System.Private.CoreLib native image file");
871                 }
872                 if (rename(coreLibBackup.c_str(), coreLib.c_str())) {
873                         _SERR("Failed to rename System.Private.CoreLib.Backup to origin");
874                 }
875         }
876
877 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
878         if (isFile(__SYSTEM_BASE_FILE)) {
879                 if (remove(__SYSTEM_BASE_FILE)) {
880                         _SERR("Failed to remove %s", __SYSTEM_BASE_FILE);
881                 }
882         }
883 #endif
884
885         removeNIUnderDirs(__pm->getRuntimePath() + ":" + __pm->getTizenFXPath());
886 }
887
888 void removeNIUnderDirs(const std::string& rootPaths)
889 {
890         auto convert = [](const std::string& path, const std::string& filename) {
891                 if (isNativeImage(path)) {
892                         if (remove(path.c_str())) {
893                                 _SERR("Failed to remove %s", path.c_str());
894                         }
895                 }
896         };
897
898         std::vector<std::string> paths;
899         splitPath(rootPaths, paths);
900         for (const auto &path : paths) {
901                 scanFilesInDirectory(path, convert, -1);
902         }
903 }
904
905 ni_error_e removeNIUnderPkgRoot(const std::string& pkgId)
906 {
907         std::string rootPath = getRootPath(pkgId);
908         if (rootPath.empty()) {
909                 _SERR("Failed to get root path from [%s]", pkgId.c_str());
910                 return NI_ERROR_INVALID_PACKAGE;
911         }
912
913         __pm->setAppRootPath(rootPath);
914
915         // getAppNIPaths returns bin/.native_image, lib/.native_image and .tac_symlink.
916         std::string appNIPaths = __pm->getAppNIPaths();
917         std::vector<std::string> paths;
918         splitPath(appNIPaths, paths);
919         for (const auto &path : paths) {
920                 if (!isReadOnlyArea(path)) {
921                         // Only the native image inside the TAC should be removed.
922                         if (strstr(path.c_str(), TAC_SYMLINK_SUB_DIR) != NULL) {
923                                 removeNIUnderDirs(path);
924                         } else {
925                                 if (isDirectory(path)) {
926                                         if (!removeAll(path.c_str())) {
927                                                 _SERR("Failed to remove app ni dir [%s]", path.c_str());
928                                         }
929                                 }
930                         }
931                 }
932         }
933
934         // In special cases, the ni file may exist in the dll location.
935         // The code below is to avoid this exceptional case.
936         std::string appPaths = __pm->getAppPaths();
937         splitPath(appPaths, paths);
938         for (const auto &path : paths) {
939                 if (isDirectory(path)) {
940                         removeNIUnderDirs(path);
941                 }
942         }
943
944         return NI_ERROR_NONE;
945 }
946
947 ni_error_e regenerateAppNI(NIOption* opt)
948 {
949         int ret = 0;
950         pkgmgrinfo_appinfo_metadata_filter_h handle;
951
952         ret = pkgmgrinfo_appinfo_metadata_filter_create(&handle);
953         if (ret != PMINFO_R_OK)
954                 return NI_ERROR_UNKNOWN;
955
956         ret = pkgmgrinfo_appinfo_metadata_filter_add(handle, AOT_METADATA_KEY, METADATA_VALUE);
957         if (ret != PMINFO_R_OK) {
958                 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
959                 return NI_ERROR_UNKNOWN;
960         }
961
962         ret = pkgmgrMDFilterForeach(handle, appAotCb, &opt);
963         if (ret != 0) {
964                 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
965                 return NI_ERROR_UNKNOWN;
966         }
967
968         pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
969         return NI_ERROR_NONE;
970 }
971
972 // callback function of "pkgmgrinfo_appinfo_metadata_filter_foreach"
973 static int regenTacCb(pkgmgrinfo_appinfo_h handle, void *userData)
974 {
975         char *pkgId = NULL;
976         NIOption **pOpt = (NIOption**)userData;
977
978         int ret = pkgmgrinfo_appinfo_get_pkgid(handle, &pkgId);
979         if (ret != PMINFO_R_OK || pkgId == NULL) {
980                 _SERR("Failed to get pkgid");
981                 return -1;
982         }
983
984         sqlite3 *tac_db = openDB(TAC_APP_LIST_DB);
985         if (!tac_db) {
986                 _SERR("Sqlite open error");
987                 return -1;
988         }
989         sqlite3_exec(tac_db, "BEGIN;", NULL, NULL, NULL);
990
991         char *sql = sqlite3_mprintf("SELECT * FROM TAC WHERE PKGID = %Q;", pkgId);
992         std::vector<std::string> nugets = selectDB(tac_db, sql);
993         sqlite3_free(sql);
994
995         if (tac_db) {
996                 closeDB(tac_db);
997                 tac_db = NULL;
998         }
999
1000         std::string nugetPaths;
1001         for (const auto &nuget : nugets) {
1002                 if (!nugetPaths.empty()) {
1003                         nugetPaths += ":";
1004                 }
1005                 nugetPaths += concatPath(__DOTNET_DIR, nuget);
1006         }
1007
1008         for (auto& nuget : nugets) {
1009                 createNIUnderTAC(concatPath(__DOTNET_DIR, nuget), nugetPaths, *pOpt);
1010         }
1011
1012         return 0;
1013 }
1014
1015 ni_error_e regenerateTACNI(NIOption* opt)
1016 {
1017         removeNIUnderDirs(__DOTNET_DIR);
1018
1019         pkgmgrinfo_appinfo_metadata_filter_h handle;
1020         int ret = pkgmgrinfo_appinfo_metadata_filter_create(&handle);
1021         if (ret != PMINFO_R_OK) {
1022                 return NI_ERROR_UNKNOWN;
1023         }
1024
1025         ret = pkgmgrinfo_appinfo_metadata_filter_add(handle, TAC_METADATA_KEY, METADATA_VALUE);
1026         if (ret != PMINFO_R_OK) {
1027                 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
1028                 return NI_ERROR_UNKNOWN;
1029         }
1030
1031         ret = pkgmgrMDFilterForeach(handle, regenTacCb, &opt);
1032         if (ret != 0) {
1033                 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
1034                 return NI_ERROR_UNKNOWN;
1035         }
1036
1037         pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
1038
1039         return NI_ERROR_NONE;
1040 }
1041
1042 static std::vector<uid_t> getUserIds()
1043 {
1044         std::vector<uid_t> list;
1045
1046         while (true) {
1047                 errno = 0; // so we can distinguish errors from no more entries
1048                 passwd* entry = getpwent();
1049                 if (!entry) {
1050                         if (errno) {
1051                                 _SERR("Error while getting userIDs");
1052                                 list.clear();
1053                                 return list;
1054                         }
1055                         break;
1056                 }
1057                 list.push_back(entry->pw_uid);
1058         }
1059         endpwent();
1060
1061         return list;
1062 }
1063
1064 static std::string getAppDataPath(const std::string& pkgId, uid_t uid)
1065 {
1066         std::string pDataFile;
1067
1068         tzplatform_set_user(uid);
1069
1070         const char* tzUserApp = tzplatform_getenv(TZ_USER_APP);
1071         if (tzUserApp != NULL) {
1072                 pDataFile = std::string(tzUserApp) + "/" + pkgId + "/data/";
1073         }
1074
1075         tzplatform_reset_user();
1076
1077         return pDataFile;
1078 }
1079
1080 ni_error_e removeAppProfileData(const std::string& pkgId)
1081 {
1082         if (pkgId.empty()) {
1083                 return NI_ERROR_INVALID_PARAMETER;
1084         }
1085
1086         std::vector<uid_t> uidList = getUserIds();
1087         for (auto& uid : uidList) {
1088                 // get data path from pkgid
1089                 std::string dataPath = getAppDataPath(pkgId, uid);
1090                 if (!dataPath.empty() && exist(dataPath)) {
1091                         std::string pDataFile = dataPath + PROFILE_BASENAME;
1092
1093                         if (exist(pDataFile)) {
1094                                 if (!removeFile(pDataFile)) {
1095                                         _SERR("Fail to remove profile data file (%s).", pDataFile.c_str());
1096                                         return NI_ERROR_UNKNOWN;
1097                                 }
1098                                 _SOUT("Profile data (%s) is removed successfully", pDataFile.c_str());
1099                         }
1100                 }
1101         }
1102
1103         return NI_ERROR_NONE;
1104 }
1105
1106 static int appTypeListCb(pkgmgrinfo_appinfo_h handle, void *user_data)
1107 {
1108         char *pkgId = NULL;
1109         int ret = pkgmgrinfo_appinfo_get_pkgid(handle, &pkgId);
1110         if (ret != PMINFO_R_OK || pkgId == NULL) {
1111                 _SERR("Fail to get pkgid");
1112                 return 0;
1113         }
1114
1115         if (removeAppProfileData(pkgId) != NI_ERROR_NONE) {
1116                 _SERR("Fail to remove profile data for (%s)", pkgId);
1117         }
1118
1119         return 0;
1120 }
1121
1122 static ni_error_e removeAppProfileByAppType(const char* type)
1123 {
1124         int ret;
1125
1126         pkgmgrinfo_appinfo_filter_h filter;
1127
1128         ret = pkgmgrinfo_appinfo_filter_create(&filter);
1129         if (ret != PMINFO_R_OK) {
1130                 _SERR("Fail to create appinfo filter");
1131                 return NI_ERROR_UNKNOWN;
1132         }
1133
1134         ret = pkgmgrinfo_appinfo_filter_add_string(filter, PMINFO_APPINFO_PROP_APP_TYPE, type);
1135         if (ret != PMINFO_R_OK) {
1136                 pkgmgrinfo_appinfo_filter_destroy(filter);
1137                 _SERR("Fail to add appinfo filter (%s)", type);
1138                 return NI_ERROR_UNKNOWN;
1139         }
1140
1141         ret = pkgmgrinfo_appinfo_filter_foreach_appinfo(filter, appTypeListCb, NULL);
1142         if (ret != PMINFO_R_OK) {
1143                 _SERR("Fail to pkgmgrinfo_pkginfo_filter_foreach_pkginfo");
1144                 pkgmgrinfo_appinfo_filter_destroy(filter);
1145                 return NI_ERROR_UNKNOWN;
1146         }
1147
1148         pkgmgrinfo_appinfo_filter_destroy(filter);
1149
1150         return NI_ERROR_NONE;
1151 }
1152
1153 void removeAllAppProfileData()
1154 {
1155         std::vector<const char*> appTypeList = {"dotnet", "dotnet-nui", "dotnet-inhouse"};
1156
1157         for (auto& type : appTypeList) {
1158                 if (removeAppProfileByAppType(type) != NI_ERROR_NONE) {
1159                         _SERR("Fail to removeAppProfileByAppType for type (%s)", type);
1160                 }
1161         }
1162 }