-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathjvmlauncher.cpp
459 lines (402 loc) · 16.1 KB
/
jvmlauncher.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2009-2012 JRuby Team (www.jruby.org).
* Copyright 1997-2008 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2008 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*
* Author: Tomas Holy
*/
#include "jvmlauncher.h"
#include <cassert>
using namespace std;
const char *JvmLauncher::JDK_KEY = "Software\\JavaSoft\\Java Development Kit";
const char *JvmLauncher::JRE_KEY = "Software\\JavaSoft\\Java Runtime Environment";
const char *JvmLauncher::CUR_VERSION_NAME = "CurrentVersion";
const char *JvmLauncher::JAVA_HOME_NAME = "JavaHome";
const char *JvmLauncher::JAVA_BIN_DIR = "\\bin";
const char *JvmLauncher::JAVA_EXE_FILE = "\\bin\\java.exe";
const char *JvmLauncher::JAVAW_EXE_FILE = "\\bin\\javaw.exe";
const char *JvmLauncher::JAVA_CLIENT_DLL_FILE = "\\bin\\client\\jvm.dll";
const char *JvmLauncher::JAVA_SERVER_DLL_FILE = "\\bin\\server\\jvm.dll";
const char *JvmLauncher::JAVA_JRE_PREFIX = "\\jre";
const char *JvmLauncher::JNI_CREATEVM_FUNC = "JNI_CreateJavaVM";
JvmLauncher::JvmLauncher()
: suppressConsole(false) {
}
JvmLauncher::JvmLauncher(const JvmLauncher& orig) {
}
JvmLauncher::~JvmLauncher() {
}
void JvmLauncher::setJavaCmd(const string cmdPath) {
javaExePath = cmdPath;
javaPath = "";
javawExePath = javaPath;
javaClientDllPath = javaPath;
javaServerDllPath = javaPath;
}
bool JvmLauncher::checkJava(std::string &path, const char *prefix) {
assert(prefix);
logMsg("checkJava('%s', '%s')", path.c_str(), prefix);
if (*path.rbegin() == '\\') {
path.erase(path.length() - 1, 1);
}
javaExePath = path + prefix + JAVA_EXE_FILE;
javawExePath = path + prefix + JAVAW_EXE_FILE;
javaClientDllPath = path + prefix + JAVA_CLIENT_DLL_FILE;
javaServerDllPath = path + prefix + JAVA_SERVER_DLL_FILE;
if (!fileExists(javaClientDllPath.c_str())) {
javaClientDllPath = "";
}
if (!fileExists(javaServerDllPath.c_str())) {
javaServerDllPath = "";
}
javaBinPath = path + prefix + JAVA_BIN_DIR;
if (fileExists(javaExePath.c_str()) || !javaClientDllPath.empty() || !javaServerDllPath.empty()) {
if (!fileExists(javawExePath.c_str())) {
logMsg("javaw.exe not exists, forcing java.exe");
javawExePath = javaExePath;
}
javaPath = path;
return true;
}
javaBinPath.clear();
javaExePath.clear();
javawExePath.clear();
javaClientDllPath.clear();
javaServerDllPath.clear();
return false;
}
bool JvmLauncher::initialize(const char *javaPathOrMinVersion) {
logMsg("JvmLauncher::initialize()\n\tjavaPathOrMinVersion: %s", javaPathOrMinVersion);
assert(javaPathOrMinVersion);
std::string pathOrVersion(javaPathOrMinVersion);
if (isVersionString(javaPathOrMinVersion)) {
return findJava(javaPathOrMinVersion);
} else {
return (checkJava(pathOrVersion, JAVA_JRE_PREFIX) || checkJava(pathOrVersion, ""));
}
}
bool JvmLauncher::getJavaPath(string &path) {
logMsg("JvmLauncher::getJavaPath()");
path = javaPath;
return !javaPath.empty();
}
bool JvmLauncher::start(const char *mainClassName, list<string> args, list<string> options, bool &separateProcess, DWORD *retCode) {
assert(mainClassName);
logMsg("JvmLauncher::start()\n\tmainClassName: %s\n\tseparateProcess: %s",
mainClassName, separateProcess ? "true" : "false");
logMsg(" args:");
for (list<string>::iterator it = args.begin(); it != args.end(); ++it) {
logMsg("\t%s", it->c_str());
}
logMsg(" options:");
for (list<string>::iterator it = options.begin(); it != options.end(); ++it) {
logMsg("\t%s", it->c_str());
}
if (javaExePath.empty() && javaClientDllPath.empty() && javaServerDllPath.empty()) {
// try to find out any java installed (check the registry)
if (!initialize("")) {
return false;
}
}
if (!separateProcess) {
// both client/server found, check option which should be used
if (!javaClientDllPath.empty() && !javaServerDllPath.empty()) {
// By default, load client VM. Load server VM only if explicitly asked.
javaDllPath = findServerOption(options) ? javaServerDllPath: javaClientDllPath;
} else {
javaDllPath = javaClientDllPath.empty() ? javaServerDllPath : javaClientDllPath;
}
// it is necessary to absolutize dll path because current dir has to be
// temporarily changed for dll loading
char absoluteJavaDllPath[MAX_PATH] = "";
strncpy(absoluteJavaDllPath, javaDllPath.c_str(), MAX_PATH);
normalizePath(absoluteJavaDllPath, MAX_PATH);
javaDllPath = absoluteJavaDllPath;
logMsg("Java DLL path: %s", javaDllPath.c_str());
if (!canLoadJavaDll()) {
logMsg("Falling back to running Java in a separate process; DLL cannot be loaded (64-bit DLL?).");
separateProcess = true;
}
}
return separateProcess ? startOutProcJvm(mainClassName, args, options, retCode)
: startInProcJvm(mainClassName, args, options);
}
bool JvmLauncher::findServerOption(list<string> &options) {
for (list<string>::iterator it = options.begin(); it != options.end(); ++it) {
if (*it == "-server") {
return true;
}
}
return false;
}
bool JvmLauncher::canLoadJavaDll() {
// be prepared for stupid placement of msvcr71.dll in java installation
// (in java 1.6/1.7 jvm.dll is dynamically linked to msvcr71.dll which si placed
// in bin directory)
PrepareDllPath prepare(javaBinPath.c_str());
HMODULE hDll = LoadLibrary(javaDllPath.c_str());
if (hDll) {
FreeLibrary(hDll);
return true;
}
logErr(true, false, "Cannot load %s.", javaDllPath.c_str());
return false;
}
bool JvmLauncher::isVersionString(const char *str) {
char *end = 0;
strtod(str, &end);
return *end == '\0';
}
bool JvmLauncher::startInProcJvm(const char *mainClassName, std::list<std::string> mbcs_args, std::list<std::string> mbcs_options) {
std::list<std::string> args;
for (std::list<std::string>::iterator it = mbcs_args.begin(); it != mbcs_args.end(); ++it) {
wchar_t wstr[2048];
UINT cp = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
MultiByteToWideChar(cp, 0, it->c_str(), -1, wstr, sizeof(wstr) / sizeof(wchar_t));
int mb_size = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL);
char *mbstr = (char*)malloc(mb_size);
WideCharToMultiByte(CP_UTF8, 0, wstr, -1, mbstr, mb_size, NULL, NULL);
args.push_back(mbstr);
}
std::list<std::string> options;
for (std::list<std::string>::iterator it = mbcs_options.begin(); it != mbcs_options.end(); ++it) {
wchar_t wstr[2048];
UINT cp = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
MultiByteToWideChar(cp, 0, it->c_str(), -1, wstr, sizeof(wstr) / sizeof(wchar_t));
int mb_size = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL);
char *mbstr = (char*)malloc(mb_size);
WideCharToMultiByte(CP_UTF8, 0, wstr, -1, mbstr, mb_size, NULL, NULL);
options.push_back(mbstr);
}
class Jvm {
public:
Jvm(JvmLauncher *jvmLauncher)
: hDll(0)
, jvm(0)
, env(0)
, jvmOptions(0)
, jvmLauncher(jvmLauncher)
{
}
~Jvm() {
if (env && env->ExceptionOccurred()) {
env->ExceptionDescribe();
}
if (jvm) {
logMsg("Destroying JVM");
jvm->DestroyJavaVM();
}
if (jvmOptions) {
delete[] jvmOptions;
}
if (hDll) {
FreeLibrary(hDll);
}
}
bool init(list<string> options) {
logMsg("JvmLauncher::Jvm::init()");
logMsg("LoadLibrary(\"%s\")", jvmLauncher->javaDllPath.c_str());
{
PrepareDllPath prepare(jvmLauncher->javaBinPath.c_str());
hDll = LoadLibrary(jvmLauncher->javaDllPath.c_str());
if (!hDll) {
logErr(true, true, "Cannot load %s.", jvmLauncher->javaDllPath.c_str());
return false;
}
}
CreateJavaVM createJavaVM = (CreateJavaVM) GetProcAddress(hDll, JNI_CREATEVM_FUNC);
if (!createJavaVM) {
logErr(true, true, "GetProcAddress for %s failed.", JNI_CREATEVM_FUNC);
return false;
}
// Explicity remove -server and -client options, they are not
// needed, since we invoke JVM in-process and already know
// which DLL to use.
options.remove("-server");
options.remove("-client");
logMsg("JVM options:");
jvmOptions = new JavaVMOption[options.size()];
int i = 0;
for (list<string>::iterator it = options.begin(); it != options.end(); ++it, ++i) {
string &option = *it;
logMsg("\t%s", option.c_str());
jvmOptions[i].optionString = (char *) option.c_str();
jvmOptions[i].extraInfo = 0;
}
JavaVMInitArgs jvmArgs;
jvmArgs.options = jvmOptions;
jvmArgs.nOptions = options.size();
jvmArgs.version = JNI_VERSION_1_4;
jvmArgs.ignoreUnrecognized = JNI_FALSE;
logMsg("Creating JVM...");
if (createJavaVM(&jvm, &env, &jvmArgs) < 0) {
logErr(false, true, "JVM creation failed");
return false;
}
logMsg("JVM created.");
return true;
}
typedef jint (CALLBACK *CreateJavaVM)(JavaVM **jvm, JNIEnv **env, void *args);
HMODULE hDll;
JavaVM *jvm;
JNIEnv *env;
JavaVMOption *jvmOptions;
JvmLauncher *jvmLauncher;
};
Jvm jvm(this);
if (!jvm.init(options)) {
return false;
}
jclass mainClass = jvm.env->FindClass(mainClassName);
if (!mainClass) {
logErr(false, true, "Cannot find class %s.", mainClassName);
return false;
}
jmethodID mainMethod = jvm.env->GetStaticMethodID(mainClass, "main", "([Ljava/lang/String;)V");
if (!mainMethod) {
logErr(false, true, "Cannot get main method.");
return false;
}
jclass jclassString = jvm.env->FindClass("java/lang/String");
if (!jclassString) {
logErr(false, true, "Cannot find java/lang/String class");
return false;
}
jstring jstringArg = jvm.env->NewStringUTF("");
if (!jstringArg) {
logErr(false, true, "NewStringUTF() failed");
return false;
}
jobjectArray mainArgs = jvm.env->NewObjectArray(args.size(), jclassString, jstringArg);
if (!mainArgs) {
logErr(false, true, "NewObjectArray() failed");
return false;
}
int i = 0;
for (list<string>::iterator it = args.begin(); it != args.end(); ++it, ++i) {
string &arg = *it;
jstring jstringArg = jvm.env->NewStringUTF(arg.c_str());
if (!jstringArg) {
logErr(false, true, "NewStringUTF() failed");
return false;
}
jvm.env->SetObjectArrayElement(mainArgs, i, jstringArg);
}
jvm.env->CallStaticVoidMethod(mainClass, mainMethod, mainArgs);
return true;
}
bool JvmLauncher::startOutProcJvm(const char *mainClassName, std::list<std::string> args, std::list<std::string> options, DWORD *retCode) {
string cmdLine = '\"' + (suppressConsole ? javawExePath : javaExePath) + '\"';
cmdLine.reserve(32*1024);
for (list<string>::iterator it = options.begin(); it != options.end(); ++it) {
cmdLine += " \"";
cmdLine += *it;
cmdLine += "\"";
}
// mainClass and args
cmdLine += ' ';
cmdLine += mainClassName;
for (list<string>::iterator it = args.begin(); it != args.end(); ++it) {
if (javaClientDllPath.empty() && *it == "-client") {
logMsg("Removing -client option, client java dll not found.");
// remove client parameter, no client java found
continue;
}
cmdLine += " \"";
cmdLine += *it;
cmdLine += "\"";
}
logMsg("Command line:\n%s", cmdLine.c_str());
if (cmdLine.size() >= 32*1024) {
logErr(false, true, "Command line is too long. Length: %u. Maximum length: %u.", cmdLine.c_str(), 32*1024);
return false;
}
STARTUPINFO si = {0};
si.cb = sizeof (STARTUPINFO);
PROCESS_INFORMATION pi = {0};
char cmdLineStr[32*1024] = "";
strcpy(cmdLineStr, cmdLine.c_str());
if (!CreateProcess(NULL, cmdLineStr, NULL, NULL, TRUE, CREATE_SUSPENDED, NULL, NULL, &si, &pi)) {
logErr(true, true, "Failed to create process");
return false;
}
// disable Ctrl-C handling in the parent process
if (!SetConsoleCtrlHandler(NULL, TRUE)) {
logErr(true, true, "Failed to disable Ctrl-C handling; Ctrl-C may behave oddly: %d", GetLastError());
}
disableFolderVirtualization(pi.hProcess);
ResumeThread(pi.hThread);
WaitForSingleObject(pi.hProcess, INFINITE);
if (retCode) {
GetExitCodeProcess(pi.hProcess, retCode);
}
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
return true;
}
bool JvmLauncher::findJava(const char *minJavaVersion) {
if (findJava(JDK_KEY, JAVA_JRE_PREFIX, minJavaVersion)) {
return true;
}
if (findJava(JRE_KEY, "", minJavaVersion)) {
return true;
}
javaPath = "";
javaExePath = "";
javaClientDllPath = "";
javaServerDllPath = "";
javaBinPath = "";
return false;
}
bool JvmLauncher::findJava(const char *javaKey, const char *prefix, const char *minJavaVersion) {
logMsg("JvmLauncher::findJava()\n\tjavaKey: %s\n\tprefix: %s\n\tminJavaVersion: %s", javaKey, prefix, minJavaVersion);
string value;
if (getStringFromRegistry(HKEY_LOCAL_MACHINE, javaKey, CUR_VERSION_NAME, value)) {
if (value >= minJavaVersion) {
string path;
if (getStringFromRegistry(HKEY_LOCAL_MACHINE, (string(javaKey) + "\\" + value).c_str(), JAVA_HOME_NAME, path)) {
if (*path.rbegin() == '\\') {
path.erase(path.length() - 1, 1);
}
return checkJava(path, prefix);
}
}
}
return false;
}