logic: revised loading Java library

* implemented a dynamic way (that does not involve the linker) to load the Java runtime library
* implemented JavaPathDetectorLinux
* Filepicker for Java runtime library now asks to pick JVM library instead of folder
* extended error handling for JavaEnvironmentFactory
This commit is contained in:
malte_langkabel
2016-08-31 12:16:29 +02:00
parent eb621eea33
commit d2de395ed5
16 changed files with 313 additions and 133 deletions
+3 -51
View File
@@ -212,11 +212,8 @@ target_include_directories(${LIB_PROJECT_NAME} SYSTEM
"${CMAKE_SOURCE_DIR}/src/external"
)
if (WIN32)
target_link_libraries(${LIB_PROJECT_NAME} ${Boost_LIBRARIES} ${LIB_LICENSE_PROJECT_NAME} ${JNI_LIBRARIES})
else()
target_link_libraries(${LIB_PROJECT_NAME} ${Boost_LIBRARIES} ${LIB_LICENSE_PROJECT_NAME})
endif()
target_link_libraries(${LIB_PROJECT_NAME} ${Boost_LIBRARIES} ${LIB_LICENSE_PROJECT_NAME})
# Lib Parser -------------------------------------------------------------------
@@ -397,24 +394,6 @@ create_source_groups(${APP_FILES})
target_link_libraries(${APP_PROJECT_NAME} ${LIB_GUI_PROJECT_NAME} ${LIB_PARSER_PROJECT_NAME} ${LIB_PROJECT_NAME} ${LIB_LICENSE_PROJECT_NAME})
if (WIN32)
SET_TARGET_PROPERTIES(
${APP_PROJECT_NAME} PROPERTIES
LINK_FLAGS "/DELAYLOAD:jvm.dll"
)
elseif (APPLE)
set(LAZY_LIB_FLAGS "")
foreach (_lib ${JNI_LIBRARIES})
set (LAZY_LIB_FLAGS "${LAZY_LIB_FLAGS} -lazy_library ${_lib}")
endforeach()
SET_TARGET_PROPERTIES(
${APP_PROJECT_NAME} PROPERTIES
LINK_FLAGS ${LAZY_LIB_FLAGS}
)
endif()
set_property(
TARGET ${APP_PROJECT_NAME}
@@ -481,23 +460,6 @@ create_source_groups(${TRIAL_FILES})
target_link_libraries(${TRIAL_PROJECT_NAME} ${LIB_GUI_PROJECT_NAME} ${LIB_PROJECT_NAME} ${LIB_LICENSE_PROJECT_NAME} )
if (WIN32)
SET_TARGET_PROPERTIES(
${TRIAL_PROJECT_NAME} PROPERTIES
LINK_FLAGS "/DELAYLOAD:jvm.dll"
)
elseif (APPLE)
set(LAZY_LIB_FLAGS2 "")
foreach (_lib ${JNI_LIBRARIES})
set (LAZY_LIB_FLAGS2 "${LAZY_LIB_FLAGS2} -lazy_library ${_lib}")
endforeach()
SET_TARGET_PROPERTIES(
${TRIAL_PROJECT_NAME} PROPERTIES
LINK_FLAGS ${LAZY_LIB_FLAGS2}
)
endif()
if(UNIX AND NOT APPLE)
target_link_libraries(${TRIAL_PROJECT_NAME} pthread dl rt)
@@ -632,17 +594,7 @@ add_executable (${TEST_PROJECT_NAME} ${TESTGEN_FILE} ${TEST_FILES} )
create_source_groups(${TEST_FILES})
if (WIN32)
target_link_libraries(${TEST_PROJECT_NAME} ${LIB_PARSER_PROJECT_NAME} ${LIB_PROJECT_NAME} ${LIB_LICENSE_PROJECT_NAME})
else()
target_link_libraries(${TEST_PROJECT_NAME} ${LIB_PARSER_PROJECT_NAME} ${LIB_PROJECT_NAME} ${LIB_LICENSE_PROJECT_NAME} ${JNI_LIBRARIES})
endif()
if (WIN32)
SET_TARGET_PROPERTIES(
${TEST_PROJECT_NAME} PROPERTIES
LINK_FLAGS "/DELAYLOAD:jvm.dll")
endif()
target_link_libraries(${TEST_PROJECT_NAME} ${LIB_PARSER_PROJECT_NAME} ${LIB_PROJECT_NAME} ${LIB_LICENSE_PROJECT_NAME})
find_package(CxxTest)
if (CXXTEST_FOUND)
+1
View File
@@ -349,6 +349,7 @@ add_files(
utility/UserPaths.h
utility/utility.cpp
utility/utility.h
utility/utilityLibrary.h
utility/utilityString.cpp
utility/utilityString.h
utility/Version.cpp
+20 -2
View File
@@ -2,6 +2,7 @@
#include "data/parser/java/JavaEnvironmentFactory.h"
#include "data/parser/java/TaskParseJava.h"
#include "utility/messaging/type/MessageStatus.h"
#include "utility/ResourcePaths.h"
#include "Application.h"
#include "isTrial.h"
@@ -30,6 +31,7 @@ JavaProject::JavaProject(
bool JavaProject::prepareIndexing()
{
std::string errorString;
if (!JavaEnvironmentFactory::getInstance() && !isTrial())
{
#ifdef _WIN32
@@ -45,12 +47,28 @@ bool JavaProject::prepareIndexing()
ResourcePaths::getJavaPath() + "javassist-3.19.0-GA.jar" + separator +
ResourcePaths::getJavaPath() + "java-symbol-solver-core.jar" + separator +
ResourcePaths::getJavaPath() + "java-symbol-solver-logic.jar" + separator +
ResourcePaths::getJavaPath() + "java-symbol-solver-model.jar"
ResourcePaths::getJavaPath() + "java-symbol-solver-model.jar",
errorString
);
}
if (errorString.size() > 0)
{
LOG_ERROR(errorString);
MessageStatus(errorString, true, false).dispatch();
}
if (!JavaEnvironmentFactory::getInstance() && !isTrial())
{
Application::getInstance()->handleDialog("Coati was unable to locate Java on this machine.\nPlease make sure to provide the correct path in your preferences.");
std::string dialogMessage =
"Coati was unable to locate Java on this machine.\nPlease make sure to provide the correct Java Path in the preferences.";
if (errorString.size() > 0)
{
dialogMessage += "\n\nError: " + errorString;
}
Application::getInstance()->handleDialog(dialogMessage);
return false;
}
@@ -2,19 +2,15 @@
#include <cstdlib>
#ifdef __APPLE__
#include <dlfcn.h>
#endif
#include <jni.h>
#include "data/parser/java/JavaEnvironment.h"
#include "settings/ApplicationSettings.h"
#include "utility/logging/logging.h"
#include "utility/messaging/type/MessageStatus.h"
#include "utility/file/FileSystem.h"
#include "utility/logging/logging.h"
#include "utility/utilityLibrary.h"
void JavaEnvironmentFactory::createInstance(std::string classPath)
void JavaEnvironmentFactory::createInstance(std::string classPath, std::string& errorString)
{
if (s_instance)
{
@@ -31,51 +27,16 @@ void JavaEnvironmentFactory::createInstance(std::string classPath)
}
}
bool javaFound = false;
std::function<jint (JavaVM**, void**, void*)> createInstanceFunction;
#ifdef _WIN32
createInstanceFunction = utility::loadFunctionFromLibrary<jint, JavaVM**, void**, void*>(
FilePath(ApplicationSettings::getInstance()->getJavaPath()),
"JNI_CreateJavaVM",
errorString
);
if (!createInstanceFunction && errorString.size() > 0)
{
std::string oldPathContent = getenv("path");
std::string javapath = ApplicationSettings::getInstance()->getJavaPath() + "/";
putenv(("path=" + javapath + ";" + oldPathContent).c_str()); // path env is only modified in the scope of this process.
javaFound = FileSystem::exists(javapath + "jvm.dll");
}
#endif
#ifdef __APPLE__
{
std::string javapath = ApplicationSettings::getInstance()->getJavaPath();
void* handle = nullptr;
if (javapath.size())
{
handle = dlopen((javapath + "/jre/lib/server/libjvm.dylib").c_str(), RTLD_NOW);
}
if (!handle && javapath.size())
{
handle = dlopen((javapath + "/libjvm.dylib").c_str(), RTLD_NOW);
}
if (!handle)
{
handle = dlopen("libjvm.dylib", RTLD_NOW);
}
if (handle)
{
javaFound = true;
}
}
#endif
if (!javaFound)
{
std::string errorMessage = "Unable to locate Java on this machine.";
LOG_ERROR(errorMessage);
MessageStatus(errorMessage, true, false).dispatch();
return;
}
@@ -96,36 +57,32 @@ void JavaEnvironmentFactory::createInstance(std::string classPath)
vm_args.options = options;
vm_args.ignoreUnrecognized = false; // invalid options make the JVM init fail
jint rc = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);
jint rc = createInstanceFunction(&jvm, (void**)&env, &vm_args);
delete [] options;
if(rc != JNI_OK)
if (rc != JNI_OK)
{
std::string errorMessage;
if(rc == JNI_EVERSION)
{
errorMessage = "JVM is oudated and doesn't meet requirements";
errorString = "JVM is oudated and doesn't meet requirements";
}
else if(rc == JNI_ENOMEM)
{
errorMessage = "not enough memory for JVM";
errorString = "not enough memory for JVM";
}
else if(rc == JNI_EINVAL)
{
errorMessage = "invalid argument for launching JVM";
errorString = "invalid argument for launching JVM";
}
else if(rc == JNI_EEXIST)
{
errorMessage = "the process can only launch one JVM an not more";
errorString = "the process can only launch one JVM an not more";
}
else
{
errorMessage = "could not create the JVM instance (error code " + std::to_string(rc) + ")";
errorString = "could not create the JVM instance (error code " + std::to_string(rc) + ")";
}
LOG_ERROR(errorMessage);
MessageStatus("Error while creating Java environment: " + errorMessage, true, false).dispatch();
}
else
{
@@ -18,7 +18,7 @@ class JavaEnvironment;
class JavaEnvironmentFactory
{
public:
static void createInstance(std::string classPath);
static void createInstance(std::string classPath, std::string& errorString);
static std::shared_ptr<JavaEnvironmentFactory> getInstance();
~JavaEnvironmentFactory();
+6
View File
@@ -3,6 +3,7 @@
#include <regex>
#include "utility/logging/logging.h"
#include "utility/utilityString.h"
FilePath::FilePath()
: m_exists(false)
@@ -216,6 +217,11 @@ std::string FilePath::str() const
return m_path.generic_string();
}
std::string FilePath::getBackslashedString() const
{
return utility::replace(str(), "/", "\\");
}
std::string FilePath::fileName() const
{
return m_path.filename().generic_string();
+1
View File
@@ -31,6 +31,7 @@ public:
bool contains(const FilePath& other) const;
std::string str() const;
std::string getBackslashedString() const;
std::string fileName() const;
std::string extension() const;
+69
View File
@@ -0,0 +1,69 @@
#ifndef UTILITY_LIBRARY_H
#define UTILITY_LIBRARY_H
#include <iostream>
#include <functional>
#include <sstream>
#include <string>
#ifdef _WIN32
#include <windows.h>
#else
#include <dlfcn.h>
#define __stdcall
#endif
#include "utility/file/FilePath.h"
namespace utility
{
template <typename Ret, typename... Args>
std::function<Ret(Args...)> loadFunctionFromLibrary(
const FilePath& libraryPath,
const std::string& functionName,
std::string& errorString)
{
#ifdef _WIN32
const std::string libraryPathString = libraryPath.getBackslashedString();
HINSTANCE handle = LoadLibrary(libraryPathString.c_str());
if (handle == NULL)
{
errorString = "Could not load library \"" + libraryPathString + "\"";
return std::function<Ret(Args...)>();
}
FARPROC functionId = GetProcAddress(handle, functionName.c_str());
if (!functionId)
{
errorString = "Could not locate the function \"" + functionName
+ "\" in library\"" + libraryPathString + "\"";
return std::function<Ret(Args...)>();
}
#else
void* handle = dlopen(libraryPath.str().c_str(), RTLD_LAZY);
if (handle == nullptr)
{
errorString = "Could not load library \"" + libraryPath.str() + "\"";
return std::function<Ret(Args...)>();
}
void* functionId = (void*) dlsym(handle, functionName.c_str());
const char *dlsym_error = dlerror();
if (dlsym_error || !functionId)
{
std::stringstream ss;
ss << "Cannot load symbol '" << functionName << "' from library '" << libraryPath.str() << "': " << dlsym_error;
errorString = ss.str();
dlclose(handle);
return std::function<Ret(Args...)>();
}
#endif
return std::function<Ret(Args...)>(reinterpret_cast<Ret (__stdcall *)(Args...)>(functionId));
}
}
#endif // UTILITY_LIBRARY_H
+2
View File
@@ -176,6 +176,8 @@ add_files(
utility/path_detector/java_runtime/JavaPathDetector.cpp
utility/path_detector/java_runtime/JavaPathDetector.h
utility/path_detector/java_runtime/JavaPathDetectorLinux.cpp
utility/path_detector/java_runtime/JavaPathDetectorLinux.h
utility/path_detector/java_runtime/JavaPathDetectorMac.cpp
utility/path_detector/java_runtime/JavaPathDetectorMac.h
utility/path_detector/java_runtime/JavaPathDetectorWindows.cpp
@@ -3,6 +3,7 @@
#include "settings/ApplicationSettings.h"
#include "utility/file/FileSystem.h"
#include "utility/messaging/type/MessageSwitchColorScheme.h"
#include "utility/path_detector/java_runtime/JavaPathDetectorLinux.h"
#include "utility/path_detector/java_runtime/JavaPathDetectorMac.h"
#include "utility/path_detector/java_runtime/JavaPathDetectorWindows.h"
#include "utility/ResourcePaths.h"
@@ -176,45 +177,57 @@ void QtProjectWizzardContentPreferences::populate(QGridLayout* layout, int& row)
layout->setRowMinimumHeight(row++, 20);
// Java
layout->addWidget(createFormTitle("JAVA"), row, QtProjectWizzardWindow::FRONT_COL, Qt::AlignLeft);
row++;
// java path
// jvm library path
m_javaPath = new QtLocationPicker(this);
m_javaPath->setPickDirectory(true);
#ifdef _WIN32
QString filter = "JVM Library (jvm.dll)";
#elif __APPLE__
QString filter = "JVM Library (libjvm.dylib)";
#else
QString filter = "JVM Library (libjvm.so)";
#endif
m_javaPath->setFileFilter(filter);
if (QSysInfo::windowsVersion() != QSysInfo::WV_None)
{
m_javaPath->setPlaceholderText("<jre_8_root>/bin/client");
m_javaPath->setPlaceholderText("<jre_path>/bin/client/jvm.dll");
}
else if (QSysInfo::macVersion() != QSysInfo::MV_None)
{
m_javaPath->setPlaceholderText("<jre_8_root>/Contents/Home");
m_javaPath->setPlaceholderText("<jre_path>Contents/Home/jre/lib/server/libjvm.dylib");
}
else
{
m_javaPath->setPlaceholderText("<jre_path>/bin/<arch>/server/libjvm.so");
}
layout->addWidget(createFormLabel("Java Path"), row, QtProjectWizzardWindow::FRONT_COL, Qt::AlignRight);
layout->addWidget(m_javaPath, row, QtProjectWizzardWindow::BACK_COL);
addHelpButton(
"Location of the folder that contains the dynamic library for your jre virtual machine."
"Location of the dynamic library for your jre virtual machine."
, layout, row
);
row++;
m_javaPathDetector = std::make_shared<CombinedPathDetector>();
if (QSysInfo::windowsVersion() != QSysInfo::WV_None)
{
m_javaPathDetector = std::make_shared<CombinedPathDetector>();
m_javaPathDetector->addDetector(std::make_shared<JavaPathDetectorWindows>("1.8"));
addJavaPathDetection(layout, row);
}
else if (QSysInfo::macVersion() != QSysInfo::MV_None)
{
m_javaPathDetector = std::make_shared<CombinedPathDetector>();
m_javaPathDetector->addDetector(std::make_shared<JavaPathDetectorMac>("1.8"));
addJavaPathDetection(layout, row);
}
else
{
m_javaPathDetector->addDetector(std::make_shared<JavaPathDetectorLinux>("1.8"));
}
addJavaPathDetection(layout, row);
layout->setRowMinimumHeight(row++, 20);
@@ -0,0 +1,128 @@
#include "utility/path_detector/java_runtime/JavaPathDetectorLinux.h"
#include "utility/utilityApp.h"
#include "utility/utilityString.h"
#ifdef __x86_64__
const std::string arch = "amd64";
#else
const std::string arch = "i386";
#endif
const std::string jvmLibPathRelativeToJavaExecutable = "/../lib/" + arch + "/server/libjvm.so";
JavaPathDetectorLinux::JavaPathDetectorLinux(const std::string javaVersion)
: JavaPathDetector("Java " + javaVersion + " for Linux", javaVersion)
{
}
JavaPathDetectorLinux::~JavaPathDetectorLinux()
{
}
FilePath JavaPathDetectorLinux::getJavaInPath() const
{
std::string command = "which java";
std::string output = utility::executeProcess(command.c_str());
if (output.size())
{
output = utility::trim(output);
FilePath javaPath(output);
if (!javaPath.empty() && javaPath.exists())
{
return javaPath;
}
}
return FilePath();
}
FilePath JavaPathDetectorLinux::readLink(const FilePath& path) const
{
std::string command = "readlink -f " + path.str();
FilePath javaPath( utility::executeProcess(command.c_str()));
if ( !javaPath.empty() )
{
return javaPath;
}
return FilePath();
}
FilePath JavaPathDetectorLinux::getFilePathRelativeToJavaExecutable(FilePath& javaExecutablePath) const
{
FilePath p(javaExecutablePath.parentDirectory().str() + jvmLibPathRelativeToJavaExecutable);
if ( p.exists() )
{
return p.canonical();
}
else
{
return FilePath();
}
}
FilePath JavaPathDetectorLinux::getJavaInJavaHome() const
{
std::string command = "";
char* p = getenv("JAVA_HOME");
if ( p == nullptr )
{
return FilePath();
}
FilePath javaPath(std::string(p) + "/bin/java");
if ( !javaPath.empty() && javaPath.exists() )
{
return javaPath;
}
return FilePath();
}
bool JavaPathDetectorLinux::checkVersion(const FilePath& path) const
{
std::string command = path.str() + " -version";
std::string output = utility::executeProcess(command.c_str());
return output.find(m_javaVersion) != std::string::npos;
}
std::vector<FilePath> JavaPathDetectorLinux::getPaths() const
{
std::vector<FilePath> paths;
FilePath p = getJavaInPath();
if( !p.empty() )
{
paths.push_back(p);
}
p = getJavaInJavaHome();
if( !p.empty() )
{
paths.push_back(p);
}
// some default paths for java
paths.push_back(FilePath("/etc/alternatives/java"));
paths.push_back(FilePath("/usr/lib/jvm/default/bin/java"));
paths.push_back(FilePath("/usr/lib/jvm/java-openjdk/bin/java"));
for ( FilePath path : paths )
{
if (checkVersion(path))
{
FilePath absoluteJavaPath = readLink(path);
FilePath jvmLibrary = getFilePathRelativeToJavaExecutable(absoluteJavaPath);
if (jvmLibrary.exists())
{
std::vector<FilePath> foundPath = { jvmLibrary };
return foundPath;
}
}
}
return std::vector<FilePath>();
}
@@ -0,0 +1,24 @@
#ifndef JAVA_PATH_DETECTOR_LINUX_H
#define JAVA_PATH_DETECTOR_LINUX_H
#include "utility/path_detector/java_runtime/JavaPathDetector.h"
class JavaPathDetectorLinux
: public JavaPathDetector
{
public:
JavaPathDetectorLinux(const std::string javaVersion);
virtual ~JavaPathDetectorLinux();
virtual std::vector<FilePath> getPaths() const;
private:
FilePath getJavaInPath() const;
FilePath readLink(const FilePath& path) const;
FilePath getJavaInJavaHome() const;
bool checkVersion(const FilePath& path) const;
FilePath getFilePathRelativeToJavaExecutable(FilePath& javaExecutablePath) const;
};
#endif // JAVA_PATH_DETECTOR_LINUX_H
@@ -15,19 +15,24 @@ JavaPathDetectorMac::~JavaPathDetectorMac()
std::vector<FilePath> JavaPathDetectorMac::getPaths() const
{
std::vector<FilePath> paths;
FilePath javaPath;
std::string command = "/usr/libexec/java_home";
std::string output = utility::executeProcess(command.c_str());
if (output.size())
{
output = utility::trim(output);
javaPath = FilePath(utility::trim(output) + "/jre/lib/server/libjvm.dylib");
}
FilePath javaPath(output);
if (!javaPath.empty() && javaPath.exists())
{
paths.push_back(javaPath);
}
if (!javaPath.exists())
{
javaPath = FilePath("/usr/lib/libjvm.dylib");
}
if (javaPath.exists())
{
paths.push_back(javaPath);
}
return paths;
@@ -28,7 +28,7 @@ std::vector<FilePath> JavaPathDetectorWindows::getPaths() const
std::vector<FilePath> paths;
if (path.exists())
{
paths.push_back(path.parentDirectory());
paths.push_back(path);
}
return paths;
}
+2
View File
@@ -1,6 +1,7 @@
#include "utility/utilityApp.h"
#include <QProcess>
#include "utility/utilityString.h"
std::string utility::executeProcess(const char *cmd)
{
@@ -10,6 +11,7 @@ std::string utility::executeProcess(const char *cmd)
process.waitForFinished();
std::string processoutput = process.readAll().toStdString();
process.close();
processoutput = utility::trim(processoutput);
return processoutput;
}
+3 -1
View File
@@ -1189,6 +1189,7 @@ private:
{
if (!JavaEnvironmentFactory::getInstance())
{
std::string errorString;
#ifdef _WIN32
const std::string separator = ";";
#else
@@ -1202,7 +1203,8 @@ private:
"../app/data/java/javassist-3.19.0-GA.jar" + separator +
"../app/data/java/java-symbol-solver-core.jar" + separator +
"../app/data/java/java-symbol-solver-logic.jar" + separator +
"../app/data/java/java-symbol-solver-model.jar" + separator
"../app/data/java/java-symbol-solver-model.jar" + separator,
errorString
);
}
}