/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
for (bool bEof = true;; bEof = false)
{ if (m_nIndex == m_nSize)
{
sal_uInt64 nRead = 0; switch (osl_readFile(
m_aGuard.getHandle(), m_aBuffer, sizeof(m_aBuffer), &nRead))
{ case osl_File_E_PIPE: //HACK! for windows
nRead = 0;
[[fallthrough]]; case osl_File_E_None: if (nRead == 0)
{
m_bLf = false; return bEof ? RESULT_EOF : RESULT_OK;
}
m_nIndex = 0;
m_nSize = static_cast< int >(nRead); break; case osl_File_E_INTR: continue;
default: return RESULT_ERROR;
}
}
if (m_bLf && m_aBuffer[m_nIndex] == 0x0A)
++m_nIndex;
m_bLf = false;
int nStart = m_nIndex; while (m_nIndex != m_nSize) switch (m_aBuffer[m_nIndex++])
{ case 0x0D:
m_bLf = true;
[[fallthrough]]; case 0x0A:
*pLine += std::string_view(m_aBuffer + nStart,
m_nIndex - 1 - nStart); //TODO! check for overflow, and not very efficient return RESULT_OK;
}
*pLine += std::string_view(m_aBuffer + nStart, m_nIndex - nStart); //TODO! check for overflow, and not very efficient
}
}
namespace {
class AsynchReader: public salhelper::Thread
{
size_t m_nDataSize;
std::unique_ptr<char[]> m_arData;
FileHandleGuard m_aGuard;
virtual ~AsynchReader() override {}
void execute() override; public:
explicit AsynchReader(oslFileHandle & rHandle);
/** only call this function after this thread has finished.
That is, call join on this instance and then call getData.
void AsynchReader::execute()
{ const sal_uInt64 BUFFER_SIZE = 4096; char aBuffer[BUFFER_SIZE]; while (true)
{
sal_uInt64 nRead; //the function blocks until something could be read or the pipe closed. switch (osl_readFile(
m_aGuard.getHandle(), aBuffer, BUFFER_SIZE, &nRead))
{ case osl_File_E_PIPE: //HACK! for windows
nRead = 0;
[[fallthrough]]; case osl_File_E_None: break; default: return;
}
if (nRead == 0)
{ break;
} elseif (nRead <= BUFFER_SIZE)
{ //Save the data we have in m_arData into a temporary array
std::unique_ptr<char[]> arTmp( newchar[m_nDataSize]); if (m_nDataSize != 0) {
memcpy(arTmp.get(), m_arData.get(), m_nDataSize);
} //Enlarge m_arData to hold the newly read data
m_arData.reset(newchar[static_cast<size_t>(m_nDataSize + nRead)]); //Copy back the data that was already in m_arData
memcpy(m_arData.get(), arTmp.get(), m_nDataSize); //Add the newly read data to m_arData
memcpy(m_arData.get() + m_nDataSize, aBuffer, static_cast<size_t>(nRead));
m_nDataSize += static_cast<size_t>(nRead);
}
}
}
OSL_ASSERT(!exePath.isEmpty());
OUString usStartDir; //We need to set the CLASSPATH in case the office is started from //a different directory. The JREProperties.class is expected to reside //next to the plugin, except on macOS where it is in ../Resources/java relative //to the plugin.
OUString sThisLib; if (!osl_getModuleURLFromAddress(reinterpret_cast<void *>(&getJavaProps),
& sThisLib.pData))
{ returnfalse;
}
sThisLib = getDirFromFile(sThisLib);
OUString sClassPath; if (osl_getSystemPathFromFileURL(sThisLib.pData, & sClassPath.pData)
!= osl_File_E_None)
{ returnfalse;
}
#ifdef MACOSX #ifdefined __x86_64__ if (!JvmfwkUtil_isLoadableJVM(exePath)) returnfalse; #endif if (sClassPath.endsWith("/"))
sClassPath += "../Resources/java/"; else
sClassPath += "/../Resources/java"; #endif
// Iterate over all subkeys of HKEY_LOCAL_MACHINE\Software\JavaSoft\Java Runtime Environment while (RegEnumKeyExW(hRoot, dwIndex, bufVersion, &nNameLen, nullptr, nullptr, nullptr, &fileTime) != ERROR_NO_MORE_ITEMS)
{
HKEY hKey; // Open a Java Runtime Environment sub key, e.g. "1.4.0" if (RegOpenKeyExW(hRoot, bufVersion, 0, KEY_QUERY_VALUE, &hKey) == ERROR_SUCCESS)
{
DWORD dwType;
DWORD dwTmpPathLen= 0; // Get the path to the JavaHome every JRE entry // Find out how long the string for JavaHome is and allocate memory to hold the path if( RegQueryValueExW(hKey, L"JavaHome", nullptr, &dwType, nullptr, &dwTmpPathLen)== ERROR_SUCCESS)
{ unsignedchar* szTmpPath= static_cast<unsignedchar *>(malloc(dwTmpPathLen+sizeof(sal_Unicode)));
assert(szTmpPath && "Don't handle OOM conditions"); // According to https://msdn.microsoft.com/en-us/ms724911, the application should ensure // that the string is properly terminated before using it for (DWORD i = 0; i < sizeof(sal_Unicode); ++i)
szTmpPath[dwTmpPathLen + i] = 0; // Get the path for the runtime lib if(RegQueryValueExW(hKey, L"JavaHome", nullptr, &dwType, szTmpPath, &dwTmpPathLen) == ERROR_SUCCESS)
{ // There can be several version entries referring with the same JavaHome,e.g 1.4 and 1.4.1
OUString usHome(reinterpret_cast<sal_Unicode*>(szTmpPath)); // check if there is already an entry with the same JavaHomeruntime lib // if so, we use the one with the more accurate version
OUString usHomeUrl; if (osl_getFileURLFromSystemPath(usHome.pData, & usHomeUrl.pData) ==
osl_File_E_None)
{ bool bAppend= true; //iterate over the vector with java home strings for (autoconst& javaHome : vecJavaHome)
{ if(usHomeUrl.equals(javaHome))
{
bAppend= false; break;
}
} // Save the home dir if(bAppend)
{
vecJavaHome.push_back(usHomeUrl);
}
}
}
free( szTmpPath);
RegCloseKey(hKey);
}
}
dwIndex ++;
nNameLen = BUFFSIZE;
}
RegCloseKey(hRoot);
} returntrue;
}
vecJavaHome.clear(); if (getJavaInfoFromRegistry(L"Software\\JavaSoft\\JDK", vecJavaHome)) { for (autoconst & javaHome: vecJavaHome) {
getAndAddJREInfoByPath(javaHome, allInfos, addedInfos);
}
}
vecJavaHome.clear(); if (getJavaInfoFromRegistry(L"Software\\JavaSoft\\JRE", vecJavaHome)) { for (autoconst & javaHome: vecJavaHome) {
getAndAddJREInfoByPath(javaHome, allInfos, addedInfos);
}
}
}
#endif// _WIN32
void bubbleSortVersion(std::vector<rtl::Reference<VendorBase> >& vec)
{ if(vec.empty()) return; int size= vec.size() - 1; int cIter= 0; // sort for version for(int i= 0; i < size; i++)
{ for(int j= size; j > 0 + cIter; j--)
{
rtl::Reference<VendorBase>& cur= vec.at(j);
rtl::Reference<VendorBase>& next= vec.at(j-1);
int nCmp = 0; // comparing invalid SunVersion s is possible, they will be less than a // valid version
//check if version of current is recognized, by comparing it with itself try
{
(void)cur->compareVersions(cur->getVersion());
} catch (MalformedVersionException &)
{
nCmp = -1; // current < next
} //The version of cur is valid, now compare with the second version if (nCmp == 0)
{ try
{
nCmp = cur->compareVersions(next->getVersion());
} catch (MalformedVersionException & )
{ //The second version is invalid, therefore it regards less.
nCmp = 1;
}
} if(nCmp == 1) // cur > next
{
std::swap(cur, next);
}
}
++cIter;
}
}
#ifdefined(_WIN32) // Get Javas from the registry
addJavaInfoFromWinReg(allInfos, addedInfos); #endif// _WIN32
if (checkJavaHomeAndPath) {
addJavaInfoFromJavaHome(allInfos, addedInfos); //this function should be called after addJavaInfosDirScan. //Otherwise in SDKs Java may be started twice
addJavaInfosFromPath(allInfos, addedInfos);
}
std::vector<OUString> getVectorFromCharArray(charconst * const * ar, int size)
{
std::vector<OUString> vec; for( int i = 0; i < size; i++)
{
OUString s(ar[i], strlen(ar[i]), RTL_TEXTENCODING_UTF8);
vec.push_back(s);
} return vec;
}
/** Checks if the path is a directory. Links are resolved. In case of an error the returned string has the length 0. Otherwise the returned string is the "resolved" file URL.
*/ static OUString resolveDirPath(const OUString & path)
{
OUString ret;
salhelper::LinkResolver aResolver(osl_FileStatus_Mask_Type |
osl_FileStatus_Mask_FileURL); if (aResolver.fetchFileStatus(path) == osl::FileBase::E_None)
{ //check if this is a directory if (aResolver.m_aStatus.getFileType() == FileStatus::Directory)
{ #ifndef JVM_ONE_PATH_CHECK
ret = aResolver.m_aStatus.getFileURL(); #else
ret = path; #endif
}
} return ret;
} /** Checks if the path is a file. If it is a link to a file than it is resolved.
*/ static OUString resolveFilePath(const OUString & path)
{
OUString ret;
salhelper::LinkResolver aResolver(osl_FileStatus_Mask_Type |
osl_FileStatus_Mask_FileURL); if (aResolver.fetchFileStatus(path) == osl::FileBase::E_None)
{ //check if this is a file if (aResolver.m_aStatus.getFileType() == FileStatus::Regular)
{ #ifndef JVM_ONE_PATH_CHECK
ret = aResolver.m_aStatus.getFileURL(); #else
ret = path; #endif
}
} return ret;
}
OUString sResolvedDir = resolveDirPath(path); // If this path is invalid then there is no chance to find a JRE here if (sResolvedDir.isEmpty())
{ return nullptr;
}
//check if the directory path is good, that is a JRE was already recognized. //Then we need not detect it again //For example, a sun JDK contains <jdk>/bin/java and <jdk>/jre/bin/java. //When <jdk>/bin/java has been found then we need not find <jdk>/jre/bin/java. //Otherwise we would execute java two times for every JDK found. auto entry2 = find_if(mapJREs.cbegin(), mapJREs.cend(),
SameOrSubDirJREMap(sResolvedDir)); if (entry2 != mapJREs.end())
{
JFW_TRACE2("JRE found again (detected before): " << sResolvedDir); return entry2->second;
}
bool bBreak = false; for (autoconst& looppath : vecPaths)
{ //if the path is a link, then resolve it //check if the executable exists at all
//path can be only "file:///". Then do not append a '/' //sizeof counts the terminating 0
OUString sFullPath; if (path.getLength() == sizeof("file:///") - 1)
sFullPath = sResolvedDir + looppath; else
sFullPath = sResolvedDir + "/" + looppath;
sFilePath = resolveFilePath(sFullPath);
if (sFilePath.isEmpty())
{ //The file path (to java exe) is not valid auto ifull = find(vecBadPaths.cbegin(), vecBadPaths.cend(), sFullPath); if (ifull == vecBadPaths.cend())
{
vecBadPaths.push_back(sFullPath);
} continue;
}
auto ifile = find(vecBadPaths.cbegin(), vecBadPaths.cend(), sFilePath); if (ifile != vecBadPaths.cend())
{ continue;
}
auto entry = mapJREs.find(sFilePath); if (entry != mapJREs.end())
{
JFW_TRACE2("JRE found again (detected before): " << sFilePath);
return entry->second;
}
bool bProcessRun= false; if (!getJavaProps(sFilePath, #ifdef JVM_ONE_PATH_CHECK
sResolvedDir, #endif
props, & bProcessRun))
{ //The java executable could not be run or the system properties //could not be retrieved. We can assume that this java is corrupt.
vecBadPaths.push_back(sFilePath); //If there was a java executable, that could be run but we did not get //the system properties, then we also assume that the whole Java installation //does not work. In a jdk there are two executables. One in jdk/bin and the other //in jdk/jre/bin. We do not search any further, because we assume that if one java //does not work then the other does not work as well. This saves us to run java //again which is quite costly. if (bProcessRun)
{ // 1.3.1 special treatment: jdk/bin/java and /jdk/jre/bin/java are links to //a script, named .java_wrapper. The script starts jdk/bin/sparc/native_threads/java //or jdk/jre/bin/sparc/native_threads/java. The script uses the name with which it was //invoked to build the path to the executable. It we start the script directly as .java_wrapper //then it tries to start a jdk/.../native_threads/.java_wrapper. Therefore the link, which //is named java, must be used to start the script.
getJavaProps(sFullPath, #ifdef JVM_ONE_PATH_CHECK
sResolvedDir, #endif
props, & bProcessRun); // Either we found a working 1.3.1 // Or the java is broken. In both cases we stop searching under this "root" directory
bBreak = true; break;
} //sFilePath is no working java executable. We continue with another possible //path. else
{ continue;
}
} //sFilePath is a java and we could get the system properties. We proceed with this //java. else
{
bBreak = true; break;
}
} if (bBreak) break;
}
if (props.empty())
{ return rtl::Reference<VendorBase>();
}
//find java.vendor property
OUString sVendorName;
for (autoconst& prop : props)
{ if (prop.first == "java.vendor")
{
sVendorName = prop.second; break;
}
}
auto knownVendor = false; if (!sVendorName.isEmpty())
{ //find the creator func for the respective vendor name for ( sal_Int32 c = 0;
gVendorMap[c].sVendorName != nullptr; ++c )
{
OUString sNameMap(gVendorMap[c].sVendorName, strlen(gVendorMap[c].sVendorName),
RTL_TEXTENCODING_ASCII_US); if (sNameMap == sVendorName)
{
ret = createInstance(gVendorMap[c].createFunc, props);
knownVendor = true; break;
}
}
} // For unknown vendors, try SunInfo as fallback: if (!knownVendor)
{
ret = createInstance(SunInfo::createInstance, props);
} if (!ret.is())
{
vecBadPaths.push_back(sFilePath);
} else
{
JFW_TRACE2("Found JRE: " << sResolvedDir << " at: " << path);
void addJavaInfoFromJavaHome(
std::vector<rtl::Reference<VendorBase>> & allInfos,
std::vector<rtl::Reference<VendorBase>> & addedInfos)
{ #if !defined JVM_ONE_PATH_CHECK // Get Java from JAVA_HOME environment
// Note that on macOS is it not normal at all to have a JAVA_HOME environment // variable. We set it in our build environment for build-time programs, though, // so it is set when running unit tests that involve Java functionality. (Which affects // at least CppunitTest_dbaccess_dialog_save, too, and not only the JunitTest ones.)
OUString sHome; if (osl_getEnvironment(u"JAVA_HOME"_ustr.pData, &sHome.pData) == osl_Process_E_None
&& !sHome.isEmpty())
{
OUString sHomeUrl; if(File::getFileURLFromSystemPath(sHome, sHomeUrl) == File::E_None)
{
getAndAddJREInfoByPath(sHomeUrl, allInfos, addedInfos);
}
} #endif
}
bool makeDriveLetterSame(OUString * fileURL)
{ bool ret = false;
DirectoryItem item; if (DirectoryItem::get(*fileURL, item) == File::E_None)
{
FileStatus status(osl_FileStatus_Mask_FileURL); if (item.getFileStatus(status) == File::E_None)
{
*fileURL = status.getFileURL();
ret = true;
}
} return ret;
}
JFW_ENSURE(errNext == File::E_None || errNext == File::E_NOENT, "[Java framework] sunjavaplugin: " "Error while iterating over contents of "
+ usDir2 + ". Osl file error: "
+ OUString::number(openErr));
} else
{ //usr/java //When we look directly into a dir like /usr, /usr/lib, etc. then we only //look for certain java directories, such as jre, jdk, etc. We do not want //to examine the whole directory because of performance reasons.
DirectoryItem item2; if(DirectoryItem::get(usDir2, item2) == File::E_None)
{ for( int k= 0; k < cJavaNames; k++)
{ // /usr/java/j2re1.4.0
OUString usDir3(usDir2 + arNames[k]);