Move defines to spec and set smack label on file with default base addresses
[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
55 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
56 static const char* __SYSTEM_BASE_FILE = __STR(SYSTEM_BASE_FILE);
57 #endif
58
59 #undef __STR
60 #undef __XSTR
61
62 static int __interval = 0;
63 static std::string __tpa;
64
65 static void waitInterval()
66 {
67         // by the recommand, ignore small value for performance.
68         if (__interval > 10000) {
69                 fprintf(stderr, "sleep %d usec\n", __interval);
70                 usleep(__interval);
71         }
72 }
73
74 static std::string getNiFilePath(const std::string& dllPath)
75 {
76         size_t index = dllPath.find_last_of(".");
77         if (index == std::string::npos) {
78                 fprintf(stderr, "File doesnot contain extension. fail to get NI file name\n");
79                 return "";
80         }
81         std::string fName = dllPath.substr(0, index);
82         std::string fExt = dllPath.substr(index, dllPath.length());
83
84         // crossgen generate file with lower case extension only
85         std::transform(fExt.begin(), fExt.end(), fExt.begin(), ::tolower);
86         std::string niPath = fName + ".ni" + fExt;
87
88         return niPath;
89 }
90
91 static std::string getAppNIPath(const std::string& niPath)
92 {
93         std::string fileName;
94         std::string niDirPath;
95         std::string prevPath;
96
97         size_t index = niPath.find_last_of("/");
98         if (index != std::string::npos) {
99                 prevPath = niPath.substr(0, index);
100                 fileName = niPath.substr(index + 1, niPath.length());
101         } else {
102                 prevPath = ".";
103                 fileName = niPath;
104         }
105
106         niDirPath = concatPath(prevPath, APP_NI_SUB_DIR);
107
108         if (!isFileExist(niDirPath)) {
109                 if (mkdir(niDirPath.c_str(), 0755) == 0) {
110                         updateAssemblyInfo(prevPath, niDirPath);
111                 } else {
112                         fprintf(stderr, "Fail to create app ni directory (%s)\n", niDirPath.c_str());
113                 }
114         }
115
116         return concatPath(niDirPath, fileName);
117 }
118
119 static bool niExist(const std::string& path)
120 {
121         std::string f = getNiFilePath(path);
122         if (f.empty()) {
123                 return false;
124         }
125
126         if (isFileExist(f)) {
127                 return true;
128         }
129
130         // native image of System.Private.CoreLib.dll should have to overwrite
131         // original file to support new coreclr
132         if (path.find("System.Private.CoreLib.dll") != std::string::npos) {
133                 std::string coreLibBackup = path + ".Backup";
134                 if (isFileExist(coreLibBackup)) {
135                         return true;
136                 }
137         }
138
139         return false;
140 }
141
142 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
143 // Get next base address to be used for system ni image from file
144 // __SYSTEM_BASE_FILE should be checked for existance before calling this function
145 static uintptr_t getNextBaseAddrFromFile()
146 {
147         FILE *pFile = fopen(__SYSTEM_BASE_FILE, "r");
148         if (pFile == NULL) {
149                 fprintf(stderr, "Failed to open %s\n", __SYSTEM_BASE_FILE);
150                 return 0;
151         }
152
153         uintptr_t addr = 0;
154         uintptr_t size = 0;
155
156         while (fscanf(pFile, "%u %u", &addr, &size) != EOF) {
157         }
158
159         fclose(pFile);
160
161         return addr + size;
162 }
163
164 // Get next base address to be used for system ni image
165 static uintptr_t getNextBaseAddr()
166 {
167         uintptr_t baseAddr = 0;
168
169         if (!isFileExist(__SYSTEM_BASE_FILE)) {
170                 // This is the starting address for all default base addresses
171                 baseAddr = DEFAULT_BASE_ADDR_START;
172         } else {
173                 baseAddr = getNextBaseAddrFromFile();
174
175                 // Round to a multple of 64K (see ZapImage::CalculateZapBaseAddress in CoreCLR)
176                 uintptr_t BASE_ADDRESS_ALIGNMENT = 0xffff;
177                 baseAddr = (baseAddr + BASE_ADDRESS_ALIGNMENT) & ~BASE_ADDRESS_ALIGNMENT;
178         }
179
180         return baseAddr;
181 }
182
183 // Save base address of system ni image to file
184 static void updateBaseAddrFile(const std::string &dllPath, uintptr_t baseAddr)
185 {
186         std::string absNiPath = getNiFilePath(dllPath);
187         if (absNiPath.empty()) {
188                 fprintf(stderr, "Failed to get ni file path for %s\n", dllPath.c_str());
189                 return;
190         }
191
192         uintptr_t niSize = getFileSize(absNiPath);
193         if (niSize == 0) {
194                 fprintf(stderr, "File %s doesn't exist\n", absNiPath.c_str());
195                 return;
196         }
197
198         // Write new entry to the file
199         FILE *pFile = fopen(__SYSTEM_BASE_FILE, "a");
200         if (pFile == NULL) {
201                 fprintf(stderr, "Failed to open %s\n", __SYSTEM_BASE_FILE);
202                 return;
203         }
204
205         fprintf(pFile, "%u %u\n", baseAddr, niSize);
206         fclose(pFile);
207 }
208
209 // check if dll is listed in TPA
210 static bool isTPADll(const std::string &dllPath)
211 {
212         std::string absDllPath = absolutePath(dllPath);
213
214         if (__tpa.find(absDllPath) != std::string::npos) {
215                 return true;
216         }
217
218         return false;
219 }
220 #endif
221
222 // baseAddr should be checked in file before getting here
223 static ni_error_e crossgen(const std::string& dllPath, const std::string& appPath, bool enableR2R, uintptr_t baseAddr = 0, bool isAppNI = false)
224 {
225         if (!isFileExist(dllPath)) {
226                 fprintf(stderr, "dll file is not exist : %s\n", dllPath.c_str());
227                 return NI_ERROR_NO_SUCH_FILE;
228         }
229
230         if (!isManagedAssembly(dllPath)) {
231                 fprintf(stderr, "Input file is not a dll file : %s\n", dllPath.c_str());
232                 return NI_ERROR_INVALID_PARAMETER;
233         }
234
235         if (niExist(dllPath)) {
236                 fprintf(stderr, "Already ni file is exist for %s\n", dllPath.c_str());
237                 return NI_ERROR_ALREADY_EXIST;
238         }
239
240         std::string absDllPath = absolutePath(dllPath);
241         std::string absNiPath = getNiFilePath(dllPath);
242         if (absNiPath.empty()) {
243                 fprintf(stderr, "Fail to get ni file name\n");
244                 return NI_ERROR_UNKNOWN;
245         }
246
247         if (isAppNI) {
248                 absNiPath = getAppNIPath(absNiPath);
249         }
250
251         pid_t pid = fork();
252         if (pid == -1)
253                 return NI_ERROR_UNKNOWN;
254
255         if (pid > 0) {
256                 int status;
257                 waitpid(pid, &status, 0);
258                 if (WIFEXITED(status)) {
259                         // Do not use niExist() function to check whether ni file created or not.
260                         // niEixst() return false for System.Private.Corelib.dll
261                         if (isFileExist(absNiPath)) {
262                                 updateAssemblyInfo(absDllPath, absNiPath);
263                                 return NI_ERROR_NONE;
264                         } else {
265                                 fprintf(stderr, "Fail to create native image for %s\n", dllPath.c_str());
266                                 return NI_ERROR_NO_SUCH_FILE;
267                         }
268                 }
269         } else {
270                 std::string jitPath = getRuntimeDir() + "/libclrjit.so";
271                 std::vector<const char*> argv = {
272                         __CROSSGEN_PATH,
273                         "/nologo",
274                         "/Trusted_Platform_Assemblies", __tpa.c_str(),
275                         "/JITPath", jitPath.c_str()
276                 };
277
278                 if (!enableR2R) {
279                         argv.push_back("/FragileNonVersionable");
280                 }
281
282 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
283                 if (baseAddr != 0) {
284                         argv.push_back("/BaseAddress");
285                         argv.push_back(std::to_string(baseAddr).c_str());
286                 }
287 #endif
288
289                 argv.push_back("/App_Paths");
290                 std::string absAppPath;
291                 if (!appPath.empty()) {
292                         absAppPath = appPath;
293                 } else {
294                         absAppPath = baseName(absDllPath);
295                 }
296                 argv.push_back(absAppPath.c_str());
297
298                 argv.push_back("/out");
299                 argv.push_back(absNiPath.c_str());
300
301                 argv.push_back(absDllPath.c_str());
302                 argv.push_back(nullptr);
303
304                 fprintf(stderr, "+ %s (%s)\n", absDllPath.c_str(), enableR2R ? "R2R" : "FNV");
305
306                 execv(__CROSSGEN_PATH, const_cast<char* const*>(argv.data()));
307                 exit(0);
308         }
309
310         return NI_ERROR_NONE;
311 }
312
313 // callback function of "pkgmgrinfo_appinfo_metadata_filter_foreach"
314 static int appAotCb(pkgmgrinfo_appinfo_h handle, void *userData)
315 {
316         char *pkgId = NULL;
317         int ret = 0;
318         bool* enableR2R = (bool*)userData;
319
320         ret = pkgmgrinfo_appinfo_get_pkgid(handle, &pkgId);
321         if (ret != PMINFO_R_OK) {
322                 fprintf(stderr, "Failed to get pkgid\n");
323                 return -1;
324         }
325
326         if (removeNiUnderPkgRoot(pkgId) != 0) {
327                 fprintf(stderr, "Failed to remove previous dlls from [%s]\n", pkgId);
328                 return -1;
329         }
330
331         // Regenerate ni files with R2R mode forcibiliy. (there is no way to now which option is used)
332         if (createNiUnderPkgRoot(pkgId, *enableR2R) != 0) {
333                 fprintf(stderr, "Failed to get root path from [%s]\n", pkgId);
334                 return -1;
335         } else {
336                 fprintf(stderr, "Complete make application to native image\n");
337         }
338
339         return 0;
340 }
341
342 static void createCoreLibNI(bool enableR2R, bool doGenUniqueBaseSystem)
343 {
344         std::string coreLib = concatPath(getRuntimeDir(), "System.Private.CoreLib.dll");
345         std::string niCoreLib = concatPath(getRuntimeDir(), "System.Private.CoreLib.ni.dll");
346         std::string coreLibBackup = concatPath(getRuntimeDir(), "System.Private.CoreLib.dll.Backup");
347
348         if (!isFileExist(coreLibBackup)) {
349                 uintptr_t baseAddr = 0;
350
351 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
352                 if (doGenUniqueBaseSystem) {
353                         baseAddr = getNextBaseAddr();
354                 }
355 #endif
356
357                 if (!crossgen(coreLib, std::string(), enableR2R, baseAddr)) {
358 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
359                         if (doGenUniqueBaseSystem && baseAddr != 0) {
360                                 updateBaseAddrFile(coreLib, baseAddr);
361                         }
362 #endif
363
364                         if (rename(coreLib.c_str(), coreLibBackup.c_str())) {
365                                 fprintf(stderr, "Failed to rename System.Private.CoreLib.dll\n");
366                         }
367                         if (rename(niCoreLib.c_str(), coreLib.c_str())) {
368                                 fprintf(stderr, "Failed to rename System.Private.CoreLib.ni.dll\n");
369                         }
370                 } else {
371                         fprintf(stderr, "Failed to create native image for %s\n", coreLib.c_str());
372                 }
373         }
374 }
375
376 ni_error_e initNICommon(NiCommonOption* option)
377 {
378 #if defined(__arm__)
379         // get interval value
380         const char* intervalFile = "/usr/share/dotnet.tizen/lib/crossgen_interval.txt";
381         std::ifstream inFile(intervalFile);
382         if (inFile) {
383                 fprintf(stderr, "crossgen_interval.txt is found\n");
384                 inFile >> __interval;
385         }
386
387         if (initializePluginManager("normal")) {
388                 fprintf(stderr, "Fail to initialize plugin manager\n");
389                 return NI_ERROR_UNKNOWN;
390         }
391         if (initializePathManager(option->runtimeDir, option->tizenFXDir, option->extraDirs)) {
392                 fprintf(stderr, "Fail to initialize path manager\n");
393                 return NI_ERROR_UNKNOWN;
394         }
395
396         __tpa = getTPA();
397
398         return NI_ERROR_NONE;
399 #else
400         fprintf(stderr, "crossgen supports arm architecture only. skip ni file generation\n");
401         return NI_ERROR_NOT_SUPPORTED;
402 #endif
403 }
404
405 void finalizeNICommon()
406 {
407         __interval = 0;
408
409         finalizePluginManager();
410         finalizePathManager();
411
412         __tpa.clear();
413 }
414
415
416 void createNiPlatform(bool enableR2R, bool doGenUniqueBaseSystem)
417 {
418         const std::string platformDirs[] = {getRuntimeDir(), getTizenFXDir()};
419         createNiUnderDirs(platformDirs, 2, enableR2R, doGenUniqueBaseSystem);
420 }
421
422 ni_error_e createNiDll(const std::string& dllPath, bool enableR2R, bool doGenUniqueBaseSystem)
423 {
424         createCoreLibNI(enableR2R, doGenUniqueBaseSystem);
425         // System.Private.CoreLib.dll is generated in the createCoreLibNI function.
426         // Skip if input dll is System.Private.CoreLib.dll
427         if (dllPath.find("System.Private.CoreLib.dll") != std::string::npos) {
428                 return NI_ERROR_NONE;
429         }
430
431         uintptr_t baseAddr = 0;
432
433 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
434         if (doGenUniqueBaseSystem && isTPADll(dllPath)) {
435                 baseAddr = getNextBaseAddr();
436         }
437 #endif
438
439         ni_error_e status = crossgen(dllPath, std::string(), enableR2R, baseAddr);
440
441 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
442         if (doGenUniqueBaseSystem && baseAddr != 0) {
443                 updateBaseAddrFile(dllPath, baseAddr);
444         }
445 #endif
446
447         return status;
448 }
449
450 void createNiUnderDirs(const std::string rootPaths[], int count, bool enableR2R, bool doGenUniqueBaseSystem, bool isAppNI)
451 {
452         createCoreLibNI(enableR2R, doGenUniqueBaseSystem);
453
454         std::string appPaths;
455         for (int i = 0; i < count; i++) {
456                 appPaths += rootPaths[i];
457                 appPaths += ':';
458         }
459
460         if (appPaths.back() == ':')
461                 appPaths.pop_back();
462
463         auto convert = [&appPaths, enableR2R, doGenUniqueBaseSystem, isAppNI](const std::string& path, const char* name) {
464                 uintptr_t baseAddr = 0;
465
466 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
467                 if (doGenUniqueBaseSystem && !isAppNI && isTPADll(path)) {
468                         baseAddr = getNextBaseAddr();
469                 }
470 #endif
471
472                 if (!crossgen(path, appPaths.c_str(), enableR2R, baseAddr, isAppNI)) {
473 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
474                         if (doGenUniqueBaseSystem && !isAppNI && baseAddr != 0) {
475                                 updateBaseAddrFile(path, baseAddr);
476                         }
477 #endif
478
479                         waitInterval();
480                 }
481         };
482
483         for (int i = 0; i < count; i++) {
484                 scanFilesInDir(rootPaths[i], convert, 1);
485         }
486 }
487
488 ni_error_e createNiUnderPkgRoot(const std::string& pkgId, bool enableR2R)
489 {
490         std::string pkgRoot;
491         if (getRootPath(pkgId, pkgRoot) != NI_ERROR_NONE) {
492                 fprintf(stderr, "Failed to get root path from [%s]\n", pkgId.c_str());
493                 return NI_ERROR_INVALID_PACKAGE;
494         }
495
496         std::string binDir = concatPath(pkgRoot, "bin");
497         std::string libDir = concatPath(pkgRoot, "lib");
498         std::string tacDir = concatPath(binDir, TAC_SYMLINK_SUB_DIR);
499         std::string paths[] = {binDir, libDir, tacDir};
500
501         createNiUnderDirs(paths, 3, enableR2R, false, true);
502
503         return NI_ERROR_NONE;
504 }
505
506 ni_error_e createNiDllUnderPkgRoot(const std::string& pkgId, const std::string& dllPath, bool enableR2R)
507 {
508         std::string pkgRoot;
509         if (getRootPath(pkgId, pkgRoot) < 0) {
510                 fprintf(stderr, "Failed to get root path from [%s]\n", pkgId.c_str());
511                 return NI_ERROR_INVALID_PACKAGE;
512         }
513
514         std::string binDir = concatPath(pkgRoot, "bin");
515         std::string libDir = concatPath(pkgRoot, "lib");
516         std::string appTAC = concatPath(binDir, ".TAC.Release");
517         std::string paths = binDir + ":" + libDir + ":" + appTAC;
518
519         return crossgen(dllPath, paths, enableR2R, 0, true);
520 }
521
522 void removeNiPlatform()
523 {
524         std::string coreLib = concatPath(getRuntimeDir(), "System.Private.CoreLib.dll");
525         std::string coreLibBackup = concatPath(getRuntimeDir(), "System.Private.CoreLib.dll.Backup");
526
527         if (!isFileExist(coreLibBackup)) {
528                 return;
529         }
530
531 #ifdef UNIQUE_DEFAULT_BASE_ADDR_SUPPORT
532         if (isFileExist(__SYSTEM_BASE_FILE)) {
533                 if (remove(__SYSTEM_BASE_FILE)) {
534                         fprintf(stderr, "Failed to remove %s\n", __SYSTEM_BASE_FILE);
535                 }
536         }
537 #endif
538
539         if (remove(coreLib.c_str())) {
540                 fprintf(stderr, "Failed to remove System.Private.CoreLib native image file\n");
541         }
542
543         if (rename(coreLibBackup.c_str(), coreLib.c_str())) {
544                 fprintf(stderr, "Failed to rename System.Private.CoreLib.Backup to origin\n");
545         }
546
547         const std::string platformDirs[] = {getRuntimeDir(), getTizenFXDir()};
548
549         removeNiUnderDirs(platformDirs, 2);
550 }
551
552 void removeNiUnderDirs(const std::string rootPaths[], int count)
553 {
554         auto convert = [](const std::string& path, std::string name) {
555                 if (isNativeImage(path)) {
556                         if (remove(path.c_str())) {
557                                 fprintf(stderr, "Failed to remove %s\n", path.c_str());
558                         }
559                 }
560         };
561
562         for (int i = 0; i < count; i++)
563                 scanFilesInDir(rootPaths[i], convert, -1);
564 }
565
566 ni_error_e removeNiUnderPkgRoot(const std::string& pkgId)
567 {
568         std::string pkgRoot;
569         if (getRootPath(pkgId, pkgRoot) < 0) {
570                 fprintf(stderr, "Failed to get root path from [%s]\n", pkgId.c_str());
571                 return NI_ERROR_INVALID_PACKAGE;
572         }
573
574         std::string binDir = concatPath(pkgRoot, "bin");
575         std::string libDir = concatPath(pkgRoot, "lib");
576         std::string paths[] = {binDir, libDir};
577
578         removeNiUnderDirs(paths, 2);
579
580         std::string binNIDir = concatPath(binDir, APP_NI_SUB_DIR);
581         if (isFileExist(binNIDir)) {
582                 if (rmdir(binNIDir.c_str()) != 0) {
583                         fprintf(stderr, "Failed to remove app ni dir [%s]\n", binNIDir.c_str());
584                 }
585         }
586
587         std::string libNIDir = concatPath(libDir, APP_NI_SUB_DIR);
588         if (isFileExist(libNIDir)) {
589                 if (rmdir(libNIDir.c_str()) != 0) {
590                         fprintf(stderr, "Failed to remove app ni dir [%s]\n", libNIDir.c_str());
591                 }
592         }
593
594         return NI_ERROR_NONE;
595 }
596
597 ni_error_e regenerateAppNI(bool enableR2R)
598 {
599         int ret = 0;
600         pkgmgrinfo_appinfo_metadata_filter_h handle;
601
602         ret = pkgmgrinfo_appinfo_metadata_filter_create(&handle);
603         if (ret != PMINFO_R_OK)
604                 return NI_ERROR_UNKNOWN;
605
606         ret = pkgmgrinfo_appinfo_metadata_filter_add(handle, AOT_METADATA_KEY, METADATA_VALUE);
607         if (ret != PMINFO_R_OK) {
608                 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
609                 return NI_ERROR_UNKNOWN;
610         }
611
612         ret = pkgmgrinfo_appinfo_metadata_filter_foreach(handle, appAotCb, &enableR2R);
613         if (ret != PMINFO_R_OK) {
614                 fprintf(stderr, "Failed pkgmgrinfo_appinfo_metadata_filter_foreach\n");
615                 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
616                 return NI_ERROR_UNKNOWN;
617         }
618
619         fprintf(stderr, "Success pkgmgrinfo_appinfo_metadata_filter_foreach\n");
620
621         pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
622         return NI_ERROR_NONE;
623 }