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