Exclude exe extension from target assembly
[platform/core/dotnet/launcher.git] / NativeLauncher / util / utils.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 <dirent.h>
18 #include <fcntl.h>
19 #include <sys/stat.h>
20 #include <unistd.h>
21 #include <limits.h>
22 #include <strings.h>
23 #include <pkgmgr_installer_info.h>
24 #include <sys/smack.h>
25 #include <sys/prctl.h>
26 #include <openssl/sha.h>
27 #include <mntent.h>
28
29 #include <cstdlib>
30 #include <cstring>
31 #include <algorithm>
32 #include <unordered_map>
33 #include <vector>
34 #include <iterator>
35 #include <fstream>
36 #include <sstream>
37 #include <map>
38 #include <iomanip>
39
40 #include "log.h"
41 #include "utils.h"
42 #include "path_manager.h"
43
44 static bool iCompare(const std::string& a, int aOffset, const std::string& b, int bOffset, int length)
45 {
46         return static_cast<int>(a.length()) - length >= aOffset &&
47                 static_cast<int>(b.length()) - length >= bOffset &&
48                 std::equal(b.begin() + bOffset, b.begin() + bOffset + length, a.begin() + aOffset,
49                         [](unsigned char a, unsigned char b)
50                         { return std::tolower(a) == std::tolower(b); });
51 }
52
53 bool isManagedAssembly(const std::string& fileName)
54 {
55         return iCompare(fileName, fileName.size()-4, ".dll", 0, 4) && !isNativeImage(fileName);
56 }
57
58 bool isNativeImage(const std::string& fileName)
59 {
60         return iCompare(fileName, fileName.size()-7, ".ni", 0, 3);
61 }
62
63 std::string concatPath(const std::string& path1, const std::string& path2)
64 {
65         std::string path(path1);
66         if (path.back() == PATH_SEPARATOR) {
67                 path.append(path2);
68         } else {
69                 path += PATH_SEPARATOR;
70                 path.append(path2);
71         }
72
73         return path;
74 }
75
76 void splitPath(const std::string& path, std::vector<std::string>& out)
77 {
78         std::istringstream ss(path);
79         std::string token;
80
81         while (std::getline(ss, token, ':')) {
82                 out.push_back(token);
83         }
84 }
85
86 std::string getAbsolutePath(const std::string& path)
87 {
88         std::string absPath;
89         char *realPath = realpath(path.c_str(), NULL);
90         if (realPath) {
91                 absPath.assign(realPath);
92                 free(realPath);
93         }
94
95         return absPath;
96 }
97
98 std::string getRootPath(const std::string& pkgId)
99 {
100         int ret = 0;
101         char *path = 0;
102         std::string rootPath;
103
104         pkgmgrinfo_pkginfo_h pkg_handle;
105         ret = pkgmgrGetPkgInfo(pkgId, &pkg_handle);
106         if (ret != 0) {
107                 return rootPath;
108         }
109
110         ret = pkgmgrinfo_pkginfo_get_root_path(pkg_handle, &path);
111         if (ret != PMINFO_R_OK) {
112                 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
113                 return rootPath;
114         }
115         rootPath = path;
116         pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
117
118         return rootPath;
119 }
120
121 std::string getExecName(const std::string& pkgId)
122 {
123         char *exec = NULL;
124         char *appId = 0;
125         std::string execName;
126
127         pkgmgrinfo_pkginfo_h pkg_handle;
128         int ret = pkgmgrGetPkgInfo(pkgId, &pkg_handle);
129         if (ret != 0) {
130                 return execName;
131         }
132
133         ret = pkgmgrinfo_pkginfo_get_mainappid(pkg_handle, &appId);
134         if (ret != PMINFO_R_OK) {
135                 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
136                 return execName;
137         }
138
139         pkgmgrinfo_appinfo_h app_handle;
140         ret = pkgmgrGetAppInfo(appId, &app_handle);
141         if (ret != 0) {
142                 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
143                 return execName;
144         }
145
146         ret = pkgmgrinfo_appinfo_get_exec(app_handle, &exec);
147         if (ret != PMINFO_R_OK) {
148                 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
149                 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
150                 return execName;
151         }
152         execName = std::string(exec).substr(std::string(exec).rfind('/') + 1);
153
154         pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
155         pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
156
157         return execName;
158 }
159
160 std::string getAppType(const std::string& pkgId)
161 {
162         char *appId = 0;
163         char *type = 0;
164         std::string appType;
165
166         pkgmgrinfo_pkginfo_h pkg_handle;
167         int ret = pkgmgrGetPkgInfo(pkgId, &pkg_handle);
168         if (ret != 0) {
169                 return appType;
170         }
171
172         ret = pkgmgrinfo_pkginfo_get_mainappid(pkg_handle, &appId);
173         if (ret != PMINFO_R_OK) {
174                 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
175                 return appType;
176         }
177
178         pkgmgrinfo_appinfo_h app_handle;
179         ret = pkgmgrGetAppInfo(appId, &app_handle);
180         if (ret != 0) {
181                 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
182                 return appType;
183         }
184
185         ret = pkgmgrinfo_appinfo_get_apptype(app_handle, &type);
186         if (ret != PMINFO_R_OK) {
187                 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
188                 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
189                 return appType;
190         }
191         appType = type;
192
193         pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
194         pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
195
196         return appType;
197 }
198
199 std::string getMetadataValue(const std::string& pkgId, const std::string& key)
200 {
201         char *value = NULL;
202         char *appId = 0;
203         std::string metadataValue;
204
205         pkgmgrinfo_pkginfo_h pkg_handle;
206         int ret = pkgmgrGetPkgInfo(pkgId, &pkg_handle);
207         if (ret != 0) {
208                 return metadataValue;
209         }
210
211         ret = pkgmgrinfo_pkginfo_get_mainappid(pkg_handle, &appId);
212         if (ret != PMINFO_R_OK) {
213                 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
214                 return metadataValue;
215         }
216
217         pkgmgrinfo_appinfo_h app_handle;
218         ret = pkgmgrGetAppInfo(appId, &app_handle);
219         if (ret != 0) {
220                 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
221                 return metadataValue;
222         }
223
224         ret = pkgmgrinfo_appinfo_get_metadata_value(app_handle, key.c_str(), &value);
225         if (ret != PMINFO_R_OK) {
226                 pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
227                 pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
228                 return metadataValue;
229         }
230         metadataValue = std::string(value);
231
232         pkgmgrinfo_appinfo_destroy_appinfo(app_handle);
233         pkgmgrinfo_pkginfo_destroy_pkginfo(pkg_handle);
234
235         return metadataValue;
236 }
237
238 bool isReadOnlyArea(const std::string& path)
239 {
240         FILE *f = NULL;
241         struct mntent *m = NULL;
242
243         // "/opt/usr" is mounted to "RW" only
244         if (path.find("/opt/usr") != std::string::npos) {
245                 return false;
246         }
247
248         // check whether "/" is mounted to RO or not
249         f = setmntent("/proc/mounts", "r");
250         if (!f) {
251                 // return true for fail case to generate NI files under RW area.
252                 return true;
253         }
254
255         while((m = getmntent(f))) {
256                 if (m->mnt_dir != NULL && strcmp(m->mnt_dir, "/") == 0 &&
257                         m->mnt_opts != NULL && strstr(m->mnt_opts, "ro,") != NULL) {
258                         endmntent(f);
259                         return true;
260                 }
261         }
262         endmntent(f);
263         return false;
264
265 }
266
267 std::string getBaseName(const std::string& path)
268 {
269         auto pos = path.find_last_of(PATH_SEPARATOR);
270         if (pos != std::string::npos)
271                 return path.substr(0, pos);
272         else
273                 return std::string(".");
274         return path;
275 }
276
277 std::string replaceAll(const std::string& str, const std::string& pattern, const std::string& replace)
278 {
279         std::string result = str;
280         std::string::size_type pos = 0;
281         std::string::size_type offset = 0;
282
283         while ((pos = result.find(pattern, offset)) != std::string::npos) {
284                 result.replace(result.begin() + pos, result.begin() + pos + pattern.size(), replace);
285                 offset = pos + replace.size();
286         }
287
288         return result;
289 }
290
291 std::string changeExtension(const std::string& path, const std::string& from, const std::string& to)
292 {
293         return path.substr(0, path.rfind(from)) + to;
294 }
295
296 bool isFile(const std::string& path)
297 {
298         struct stat sb;
299         return lstat(path.c_str(), &sb) == 0;
300 }
301
302 bool isSymlinkFile(const std::string& path)
303 {
304         struct stat sb;
305         if (lstat(path.c_str(), &sb) != 0) {
306                 return false;
307         }
308         return (sb.st_mode & S_IFMT) == S_IFLNK;
309 }
310
311 bool isDirectory(const std::string& path)
312 {
313         struct stat sb;
314         if (stat(path.c_str(), &sb) != 0) {
315                 return false;
316         }
317         return (sb.st_mode & S_IFMT) == S_IFDIR;
318 }
319
320 std::string getAssemblyNameFromPath(const std::string& path)
321 {
322         std::string ret(getFileName(path));
323
324         if (ret.find_last_of(".") == std::string::npos)
325                 return ret;
326         ret.erase(ret.find_last_of("."));
327
328         if (ret.size() > 3 && std::equal(ret.begin() + ret.size() - 3, ret.end(), ".ni"))
329                 ret.erase(ret.size() - 3);
330
331         return ret;
332 }
333
334 void addAssembliesFromDirectories(const std::vector<std::string>& directories, std::string& list)
335 {
336         std::vector<std::string> assems;
337         std::unordered_map<std::string, std::string> assemPaths;
338
339         auto reader = [&assems, &assemPaths](const std::string& path, const std::string& filename) {
340                 if (isManagedAssembly(filename) || isNativeImage(filename)) {
341                         std::string assem = getAssemblyNameFromPath(filename);
342
343                         if (assemPaths.count(assem) == 0) {
344                                 assems.push_back(assem);
345                                 assemPaths[assem] = path;
346                         } else if (isManagedAssembly(assemPaths[assem]) && isNativeImage(filename)) {
347                                 // Update only if a native image is found in the same directory.
348                                 // For example, if we have two directories = { X, Y } where X contains A.dll and
349                                 // Y contains both A.dll and A.ni.dll, always A.dll in X will be used.
350                                 if (getBaseName(assemPaths[assem]).compare(getBaseName(path)) == 0)
351                                         assemPaths[assem] = path;
352                         }
353                 }
354         };
355         for (auto& directory : directories)
356                 scanFilesInDirectory(directory, reader, 0);
357
358         if (!list.empty() && list.back() != ':')
359                 list.push_back(':');
360
361         for (auto& assem : assems)
362                 list += assemPaths[assem] + ":";
363
364         if (list.back() == ':')
365                 list.pop_back();
366 }
367
368 void scanFilesInDirectory(const std::string& directory, FileReader reader, unsigned int depth)
369 {
370         DIR *dir;
371         struct dirent* entry;
372         bool isDir;
373
374         dir = opendir(directory.c_str());
375
376         if (dir == nullptr)
377                 return;
378
379         std::vector<std::string> innerDirectories;
380
381         while ((entry = readdir(dir)) != nullptr) {
382                 isDir = false;
383                 std::string path = concatPath(directory, entry->d_name);
384                 switch (entry->d_type) {
385                         case DT_REG: break;
386                         case DT_DIR:
387                                 isDir = true;
388                                 break;
389                         // symlink is added to the list even if there is no original file.
390                         // It used to remove broken symlinks related to TAC
391                         case DT_LNK:
392                                 break;
393                         case DT_UNKNOWN:
394                                 continue;
395                         default:
396                                 continue;
397                 }
398                 if (!isDir)
399                         reader(path, entry->d_name);
400                 else if (depth > 0 && strcmp(entry->d_name, ".") && strcmp(entry->d_name, ".."))
401                         innerDirectories.push_back(path);
402         }
403
404         if (depth > 0)
405                 for (auto& d : innerDirectories)
406                         scanFilesInDirectory(d, reader, depth - 1);
407
408         closedir(dir);
409 }
410
411 void copySmackAndOwnership(const std::string& fromPath, const std::string& toPath, bool isSymlink)
412 {
413         char* label = NULL;
414         struct stat info;
415
416         if (isSymlink) {
417                 // change smack label for symbolic link.
418                 if (smack_lgetlabel(fromPath.c_str(), &label, SMACK_LABEL_ACCESS) == 0) {
419                         if (smack_lsetlabel(toPath.c_str(), label, SMACK_LABEL_ACCESS) < 0) {
420                                 _SERR("Fail to set smack label");
421                         }
422                         free(label);
423                 }
424
425                 // change owner and groupsfor symbolic link.
426                 // change mode is skipped for symlink because permission of symlink file is meaningless.
427                 if (!lstat(fromPath.c_str(), &info)) {
428                         if (lchown(toPath.c_str(), info.st_uid, info.st_gid) == -1)
429                                 _SERR("Failed to change owner and group name");
430                 }
431         } else {
432                 // change smack label
433                 if (smack_getlabel(fromPath.c_str(), &label, SMACK_LABEL_ACCESS) == 0) {
434                         if (smack_setlabel(toPath.c_str(), label, SMACK_LABEL_ACCESS) < 0) {
435                                 _SERR("Fail to set smack label");
436                         }
437                         free(label);
438                 }
439
440                 // change owner, groups and mode for generated ni file.
441                 if (!stat(fromPath.c_str(), &info)) {
442                         if (chown(toPath.c_str(), info.st_uid, info.st_gid) == -1)
443                                 _SERR("Failed to change owner and group name");
444                         if (chmod(toPath.c_str(), info.st_mode) == -1)
445                                 _SERR("Failed to change mode");
446                 }
447         }
448 }
449
450 static bool setOwnership(const bf::path& path, uid_t uid, gid_t gid)
451 {
452         int fd = open(path.c_str(), O_RDONLY);
453         if (fd < 0) {
454                 _ERR("Can't open directory: %s", path.c_str());
455                 return false;
456         }
457         int ret = fchown(fd, uid, gid);
458         close(fd);
459         if (ret != 0) {
460                 _ERR("Failed to change owner of: %s", path.c_str());
461                 return false;
462         }
463         return true;
464 }
465
466 static bool setDirPermissions(const bf::path& path, bf::perms permissions)
467 {
468         bs::error_code error;
469         bf::permissions(path, permissions, error);
470         if (error) {
471                 _ERR("Failed to set permissions for directory: %s, %s", path.c_str(), error.message().c_str());
472                 return false;
473         }
474         return true;
475 }
476
477 static bool setDirOwnershipAndPermissions(const bf::path& path, bf::perms permissions, uid_t uid, gid_t gid)
478 {
479         if (!setOwnership(path, uid, gid)) {
480                 _ERR("Failed to change owner: %s, (uid: %d, gid: %d)", path.c_str(), uid, gid);
481                 return false;
482         }
483         if (!setDirPermissions(path, permissions)) {
484                 _ERR("Failed to change permission: %s, (%d)", path.c_str(), permissions);
485                 return false;
486         }
487         return true;
488 }
489
490 static bool copyOwnershipAndPermissions(const bf::path& path, const bf::path& path2)
491 {
492         if (!exist(path)) {
493                 _ERR("Failed to copy ownership and permissions from %s to %s", path.c_str(), path2.c_str());
494                 return false;
495         }
496         bs::error_code error;
497         bf::perms permissions = bf::status(path, error).permissions();
498         if (error) {
499                 _ERR("Failed to copy ownership and permissions : %s", error.message().c_str());
500                 return false;
501         }
502         struct stat stats;
503         if (stat(path.c_str(), &stats) != 0) {
504                 return false;
505         }
506         if (!setDirOwnershipAndPermissions(path2, permissions, stats.st_uid, stats.st_gid)) {
507                 _ERR("Failed to copy ownership and permissions from %s to %s", path.c_str(), path2.c_str());
508                 return false;
509         }
510         return true;
511 }
512
513 bool exist(const bf::path& path)
514 {
515         bs::error_code error;
516         int ret = bf::exists(path, error);
517         if (error) {
518                 if ((error.value() != bs::errc::success) && (error.value() != bs::errc::no_such_file_or_directory)) {
519                         _ERR("Failed to check %s exists : %s", path.c_str(), error.message().c_str());
520                 }
521         }
522         return ret;
523 }
524
525 bool createDir(const bf::path& path)
526 {
527         if (exist(path)) {
528                 return true;
529         }
530         bs::error_code error;
531         bf::create_directories(path, error);
532         if (error) {
533                 _ERR("Failed to create directory: %s", error.message().c_str());
534                 return false;
535         }
536         return true;
537 }
538
539 bool copyDir(const bf::path& path1, const bf::path& path2, FSFlag flags)
540 {
541         try {
542                 // Check whether the function call is valid
543                 if (!exist(path1) || !bf::is_directory(path1)) {
544                         _ERR("Source directory %s does not exist or is not a directory", path1.c_str());
545                         return false;
546                 }
547                 if (!exist(path2)) {
548                         // Create the destination directory
549                         if (!createDir(path2)) {
550                                 _ERR("Unable to create destination directory %s", path2.c_str());
551                                 return false;
552                         }
553                         if (flags & FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS) {
554                                 copyOwnershipAndPermissions(path1, path2);
555                         }
556                 } else {
557                         if (!(flags & (FS_MERGE_SKIP | FS_MERGE_OVERWRITE))) {
558                                 _ERR("Destination directory %s already exists", path2.c_str());
559                                 return false;
560                         }
561                         if (flags & (FS_MERGE_OVERWRITE | FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS)) {
562                                 copyOwnershipAndPermissions(path1, path2);
563                         }
564                 }
565         } catch (const bf::filesystem_error& error) {
566                 _ERR("Failed to copy directory: %s", error.what());
567                 return false;
568         }
569
570         // Iterate through the source directory
571         try {
572                 for (bf::directory_iterator file(path1); file != bf::directory_iterator(); ++file) {
573                         bf::path current(file->path());
574                         bf::path target = path2 / current.filename();
575                         if (bf::is_symlink(bf::symlink_status(current))) {
576                                 if ((flags & (FS_MERGE_SKIP | FS_MERGE_OVERWRITE)) && exist(target)) {
577                                         continue;
578                                 }
579                                 bs::error_code error;
580                                 bf::copy_symlink(current, target, error);
581                                 if (error) {
582                                         _ERR("Failed to copy symlink: %s, %s", current.c_str(), error.message().c_str());
583                                         return false;
584                                 }
585                         } else if (bf::is_directory(current)) {
586                                 // Found directory: Recursion
587                                 if (!copyDir(current, target, flags)) {
588                                         return false;
589                                 }
590                         } else {
591                                 if ((flags & FS_MERGE_SKIP) && exist(target)) {
592                                         continue;
593                                 }
594                                 bf::path destination = target;
595                                 if (flags & FS_COMMIT_COPY_FILE) {
596                                         destination = bf::unique_path(target.parent_path() / "%%%%-%%%%-%%%%-%%%%");
597                                 }
598                                 if (flags & FS_MERGE_OVERWRITE) {
599                                         bf::copy_file(current, destination, bf::copy_option::overwrite_if_exists);
600                                 } else {
601                                         bf::copy_file(current, destination);
602                                 }
603                                 if (flags & FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS) {
604                                         copyOwnershipAndPermissions(current, destination);
605                                 }
606                                 if (flags & FS_COMMIT_COPY_FILE) {
607                                         if (flags & FS_MERGE_OVERWRITE) {
608                                                 bf::remove(target);
609                                         }
610                                         bf::rename(destination, target);
611                                 }
612                         }
613                 }
614         } catch (const bf::filesystem_error& error) {
615                 _ERR("Failed to copy directory: %s", error.what());
616                 return false;
617         }
618
619         return true;
620 }
621
622 bool copyFile(const bf::path& path1, const bf::path& path2)
623 {
624         bs::error_code error;
625         if (!exist(path1)) {
626                 return false;
627         }
628         bf::copy_file(path1, path2, bf::copy_option::overwrite_if_exists, error);
629         if (error) {
630                 _ERR("copy file %s due to error [%s]", path1.c_str(), error.message().c_str());
631                 return false;
632         }
633         return true;
634 }
635
636 bool moveFile(const bf::path& path1, const bf::path& path2)
637 {
638         if (!exist(path1) || exist(path2)) {
639                 return false;
640         }
641         bs::error_code error;
642         bf::rename(path1, path2, error);
643         if (error) {
644                 _ERR("Cannot move file: %s. Will copy/remove... with error [%s]", path1.c_str(), error.message().c_str());
645                 bf::copy_file(path1, path2, bf::copy_option::overwrite_if_exists, error);
646                 if (error) {
647                         _ERR("Cannot copy file %s due to error [%s]", path1.c_str(), error.message().c_str());
648                         return false;
649                 }
650                 bf::remove_all(path1, error);
651                 if (error) {
652                         _ERR("Cannot remove old file when coping: %s with error [%s]", path1.c_str(), error.message().c_str());
653                         return false;
654                 }
655         }
656         return true;
657 }
658
659 bool removeFile(const bf::path& path)
660 {
661         if (!exist(path)) {
662                 return true;
663         }
664         bs::error_code error;
665         bf::remove(path, error);
666         if (error) {
667                 _ERR("Cannot remove: %s, %s", path.c_str(), error.message().c_str());
668                 return false;
669         }
670         return true;
671 }
672
673 bool removeAll(const bf::path& path)
674 {
675         if (!exist(path)) {
676                 return true;
677         }
678         bs::error_code error;
679         bf::remove_all(path, error);
680         if (error) {
681                 _ERR("Cannot remove: %s, %s", path.c_str(), error.message().c_str());
682                 return false;
683         }
684         return true;
685 }
686
687 void setCmdName(const std::string& name)
688 {
689         #define PRC_NAME_LENGTH         16
690
691         char processName[PRC_NAME_LENGTH] = {0, };
692
693         if (name.empty())
694                 return;
695
696         memset(processName, '\0', PRC_NAME_LENGTH);
697         snprintf(processName, PRC_NAME_LENGTH, "%s", name.c_str());
698         prctl(PR_SET_NAME, processName);
699 }
700
701 std::string getFileName(const std::string& path)
702 {
703         std::string ret(path);
704         size_t index = ret.find_last_of(PATH_SEPARATOR);
705         return index == std::string::npos ? ret : ret.substr(index + 1);
706 }
707
708 std::string SHA256(const std::string& path)
709 {
710         std::string output = "";
711         FILE *file = fopen(path.c_str(), "rb");
712         if (!file) {
713                 return output;
714         }
715
716         unsigned char hash[SHA256_DIGEST_LENGTH];
717         SHA256_CTX sha256;
718         SHA256_Init(&sha256);
719         int bytesRead = 0;
720         const int bufSize = 32768;
721         char *buffer = (char*)malloc(bufSize);
722         if (!buffer) {
723                 fclose(file);
724                 return output;
725         }
726
727         while ((bytesRead = fread(buffer, 1, bufSize, file))) {
728                 SHA256_Update(&sha256, buffer, bytesRead);
729         }
730         SHA256_Final(hash, &sha256);
731
732         std::stringstream ss;
733         for (int i = 0; i < SHA256_DIGEST_LENGTH; i++) {
734                 ss << std::hex << std::setw(2) << std::setfill('0') << (int)hash[i];
735         }
736         output = ss.str();
737
738         fclose(file);
739         free(buffer);
740
741         return output;
742 }
743
744 int pkgmgrGetPkgInfo(const std::string& pkgId, pkgmgrinfo_pkginfo_h* handle)
745 {
746         uid_t uid = 0;
747         int ret = 0;
748
749         if (pkgmgr_installer_info_get_target_uid(&uid) < 0) {
750                 _ERR("Failed to get UID");
751                 return -1;
752         }
753
754         ret = pkgmgrinfo_pkginfo_get_usr_pkginfo(pkgId.c_str(), uid, handle);
755         if (ret != PMINFO_R_OK) {
756                 _ERR("Failed to get pkginfo (%d)", ret);
757                 return -1;
758         }
759
760         return 0;
761 }
762
763 int pkgmgrGetAppInfo(const std::string& appId, pkgmgrinfo_appinfo_h* handle)
764 {
765         uid_t uid = 0;
766         int ret = 0;
767
768         if (pkgmgr_installer_info_get_target_uid(&uid) < 0) {
769                 _ERR("Failed to get UID");
770                 return -1;
771         }
772
773         ret = pkgmgrinfo_appinfo_get_usr_appinfo(appId.c_str(), uid, handle);
774         if (ret != PMINFO_R_OK) {
775                 _ERR("Failed to get appinfo (%d)", ret);
776                 return -1;
777         }
778
779         return 0;
780 }
781
782 int pkgmgrMDFilterForeach(pkgmgrinfo_appinfo_metadata_filter_h handle,
783                                                         pkgmgrinfo_app_list_cb app_cb,
784                                                         void *user_data)
785 {
786         uid_t uid = 0;
787         int ret = 0;
788
789         if (pkgmgr_installer_info_get_target_uid(&uid) < 0) {
790                 _ERR("Failed to get UID");
791                 return -1;
792         }
793
794
795         ret = pkgmgrinfo_appinfo_usr_metadata_filter_foreach(handle, app_cb, user_data, uid);
796         if (ret != PMINFO_R_OK) {
797                 _ERR("Failed to execute the metadata filter query (%d)", ret);
798                 return -1;
799         }
800
801         return 0;
802 }
803
804 void printHWClockLog(const char* format, ...)
805 {
806         char buf[1024] = {0,};
807         va_list ap;
808
809         va_start(ap, format);
810         vsnprintf(buf, sizeof(buf), format, ap);
811         va_end(ap);
812
813         prctl(PR_TASK_PERF_USER_TRACE, buf, strlen(buf));
814 }
815
816 const char* getNCDBStartupHook()
817 {
818         return "/home/owner/share/tmp/sdk_tools/netcoredbg/ncdbhook.dll";
819 }
820
821 bool isNCDBStartupHookProvided()
822 {
823         char *env = nullptr;
824         env = getenv("DOTNET_STARTUP_HOOKS");
825         if (env == nullptr)
826                 return false;
827
828         // Note, `DOTNET_STARTUP_HOOKS` env could provide list of dlls with ':' delimiter,
829         // for example: "/path1/name1.dll:/path2/name2.dll"
830         while (*env != '\0')
831         {
832                 const char *ncdbCur = getNCDBStartupHook();
833                 while (*ncdbCur != '\0' && *env != '\0' && *env != ':')
834                 {
835                         if (*ncdbCur != *env)
836                                 break;
837
838                         ncdbCur++;
839                         env++;
840
841                         if (*ncdbCur == '\0' && (*env == '\0' || *env == ':'))
842                                 return true;
843                 }
844                 while (*env != '\0' && *env != ':')
845                 {
846                         env++;
847                 }
848                 if (*env == ':')
849                         env++;
850         }
851
852         return false;
853 }