dislagent.c 16.1 KB
Newer Older
1 2 3
#include "common.h"
#include "dislagent.h"

4
#include "jvmtiutil.h"
5
#include "connection.h"
6 7
#include "network.h"
#include "msgchannel.h"
8

9
#include "bytecode.h"
10
#include "classparser.h"
11 12
#include "codeflags.h"

13 14 15 16 17 18 19
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <jni.h>
#include <jvmti.h>

20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39

// ****************************************************************************
// AGENT CONFIG
// ****************************************************************************

#define DISL_SERVER_HOST "disl.server.host"
#define DISL_SERVER_HOST_DEFAULT "localhost"

#define DISL_SERVER_PORT "disl.server.port"
#define DISL_SERVER_PORT_DEFAULT "11217"

#define DISL_BYPASS "disl.bypass"
#define DISL_BYPASS_DEFAULT "dynamic"

#define DISL_SPLIT_METHODS "disl.splitmethods"
#define DISL_SPLIT_METHODS_DEFAULT true

#define DISL_CATCH_EXCEPTIONS "disl.excepthandler"
#define DISL_CATCH_EXCEPTIONS_DEFAULT false

40 41 42 43 44 45
#define DISL_FORCE_SUPERCLASS "disl.forcesuperclass"
#define DISL_FORCE_SUPERCLASS_DEFAULT false

#define DISL_FORCE_INTERFACES "disl.forceinterfaces"
#define DISL_FORCE_INTERFACES_DEFAULT false

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
#define DISL_DEBUG "debug"
#define DISL_DEBUG_DEFAULT false


/**
 * The instrumentation bypass mode.
 * NOTE: The ordering of the modes is important!
 */
enum bypass_mode {
	/**
	 * The original method code will not be preserved. Consequently, the
	 * instrumented version of a method will be always executed, even when
	 * invoked inside a DiSL snippet.
	 */
	BYPASS_MODE_DISABLED = 0,

	/**
	 * The original method code will be preserved, and will be always
	 * executed instead of the instrumented version during JVM bootstrap.
	 * After bootstrap, only the instrumented version of a method will
	 * be executed.
	 */
	BYPASS_MODE_BOOTSTRAP = 1,

	/**
	 * The original method code will be preserved, and executed whenever
	 * invoked from inside a DiSL snippet.
	 */
	BYPASS_MODE_DYNAMIC = 2
};


/**
 * Flags representing code options, derived from the values generated from Java.
 */
enum code_flags {
	CF_CREATE_BYPASS = ch_usi_dag_disl_DiSL_CodeOption_Flag_CREATE_BYPASS,
	CF_DYNAMIC_BYPASS = ch_usi_dag_disl_DiSL_CodeOption_Flag_DYNAMIC_BYPASS,
	CF_SPLIT_METHODS = ch_usi_dag_disl_DiSL_CodeOption_Flag_SPLIT_METHODS,
	CF_CATCH_EXCEPTIONS = ch_usi_dag_disl_DiSL_CodeOption_Flag_CATCH_EXCEPTIONS,
};


struct config {
	char * server_host;
	char * server_port;

	enum bypass_mode bypass_mode;
	bool split_methods;
	bool catch_exceptions;
96 97
	bool force_superclass;
	bool force_interfaces;
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

	bool debug;
};


/**
 * Agent configuration.
 */
static struct config agent_config;


/**
 * Code option flags that control the instrumentation.
 */
static volatile jint agent_code_flags;


/**
 * Prints a debug message to stdout, if runtime agent debugging is enabled.
 *
 * @format	format string for printf
 * @args	arguments associated with the format string
 *
 */
#define rdprintf(args...) \
	if (agent_config.debug) { \
		fprintf (stdout, "agent: "); \
		fprintf (stdout, args); \
	}


// ****************************************************************************
// CLASS FILE LOAD
// ****************************************************************************

static jint
__calc_code_flags (struct config * config, bool jvm_is_booting) {
	jint result = 0;

	//
	// If bypass is desired, always create bypass code while the JVM is
	// bootstrapping. If dynamic bypass is desired, create bypass code as
	// well as code to control it dynamically.
	//
	if (config->bypass_mode > BYPASS_MODE_DISABLED) {
		result |= jvm_is_booting ? CF_CREATE_BYPASS : 0;
		if (config->bypass_mode > BYPASS_MODE_BOOTSTRAP) {
			result |= (CF_CREATE_BYPASS | CF_DYNAMIC_BYPASS);
		}
	}

	result |= config->split_methods ? CF_SPLIT_METHODS : 0;
	result |= config->catch_exceptions ? CF_CATCH_EXCEPTIONS : 0;

	return result;
}


156 157 158 159 160 161
static inline const char *
__safe (const char * class_name) {
	return (class_name != NULL) ? class_name : "<unknown class>";
}


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
/**
 * Sends the given class to the remote server for instrumentation. If the
 * server modified the class, provided class definition structure is updated
 * and the function returns TRUE. Otherwise, the structure is left unmodified
 * and FALSE is returned.
 *
 * NOTE: The class_name parameter may be NULL -- this is often the case for
 * anonymous classes.
 */
static bool
__instrument_class (
	jint request_flags, const char * class_name,
	jvmtiClassDefinition * class_def
) {
	//
	// Put the class data into a request message, acquire a connection and
	// send the it to the server. Receive the response and release the
	// connection again.
	//
	struct message request = {
		.message_flags = request_flags,
		.control_size = (class_name != NULL) ? strlen (class_name) : 0,
		.classcode_size = class_def->class_byte_count,
		.control = (unsigned char *) class_name,
		.classcode = class_def->class_bytes,
	};

	//

	struct connection * conn = network_acquire_connection ();
	message_send (conn, &request);

	struct message response;
	message_recv (conn, &response);
	network_release_connection (conn);

	//
	// Check if error occurred on the server.
	// The control field of the response contains the error message.
	//
	if (response.control_size > 0) {
		fprintf (
204
			stderr, "%sinstrumentation server error:\n%s\n",
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
			ERROR_PREFIX, response.control
		);

		exit (ERROR_SERVER);
	}

	//
	// Update the class definition and signal that the class has been
	// modified if non-empty class code has been returned. Otherwise,
	// signal that the class has not been modified.
	//
	if (response.classcode_size > 0) {
		class_def->class_byte_count = response.classcode_size;
		class_def->class_bytes = response.classcode;
		return true;

	} else {
		return false;
	}
}


227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
static void
__handle_exception (JNIEnv * jni, jthrowable ex_obj) {
	jclass ex_class = (* jni)->GetObjectClass (jni, ex_obj);
	jmethodID m_getClass = (* jni)->GetMethodID (jni, ex_class, "getClass", "()Ljava/lang/Class;");
	jobject cl_obj = (* jni)->CallObjectMethod (jni, ex_obj, m_getClass);

	jclass cl_class = (* jni)->GetObjectClass (jni, cl_obj);
	jmethodID m_getName = (* jni)->GetMethodID (jni, cl_class, "getName", "()Ljava/lang/String;");
	jstring cl_name = (* jni)->CallObjectMethod (jni, cl_obj, m_getName);

	const char * cl_name_chars = (* jni)->GetStringUTFChars (jni, cl_name, NULL);
	rdprintf ("\texception %s occured, cleared\n", cl_name_chars);
	(* jni)->ReleaseStringUTFChars (jni, cl_name, cl_name_chars);
}


243 244 245 246 247 248 249
static void
__force_class (JNIEnv * jni, const char * class_name, const char * kind) {
	rdprintf ("\tforce-loading %s %s\n", kind, class_name);
	if (jni != NULL) {
		jclass found_class = (* jni)->FindClass (jni, class_name);
		if (found_class == NULL) {
			warn ("failed to force-load %s %s\n", kind, class_name);
250 251 252 253 254
			jthrowable exception = (* jni)->ExceptionOccurred (jni);
			if (exception != NULL) {
				(* jni)->ExceptionClear (jni);
				__handle_exception (jni, exception);
			}
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
		}

	} else {
		rdprintf ("\tJNI not ready, force-loading aborted\n");
	}
}

static void
__force_superclass (JNIEnv * jni, class_t inst_class) {
	char * super_name = class_super_class_name (inst_class);
	if (super_name != NULL) {
		__force_class (jni, super_name, "super class");
		free (super_name);

	} else {
		rdprintf ("\tclass does not have super class\n");
	}
}


static void
__force_interfaces (JNIEnv * jni, class_t inst_class) {
	int count = class_interface_count (inst_class);
	if (count == 0) {
		rdprintf ("\tclass does not implement interfaces\n");
		return;
	}

	for (int index = 0; index < count; index++) {
		char * iface_name = class_interface_name (inst_class, index);
		if  (iface_name != NULL) {
			__force_class (jni, iface_name, "interface");
			free (iface_name);

		} else {
			warn ("failed to get the name of interface %d\n", index);
		}
	}
}


/**
 * Forces loading of the super class (or the implemented interfaces) of the
 * class being instrumented. For this, we need to parse the constant pool
 * of the class to discover the names of the classes to be force-loaded.
 * We then use JNI to find the classes, which will force their loading.
 */
static void
__force_classes (
	JNIEnv * jni, const char * class_name,
	const unsigned char * class_bytes, jint class_byte_count
) {
	class_t inst_class = class_alloc (class_bytes, class_byte_count);
	if (inst_class != NULL) {
		if (agent_config.force_superclass) {
			__force_superclass (jni, inst_class);
		}

		if (agent_config.force_interfaces) {
			__force_interfaces (jni, inst_class);
		}

		class_free (inst_class);

	} else {
		warn ("failed to parse class %s\n", __safe (class_name));
	}
}


325 326 327 328 329 330 331 332 333 334 335 336
static void JNICALL
jvmti_callback_class_file_load (
	jvmtiEnv * jvmti, JNIEnv * jni,
	jclass class_being_redefined, jobject loader,
	const char * class_name, jobject protection_domain,
	jint class_byte_count, const unsigned char * class_bytes,
	jint * new_class_byte_count, unsigned char ** new_class_bytes
) {
	assert (jvmti != NULL);

	rdprintf (
		"%s loaded, %ld bytes at %p\n",
337
		__safe (class_name), (long) class_byte_count, class_bytes
338 339 340 341 342
	);

	//
	// Avoid instrumenting the bypass check class.
	//
343
	if (class_name != NULL && strcmp (class_name, BPC_CLASS_NAME) == 0) {
344 345 346 347
		rdprintf ("skipping bypass check class (%s)\n", class_name);
		return;
	}

348 349 350 351 352 353 354
	//
	// Force loading of the super class or the interface classes.
	//
	if (agent_config.force_superclass || agent_config.force_interfaces) {
		rdprintf ("forcing classes for %s\n", __safe (class_name));
		__force_classes (jni, class_name, class_bytes, class_byte_count);
	}
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 460 461 462 463 464 465

	//
	// Instrument the class and if changed by the server, provide the
	// code to the JVM in its own memory.
	//
	jvmtiClassDefinition class_def = {
		.class_byte_count = class_byte_count,
		.class_bytes = class_bytes,
	};

	bool class_changed = __instrument_class (
		agent_code_flags, class_name, &class_def
	);

	if (class_changed) {
		unsigned char * jvm_class_bytes = jvmti_alloc_copy (
			jvmti, class_def.class_bytes, class_def.class_byte_count
		);

		free ((void *) class_def.class_bytes);

		*new_class_byte_count = class_def.class_byte_count;
		*new_class_bytes = jvm_class_bytes;

		rdprintf (
			"class redefined, %ld bytes at %p\n",
			(long) class_def.class_byte_count, jvm_class_bytes
		);
	} else {
		rdprintf ("class not modified\n");
	}
}


// ****************************************************************************
// JVMTI EVENT: VM INIT
// ****************************************************************************

static void JNICALL
jvmti_callback_vm_init (jvmtiEnv * jvmti, JNIEnv * jni, jthread thread) {
	rdprintf ("the VM has been initialized\n");

	//
	// Update code flags to reflect that the VM has stopped booting.
	//
	agent_code_flags = __calc_code_flags (&agent_config, false);

	//
	// Redefine the bypass check class. If dynamic bypass is required, use
	// a class that honors the dynamic bypass state for the current thread.
	// Otherwise use a class that disables bypassing instrumented code.
	//
	jvmtiClassDefinition * bpc_classdef;
	if (agent_config.bypass_mode == BYPASS_MODE_DYNAMIC) {
		rdprintf ("redefining BypassCheck for dynamic bypass\n");
		bpc_classdef = &dynamic_BypassCheck_classdef;
	} else {
		rdprintf ("redefining BypassCheck to disable bypass\n");
		bpc_classdef = &never_BypassCheck_classdef;
	}

	jvmti_redefine_class (jvmti, jni, BPC_CLASS_NAME, bpc_classdef);
}


// ****************************************************************************
// JVMTI EVENT: VM DEATH
// ****************************************************************************

static void JNICALL
jvmti_callback_vm_death (jvmtiEnv * jvmti, JNIEnv * jni) {
	rdprintf ("the VM is shutting down, closing connections\n");

	//
	// Just close all the connections.
	//
	network_fini ();
}


// ****************************************************************************
// AGENT ENTRY POINT: ON LOAD
// ****************************************************************************

static void
__configure_from_properties (jvmtiEnv * jvmti, struct config * config) {
	//
	// Get bypass mode configuration
	//
	char * bypass = jvmti_get_system_property_string (
		jvmti, DISL_BYPASS, DISL_BYPASS_DEFAULT
	);

	static const char * values [] = { "disabled", "bootstrap", "dynamic" };
	int bypass_index = find_value_index (bypass, values, sizeof_array (values));
	check_error (bypass_index < 0, "invalid bypass mode, check " DISL_BYPASS);

	config->bypass_mode = bypass_index;
	free (bypass);

	//
	// Get boolean values from system properties
	//
	config->split_methods = jvmti_get_system_property_bool (
		jvmti, DISL_SPLIT_METHODS, DISL_SPLIT_METHODS_DEFAULT
	);

	config->catch_exceptions = jvmti_get_system_property_bool (
		jvmti, DISL_CATCH_EXCEPTIONS, DISL_CATCH_EXCEPTIONS_DEFAULT
	);

466 467 468 469 470 471 472 473
	config->force_superclass = jvmti_get_system_property_bool (
		jvmti, DISL_FORCE_SUPERCLASS, DISL_FORCE_SUPERCLASS_DEFAULT
	);

	config->force_interfaces = jvmti_get_system_property_bool (
		jvmti, DISL_FORCE_INTERFACES, DISL_FORCE_INTERFACES_DEFAULT
	);

474 475 476
	config->debug = jvmti_get_system_property_bool (
		jvmti, DISL_DEBUG, DISL_DEBUG_DEFAULT
	);
477 478 479 480 481 482 483 484 485

	//
	// Configuration summary.
	//
	rdprintf ("bypass mode: %s\n", values [bypass_index]);
	rdprintf ("split methods: %d\n", config->split_methods);
	rdprintf ("catch exceptions: %d\n", config->catch_exceptions);
	rdprintf ("force superclass: %d\n", config->force_superclass);
	rdprintf ("force interfaces: %d\n", config->force_interfaces);
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
}


static void
__configure_from_options (const char * options, struct config * config) {
	//
	// Assign default host name and port and bail out
	// if there are no agent options.
	//
	if (options == NULL) {
		config->server_host = strdup (DISL_SERVER_HOST_DEFAULT);
		config->server_port = strdup (DISL_SERVER_PORT_DEFAULT);
		return;
	}

	//
	// Parse the host name and port of the remote server.
	// Look for port specification first, then take the prefix
	// before ':' as the host name.
	//
	char * host_start = strdup (options);
	char * port_start = strchr (host_start, ':');
	if (port_start != NULL) {
		//
		// Split the option string at the port delimiter (':')
		// using an end-of-string character ('\0') and copy
		// the port.
		//
		port_start [0] = '\0';
		port_start++;

		config->server_port = strdup (port_start);
	}

	config->server_host = strdup (host_start);
}


static jvmtiEnv *
__get_jvmti (JavaVM * jvm) {
	jvmtiEnv * jvmti = NULL;

	jint result = (*jvm)->GetEnv (jvm, (void **) &jvmti, JVMTI_VERSION_1_0);
	if (result != JNI_OK || jvmti == NULL) {
		//
		// The VM was unable to provide the requested version of the
		// JVMTI interface. This is a fatal error for the agent.
		//
		fprintf (
			stderr,
			"%sFailed to obtain JVMTI interface Version 1 (0x%x)\n"
			"JVM GetEnv() returned %ld - is your Java runtime "
			"version 1.5 or newer?\n",
			ERROR_PREFIX, JVMTI_VERSION_1, (long) result
		);

		exit (ERROR_JVMTI);
	}

	return jvmti;
}


JNIEXPORT jint JNICALL VISIBLE
Agent_OnLoad (JavaVM * jvm, char * options, void * reserved) {
	jvmtiEnv * jvmti = __get_jvmti (jvm);

	// add capabilities
	jvmtiCapabilities caps = {
		.can_redefine_classes = 1,
		.can_generate_all_class_hook_events = 1,
	};

	jvmtiError error = (*jvmti)->AddCapabilities (jvmti, &caps);
	check_jvmti_error (jvmti, error, "failed to add capabilities");


	// configure agent and init connections
	__configure_from_options (options, &agent_config);
	__configure_from_properties (jvmti, &agent_config);

	agent_code_flags = __calc_code_flags (&agent_config, true);
	network_init (agent_config.server_host, agent_config.server_port);


	// register callbacks
	jvmtiEventCallbacks callbacks = {
		.VMInit = &jvmti_callback_vm_init,
		.VMDeath = &jvmti_callback_vm_death,
		.ClassFileLoadHook = &jvmti_callback_class_file_load,
	};

	error = (*jvmti)->SetEventCallbacks (jvmti, &callbacks, (jint) sizeof (callbacks));
	check_jvmti_error (jvmti, error, "failed to register event callbacks");


	// enable event notification
	error = (*jvmti)->SetEventNotificationMode (jvmti, JVMTI_ENABLE, JVMTI_EVENT_VM_INIT, NULL);
	check_jvmti_error (jvmti, error, "failed to enable VM INIT event");

	error = (*jvmti)->SetEventNotificationMode (jvmti, JVMTI_ENABLE, JVMTI_EVENT_VM_DEATH, NULL);
	check_jvmti_error (jvmti, error, "failed to enable VM DEATH event");

	error = (*jvmti)->SetEventNotificationMode (jvmti, JVMTI_ENABLE, JVMTI_EVENT_CLASS_FILE_LOAD_HOOK, NULL);
	check_jvmti_error (jvmti, error, "failed to enable CLASS FILE LOAD event");

	return 0;
}