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