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