Add nitool option to compile system libs with unique default base address
[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-info.h>
24 #include <pkgmgr_installer_info.h>
25 #include <sys/smack.h>
26
27 #include <cstdlib>
28 #include <cstring>
29 #include <algorithm>
30 #include <unordered_map>
31 #include <vector>
32 #include <iterator>
33 #include <sstream>
34 #include <map>
35
36 #include "log.h"
37 #include "utils.h"
38 #include "path_manager.h"
39
40 static bool iCompare(const std::string& a, int aOffset, const std::string& b, int bOffset, int length)
41 {
42         return static_cast<int>(a.length()) - length >= aOffset &&
43                 static_cast<int>(b.length()) - length >= bOffset &&
44                 std::equal(b.begin() + bOffset, b.begin() + bOffset + length, a.begin() + aOffset,
45                         [](unsigned char a, unsigned char b)
46                         { return std::tolower(a) == std::tolower(b); });
47 }
48
49 bool isManagedAssembly(const std::string& fileName)
50 {
51         return (iCompare(fileName, fileName.size()-4, ".dll", 0, 4) ||
52                         iCompare(fileName, fileName.size()-4, ".exe", 0, 4)) &&
53                         !isNativeImage(fileName);
54 }
55
56 bool isNativeImage(const std::string& fileName)
57 {
58         return iCompare(fileName, fileName.size()-7, ".ni", 0, 3);
59 }
60
61 bool cmdOptionExists(char** begin, char** end, const std::string& option)
62 {
63         return std::find(begin, end, option) != end;
64 }
65
66 std::string readSelfPath()
67 {
68         char buff[PATH_MAX];
69         ssize_t len = ::readlink("/proc/self/exe", buff, sizeof(buff)-1);
70         if (len != -1) {
71                 buff[len] = '\0';
72                 return std::string(buff);
73         }
74
75         return "";
76 }
77
78 std::string concatPath(const std::string& path1, const std::string& path2)
79 {
80         std::string path(path1);
81         if (path.back() == PATH_SEPARATOR) {
82                 path.append(path2);
83         } else {
84                 path += PATH_SEPARATOR;
85                 path.append(path2);
86         }
87
88         return path;
89 }
90
91 void splitPath(const std::string& path, std::vector<std::string>& out)
92 {
93         std::istringstream ss(path);
94         std::string token;
95
96         while (std::getline(ss, token, ':')) {
97                 out.push_back(token);
98         }
99 }
100
101 std::string absolutePath(const std::string& path)
102 {
103         std::string absPath;
104         char realPath[PATH_MAX];
105         if (realpath(path.c_str(), realPath) != nullptr && realPath[0] != '\0')
106                 absPath.assign(realPath);
107
108         return absPath;
109 }
110
111 int getRootPath(std::string pkgId, std::string& rootPath)
112 {
113         int ret = 0;
114         char *path = 0;
115         uid_t uid = 0;
116
117         if (pkgmgr_installer_info_get_target_uid(&uid) < 0) {
118                 _ERR("Failed to get UID");
119                 return -1;
120         }
121
122         pkgmgrinfo_pkginfo_h handle;
123         if (uid == 0) {
124                 ret = pkgmgrinfo_pkginfo_get_pkginfo(pkgId.c_str(), &handle);
125                 if (ret != PMINFO_R_OK) {
126                         return -1;
127                 }
128         } else {
129                 ret = pkgmgrinfo_pkginfo_get_usr_pkginfo(pkgId.c_str(), uid, &handle);
130                 if (ret != PMINFO_R_OK) {
131                         return -1;
132                 }
133         }
134
135         ret = pkgmgrinfo_pkginfo_get_root_path(handle, &path);
136         if (ret != PMINFO_R_OK) {
137                 pkgmgrinfo_pkginfo_destroy_pkginfo(handle);
138                 return -1;
139         }
140         rootPath = path;
141         pkgmgrinfo_pkginfo_destroy_pkginfo(handle);
142         return 0;
143 }
144
145 std::string baseName(const std::string& path)
146 {
147         auto pos = path.find_last_of(PATH_SEPARATOR);
148         if (pos != std::string::npos)
149                 return path.substr(0, pos);
150         else
151                 return std::string(".");
152         return path;
153 }
154
155 bool isFileExist(const std::string& path)
156 {
157         struct stat sb;
158         return stat(path.c_str(), &sb) == 0;
159 }
160
161 uintptr_t getFileSize(const std::string& path)
162 {
163         struct stat sb;
164
165         if (stat(path.c_str(), &sb) == 0) {
166                 return sb.st_size;
167         }
168
169         return 0;
170 }
171
172 std::string stripNiDLL(const std::string& path)
173 {
174         std::string niPath(path);
175         if (path.size() < 5) return niPath;
176         if (!strncasecmp(path.c_str() + path.size() - 4, ".dll", 4))
177                 niPath = path.substr(0, path.size()-4);
178         else if (!strncasecmp(path.c_str() + path.size() - 4, ".exe", 4))
179                 niPath = path.substr(0, path.size()-4);
180
181         if (!strncasecmp(niPath.c_str() + niPath.size() - 3, ".ni", 3))
182                 return niPath.substr(0, niPath.size()-3);
183
184         return niPath;
185 }
186
187 void assembliesInDirectory(const std::vector<std::string>& directories, std::string& tpaList)
188 {
189         std::map<std::string, std::string> assemblyList;
190         std::map<std::string, std::string> tmpList;
191
192         auto reader = [&assemblyList, &tmpList] (const std::string& path, const char* name) {
193                 if (isManagedAssembly(path) || isNativeImage(path)) {
194                         std::string dllName = stripNiDLL(name);
195                         std::pair<std::map<std::string, std::string>::iterator, bool> ret;
196                         ret = tmpList.insert(std::pair<std::string, std::string>(dllName, path));
197                         if (ret.second == false) {
198                                 if (isNativeImage(path))
199                                         tmpList[dllName] = path;
200                         }
201                 }
202         };
203
204         for (auto directory : directories) {
205                 scanFilesInDir(directory.c_str(), reader, 1);
206                 // merge scaned dll list to tpa list.
207                 // if the dll is already exist in the list, that is skipped.
208                 assemblyList.insert(tmpList.begin(), tmpList.end());
209         }
210
211         std::map<std::string, std::string>::iterator it;
212         for (it = assemblyList.begin(); it != assemblyList.end(); it++)
213                 tpaList += it->second + ':';
214
215         if (tpaList.back() == ':')
216                 tpaList.pop_back();
217 }
218
219 void scanFilesInDir(const std::string& directory, FileReader reader, unsigned int depth)
220 {
221         DIR *dir;
222         struct dirent* entry;
223         bool isDir;
224
225         if (strstr(directory.c_str(), TAC_SYMLINK_SUB_DIR) != NULL)
226                 return; // skip nitool --regen-all-app (--r2r)
227
228         dir = opendir(directory.c_str());
229
230         if (dir == nullptr)
231                 return;
232
233         std::vector<std::string> innerDirectories;
234
235         while ((entry = readdir(dir)) != nullptr) {
236                 isDir = false;
237                 std::string path = concatPath(directory, entry->d_name);
238                 switch (entry->d_type) {
239                         case DT_REG: break;
240                         case DT_DIR:
241                                 isDir = true;
242                                 break;
243                         case DT_LNK:
244                         case DT_UNKNOWN:
245                                 struct stat sb;
246                                 if (stat(path.c_str(), &sb) == -1)
247                                         continue;
248
249                                 if (S_ISREG(sb.st_mode) || S_ISDIR(sb.st_mode))
250                                         break;
251                         default:
252                                 continue;
253                 }
254                 if (!isDir)
255                         reader(path, entry->d_name);
256                 else if (depth > 1 && strcmp(entry->d_name, ".") && strcmp(entry->d_name, ".."))
257                         innerDirectories.push_back(path);
258         }
259
260         if (depth != 0)
261                 for (auto& d : innerDirectories)
262                         scanFilesInDir(d.c_str(), reader, depth - 1);
263
264         closedir(dir);
265 }
266
267 void updateAssemblyInfo(const std::string& getPath, const std::string& setPath)
268 {
269         char* label = NULL;
270
271         // change smack label
272         if (smack_getlabel(getPath.c_str(), &label, SMACK_LABEL_ACCESS) == 0) {
273                 if (smack_setlabel(setPath.c_str(), label, SMACK_LABEL_ACCESS) < 0) {
274                         fprintf(stderr, "Fail to set smack label\n");
275                 }
276                 free(label);
277         }
278
279         // change owner and groups for generated ni file.
280         struct stat info;
281         if (!stat(getPath.c_str(), &info)) {
282                 if (chown(setPath.c_str(), info.st_uid, info.st_gid) == -1)
283                         fprintf(stderr, "Failed to change owner and group name\n");
284         }
285 }
286
287 static bool setOwnership(const bf::path& path, uid_t uid, gid_t gid) {
288         int fd = open(path.c_str(), O_RDONLY);
289         if (fd < 0) {
290                 _ERR("Can't open directory: %s", path.c_str());
291                 return false;
292         }
293         int ret = fchown(fd, uid, gid);
294         close(fd);
295         if (ret != 0) {
296                 _ERR("Failed to change owner of: %s", path.c_str());
297                 return false;
298         }
299         return true;
300 }
301
302 static bool setDirPermissions(const bf::path& path, bf::perms permissions) {
303         bs::error_code error;
304         bf::permissions(path, permissions, error);
305         if (error) {
306                 _ERR("Failed to set permissions for directory: %s, %s", path.c_str(), error.message().c_str());
307                 return false;
308         }
309         return true;
310 }
311
312 static bool setDirOwnershipAndPermissions(const bf::path& path, bf::perms permissions, uid_t uid, gid_t gid) {
313         if (!setOwnership(path, uid, gid)) {
314                 _ERR("Failed to change owner: %s, (uid: %d, gid: %d)", path.c_str(), uid, gid);
315                 return false;
316         }
317         if (!setDirPermissions(path, permissions)) {
318                 _ERR("Failed to change permission: %s, (%d)", path.c_str(), permissions);
319                 return false;
320         }
321         return true;
322 }
323
324 static bool copyOwnershipAndPermissions(const bf::path& path, const bf::path& path2) {
325         if (!bf::exists(path)) {
326                 _ERR("Failed to copy ownership and permissions from %s to %s", path.c_str(), path2.c_str());
327                 return false;
328         }
329         bf::perms permissions = bf::status(path).permissions();
330         struct stat stats;
331         if (stat(path.c_str(), &stats) != 0) {
332                 return false;
333         }
334         if (!setDirOwnershipAndPermissions(path2, permissions, stats.st_uid, stats.st_gid)) {
335                 _ERR("Failed to copy ownership and permissions from %s to %s", path.c_str(), path2.c_str());
336                 return false;
337         }
338         return true;
339 }
340
341 bool createDir(const bf::path& path) {
342         if (bf::exists(path)) {
343                 return true;
344         }
345         bs::error_code error;
346         bf::create_directories(path, error);
347         if (error) {
348                 _ERR("Failed to create directory: %s", error.message().c_str());
349                 return false;
350         }
351         return true;
352 }
353
354 bool copyDir(const bf::path& path1, const bf::path& path2, FSFlag flags) {
355         try {
356                 // Check whether the function call is valid
357                 if (!bf::exists(path1) || !bf::is_directory(path1)) {
358                         _ERR("Source directory %s does not exist or is not a directory", path1.c_str());
359                         return false;
360                 }
361                 if (!bf::exists(path2)) {
362                         // Create the destination directory
363                         if (!createDir(path2)) {
364                                 _ERR("Unable to create destination directory %s", path2.c_str());
365                                 return false;
366                         }
367                         if (flags & FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS) {
368                                 copyOwnershipAndPermissions(path1, path2);
369                         }
370                 } else {
371                         if (!(flags & (FS_MERGE_SKIP | FS_MERGE_OVERWRITE))) {
372                                 _ERR("Destination directory %s already exists", path2.c_str());
373                                 return false;
374                         }
375                         if (flags & (FS_MERGE_OVERWRITE | FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS)) {
376                                 copyOwnershipAndPermissions(path1, path2);
377                         }
378                 }
379         } catch (const bf::filesystem_error& error) {
380                 _ERR("Failed to copy directory: %s", error.what());
381                 return false;
382         }
383
384         // Iterate through the source directory
385         for (bf::directory_iterator file(path1); file != bf::directory_iterator(); ++file) {
386                 try {
387                         bf::path current(file->path());
388                         bf::path target = path2 / current.filename();
389                         if (bf::is_symlink(symlink_status(current))) {
390                                 if ((flags & (FS_MERGE_SKIP | FS_MERGE_OVERWRITE)) && bf::exists(target)) {
391                                         continue;
392                                 }
393                                 bs::error_code error;
394                                 bf::copy_symlink(current, target, error);
395                                 if (error) {
396                                         _ERR("Failed to copy symlink: %s, %s", current.c_str(), error.message().c_str());
397                                         return false;
398                                 }
399                         } else if (bf::is_directory(current)) {
400                                 // Found directory: Recursion
401                                 if (!copyDir(current, target, flags)) {
402                                         return false;
403                                 }
404                         } else {
405                                 if ((flags & FS_MERGE_SKIP) && bf::exists(target)) {
406                                         continue;
407                                 }
408                                 bf::path destination = target;
409                                 if (flags & FS_COMMIT_COPY_FILE) {
410                                         destination = bf::unique_path(target.parent_path() / "%%%%-%%%%-%%%%-%%%%");
411                                 }
412                                 if (flags & FS_MERGE_OVERWRITE) {
413                                         bf::copy_file(current, destination, bf::copy_option::overwrite_if_exists);
414                                 } else {
415                                         bf::copy_file(current, destination);
416                                 }
417                                 if (flags & FS_PRESERVE_OWNERSHIP_AND_PERMISSIONS) {
418                                         copyOwnershipAndPermissions(current, destination);
419                                 }
420                                 if (flags & FS_COMMIT_COPY_FILE) {
421                                         if (flags & FS_MERGE_OVERWRITE) {
422                                                 bf::remove(target);
423                                         }
424                                         bf::rename(destination, target);
425                                 }
426                         }
427                 } catch (const bf::filesystem_error& error) {
428                         _ERR("Failed to copy directory: %s", error.what());
429                         return false;
430                 }
431         }
432         return true;
433 }
434
435 bool copyFile(const bf::path& path1, const bf::path& path2) {
436         bs::error_code error;
437         bf::copy_file(path1, path2, bf::copy_option::overwrite_if_exists, error);
438         if (error) {
439                 _ERR("copy file %s due to error [%s]", path1.c_str(), error.message().c_str());
440                 return false;
441         }
442         return true;
443 }
444
445 bool moveFile(const bf::path& path1, const bf::path& path2) {
446         if (bf::exists(path2)) {
447                 return false;
448         }
449         bs::error_code error;
450         bf::rename(path1, path2, error);
451         if (error) {
452                 _ERR("Cannot move file: %s. Will copy/remove... with error [%s]", path1.c_str(), error.message().c_str());
453                 bf::copy_file(path1, path2, bf::copy_option::overwrite_if_exists, error);
454                 if (error) {
455                         _ERR("Cannot copy file %s due to error [%s]", path1.c_str(), error.message().c_str());
456                         return false;
457                 }
458                 bf::remove_all(path1, error);
459                 if (error) {
460                         _ERR("Cannot remove old file when coping: %s with error [%s]", path1.c_str(), error.message().c_str());
461                         return false;
462                 }
463         }
464         return true;
465 }
466
467 bool removeFile(const bf::path& path) {
468         if (!bf::exists(path)) {
469                 return true;
470         }
471         bs::error_code error;
472         bf::remove(path, error);
473         if (error) {
474                 _ERR("Cannot remove: %s, %s", path.c_str(), error.message().c_str());
475                 return false;
476         }
477         return true;
478 }
479
480 bool removeAll(const bf::path& path) {
481         if (!exists(path)) {
482                 return true;
483         }
484         bs::error_code error;
485         bf::remove_all(path, error);
486         if (error) {
487                 _ERR("Cannot remove: %s, %s", path.c_str(), error.message().c_str());
488                 return false;
489         }
490         return true;
491 }