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