TAC support for memory optimization
[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 std::string getNiFileName(const std::string& dllPath)
73 {
74         size_t index = dllPath.find_last_of(".");
75         if (index == std::string::npos) {
76                 fprintf(stderr, "File doesnot contain extension. fail to get NI file name\n");
77                 return "";
78         }
79         std::string fName = dllPath.substr(0, index);
80         std::string fExt = dllPath.substr(index, dllPath.length());
81
82         // crossgen generate file with lower case extension only
83         std::transform(fExt.begin(), fExt.end(), fExt.begin(), ::tolower);
84         std::string niPath = fName + ".ni" + fExt;
85
86         return niPath;
87 }
88
89 static bool niExist(const std::string& path)
90 {
91         std::string f = getNiFileName(path);
92         if (f.empty()) {
93                 return false;
94         }
95
96         if (isFileExist(f)) {
97                 return true;
98         }
99
100         // native image of System.Private.CoreLib.dll should have to overwrite
101         // original file to support new coreclr
102         if (path.find("System.Private.CoreLib.dll") != std::string::npos) {
103                 std::string coreLibBackup = path + ".Backup";
104                 if (isFileExist(coreLibBackup)) {
105                         return true;
106                 }
107         }
108
109         return false;
110 }
111
112 static void updateNiFileInfo(const std::string& dllPath, const std::string& niPath)
113 {
114         char* label = NULL;
115
116         // change smack label
117         if (smack_getlabel(dllPath.c_str(), &label, SMACK_LABEL_ACCESS) == 0) {
118                 if (smack_setlabel(niPath.c_str(), label, SMACK_LABEL_ACCESS) < 0) {
119                         fprintf(stderr, "Fail to set smack label\n");
120                 }
121                 free(label);
122         }
123
124         // change owner and groups for generated ni file.
125         struct stat info;
126         if (!stat(dllPath.c_str(), &info)) {
127                 if (chown(niPath.c_str(), info.st_uid, info.st_gid) == -1)
128                         fprintf(stderr, "Failed to change owner and group name\n");
129         }
130 }
131
132 static int crossgen(const std::string& dllPath, const std::string& appPath, bool enableR2R)
133 {
134         if (!isFileExist(dllPath)) {
135                 fprintf(stderr, "dll file is not exist : %s\n", dllPath.c_str());
136                 return -1;
137         }
138
139         if (!isManagedAssembly(dllPath)) {
140                 fprintf(stderr, "Input file is not a dll file : %s\n", dllPath.c_str());
141                 return -1;
142         }
143
144         if (niExist(dllPath)) {
145                 fprintf(stderr, "Already ni file is exist for %s\n", dllPath.c_str());
146                 return -1;
147         }
148
149         std::string absDllPath = absolutePath(dllPath);
150         std::string absNiPath = getNiFileName(dllPath);
151         if (absNiPath.empty()) {
152                 fprintf(stderr, "Fail to get ni file name\n");
153                 return -1;
154         }
155
156         pid_t pid = fork();
157         if (pid == -1)
158                 return -1;
159
160         if (pid > 0) {
161                 int status;
162                 waitpid(pid, &status, 0);
163                 if (WIFEXITED(status)) {
164                         // Do not use niExist() function to check whether ni file created or not.
165                         // niEixst() return false for System.Private.Corelib.dll
166                         if (isFileExist(absNiPath)) {
167                                 updateNiFileInfo(absDllPath, absNiPath);
168                                 return 0;
169                         } else {
170                                 fprintf(stderr, "Fail to create native image for %s\n", dllPath.c_str());
171                                 return -1;
172                         }
173                 }
174         } else {
175                 std::string jitPath = getRuntimeDir() + "/libclrjit.so";
176                 std::vector<const char*> argv = {
177                         __CROSSGEN_PATH,
178                         "/nologo",
179                         "/Trusted_Platform_Assemblies", __tpa.c_str(),
180                         "/JITPath", jitPath.c_str()
181                 };
182
183                 if (!enableR2R) {
184                         argv.push_back("/FragileNonVersionable");
185                 }
186
187                 argv.push_back("/App_Paths");
188                 std::string absAppPath;
189                 if (!appPath.empty()) {
190                         absAppPath = appPath;
191                 } else {
192                         absAppPath = baseName(absDllPath);
193                 }
194                 argv.push_back(absAppPath.c_str());
195
196                 argv.push_back("/out");
197                 argv.push_back(absNiPath.c_str());
198
199                 argv.push_back(absDllPath.c_str());
200                 argv.push_back(nullptr);
201
202                 fprintf(stderr, "+ %s (%s)\n", absDllPath.c_str(), enableR2R ? "R2R" : "FNV");
203
204                 execv(__CROSSGEN_PATH, const_cast<char* const*>(argv.data()));
205                 exit(0);
206         }
207
208         return 0;
209 }
210
211 static int getRootPath(std::string pkgId, std::string& rootPath)
212 {
213         int ret = 0;
214         char *path = 0;
215
216         uid_t uid = 0;
217
218         if (pkgmgr_installer_info_get_target_uid(&uid) < 0) {
219                 _ERR("Failed to get UID");
220                 return -1;
221         }
222
223         pkgmgrinfo_pkginfo_h handle;
224         if (uid == 0) {
225                 ret = pkgmgrinfo_pkginfo_get_pkginfo(pkgId.c_str(), &handle);
226                 if (ret != PMINFO_R_OK)
227                         return -1;
228         } else {
229                 ret = pkgmgrinfo_pkginfo_get_usr_pkginfo(pkgId.c_str(), uid, &handle);
230                 if (ret != PMINFO_R_OK)
231                         return -1;
232         }
233
234         ret = pkgmgrinfo_pkginfo_get_root_path(handle, &path);
235         if (ret != PMINFO_R_OK) {
236                 pkgmgrinfo_pkginfo_destroy_pkginfo(handle);
237                 return -1;
238         }
239         rootPath = path;
240         pkgmgrinfo_pkginfo_destroy_pkginfo(handle);
241
242         return 0;
243 }
244
245 static int appAotCb(pkgmgrinfo_appinfo_h handle, void *userData)
246 {
247         char *pkgId = NULL;
248         int ret = 0;
249         bool* enableR2R = (bool*)userData;
250
251         ret = pkgmgrinfo_appinfo_get_pkgid(handle, &pkgId);
252         if (ret != PMINFO_R_OK) {
253                 fprintf(stderr, "Failed to get pkgid\n");
254                 return -1;
255         }
256
257         if (removeNiUnderPkgRoot(pkgId) != 0) {
258                 fprintf(stderr, "Failed to remove previous dlls from [%s]\n", pkgId);
259                 return -1;
260         }
261
262         // Regenerate ni files with R2R mode forcibiliy. (there is no way to now which option is used)
263         if (createNiUnderPkgRoot(pkgId, *enableR2R) != 0) {
264                 fprintf(stderr, "Failed to get root path from [%s]\n", pkgId);
265                 return -1;
266         } else {
267                 fprintf(stderr, "Complete make application to native image\n");
268         }
269
270         return 0;
271 }
272
273 static void createCoreLibNI(bool enableR2R)
274 {
275         std::string coreLib = concatPath(getRuntimeDir(), "System.Private.CoreLib.dll");
276         std::string niCoreLib = concatPath(getRuntimeDir(), "System.Private.CoreLib.ni.dll");
277         std::string coreLibBackup = concatPath(getRuntimeDir(), "System.Private.CoreLib.dll.Backup");
278
279         if (!isFileExist(coreLibBackup)) {
280                 if (!crossgen(coreLib, std::string(), enableR2R)) {
281                         if (rename(coreLib.c_str(), coreLibBackup.c_str())) {
282                                 fprintf(stderr, "Failed to rename System.Private.CoreLib.dll\n");
283                         }
284                         if (rename(niCoreLib.c_str(), coreLib.c_str())) {
285                                 fprintf(stderr, "Failed to rename System.Private.CoreLib.ni.dll\n");
286                         }
287                 } else {
288                         fprintf(stderr, "Failed to create native image for %s\n", coreLib.c_str());
289                 }
290         }
291 }
292
293 int initNICommon(NiCommonOption* option)
294 {
295 #if defined(__arm__)
296         // get interval value
297         const char* intervalFile = "/usr/share/dotnet.tizen/lib/crossgen_interval.txt";
298         std::ifstream inFile(intervalFile);
299         if (inFile) {
300                 fprintf(stderr, "crossgen_interval.txt is found\n");
301                 inFile >> __interval;
302         }
303
304         if (initializePluginManager("normal")) {
305                 fprintf(stderr, "Fail to initialize plugin manager\n");
306                 return -1;
307         }
308         if (initializePathManager(option->runtimeDir, option->tizenFXDir, option->extraDirs)) {
309                 fprintf(stderr, "Fail to initialize path manager\n");
310                 return -1;
311         }
312
313         __tpa = getTPA();
314
315         return 0;
316 #else
317         fprintf(stderr, "crossgen supports arm architecture only. skip ni file generation\n");
318         return -1;
319 #endif
320 }
321
322 void finalizeNICommon()
323 {
324         __interval = 0;
325
326         finalizePluginManager();
327         finalizePathManager();
328
329         __tpa.clear();
330 }
331
332
333 void createNiPlatform(bool enableR2R)
334 {
335         const std::string platformDirs[] = {getRuntimeDir(), getTizenFXDir()};
336         createNiUnderDirs(platformDirs, 2, enableR2R);
337 }
338
339 int createNiDll(const std::string& dllPath, bool enableR2R)
340 {
341         createCoreLibNI(enableR2R);
342         return crossgen(dllPath, std::string(), enableR2R);
343 }
344
345 void createNiUnderDirs(const std::string rootPaths[], int count, bool enableR2R)
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](const std::string& path, const char* name) {
359                 if (!crossgen(path, appPaths.c_str(), enableR2R)) {
360                         waitInterval();
361                 }
362         };
363
364         for (int i = 0; i < count; i++) {
365                 scanFilesInDir(rootPaths[i], convert, 1);
366         }
367 }
368
369 int createNiUnderPkgRoot(const std::string& pkgName, bool enableR2R)
370 {
371         std::string pkgRoot;
372         if (getRootPath(pkgName, pkgRoot) < 0) {
373                 fprintf(stderr, "Failed to get root path from [%s]\n", pkgName.c_str());
374                 return -1;
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);
383
384         return 0;
385 }
386
387 int createNiDllUnderPkgRoot(const std::string& pkgName, const std::string& dllPath, bool enableR2R)
388 {
389         std::string pkgRoot;
390         if (getRootPath(pkgName, pkgRoot) < 0) {
391                 fprintf(stderr, "Failed to get root path from [%s]\n", pkgName.c_str());
392                 return -1;
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);
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 int removeNiUnderPkgRoot(const std::string& pkgName)
439 {
440         std::string pkgRoot;
441         if (getRootPath(pkgName, pkgRoot) < 0) {
442                 fprintf(stderr, "Failed to get root path from [%s]\n", pkgName.c_str());
443                 return -1;
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         return 0;
453 }
454
455 int regenerateAppNI(bool enableR2R)
456 {
457         int ret = 0;
458         pkgmgrinfo_appinfo_metadata_filter_h handle;
459
460         ret = pkgmgrinfo_appinfo_metadata_filter_create(&handle);
461         if (ret != PMINFO_R_OK)
462                 return -1;
463
464         ret = pkgmgrinfo_appinfo_metadata_filter_add(handle, "http://tizen.org/metadata/prefer_dotnet_aot", "true");
465         if (ret != PMINFO_R_OK) {
466                 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
467                 return -1;
468         }
469
470         ret = pkgmgrinfo_appinfo_metadata_filter_foreach(handle, appAotCb, &enableR2R);
471         if (ret != PMINFO_R_OK) {
472                 fprintf(stderr, "Failed pkgmgrinfo_appinfo_metadata_filter_foreach\n");
473                 pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
474                 return -1;
475         }
476
477         fprintf(stderr, "Success pkgmgrinfo_appinfo_metadata_filter_foreach\n");
478
479         pkgmgrinfo_appinfo_metadata_filter_destroy(handle);
480         return 0;
481 }