Modified to pass the argument by constant reference (#242)
[platform/core/dotnet/launcher.git] / NativeLauncher / util / utils.cc
index b265ae8..f399b2c 100644 (file)
@@ -23,8 +23,7 @@
 #include <pkgmgr-info.h>
 #include <pkgmgr_installer_info.h>
 #include <sys/smack.h>
-#include <json/json.h>
-#include <openssl/sha.h>
+#include <sys/prctl.h>
 
 #include <cstdlib>
 #include <cstring>
 #include <unordered_map>
 #include <vector>
 #include <iterator>
+#include <fstream>
 #include <sstream>
 #include <map>
 
 #include "log.h"
 #include "utils.h"
 #include "path_manager.h"
-#include "db_manager.h"
-
-#define __XSTR(x) #x
-#define __STR(x) __XSTR(x)
-static const char* __TAC_DIR = __STR(TAC_DIR);
-#undef __STR
-#undef __XSTR
 
 static bool iCompare(const std::string& a, int aOffset, const std::string& b, int bOffset, int length)
 {
@@ -107,17 +100,19 @@ void splitPath(const std::string& path, std::vector<std::string>& out)
        }
 }
 
-std::string absolutePath(const std::string& path)
+std::string getAbsolutePath(const std::string& path)
 {
        std::string absPath;
-       char realPath[PATH_MAX];
-       if (realpath(path.c_str(), realPath) != nullptr && realPath[0] != '\0')
+       char *realPath = realpath(path.c_str(), NULL);
+       if (realPath) {
                absPath.assign(realPath);
+               free(realPath);
+       }
 
        return absPath;
 }
 
-int getRootPath(std::string pkgId, std::string& rootPath)
+int getRootPath(const std::string& pkgId, std::string& rootPath)
 {
        int ret = 0;
        char *path = 0;
@@ -151,7 +146,7 @@ int getRootPath(std::string pkgId, std::string& rootPath)
        return 0;
 }
 
-int getExecName(std::string pkgId, std::string& execName)
+int getExecName(const std::string& pkgId, std::string& execName)
 {
        char *exec = NULL;
        char *appId = 0;
@@ -186,7 +181,7 @@ int getExecName(std::string pkgId, std::string& execName)
        return 0;
 }
 
-int getMetadataValue(std::string pkgId, std::string metadataKey, std::string& metadataValue)
+int getMetadataValue(const std::string& pkgId, const std::string& metadataKey, std::string& metadataValue)
 {
        char *value = NULL;
        char *appId = 0;
@@ -222,7 +217,7 @@ int getMetadataValue(std::string pkgId, std::string metadataKey, std::string& me
        return 0;
 }
 
-std::string baseName(const std::string& path)
+std::string getBaseName(const std::string& path)
 {
        auto pos = path.find_last_of(PATH_SEPARATOR);
        if (pos != std::string::npos)
@@ -232,7 +227,7 @@ std::string baseName(const std::string& path)
        return path;
 }
 
-std::string replaceAll(const std::string &str, const std::string &pattern, const std::string &replace)
+std::string replaceAll(const std::string& str, const std::string& pattern, const std::string& replace)
 {
        std::string result = str;
        std::string::size_type pos = 0;
@@ -246,12 +241,24 @@ std::string replaceAll(const std::string &str, const std::string &pattern, const
        return result;
 }
 
-bool isFileExist(const std::string& path)
+bool isFile(const std::string& path)
 {
        struct stat sb;
        return stat(path.c_str(), &sb) == 0;
 }
 
+bool isDirectory(const std::string& path)
+{
+       struct stat sb;
+       if (stat(path.c_str(), &sb) != 0) {
+               return false;
+       } else if (sb.st_mode & S_IFDIR) {
+               return true;
+       } else {
+               return false;
+       }
+}
+
 uintptr_t getFileSize(const std::string& path)
 {
        struct stat sb;
@@ -263,54 +270,54 @@ uintptr_t getFileSize(const std::string& path)
        return 0;
 }
 
-std::string stripNiDLL(const std::string& path)
+std::string getAssemblyNameFromPath(const std::string& path)
 {
-       std::string niPath(path);
-       if (path.size() < 5) return niPath;
-       if (!strncasecmp(path.c_str() + path.size() - 4, ".dll", 4))
-               niPath = path.substr(0, path.size()-4);
-       else if (!strncasecmp(path.c_str() + path.size() - 4, ".exe", 4))
-               niPath = path.substr(0, path.size()-4);
+       std::string ret(getFileName(path));
+
+       if (ret.find_last_of(".") == std::string::npos)
+               return ret;
+       ret.erase(ret.find_last_of("."));
 
-       if (!strncasecmp(niPath.c_str() + niPath.size() - 3, ".ni", 3))
-               return niPath.substr(0, niPath.size()-3);
+       if (ret.size() > 3 && std::equal(ret.begin() + ret.size() - 3, ret.end(), ".ni"))
+               ret.erase(ret.size() - 3);
 
-       return niPath;
+       return ret;
 }
 
-void assembliesInDirectory(const std::vector<std::string>& directories, std::string& tpaList)
-{
-       std::map<std::string, std::string> assemblyList;
-       std::map<std::string, std::string> tmpList;
-
-       auto reader = [&assemblyList, &tmpList] (const std::string& path, const char* name) {
-               if (isManagedAssembly(path) || isNativeImage(path)) {
-                       std::string dllName = stripNiDLL(name);
-                       std::pair<std::map<std::string, std::string>::iterator, bool> ret;
-                       ret = tmpList.insert(std::pair<std::string, std::string>(dllName, path));
-                       if (ret.second == false) {
-                               if (isNativeImage(path))
-                                       tmpList[dllName] = path;
+void addAssembliesFromDirectories(const std::vector<std::string>& directories, std::string& list) {
+       std::vector<std::string> assems;
+       std::unordered_map<std::string, std::string> assemPaths;
+
+       auto reader = [&assems, &assemPaths](const std::string& path, const std::string& filename) {
+               if (isManagedAssembly(filename) || isNativeImage(filename)) {
+                       std::string assem = getAssemblyNameFromPath(filename);
+
+                       if (assemPaths.count(assem) == 0) {
+                               assems.push_back(assem);
+                               assemPaths[assem] = path;
+                       } else if (isManagedAssembly(assemPaths[assem]) && isNativeImage(filename)) {
+                               // Update only if a native image is found in the same directory.
+                               // For example, if we have two directories = { X, Y } where X contains A.dll and
+                               // Y contains both A.dll and A.ni.dll, always A.dll in X will be used.
+                               if (getBaseName(assemPaths[assem]).compare(getBaseName(path)) == 0)
+                                       assemPaths[assem] = path;
                        }
                }
        };
+       for (auto& directory : directories)
+               scanFilesInDirectory(directory, reader, 0);
 
-       for (auto directory : directories) {
-               scanFilesInDir(directory.c_str(), reader, 1);
-               // merge scaned dll list to tpa list.
-               // if the dll is already exist in the list, that is skipped.
-               assemblyList.insert(tmpList.begin(), tmpList.end());
-       }
+       if (!list.empty() && list.back() != ':')
+               list.push_back(':');
 
-       std::map<std::string, std::string>::iterator it;
-       for (it = assemblyList.begin(); it != assemblyList.end(); it++)
-               tpaList += it->second + ':';
+       for (auto& assem : assems)
+               list += assemPaths[assem] + ":";
 
-       if (tpaList.back() == ':')
-               tpaList.pop_back();
+       if (list.back() == ':')
+               list.pop_back();
 }
 
-void scanFilesInDir(const std::string& directory, FileReader reader, unsigned int depth)
+void scanFilesInDirectory(const std::string& directory, FileReader reader, unsigned int depth)
 {
        DIR *dir;
        struct dirent* entry;
@@ -347,48 +354,48 @@ void scanFilesInDir(const std::string& directory, FileReader reader, unsigned in
                }
                if (!isDir)
                        reader(path, entry->d_name);
-               else if (depth > 1 && strcmp(entry->d_name, ".") && strcmp(entry->d_name, ".."))
+               else if (depth > 0 && strcmp(entry->d_name, ".") && strcmp(entry->d_name, ".."))
                        innerDirectories.push_back(path);
        }
 
-       if (depth != 0)
+       if (depth > 0)
                for (auto& d : innerDirectories)
-                       scanFilesInDir(d.c_str(), reader, depth - 1);
+                       scanFilesInDirectory(d, reader, depth - 1);
 
        closedir(dir);
 }
 
-void updateAssemblyInfo(const std::string& getPath, const std::string& setPath, bool isSymlink)
+void copySmackAndOwnership(const std::string& fromPath, const std::string& toPath, bool isSymlink)
 {
        char* label = NULL;
        struct stat info;
 
        if (isSymlink) {
                // change smack label for symbolic link.
-               if (smack_lgetlabel(getPath.c_str(), &label, SMACK_LABEL_ACCESS) == 0) {
-                       if (smack_lsetlabel(setPath.c_str(), label, SMACK_LABEL_ACCESS) < 0) {
+               if (smack_lgetlabel(fromPath.c_str(), &label, SMACK_LABEL_ACCESS) == 0) {
+                       if (smack_lsetlabel(toPath.c_str(), label, SMACK_LABEL_ACCESS) < 0) {
                                fprintf(stderr, "Fail to set smack label\n");
                        }
                        free(label);
                }
 
                // change owner and groups for symbolic link.
-               if (!stat(getPath.c_str(), &info)) {
-                       if (lchown(setPath.c_str(), info.st_uid, info.st_gid) == -1)
+               if (!stat(fromPath.c_str(), &info)) {
+                       if (lchown(toPath.c_str(), info.st_uid, info.st_gid) == -1)
                                fprintf(stderr, "Failed to change owner and group name\n");
                }
        } else {
                // change smack label
-               if (smack_getlabel(getPath.c_str(), &label, SMACK_LABEL_ACCESS) == 0) {
-                       if (smack_setlabel(setPath.c_str(), label, SMACK_LABEL_ACCESS) < 0) {
+               if (smack_getlabel(fromPath.c_str(), &label, SMACK_LABEL_ACCESS) == 0) {
+                       if (smack_setlabel(toPath.c_str(), label, SMACK_LABEL_ACCESS) < 0) {
                                fprintf(stderr, "Fail to set smack label\n");
                        }
                        free(label);
                }
 
                // change owner and groups for generated ni file.
-               if (!stat(getPath.c_str(), &info)) {
-                       if (chown(setPath.c_str(), info.st_uid, info.st_gid) == -1)
+               if (!stat(fromPath.c_str(), &info)) {
+                       if (chown(toPath.c_str(), info.st_uid, info.st_gid) == -1)
                                fprintf(stderr, "Failed to change owner and group name\n");
                }
        }
@@ -603,122 +610,23 @@ bool removeAll(const bf::path& path) {
        return true;
 }
 
-static void SHA256(std::string path, char outputBuffer[65])
+void setCmdName(const std::string& name)
 {
-       FILE *file = fopen(path.c_str(), "rb");
-       if (!file) {
-               return;
-       }
+       #define PRC_NAME_LENGTH         16
 
-       unsigned char hash[SHA256_DIGEST_LENGTH];
-       SHA256_CTX sha256;
-       SHA256_Init(&sha256);
-       int bytesRead = 0;
-       const int bufSize = 32768;
-       char *buffer = (char*)malloc(bufSize);
-       if (!buffer) {
-               fclose(file);
-               return;
-       }
+       char processName[PRC_NAME_LENGTH] = {0, };
 
-       while ((bytesRead = fread(buffer, 1, bufSize, file))) {
-               SHA256_Update(&sha256, buffer, bytesRead);
-       }
-       SHA256_Final(hash, &sha256);
-       for (int i = 0; i < SHA256_DIGEST_LENGTH; i++) {
-               sprintf(outputBuffer + (i * 2), "%02x", hash[i]);
-       }
-       outputBuffer[64] = 0;
+       if (name.empty())
+               return;
 
-       fclose(file);
-       free(buffer);
+       memset(processName, '\0', PRC_NAME_LENGTH);
+       snprintf(processName, PRC_NAME_LENGTH, "%s", name.c_str());
+       prctl(PR_SET_NAME, processName);
 }
 
-std::vector<std::string> depsJsonParser(std::string pkgId, std::string rootPath, std::string execName, std::string tpaList, bool isTool, sqlite3 *tac_db)
+std::string getFileName(const std::string& path)
 {
-       std::vector<std::string> parserData;
-       std::string depsJsonName = execName.substr(0, execName.rfind(".dll")) + ".deps.json";
-       std::string depsJsonPath = concatPath(rootPath, depsJsonName);
-       std::string binPath = concatPath(rootPath, "bin");
-       if (bf::exists(depsJsonPath)) {
-               std::ifstream ifs(depsJsonPath);
-               Json::CharReaderBuilder reader;
-               Json::Value root;
-               std::string error;
-               if (ifs.is_open()) {
-                       if (!Json::parseFromStream(reader, ifs, &root, &error)) {
-                               _ERR("Failed to parse of deps.json");
-                               ifs.close();
-                               return parserData;
-                       }
-                       const Json::Value runtimeTargetName = root["runtimeTarget"]["name"];
-                       const Json::Value nugetPackages = root["targets"][runtimeTargetName.asString().c_str()];
-                       for (auto& nuget : nugetPackages.getMemberNames()) {
-                               if (strstr(nuget.c_str(), TIZEN_DOTNET_NUGET) != NULL ||
-                                       strstr(nuget.c_str(), TIZEN_DOTNET_SDK_NUGET) != NULL ||
-                                       strstr(nuget.c_str(), (execName.substr(0, execName.find(".Tizen."))).c_str()) != NULL ||
-                                       strstr(nuget.c_str(), (execName.substr(0, execName.find(".dll"))).c_str()) != NULL) {
-                                       continue;
-                               } else {
-                                       const Json::Value assemblies = nugetPackages[nuget.c_str()]["runtime"];
-                                       if (assemblies != Json::nullValue) {
-                                               const Json::Value dependencies = nugetPackages[nuget.c_str()]["dependencies"];
-                                               bool isDependency = false;
-                                               for (auto& dependency : dependencies.getMemberNames()) {
-                                                       if (strstr(dependency.c_str(), TIZEN_DOTNET_NUGET) != NULL ||
-                                                               strstr(dependency.c_str(), NET_STANDARD_LIBRARY_NUGET) != NULL) {
-                                                               continue;
-                                                       } else {
-                                                               isDependency = true;
-                                                       }
-                                               }
-                                               if (!isDependency) {
-                                                       bool isExistTpaAssembly = false;
-                                                       for (auto& assembly : assemblies.getMemberNames()) {
-                                                               std::string assembly_name = assembly.substr(assembly.rfind('/') + 1);
-                                                               if (strstr(replaceAll(tpaList, ".ni.dll", ".dll").c_str(), assembly_name.c_str()) != NULL) {
-                                                                       isExistTpaAssembly = true;
-                                                                       break;
-                                                               }
-                                                       }
-                                                       if (!isExistTpaAssembly) {
-                                                               _INFO("Nuget : %s", nuget.c_str());
-                                                               if (isTool) {
-                                                                       if (tac_db) {
-                                                                               std::string name = nuget.substr(0, nuget.find('/'));
-                                                                               std::string version = nuget.substr(nuget.rfind('/') + 1);
-                                                                               std::string sql = "INSERT INTO TAC (PKGID, NUGET, NAME, VERSION) " \
-                                                                               "VALUES ('" + pkgId + "', '" + nuget + "', '" + name + "', '" + version + "');";
-                                                                               dbInsert(tac_db, TAC_APP_LIST_RESTORE_DB, sql);
-                                                                               parserData.push_back(concatPath(__TAC_DIR, name));
-                                                                       } else {
-                                                                               std::string nugetPath = concatPath(__TAC_DIR, nuget);
-                                                                               if (bf::exists(nugetPath)) {
-                                                                                       for (auto& assembly : assemblies.getMemberNames()) {
-                                                                                               std::string assemblyName = assembly.substr(assembly.rfind('/') + 1);
-                                                                                               std::string originPath = concatPath(nugetPath, assemblyName);
-                                                                                               if (bf::exists(originPath)) {
-                                                                                                       parserData.push_back(originPath);
-                                                                                               }
-                                                                                       }
-                                                                               }
-                                                                       }
-                                                               } else {
-                                                                       for (auto& assembly : assemblies.getMemberNames()) {
-                                                                               std::string assembly_name = assembly.substr(assembly.rfind('/') + 1);
-                                                                               char buffer[65] = {0};
-                                                                               SHA256(concatPath(binPath, assembly_name), buffer);
-                                                                               parserData.push_back(nuget + "/" + assembly_name + "/" + buffer);
-                                                                               _INFO("Assembly / SHA256 : %s / %s", assembly_name.c_str(), buffer);
-                                                                       }
-                                                               }
-                                                       }
-                                               }
-                                       }
-                               }
-                       }
-                       ifs.close();
-               }
-       }
-       return parserData;
-}
\ No newline at end of file
+       std::string ret(path);
+       size_t index = ret.find_last_of(PATH_SEPARATOR);
+       return index == std::string::npos ? ret : ret.substr(index + 1);
+}