blob: 9221ab58f99cd87606b47fcee5402f9609a26f8b [file] [log] [blame]
J. Duke319a3b92007-12-01 00:00:00 +00001/*
2 * Copyright 2003-2007 Sun Microsystems, Inc. All Rights Reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Sun designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Sun in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
22 * CA 95054 USA or visit www.sun.com if you need additional information or
23 * have any questions.
24 */
25
26/*
27 * Copyright 2003 Wily Technology, Inc.
28 */
29
30#include <string.h>
31#include <stdlib.h>
32
33#include "jni.h"
34
35#include "Utilities.h"
36#include "JPLISAssert.h"
37#include "JPLISAgent.h"
38#include "JavaExceptions.h"
39
40#include "EncodingSupport.h"
41#include "FileSystemSupport.h"
42#include "JarFacade.h"
43#include "PathCharsValidator.h"
44
45/**
46 * This module contains the direct interface points with the JVMTI.
47 * The OnLoad handler is here, along with the various event handlers.
48 */
49
50static int
51appendClassPath(JPLISAgent* agent,
52 const char* jarfile);
53
54static void
55appendBootClassPath(JPLISAgent* agent,
56 const char* jarfile,
57 const char* pathList);
58
59
60/*
61 * Parse -javaagent tail, of the form name[=options], into name
62 * and options. Returned values are heap allocated and options maybe
63 * NULL. Returns 0 if parse succeeds, -1 if allocation fails.
64 */
65static int
66parseArgumentTail(char* tail, char** name, char** options) {
67 int len;
68 char* pos;
69
70 pos = strchr(tail, '=');
71 len = (pos == NULL) ? (int)strlen(tail) : (int)(pos - tail);
72
73 *name = (char*)malloc(len+1);
74 if (*name == NULL) {
75 return -1;
76 }
77 memcpy(*name, tail, len);
78 (*name)[len] = '\0';
79
80 if (pos == NULL) {
81 *options = NULL;
82 } else {
83 char * str = (char*)malloc( (int)strlen(pos + 1) + 1 );
84 if (str == NULL) {
85 free(*name);
86 return -1;
87 }
88 strcpy(str, pos +1);
89 *options = str;
90 }
91 return 0;
92}
93
94/*
95 * Get the value of an attribute in an attribute list. Returns NULL
96 * if attribute not found.
97 */
98jboolean
99getBooleanAttribute(const jarAttribute* attributes, const char* name) {
100 char* attributeValue = getAttribute(attributes, name);
101 return attributeValue != NULL && strcasecmp(attributeValue, "true") == 0;
102}
103
104/*
105 * Parse any capability settings in the JAR manifest and
106 * convert them to JVM TI capabilities.
107 */
108void
109convertCapabilityAtrributes(const jarAttribute* attributes, JPLISAgent* agent) {
110 /* set redefineClasses capability */
111 if (getBooleanAttribute(attributes, "Can-Redefine-Classes")) {
112 addRedefineClassesCapability(agent);
113 }
114
115 /* create an environment which has the retransformClasses capability */
116 if (getBooleanAttribute(attributes, "Can-Retransform-Classes")) {
117 retransformableEnvironment(agent);
118 }
119
120 /* set setNativeMethodPrefix capability */
121 if (getBooleanAttribute(attributes, "Can-Set-Native-Method-Prefix")) {
122 addNativeMethodPrefixCapability(agent);
123 }
124
125 /* for retransformClasses testing, set capability to use original method order */
126 if (getBooleanAttribute(attributes, "Can-Maintain-Original-Method-Order")) {
127 addOriginalMethodOrderCapability(agent);
128 }
129}
130
131/*
132 * This will be called once for every -javaagent on the command line.
133 * Each call to Agent_OnLoad will create its own agent and agent data.
134 *
135 * The argument tail string provided to Agent_OnLoad will be of form
136 * <jarfile>[=<options>]. The tail string is split into the jarfile and
137 * options components. The jarfile manifest is parsed and the value of the
138 * Premain-Class attribute will become the agent's premain class. The jar
139 * file is then added to the system class path, and if the Boot-Class-Path
140 * attribute is present then all relative URLs in the value are processed
141 * to create boot class path segments to append to the boot class path.
142 */
143JNIEXPORT jint JNICALL
144Agent_OnLoad(JavaVM *vm, char *tail, void * reserved) {
145 JPLISInitializationError initerror = JPLIS_INIT_ERROR_NONE;
146 jint result = JNI_OK;
147 JPLISAgent * agent = NULL;
148
149 initerror = createNewJPLISAgent(vm, &agent);
150 if ( initerror == JPLIS_INIT_ERROR_NONE ) {
151 int oldLen, newLen;
152 char * jarfile;
153 char * options;
154 jarAttribute* attributes;
155 char * premainClass;
156 char * agentClass;
157 char * bootClassPath;
158
159 /*
160 * Parse <jarfile>[=options] into jarfile and options
161 */
162 if (parseArgumentTail(tail, &jarfile, &options) != 0) {
163 fprintf(stderr, "-javaagent: memory allocation failure.\n");
164 return JNI_ERR;
165 }
166
167 /*
168 * Agent_OnLoad is specified to provide the agent options
169 * argument tail in modified UTF8. However for 1.5.0 this is
170 * actually in the platform encoding - see 5049313.
171 *
172 * Open zip/jar file and parse archive. If can't be opened or
173 * not a zip file return error. Also if Premain-Class attribute
174 * isn't present we return an error.
175 */
176 attributes = readAttributes(jarfile);
177 if (attributes == NULL) {
178 fprintf(stderr, "Error opening zip file or JAR manifest missing : %s\n", jarfile);
179 free(jarfile);
180 if (options != NULL) free(options);
181 return JNI_ERR;
182 }
183
184 premainClass = getAttribute(attributes, "Premain-Class");
185 if (premainClass == NULL) {
186 fprintf(stderr, "Failed to find Premain-Class manifest attribute in %s\n",
187 jarfile);
188 free(jarfile);
189 if (options != NULL) free(options);
190 freeAttributes(attributes);
191 return JNI_ERR;
192 }
193
194 /*
195 * Add to the jarfile
196 */
197 appendClassPath(agent, jarfile);
198
199 /*
200 * The value of the Premain-Class attribute becomes the agent
201 * class name. The manifest is in UTF8 so need to convert to
202 * modified UTF8 (see JNI spec).
203 */
204 oldLen = (int)strlen(premainClass);
205 newLen = modifiedUtf8LengthOfUtf8(premainClass, oldLen);
206 if (newLen == oldLen) {
207 premainClass = strdup(premainClass);
208 } else {
209 char* str = (char*)malloc( newLen+1 );
210 if (str != NULL) {
211 convertUtf8ToModifiedUtf8(premainClass, oldLen, str, newLen);
212 }
213 premainClass = str;
214 }
215 if (premainClass == NULL) {
216 fprintf(stderr, "-javaagent: memory allocation failed\n");
217 free(jarfile);
218 if (options != NULL) free(options);
219 freeAttributes(attributes);
220 return JNI_ERR;
221 }
222
223 /*
224 * If the Boot-Class-Path attribute is specified then we process
225 * each relative URL and add it to the bootclasspath.
226 */
227 bootClassPath = getAttribute(attributes, "Boot-Class-Path");
228 if (bootClassPath != NULL) {
229 appendBootClassPath(agent, jarfile, bootClassPath);
230 }
231
232 /*
233 * Convert JAR attributes into agent capabilities
234 */
235 convertCapabilityAtrributes(attributes, agent);
236
237 /*
238 * Track (record) the agent class name and options data
239 */
240 initerror = recordCommandLineData(agent, premainClass, options);
241
242 /*
243 * Clean-up
244 */
245 free(jarfile);
246 if (options != NULL) free(options);
247 freeAttributes(attributes);
248 free(premainClass);
249 }
250
251 switch (initerror) {
252 case JPLIS_INIT_ERROR_NONE:
253 result = JNI_OK;
254 break;
255 case JPLIS_INIT_ERROR_CANNOT_CREATE_NATIVE_AGENT:
256 result = JNI_ERR;
257 fprintf(stderr, "java.lang.instrument/-javaagent: cannot create native agent.\n");
258 break;
259 case JPLIS_INIT_ERROR_FAILURE:
260 result = JNI_ERR;
261 fprintf(stderr, "java.lang.instrument/-javaagent: initialization of native agent failed.\n");
262 break;
263 case JPLIS_INIT_ERROR_ALLOCATION_FAILURE:
264 result = JNI_ERR;
265 fprintf(stderr, "java.lang.instrument/-javaagent: allocation failure.\n");
266 break;
267 case JPLIS_INIT_ERROR_AGENT_CLASS_NOT_SPECIFIED:
268 result = JNI_ERR;
269 fprintf(stderr, "-javaagent: agent class not specified.\n");
270 break;
271 default:
272 result = JNI_ERR;
273 fprintf(stderr, "java.lang.instrument/-javaagent: unknown error\n");
274 break;
275 }
276 return result;
277}
278
279/*
280 * Agent_OnAttach returns a jint. 0/JNI_OK indicates success and non-0
281 * indicates an error. To allow the attach mechanism throw an
282 * AgentInitializationException with a reasonable exception message we define
283 * a few specific errors here.
284 */
285#define AGENT_ERROR_BADJAR ((jint)100) /* Agent JAR not found or no Agent-Class attribute */
286#define AGENT_ERROR_NOTONCP ((jint)101) /* Unable to add JAR file to system class path */
287#define AGENT_ERROR_STARTFAIL ((jint)102) /* No agentmain method or agentmain failed */
288
289/*
290 * This will be called once each time a tool attaches to the VM and loads
291 * the JPLIS library.
292 */
293JNIEXPORT jint JNICALL
294Agent_OnAttach(JavaVM* vm, char *args, void * reserved) {
295 JPLISInitializationError initerror = JPLIS_INIT_ERROR_NONE;
296 jint result = JNI_OK;
297 JPLISAgent * agent = NULL;
298 JNIEnv * jni_env = NULL;
299
300 /*
301 * Need JNIEnv - guaranteed to be called from thread that is already
302 * attached to VM
303 */
304 result = (*vm)->GetEnv(vm, (void**)&jni_env, JNI_VERSION_1_2);
305 jplis_assert(result==JNI_OK);
306
307 initerror = createNewJPLISAgent(vm, &agent);
308 if ( initerror == JPLIS_INIT_ERROR_NONE ) {
309 int oldLen, newLen;
310 char * jarfile;
311 char * options;
312 jarAttribute* attributes;
313 char * agentClass;
314 char * bootClassPath;
315 jboolean success;
316
317 /*
318 * Parse <jarfile>[=options] into jarfile and options
319 */
320 if (parseArgumentTail(args, &jarfile, &options) != 0) {
321 return JNI_ENOMEM;
322 }
323
324 /*
325 * Open the JAR file and parse the manifest
326 */
327 attributes = readAttributes( jarfile );
328 if (attributes == NULL) {
329 fprintf(stderr, "Error opening zip file or JAR manifest missing: %s\n", jarfile);
330 free(jarfile);
331 if (options != NULL) free(options);
332 return AGENT_ERROR_BADJAR;
333 }
334
335 agentClass = getAttribute(attributes, "Agent-Class");
336 if (agentClass == NULL) {
337 fprintf(stderr, "Failed to find Agent-Class manifest attribute from %s\n",
338 jarfile);
339 free(jarfile);
340 if (options != NULL) free(options);
341 freeAttributes(attributes);
342 return AGENT_ERROR_BADJAR;
343 }
344
345 /*
346 * Add the jarfile to the system class path
347 */
348 if (appendClassPath(agent, jarfile)) {
349 fprintf(stderr, "Unable to add %s to system class path "
350 "- not supported by system class loader or configuration error!\n",
351 jarfile);
352 free(jarfile);
353 if (options != NULL) free(options);
354 freeAttributes(attributes);
355 return AGENT_ERROR_NOTONCP;
356 }
357
358 /*
359 * The value of the Agent-Class attribute becomes the agent
360 * class name. The manifest is in UTF8 so need to convert to
361 * modified UTF8 (see JNI spec).
362 */
363 oldLen = strlen(agentClass);
364 newLen = modifiedUtf8LengthOfUtf8(agentClass, oldLen);
365 if (newLen == oldLen) {
366 agentClass = strdup(agentClass);
367 } else {
368 char* str = (char*)malloc( newLen+1 );
369 if (str != NULL) {
370 convertUtf8ToModifiedUtf8(agentClass, oldLen, str, newLen);
371 }
372 agentClass = str;
373 }
374 if (agentClass == NULL) {
375 free(jarfile);
376 if (options != NULL) free(options);
377 freeAttributes(attributes);
378 return JNI_ENOMEM;
379 }
380
381 /*
382 * If the Boot-Class-Path attribute is specified then we process
383 * each URL - in the live phase only JAR files will be added.
384 */
385 bootClassPath = getAttribute(attributes, "Boot-Class-Path");
386 if (bootClassPath != NULL) {
387 appendBootClassPath(agent, jarfile, bootClassPath);
388 }
389
390 /*
391 * Convert JAR attributes into agent capabilities
392 */
393 convertCapabilityAtrributes(attributes, agent);
394
395 /*
396 * Create the java.lang.instrument.Instrumentation instance
397 */
398 success = createInstrumentationImpl(jni_env, agent);
399 jplis_assert(success);
400
401 /*
402 * Turn on the ClassFileLoadHook.
403 */
404 if (success) {
405 success = setLivePhaseEventHandlers(agent);
406 jplis_assert(success);
407 }
408
409 /*
410 * Start the agent
411 */
412 if (success) {
413 success = startJavaAgent(agent,
414 jni_env,
415 agentClass,
416 options,
417 agent->mAgentmainCaller);
418 }
419
420 if (!success) {
421 fprintf(stderr, "Agent failed to start!\n");
422 result = AGENT_ERROR_STARTFAIL;
423 }
424
425 /*
426 * Clean-up
427 */
428 free(jarfile);
429 if (options != NULL) free(options);
430 free(agentClass);
431 freeAttributes(attributes);
432 }
433
434 return result;
435}
436
437
438JNIEXPORT void JNICALL
439Agent_OnUnload(JavaVM *vm) {
440}
441
442
443/*
444 * JVMTI callback support
445 *
446 * We have two "stages" of callback support.
447 * At OnLoad time, we install a VMInit handler.
448 * When the VMInit handler runs, we remove the VMInit handler and install a
449 * ClassFileLoadHook handler.
450 */
451
452void JNICALL
453eventHandlerVMInit( jvmtiEnv * jvmtienv,
454 JNIEnv * jnienv,
455 jthread thread) {
456 JPLISEnvironment * environment = NULL;
457 jboolean success = JNI_FALSE;
458
459 environment = getJPLISEnvironment(jvmtienv);
460
461 /* process the premain calls on the all the JPL agents */
462 if ( environment != NULL ) {
463 jthrowable outstandingException = preserveThrowable(jnienv);
464 success = processJavaStart( environment->mAgent,
465 jnienv);
466 restoreThrowable(jnienv, outstandingException);
467 }
468
469 /* if we fail to start cleanly, bring down the JVM */
470 if ( !success ) {
471 abortJVM(jnienv, JPLIS_ERRORMESSAGE_CANNOTSTART);
472 }
473}
474
475void JNICALL
476eventHandlerClassFileLoadHook( jvmtiEnv * jvmtienv,
477 JNIEnv * jnienv,
478 jclass class_being_redefined,
479 jobject loader,
480 const char* name,
481 jobject protectionDomain,
482 jint class_data_len,
483 const unsigned char* class_data,
484 jint* new_class_data_len,
485 unsigned char** new_class_data) {
486 JPLISEnvironment * environment = NULL;
487
488 environment = getJPLISEnvironment(jvmtienv);
489
490 /* if something is internally inconsistent (no agent), just silently return without touching the buffer */
491 if ( environment != NULL ) {
492 jthrowable outstandingException = preserveThrowable(jnienv);
493 transformClassFile( environment->mAgent,
494 jnienv,
495 loader,
496 name,
497 class_being_redefined,
498 protectionDomain,
499 class_data_len,
500 class_data,
501 new_class_data_len,
502 new_class_data,
503 environment->mIsRetransformer);
504 restoreThrowable(jnienv, outstandingException);
505 }
506}
507
508
509
510
511/*
512 * URLs in Boot-Class-Path attributes are separated by one or more spaces.
513 * This function splits the attribute value into a list of path segments.
514 * The attribute value is in UTF8 but cannot contain NUL. Also non US-ASCII
515 * characters must be escaped (URI syntax) so safe to iterate through the
516 * value as a C string.
517 */
518static void
519splitPathList(const char* str, int* pathCount, char*** paths) {
520 int count = 0;
521 char** segments = NULL;
522 char* c = (char*) str;
523 while (*c != '\0') {
524 while (*c == ' ') c++; /* skip leading spaces */
525 if (*c == '\0') {
526 break;
527 }
528 if (segments == NULL) {
529 segments = (char**)malloc( sizeof(char**) );
530 } else {
531 segments = (char**)realloc( segments, (count+1)*sizeof(char**) );
532 }
533 jplis_assert(segments != (char**)NULL);
534 segments[count++] = c;
535 c = strchr(c, ' ');
536 if (c == NULL) {
537 break;
538 }
539 *c = '\0';
540 c++;
541 }
542 *pathCount = count;
543 *paths = segments;
544}
545
546
547/* URI path decoding - ported from src/share/classes/java/net/URI.java */
548
549static int
550decodeNibble(char c) {
551 if ((c >= '0') && (c <= '9'))
552 return c - '0';
553 if ((c >= 'a') && (c <= 'f'))
554 return c - 'a' + 10;
555 if ((c >= 'A') && (c <= 'F'))
556 return c - 'A' + 10;
557 return -1;
558}
559
560static int
561decodeByte(char c1, char c2) {
562 return (((decodeNibble(c1) & 0xf) << 4) | ((decodeNibble(c2) & 0xf) << 0));
563}
564
565/*
566 * Evaluates all escapes in s. Assumes that escapes are well-formed
567 * syntactically, i.e., of the form %XX.
568 * If the path does not require decoding the the original path is
569 * returned. Otherwise the decoded path (heap allocated) is returned,
570 * along with the length of the decoded path. Note that the return
571 * string will not be null terminated after decoding.
572 */
573static
574char *decodePath(const char *s, int* decodedLen) {
575 int n;
576 char *result;
577 char *resultp;
578 int c;
579 int i;
580
581 n = (int)strlen(s);
582 if (n == 0) {
583 *decodedLen = 0;
584 return (char*)s;
585 }
586 if (strchr(s, '%') == NULL) {
587 *decodedLen = n;
588 return (char*)s; /* no escapes, we are done */
589 }
590
591 resultp = result = calloc(n+1, 1);
592 c = s[0];
593 for (i = 0; i < n;) {
594 if (c != '%') {
595 *resultp++ = c;
596 if (++i >= n)
597 break;
598 c = s[i];
599 continue;
600 }
601 for (;;) {
602 char b1 = s[++i];
603 char b2 = s[++i];
604 int decoded = decodeByte(b1, b2);
605 *resultp++ = decoded;
606 if (++i >= n)
607 break;
608 c = s[i];
609 if (c != '%')
610 break;
611 }
612 }
613 *decodedLen = (int)(resultp - result);
614 return result; // not null terminated.
615}
616
617/*
618 * Append the given jar file to the system class path. This should succeed in the
619 * onload phase but may fail in the live phase if the system class loader doesn't
620 * support appending to the class path.
621 */
622static int
623appendClassPath( JPLISAgent* agent,
624 const char* jarfile ) {
625 jvmtiEnv* jvmtienv = jvmti(agent);
626 jvmtiError jvmtierr;
627
628 jvmtierr = (*jvmtienv)->AddToSystemClassLoaderSearch(jvmtienv, jarfile);
629
630 if (jvmtierr == JVMTI_ERROR_NONE) {
631 return 0;
632 } else {
633 jvmtiPhase phase;
634 jvmtiError err;
635
636 err = (*jvmtienv)->GetPhase(jvmtienv, &phase);
637 jplis_assert(err == JVMTI_ERROR_NONE);
638
639 if (phase == JVMTI_PHASE_LIVE) {
640 switch (jvmtierr) {
641 case JVMTI_ERROR_CLASS_LOADER_UNSUPPORTED :
642 fprintf(stderr, "System class loader does not support adding "
643 "JAR file to system class path during the live phase!\n");
644 break;
645 default:
646 fprintf(stderr, "Unexpected error (%d) returned by "
647 "AddToSystemClassLoaderSearch\n", jvmtierr);
648 break;
649 }
650 return -1;
651 }
652 jplis_assert(0);
653 }
654 return -2;
655}
656
657
658/*
659 * res = func, free'ing the previous value of 'res' if function
660 * returns a new result.
661 */
662#define TRANSFORM(res,func) { \
663 char* tmp = func; \
664 if (tmp != res) { \
665 free(res); \
666 res = tmp; \
667 } \
668 jplis_assert((void*)res != (void*)NULL); \
669}
670
671
672/*
673 * This function takes the value of the Boot-Class-Path attribute,
674 * splits it into the individual path segments, and then combines it
675 * with the path to the jar file to create the path to be added
676 * to the bootclasspath.
677 *
678 * Each individual path segment starts out as a UTF8 string. Additionally
679 * as the path is specified to use URI path syntax all non US-ASCII
680 * characters are escaped. Once the URI path is decoded we get a UTF8
681 * string which must then be converted to the platform encoding (as it
682 * will be combined with the platform path of the jar file). Once
683 * converted it is then normalized (remove duplicate slashes, etc.).
684 * If the resulting path is an absolute path (starts with a slash for
685 * example) then the path will be added to the bootclasspath. Otherwise
686 * if it's not absolute then we get the canoncial path of the agent jar
687 * file and then resolve the path in the context of the base path of
688 * the agent jar.
689 */
690static void
691appendBootClassPath( JPLISAgent* agent,
692 const char* jarfile,
693 const char* pathList ) {
694 char canonicalPath[MAXPATHLEN];
695 char *parent = NULL;
696 int haveBasePath = 0;
697
698 int count, i;
699 char **paths;
700 jvmtiEnv* jvmtienv = jvmti(agent);
701 jvmtiError jvmtierr;
702
703 /*
704 * Split the attribute value into the individual path segments
705 * and process each in sequence
706 */
707 splitPathList(pathList, &count, &paths);
708
709 for (i=0; i<count; i++) {
710 int len;
711 char* path;
712 char* pos;
713
714 /*
715 * The path segment at this point is a pointer into the attribute
716 * value. As it will go through a number of transformation (tossing away
717 * the previous results as we go along) it make it easier if the path
718 * starts out as a heap allocated string.
719 */
720 path = strdup(paths[i]);
721 jplis_assert(path != (char*)NULL);
722
723 /*
724 * The attribute is specified to be a list of relative URIs so in theory
725 * there could be a query component - if so, get rid of it.
726 */
727 pos = strchr(path, '?');
728 if (pos != NULL) {
729 *pos = '\0';
730 }
731
732 /*
733 * Check for characters that are not allowed in the path component of
734 * a URI.
735 */
736 if (validatePathChars(path)) {
737 fprintf(stderr, "WARNING: illegal character in Boot-Class-Path value: %s\n",
738 path);
739 free(path);
740 continue;
741 }
742
743
744 /*
745 * Next decode any escaped characters. The result is a UTF8 string.
746 */
747 TRANSFORM(path, decodePath(path,&len));
748
749 /*
750 * Convert to the platform encoding
751 */
752 {
753 char platform[MAXPATHLEN];
754 int new_len = convertUft8ToPlatformString(path, len, platform, MAXPATHLEN);
755 free(path);
756 if (new_len < 0) {
757 /* bogus value - exceeds maximum path size or unable to convert */
758 continue;
759 }
760 path = strdup(platform);
761 jplis_assert(path != (char*)NULL);
762 }
763
764 /*
765 * Post-process the URI path - needed on Windows to transform
766 * /c:/foo to c:/foo.
767 */
768 TRANSFORM(path, fromURIPath(path));
769
770 /*
771 * Normalize the path - no duplicate slashes (except UNCs on Windows), trailing
772 * slash removed.
773 */
774 TRANSFORM(path, normalize(path));
775
776 /*
777 * If the path is an absolute path then add to the bootclassloader
778 * search path. Otherwise we get the canonical path of the agent jar
779 * and then use its base path (directory) to resolve the given path
780 * segment.
781 *
782 * NOTE: JVMTI is specified to use modified UTF8 strings (like JNI).
783 * In 1.5.0 the AddToBootstrapClassLoaderSearch takes a platform string
784 * - see 5049313.
785 */
786 if (isAbsolute(path)) {
787 jvmtierr = (*jvmtienv)->AddToBootstrapClassLoaderSearch(jvmtienv, path);
788 } else {
789 char* resolved;
790
791 if (!haveBasePath) {
792 if (canonicalize((char*)jarfile, canonicalPath, sizeof(canonicalPath)) != 0) {
793 fprintf(stderr, "WARNING: unable to canonicalize %s\n", jarfile);
794 free(path);
795 continue;
796 }
797 parent = basePath(canonicalPath);
798 jplis_assert(parent != (char*)NULL);
799 haveBasePath = 1;
800 }
801
802 resolved = resolve(parent, path);
803 jvmtierr = (*jvmtienv)->AddToBootstrapClassLoaderSearch(jvmtienv, resolved);
804 }
805
806 /* print warning if boot class path not updated */
807 if (jvmtierr != JVMTI_ERROR_NONE) {
808 fprintf(stderr, "WARNING: %s not added to bootstrap class loader search: ", path);
809 switch (jvmtierr) {
810 case JVMTI_ERROR_ILLEGAL_ARGUMENT :
811 fprintf(stderr, "Illegal argument or not JAR file\n");
812 break;
813 default:
814 fprintf(stderr, "Unexpected error: %d\n", jvmtierr);
815 }
816 }
817
818 /* finished with the path */
819 free(path);
820 }
821
822
823 /* clean-up */
824 if (haveBasePath && parent != canonicalPath) {
825 free(parent);
826 }
827}