Merge "change log tag from ERR to INFO for C# log" into tizen
[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 <stdio.h>
18 #include <dirent.h>
19 #include <sys/stat.h>
20 #include <unistd.h>
21 #include <limits.h>
22 #include <strings.h>
23 #include <pthread.h>
24
25 #include <cstdlib>
26 #include <cstring>
27 #include <algorithm>
28 #include <unordered_map>
29 #include <vector>
30 #include <iterator>
31 #include <sstream>
32
33 #include "utils.h"
34 #include "log.h"
35
36 static pthread_t loggingThread;
37
38 bool iCompare(const std::string& a, const std::string& b)
39 {
40         return a.length() == b.length() &&
41                 std::equal(b.begin(), b.end(), a.begin(),
42                         [](unsigned char a, unsigned char b)
43                         { return std::tolower(a) == std::tolower(b); });
44 }
45
46 bool iCompare(const std::string& a, int aOffset, const std::string& b, int bOffset, int length)
47 {
48         return static_cast<int>(a.length()) - length >= aOffset &&
49                 static_cast<int>(b.length()) - length >= bOffset &&
50                 std::equal(b.begin() + bOffset, b.begin() + bOffset + length, a.begin() + aOffset,
51                         [](unsigned char a, unsigned char b)
52                         { return std::tolower(a) == std::tolower(b); });
53 }
54
55 bool isManagedAssembly(const std::string& fileName)
56 {
57         return iCompare(fileName, fileName.size()-4, ".dll", 0, 4) ||
58                 iCompare(fileName, fileName.size()-4, ".exe", 0, 4);
59 }
60
61 bool isNativeImage(const std::string& fileName)
62 {
63         return iCompare(fileName, fileName.size()-7, ".ni", 0, 3);
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 appendPath(std::string& path1, const std::string& path2)
92 {
93         if (path1.back() == PATH_SEPARATOR) {
94                 path1.append(path2);
95         } else {
96                 path1 += PATH_SEPARATOR;
97                 path1.append(path2);
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 std::string baseName(const std::string& path)
112 {
113         auto pos = path.find_last_of(PATH_SEPARATOR);
114         if (pos != std::string::npos)
115                 return path.substr(0, pos);
116         else
117                 return std::string(".");
118         return path;
119 }
120
121 bool endWithIgnoreCase(const std::string& str1, const std::string& str2, std::string& fileName)
122 {
123         std::string::size_type len1 = str1.length();
124         std::string::size_type len2 = str2.length();
125         if (len2 > len1)
126                 return false;
127
128         int i = 0;
129         bool result = std::all_of(str1.cend() - len2, str1.end(),
130                                 [&i, &str2] (char x) {
131                                         return std::tolower(x) == std::tolower(str2[i++]);
132                                 });
133         if (result)
134                 fileName = str1.substr(0, len1 - len2);
135
136         return result;
137 }
138
139 bool fileNotExist(const std::string& path)
140 {
141         struct stat sb;
142         return stat(path.c_str(), &sb) != 0;
143 }
144
145 #ifdef NOT_USE_FUNCTION
146 static bool extCheckAndGetFileNameIfExist(const std::string& dir, const std::string& ext, struct dirent* entry, std::string& fileName)
147 {
148         std::string fName(entry->d_name);
149         if (fName.length() < ext.length() ||
150                         fHame.compare(fName.length() - ext.length(), ext.length(), ext) != 0) {
151                 return false;
152         }
153
154         std::string fullName = concatPath(dir, entry->d_name);
155         switch (entry->d_type) {
156                 case DT_REG: break;
157                 case DT_LNK:
158                 case DT_UNKNOWN:
159                         if (fileNotExist(fullName))
160                                 return false;
161                 default:
162                         return false;
163         }
164
165         fileName = fullName;
166
167         return true;
168 }
169 #endif
170
171 std::string stripNiDLL(const std::string& path)
172 {
173         std::string niPath(path);
174         if (path.size() < 5) return niPath;
175         if (!strncasecmp(path.c_str() + path.size() - 4, ".dll", 4))
176                 niPath = path.substr(0, path.size()-4);
177         else if (!strncasecmp(path.c_str() + path.size() - 4, ".exe", 4))
178                 niPath = path.substr(0, path.size()-4);
179
180         if (!strncasecmp(niPath.c_str() + niPath.size() - 3, ".ni", 3))
181                 return niPath.substr(0, niPath.size()-3);
182
183         return niPath;
184 }
185
186 std::string joinStrings(const std::vector<std::string>& strings, const char* const delimeter)
187 {
188         switch (strings.size()) {
189                 case 0:
190                         return "";
191                 case 1:
192                         return strings[0];
193                 default:
194                         std::ostringstream os;
195                         std::copy(strings.begin(), strings.end()-1, std::ostream_iterator<std::string>(os, delimeter));
196                         os << *strings.rbegin();
197                         return os.str();
198         }
199 }
200
201 struct AssemblyFile {
202         std::string noExt;
203         std::string ext;
204 };
205
206 bool operator == (const AssemblyFile& lhs, const AssemblyFile& rhs)
207 {
208         return lhs.noExt == rhs.noExt && lhs.ext == rhs.ext;
209 }
210
211 namespace std {
212         template<>
213         struct hash<AssemblyFile> {
214                 std::size_t operator () (const AssemblyFile& f) const {
215                         const std::size_t h1 = std::hash<std::string>{}(f.noExt);
216                         const std::size_t h2 = std::hash<std::string>{}(f.ext);
217
218                         return h1 ^ (h2 << 1);
219                 }
220         };
221 }
222
223 void assembliesInDirectory(const std::vector<std::string>& directories, std::string& tpaList)
224 {
225         std::map<std::string, std::string> assemblyList;
226         std::map<std::string, std::string> tmpList;
227
228         auto reader = [&assemblyList, &tmpList] (const char* path, const char* name) {
229                 std::string pathStr(path);
230                 if (isManagedAssembly(pathStr)) {
231                         std::string dllName = stripNiDLL(name);
232                         std::pair<std::map<std::string, std::string>::iterator, bool> ret;
233                         ret = tmpList.insert(std::pair<std::string, std::string>(dllName, pathStr));
234                         if (ret.second == false) {
235                                 if (isNativeImage(pathStr))
236                                         tmpList[dllName] = pathStr;
237                         }
238                 }
239         };
240
241         for (auto directory : directories) {
242                 scanFilesInDir(directory.c_str(), reader, 1);
243                 // merge scaned dll list to tpa list.
244                 // if the dll is already exist in the list, that is skipped.
245                 assemblyList.insert(tmpList.begin(), tmpList.end());
246         }
247
248         std::map<std::string, std::string>::iterator it;
249         for (it = assemblyList.begin(); it != assemblyList.end(); it++)
250                 tpaList += it->second + ':';
251
252         if (tpaList.back() == ':')
253                 tpaList.pop_back();
254 }
255
256 void scanFilesInDir(const char* directory, FileReader reader, unsigned int depth)
257 {
258         DIR *dir;
259         struct dirent* entry;
260         bool isDir;
261
262         dir = opendir(directory);
263
264         if (dir == nullptr)
265                 return;
266
267         std::vector<std::string> innerDirectories;
268
269         while ((entry = readdir(dir)) != nullptr) {
270                 isDir = false;
271                 std::string path = concatPath(directory, entry->d_name);
272                 switch (entry->d_type) {
273                         case DT_REG: break;
274                         case DT_DIR:
275                                 isDir = true;
276                                 break;
277                         case DT_LNK:
278                         case DT_UNKNOWN:
279                                 struct stat sb;
280                                 if (stat(path.c_str(), &sb) == -1)
281                                         continue;
282
283                                 if (S_ISREG(sb.st_mode) || S_ISDIR(sb.st_mode))
284                                         break;
285                         default:
286                                 continue;
287                 }
288                 if (!isDir)
289                         reader(path.c_str(), entry->d_name);
290                 else if (depth > 1 && strcmp(entry->d_name, ".") && strcmp(entry->d_name, ".."))
291                         innerDirectories.push_back(path);
292         }
293
294         if (depth != 0)
295                 for (auto& d : innerDirectories)
296                         scanFilesInDir(d.c_str(), reader, depth-1);
297
298         closedir(dir);
299 }
300
301 static void *stdlog(void*)
302 {
303         int pfd[2];
304     ssize_t readSize;
305     char buf[1024];
306
307     if (setvbuf(stdout, NULL, _IOLBF, 0) < 0) {
308                 _DBG("fail to make stdout line-buffered");
309                 return 0;
310     }
311
312     if (setvbuf(stderr, NULL, _IONBF, 0) < 0) {
313                 _DBG("make stderr unbuffered");
314                 return 0;
315         }
316
317     /* create the pipe and redirect stdout and stderr */
318     if (pipe(pfd) < 0) {
319                 _DBG("fail to create pipe for logging");
320                 return 0;
321     }
322
323     if (dup2(pfd[1], fileno(stdout)) == -1) {
324                 _DBG("fail to duplicate fd to stdout");
325                 return 0;
326     }
327
328     if (dup2(pfd[1], fileno(stderr)) == -1) {
329                 _DBG("fail to duplicate fd to stderr");
330                 return 0;
331         }
332
333         close(pfd[1]);
334
335     while ((readSize = read(pfd[0], buf, sizeof buf - 1)) > 0) {
336         if (buf[readSize - 1] == '\n') {
337             --readSize;
338         }
339
340         buf[readSize] = 0;
341
342         _LOGX("%s", buf);
343     }
344
345         close(pfd[0]);
346
347     return 0;
348 }
349
350 int runLoggingThread() {
351     /* spawn the logging thread */
352     if (pthread_create(&loggingThread, 0, stdlog, 0) != 0) {
353                 _DBG("fail to create pthread");
354         return -1;
355     }
356
357     if (pthread_detach(loggingThread) != 0) {
358                 _DBG("fail to detach pthread");
359                 return -1;
360         }
361
362     return 0;
363 }
364