Merge "Remove unnecessary executable flag" 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
18 #include <dirent.h>
19 #include <sys/stat.h>
20 #include <unistd.h>
21 #include <limits.h>
22 #include <strings.h>
23
24 #include <cstdlib>
25 #include <cstring>
26 #include <algorithm>
27 #include <unordered_map>
28 #include <vector>
29 #include <iterator>
30 #include <sstream>
31
32 #include "utils.h"
33
34 bool ICompare(const std::string& a, const std::string& b)
35 {
36   return a.length() == b.length() &&
37     std::equal(b.begin(), b.end(), a.begin(),
38         [](unsigned char a, unsigned char b)
39         { return std::tolower(a) == std::tolower(b); });
40 }
41
42 bool ICompare(const std::string& a, int a_offset, const std::string& b, int b_offset, int length)
43 {
44   return static_cast<int>(a.length()) - length >= a_offset &&
45     static_cast<int>(b.length()) - length >= b_offset &&
46     std::equal(b.begin() + b_offset, b.begin() + b_offset + length, a.begin() + a_offset,
47         [](unsigned char a, unsigned char b)
48         { return std::tolower(a) == std::tolower(b); });
49 }
50
51 bool IsManagedAssembly(const std::string& filename)
52 {
53   return ICompare(filename, filename.size()-4, ".dll", 0, 4) ||
54     ICompare(filename, filename.size()-4, ".exe", 0, 4);
55 }
56
57 bool IsNativeImage(const std::string& filename)
58 {
59   return ICompare(filename, filename.size()-7, ".ni", 0, 3);
60 }
61
62 std::string ReadSelfPath()
63 {
64   char buff[PATH_MAX];
65   ssize_t len = ::readlink("/proc/self/exe", buff, sizeof(buff)-1);
66   if (len != -1) {
67     buff[len] = '\0';
68     return std::string(buff);
69   }
70
71   return "";
72 }
73
74 std::string ConcatPath(const std::string& path1, const std::string& path2)
75 {
76   std::string path(path1);
77   if (path.back() == PATH_SEPARATOR)
78   {
79     path.append(path2);
80   }
81   else
82   {
83     path += PATH_SEPARATOR;
84     path.append(path2);
85   }
86
87   return path;
88 }
89
90 void AppendPath(std::string& path1, const std::string& path2)
91 {
92   if (path1.back() == PATH_SEPARATOR)
93   {
94     path1.append(path2);
95   }
96   else
97   {
98     path1 += PATH_SEPARATOR;
99     path1.append(path2);
100   }
101 }
102
103 std::string AbsolutePath(const std::string& path)
104 {
105   std::string absPath;
106
107   char realPath[PATH_MAX];
108   if (realpath(path.c_str(), realPath) != nullptr && realPath[0] != '\0')
109   {
110     absPath.assign(realPath);
111   }
112
113   return absPath;
114 }
115
116 std::string Basename(const std::string& path)
117 {
118   auto pos = path.find_last_of(PATH_SEPARATOR);
119   if (pos != std::string::npos)
120   {
121     return path.substr(0, pos);
122   }
123   else
124   {
125     return std::string(".");
126   }
127   return path;
128 }
129
130 bool EndWithIgnoreCase(const std::string& str1, const std::string& str2, std::string& filename)
131 {
132   std::string::size_type len1 = str1.length();
133   std::string::size_type len2 = str2.length();
134   if (len2 > len1) return false;
135
136   int i = 0;
137   bool result = std::all_of(str1.cend() - len2, str1.end(),
138         [&i, &str2] (char x) {
139           return std::tolower(x) == std::tolower(str2[i++]);
140         });
141   if (result)
142   {
143     filename = str1.substr(0, len1 - len2);
144   }
145   return result;
146 }
147
148 bool FileNotExist(const std::string& path)
149 {
150   struct stat sb;
151   return stat(path.c_str(), &sb) != 0;
152 }
153
154 #ifdef NOT_USE_FUNCTION
155 static bool ExtCheckAndGetFileNameIfExist(const std::string&  dir, const std::string& ext, struct dirent* entry, std::string& filename)
156 {
157   std::string fname(entry->d_name);
158   if (fname.length() < ext.length() ||
159       fname.compare(fname.length() - ext.length(), ext.length(), ext) != 0)
160   {
161     return false;
162   }
163   std::string fullname = ConcatPath(dir, entry->d_name);
164   switch (entry->d_type)
165   {
166     case DT_REG: break;
167     case DT_LNK:
168     case DT_UNKNOWN:
169       if (FileNotExist(fullname))
170       {
171         return false;
172       }
173     default:
174       return false;
175   }
176
177   filename = fullname;
178
179   return true;
180 }
181 #endif
182
183 std::string StripNIDLL(const std::string& path)
184 {
185   std::string npath(path);
186   if (path.size() < 5) return npath;
187   if (!strncasecmp(path.c_str() + path.size() - 4, ".dll", 4))
188   {
189     npath = path.substr(0, path.size()-4);
190   }else if (!strncasecmp(path.c_str() + path.size() - 4, ".exe", 4))
191   {
192     npath = path.substr(0, path.size()-4);
193   }
194   if (!strncasecmp(npath.c_str() + npath.size() - 3, ".ni", 3))
195   {
196     return npath.substr(0, npath.size()-3);
197   }
198   return npath;
199 }
200
201 std::string JoinStrings(const std::vector<std::string>& strings, const char* const delimeter)
202 {
203   switch (strings.size())
204   {
205     case 0:
206       return "";
207     case 1:
208       return strings[0];
209     default:
210       std::ostringstream os; 
211       std::copy(strings.begin(), strings.end()-1, std::ostream_iterator<std::string>(os, delimeter));
212       os << *strings.rbegin();
213       return os.str();
214   }
215 }
216
217 struct AssemblyFile
218 {
219   std::string noext;
220   std::string ext;
221 };
222
223 bool operator == (const AssemblyFile& lhs, const AssemblyFile& rhs)
224 {
225   return lhs.noext == rhs.noext && lhs.ext == rhs.ext;
226 }
227
228 namespace std
229 {
230   template<>
231   struct hash<AssemblyFile>
232   {
233     std::size_t operator () (const AssemblyFile& f) const
234     {
235       const std::size_t h1 = std::hash<std::string>{}(f.noext);
236       const std::size_t h2 = std::hash<std::string>{}(f.ext);
237
238       return h1 ^ (h2 << 1);
239     }
240   };
241 }
242
243 void AssembliesInDirectory(const std::vector<std::string>& directories, std::string& tpaList)
244 {
245   std::map<std::string, std::string> assemblyList;
246   std::map<std::string, std::string> tmpList;
247
248   auto reader = [&assemblyList, &tmpList] (const char* path, const char* name)
249   {
250     std::string _path(path);
251     if (IsManagedAssembly(_path))
252     {
253       std::string dll_name = StripNIDLL(name);
254       std::pair<std::map<std::string, std::string>::iterator, bool> ret;
255       ret = tmpList.insert(std::pair<std::string, std::string>(dll_name, _path));
256       if (ret.second == false)
257       {
258         if (IsNativeImage(_path))
259         {
260           tmpList[dll_name] = _path;
261         }
262       }
263     }
264   };
265
266   for (auto directory : directories)
267   {
268     ScanFilesInDir(directory.c_str(), reader, 1);
269     // merge scaned dll list to tpa list.
270     // if the dll is already exist in the list, that is skipped.
271     assemblyList.insert(tmpList.begin(), tmpList.end());
272   }
273
274   std::map<std::string, std::string>::iterator it;
275   for (it = assemblyList.begin(); it != assemblyList.end(); it++)
276   {
277     tpaList += it->second + ':';
278   }
279   if (tpaList.back() == ':')
280   {
281     tpaList.pop_back();
282   }
283 }
284
285 void ScanFilesInDir(const char* directory, FileReader reader, unsigned int depth)
286 {
287   DIR *dir;
288   struct dirent* entry;
289   bool isDir;
290
291   dir = opendir(directory);
292
293   if (dir == nullptr)
294   {
295     //_ERR("Can not open directory : %s", directory);
296     return;
297   }
298
299   std::vector<std::string> innerDirectories;
300
301   while ((entry = readdir(dir)) != nullptr)
302   {
303     isDir = false;
304     std::string path = ConcatPath(directory, entry->d_name);
305     switch (entry->d_type)
306     {
307       case DT_REG: break;
308       case DT_DIR:
309         isDir = true;
310         break;
311       case DT_LNK:
312       case DT_UNKNOWN:
313         struct stat sb;
314         if (stat(path.c_str(), &sb) == -1)
315         {
316           continue;
317         }
318
319         if (S_ISREG(sb.st_mode) || S_ISDIR(sb.st_mode))
320         {
321           break;
322         }
323       default:
324         continue;
325     }
326     if (!isDir)
327     {
328       reader(path.c_str(), entry->d_name);
329     }
330     else if (depth > 1 && strcmp(entry->d_name, ".") && strcmp(entry->d_name, ".."))
331     {
332       innerDirectories.push_back(path);
333     }
334   }
335
336   if (depth != 0)
337   {
338     for (auto& d : innerDirectories)
339     {
340       ScanFilesInDir(d.c_str(), reader, depth-1);
341     }
342   }
343
344   closedir(dir);
345 }