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