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