Merge pull request #67 from g-balykov/add-setenvvariable-wrapper
[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
21 #include "log.h"
22 #include "utils.h"
23 #include "pkgmgr_parser_plugin_interface.h"
24
25 #include <wait.h>
26 #include <dirent.h>
27 #include <sys/stat.h>
28
29 #include <algorithm>
30 #include <string>
31
32 #include <pwd.h>
33 #include <grp.h>
34 #include <sys/stat.h>
35 #include <unistd.h>
36 #include <string.h>
37
38 #include <fstream>
39 #include <sys/smack.h>
40
41 #include "ni_common.h"
42 #include "path_manager.h"
43 #include "plugin_manager.h"
44
45 #ifdef  LOG_TAG
46 #undef  LOG_TAG
47 #endif
48 #define LOG_TAG "NETCORE_INSTALLER_PLUGIN"
49
50 #ifndef CROSSGEN_PATH
51 #error "CROSSGEN_PATH is missed"
52 #endif
53
54 #define __XSTR(x) #x
55 #define __STR(x) __XSTR(x)
56 static const char* __CROSSGEN_PATH = __STR(CROSSGEN_PATH);
57 #undef __STR
58 #undef __XSTR
59
60 static int __interval = 0;
61 static std::string __tpa;
62
63 static void waitInterval()
64 {
65         // by the recommand, ignore small value for performance.
66         if (__interval > 10000) {
67                 fprintf(stderr, "sleep %d usec\n", __interval);
68                 usleep(__interval);
69         }
70 }
71
72 static void updateNiFileInfo(const std::string& dllPath, const std::string& niPath)
73 {
74         char* label = NULL;
75
76         // change smack label
77         if (smack_getlabel(dllPath.c_str(), &label, SMACK_LABEL_ACCESS) == 0) {
78                 if (smack_setlabel(niPath.c_str(), label, SMACK_LABEL_ACCESS) < 0) {
79                         fprintf(stderr, "Fail to set smack label\n");
80                 }
81                 free(label);
82         }
83
84         // change owner and groups for generated ni file.
85         struct stat info;
86         if (!stat(dllPath.c_str(), &info)) {
87                 if (chown(niPath.c_str(), info.st_uid, info.st_gid) == -1)
88                         fprintf(stderr, "Failed to change owner and group name\n");
89         }
90 }
91
92 static std::string getNiFilePath(const std::string& dllPath)
93 {
94         size_t index = dllPath.find_last_of(".");
95         if (index == std::string::npos) {
96                 fprintf(stderr, "File doesnot contain extension. fail to get NI file name\n");
97                 return "";
98         }
99         std::string fName = dllPath.substr(0, index);
100         std::string fExt = dllPath.substr(index, dllPath.length());
101
102         // crossgen generate file with lower case extension only
103         std::transform(fExt.begin(), fExt.end(), fExt.begin(), ::tolower);
104         std::string niPath = fName + ".ni" + fExt;
105
106         return niPath;
107 }
108
109 static std::string getAppNIPath(const std::string& niPath)
110 {
111         std::string fileName;
112         std::string niDirPath;
113         std::string prevPath;
114
115         size_t index = niPath.find_last_of("/");
116         if (index != std::string::npos) {
117                 prevPath = niPath.substr(0, index);
118                 fileName = niPath.substr(index + 1, niPath.length());
119         } else {
120                 prevPath = ".";
121                 fileName = niPath;
122         }
123
124         niDirPath = concatPath(prevPath, APP_NI_SUB_DIR);
125
126         if (!isFileExist(niDirPath)) {
127                 if (mkdir(niDirPath.c_str(), 0755) == 0) {
128                         updateNiFileInfo(prevPath, niDirPath);
129                 } else {
130                         fprintf(stderr, "Fail to create app ni directory (%s)\n", niDirPath.c_str());
131                 }
132         }
133
134         return concatPath(niDirPath, fileName);
135 }
136
137 static bool niExist(const std::string& path)
138 {
139         std::string f = getNiFilePath(path);
140         if (f.empty()) {
141                 return false;
142         }
143
144         if (isFileExist(f)) {
145                 return true;
146         }
147
148         // native image of System.Private.CoreLib.dll should have to overwrite
149         // original file to support new coreclr
150         if (path.find("System.Private.CoreLib.dll") != std::string::npos) {
151                 std::string coreLibBackup = path + ".Backup";
152                 if (isFileExist(coreLibBackup)) {
153                         return true;
154                 }
155         }
156
157         return false;
158 }
159
160 static ni_error_e crossgen(const std::string& dllPath, const std::string& appPath, bool enableR2R, bool isAppNI = false)
161 {
162         if (!isFileExist(dllPath)) {
163                 fprintf(stderr, "dll file is not exist : %s\n", dllPath.c_str());
164                 return NI_ERROR_NO_SUCH_FILE;
165         }
166
167         if (!isManagedAssembly(dllPath)) {
168                 fprintf(stderr, "Input file is not a dll file : %s\n", dllPath.c_str());
169                 return NI_ERROR_INVALID_PARAMETER;
170         }
171
172         if (niExist(dllPath)) {
173                 fprintf(stderr, "Already ni file is exist for %s\n", dllPath.c_str());
174                 return NI_ERROR_ALREADY_EXIST;
175         }
176
177         std::string absDllPath = absolutePath(dllPath);
178         std::string absNiPath = getNiFilePath(dllPath);
179         if (absNiPath.empty()) {
180                 fprintf(stderr, "Fail to get ni file name\n");
181                 return NI_ERROR_UNKNOWN;
182         }
183
184         if (isAppNI) {
185                 absNiPath = getAppNIPath(absNiPath);
186         }
187
188         pid_t pid = fork();
189         if (pid == -1)
190                 return NI_ERROR_UNKNOWN;
191
192         if (pid > 0) {
193                 int status;
194                 waitpid(pid, &status, 0);
195                 if (WIFEXITED(status)) {
196                         // Do not use niExist() function to check whether ni file created or not.
197                         // niEixst() return false for System.Private.Corelib.dll
198                         if (isFileExist(absNiPath)) {
199                                 updateNiFileInfo(absDllPath, absNiPath);
200                                 return NI_ERROR_NONE;
201                         } else {
202                                 fprintf(stderr, "Fail to create native image for %s\n", dllPath.c_str());
203                                 return NI_ERROR_NO_SUCH_FILE;
204                         }
205                 }
206         } else {
207                 std::string jitPath = getRuntimeDir() + "/libclrjit.so";
208                 std::vector<const char*> argv = {
209                         __CROSSGEN_PATH,
210                         "/nologo",
211                         "/Trusted_Platform_Assemblies", __tpa.c_str(),
212                         "/JITPath", jitPath.c_str()
213                 };
214
215                 if (!enableR2R) {
216                         argv.push_back("/FragileNonVersionable");
217                 }
218
219                 argv.push_back("/App_Paths");
220                 std::string absAppPath;
221                 if (!appPath.empty()) {
222                         absAppPath = appPath;
223                 } else {
224                         absAppPath = baseName(absDllPath);
225                 }
226                 argv.push_back(absAppPath.c_str());
227
228                 argv.push_back("/out");
229                 argv.push_back(absNiPath.c_str());
230
231                 argv.push_back(absDllPath.c_str());
232                 argv.push_back(nullptr);
233
234                 fprintf(stderr, "+ %s (%s)\n", absDllPath.c_str(), enableR2R ? "R2R" : "FNV");
235
236                 execv(__CROSSGEN_PATH, const_cast<char* const*>(argv.data()));
237                 exit(0);
238         }
239
240         return NI_ERROR_NONE;
241 }
242
243 // callback function of "pkgmgrinfo_appinfo_metadata_filter_foreach"
244 static int appAotCb(pkgmgrinfo_appinfo_h handle, void *userData)
245 {
246         char *pkgId = NULL;
247         int ret = 0;
248         bool* enableR2R = (bool*)userData;
249
250         ret = pkgmgrinfo_appinfo_get_pkgid(handle, &pkgId);
251         if (ret != PMINFO_R_OK) {
252                 fprintf(stderr, "Failed to get pkgid\n");
253                 return -1;
254         }
255
256         if (removeNiUnderPkgRoot(pkgId) != 0) {
257                 fprintf(stderr, "Failed to remove previous dlls from [%s]\n", pkgId);
258                 return -1;
259         }
260
261         // Regenerate ni files with R2R mode forcibiliy. (there is no way to now which option is used)
262         if (createNiUnderPkgRoot(pkgId, *enableR2R) != 0) {
263                 fprintf(stderr, "Failed to get root path from [%s]\n", pkgId);
264                 return -1;
265         } else {
266                 fprintf(stderr, "Complete make application to native image\n");
267         }
268
269         return 0;
270 }
271
272 static void createCoreLibNI(bool enableR2R)
273 {
274         std::string coreLib = concatPath(getRuntimeDir(), "System.Private.CoreLib.dll");
275         std::string niCoreLib = concatPath(getRuntimeDir(), "System.Private.CoreLib.ni.dll");
276         std::string coreLibBackup = concatPath(getRuntimeDir(), "System.Private.CoreLib.dll.Backup");
277
278         if (!isFileExist(coreLibBackup)) {
279                 if (!crossgen(coreLib, std::string(), enableR2R)) {
280                         if (rename(coreLib.c_str(), coreLibBackup.c_str())) {
281                                 fprintf(stderr, "Failed to rename System.Private.CoreLib.dll\n");
282                         }
283                         if (rename(niCoreLib.c_str(), coreLib.c_str())) {
284                                 fprintf(stderr, "Failed to rename System.Private.CoreLib.ni.dll\n");
285                         }
286                 } else {
287                         fprintf(stderr, "Failed to create native image for %s\n", coreLib.c_str());
288                 }
289         }
290 }
291
292 ni_error_e initNICommon(NiCommonOption* option)
293 {
294 #if defined(__arm__)
295         // get interval value
296         const char* intervalFile = "/usr/share/dotnet.tizen/lib/crossgen_interval.txt";
297         std::ifstream inFile(intervalFile);
298         if (inFile) {
299                 fprintf(stderr, "crossgen_interval.txt is found\n");
300                 inFile >> __interval;
301         }
302
303         if (initializePluginManager("normal")) {
304                 fprintf(stderr, "Fail to initialize plugin manager\n");
305                 return NI_ERROR_UNKNOWN;
306         }
307         if (initializePathManager(option->runtimeDir, option->tizenFXDir, option->extraDirs)) {
308                 fprintf(stderr, "Fail to initialize path manager\n");
309                 return NI_ERROR_UNKNOWN;
310         }
311
312         __tpa = getTPA();
313
314         return NI_ERROR_NONE;
315 #else
316         fprintf(stderr, "crossgen supports arm architecture only. skip ni file generation\n");
317         return NI_ERROR_NOT_SUPPORTED;
318 #endif
319 }
320
321 void finalizeNICommon()
322 {
323         __interval = 0;
324
325         finalizePluginManager();
326         finalizePathManager();
327
328         __tpa.clear();
329 }
330
331
332 void createNiPlatform(bool enableR2R)
333 {
334         const std::string platformDirs[] = {getRuntimeDir(), getTizenFXDir()};
335         createNiUnderDirs(platformDirs, 2, enableR2R);
336 }
337
338 ni_error_e createNiDll(const std::string& dllPath, bool enableR2R)
339 {
340         createCoreLibNI(enableR2R);
341         // System.Private.CoreLib.dll is generated in the createCoreLibNI function.
342         // Skip if input dll is System.Private.CoreLib.dll
343         if (dllPath.find("System.Private.CoreLib.dll") != std::string::npos) {
344                 return NI_ERROR_NONE;
345         }
346
347         return crossgen(dllPath, std::string(), enableR2R);
348 }
349
350 void createNiUnderDirs(const std::string rootPaths[], int count, bool enableR2R, bool isAppNI)
351 {
352         createCoreLibNI(enableR2R);
353
354         std::string appPaths;
355         for (int i = 0; i < count; i++) {
356                 appPaths += rootPaths[i];
357                 appPaths += ':';
358         }
359
360         if (appPaths.back() == ':')
361                 appPaths.pop_back();
362
363         auto convert = [&appPaths, enableR2R, isAppNI](const std::string& path, const char* name) {
364                 if (!crossgen(path, appPaths.c_str(), enableR2R, isAppNI)) {
365                         waitInterval();
366                 }
367         };
368
369         for (int i = 0; i < count; i++) {
370                 scanFilesInDir(rootPaths[i], convert, 1);
371         }
372 }
373
374 ni_error_e createNiUnderPkgRoot(const std::string& pkgId, bool enableR2R)
375 {
376         std::string pkgRoot;
377         if (getRootPath(pkgId, pkgRoot) != NI_ERROR_NONE) {
378                 fprintf(stderr, "Failed to get root path from [%s]\n", pkgId.c_str());
379                 return NI_ERROR_INVALID_PACKAGE;
380         }
381
382         std::string binDir = concatPath(pkgRoot, "bin");
383         std::string libDir = concatPath(pkgRoot, "lib");
384         std::string appTAC = concatPath(binDir, ".TAC.Release");
385         std::string paths[] = {binDir, libDir, appTAC};
386
387         createNiUnderDirs(paths, 3, enableR2R, true);
388
389         return NI_ERROR_NONE;
390 }
391
392 ni_error_e createNiDllUnderPkgRoot(const std::string& pkgId, const std::string& dllPath, bool enableR2R)
393 {
394         std::string pkgRoot;
395         if (getRootPath(pkgId, pkgRoot) < 0) {
396                 fprintf(stderr, "Failed to get root path from [%s]\n", pkgId.c_str());
397                 return NI_ERROR_INVALID_PACKAGE;
398         }
399
400         std::string binDir = concatPath(pkgRoot, "bin");
401         std::string libDir = concatPath(pkgRoot, "lib");
402         std::string appTAC = concatPath(binDir, ".TAC.Release");
403         std::string paths = binDir + ":" + libDir + ":" + appTAC;
404
405         return crossgen(dllPath, paths, enableR2R, true);
406 }
407
408 void removeNiPlatform()
409 {
410         std::string coreLib = concatPath(getRuntimeDir(), "System.Private.CoreLib.dll");
411         std::string coreLibBackup = concatPath(getRuntimeDir(), "System.Private.CoreLib.dll.Backup");
412
413         if (!isFileExist(coreLibBackup)) {
414                 return;
415         }
416
417         if (remove(coreLib.c_str())) {
418                 fprintf(stderr, "Failed to remove System.Private.CoreLib native image file\n");
419         }
420
421         if (rename(coreLibBackup.c_str(), coreLib.c_str())) {
422                 fprintf(stderr, "Failed to rename System.Private.CoreLib.Backup to origin\n");
423         }
424
425         const std::string platformDirs[] = {getRuntimeDir(), getTizenFXDir()};
426
427         removeNiUnderDirs(platformDirs, 2);
428 }
429
430 void removeNiUnderDirs(const std::string rootPaths[], int count)
431 {
432         auto convert = [](const std::string& path, std::string name) {
433                 if (isNativeImage(path)) {
434                         if (remove(path.c_str())) {
435                                 fprintf(stderr, "Failed to remove %s\n", path.c_str());
436                         }
437                 }
438         };
439
440         for (int i = 0; i < count; i++)
441                 scanFilesInDir(rootPaths[i], convert, -1);
442 }
443
444 ni_error_e removeNiUnderPkgRoot(const std::string& pkgId)
445 {
446         std::string pkgRoot;
447         if (getRootPath(pkgId, pkgRoot) < 0) {
448                 fprintf(stderr, "Failed to get root path from [%s]\n", pkgId.c_str());
449                 return NI_ERROR_INVALID_PACKAGE;
450         }
451
452         std::string binDir = concatPath(pkgRoot, "bin");
453         std::string libDir = concatPath(pkgRoot, "lib");
454         std::string paths[] = {binDir, libDir};
455
456         removeNiUnderDirs(paths, 2);
457
458         std::string binNIDir = concatPath(binDir, APP_NI_SUB_DIR);
459         if (isFileExist(binNIDir)) {
460                 if (rmdir(binNIDir.c_str()) != 0) {
461                         fprintf(stderr, "Failed to remove app ni dir [%s]\n", binNIDir.c_str());
462                 }
463         }
464
465         std::string libNIDir = concatPath(libDir, APP_NI_SUB_DIR);
466         if (isFileExist(libNIDir)) {
467                 if (rmdir(libNIDir.c_str()) != 0) {
468                         fprintf(stderr, "Failed to remove app ni dir [%s]\n", libNIDir.c_str());
469                 }
470         }
471
472         return NI_ERROR_NONE;
473 }
474
475 ni_error_e regenerateAppNI(bool enableR2R)
476 {
477         int ret = 0;
478         pkgmgrinfo_appinfo_metadata_filter_h handle;
479
480         ret = pkgmgrinfo_appinfo_metadata_filter_create(&handle);
481         if (ret != PMINFO_R_OK)
482                 return NI_ERROR_UNKNOWN;
483
484         ret = pkgmgrinfo_appinfo_metadata_filter_add(handle, AOT_METADATA_KEY, AOT_METADATA_VALUE);
485         if (ret != PMINFO_R_OK) {
486                 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
487                 return NI_ERROR_UNKNOWN;
488         }
489
490         ret = pkgmgrinfo_appinfo_metadata_filter_foreach(handle, appAotCb, &enableR2R);
491         if (ret != PMINFO_R_OK) {
492                 fprintf(stderr, "Failed pkgmgrinfo_appinfo_metadata_filter_foreach\n");
493                 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
494                 return NI_ERROR_UNKNOWN;
495         }
496
497         fprintf(stderr, "Success pkgmgrinfo_appinfo_metadata_filter_foreach\n");
498
499         pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
500         return NI_ERROR_NONE;
501 }