def jvm(max_mem=None): """Return the jpype module, after guaranteeing the JVM is running and the classpath has been loaded properly.""" jarpaths = (os.path.abspath( os.path.join(os.path.dirname(__file__), "../lib")), os.path.abspath( os.path.join(os.path.dirname(__file__), "../dist"))) # TODO(JMC): Make sure these directories exist # LOG.debug("Jarpath is %s", jarpaths) if not jpype.isJVMStarted(): max_mem = get_jvm_max_mem(max_mem) LOG.debug("Default JVM path is %s" % jpype.getDefaultJVMPath()) jpype.startJVM( jpype.getDefaultJVMPath(), "-Djava.ext.dirs=%s:%s" % jarpaths, #"-Dnet.spy.log.LoggerImpl=net.spy.memcached.compat.log.Log4JLogger", # "-Dlog4j.debug", "-Dlog4j.configuration=log4j.properties", "-Dlog4j.rootLogger=%s, A1" % (FLAGS.debug.upper()), # "-Dlog4j.rootLogger=DEBUG, A1", "-Xmx%sM" % max_mem) if FLAGS.capture_java_debug: mystream = jpype.JProxy("org.gem.IPythonPipe", inst=sys.stdout) errstream = jpype.JProxy("org.gem.IPythonPipe", inst=sys.stderr) outputstream = jpype.JClass("org.gem.PythonOutputStream")() err_stream = jpype.JClass("org.gem.PythonOutputStream")() outputstream.setPythonStdout(mystream) err_stream.setPythonStdout(errstream) ps = jpype.JClass("java.io.PrintStream") jpype.java.lang.System.setOut(ps(outputstream)) jpype.java.lang.System.setErr(ps(err_stream)) return jpype
def main(): if len(sys.argv)!=2: print len(sys.argv) print "Usage " +str(sys.argv[0])+" <edf file> " sys.exit(0) else: fl = str(sys.argv[1]) dataObj = EEGData(fl) jpype.startJVM(jpype.getDefaultJVMPath()) pyobs = Observer() pyobs.setData(dataObj) jobs = jpype.JClass("Observer") obsprox = jpype.JProxy(jobs, inst=pyobs) jdata = jpype.JClass("EEGData") dataprox = jpype.JProxy(jdata,inst=dataObj) projObj = projectManager() jproj = jpype.JClass("ProjectManager") projprox = jpype.JProxy(jproj,inst=projObj) gui = jpype.JClass("GUI") print 'gui init' gui(obsprox,dataprox,projprox) time.sleep(1000) jpype.shutdownJVM()
def create_event_handler(handler): class ProtobufHandler: def notifyStart(self): if hasattr(handler, "notifyStart"): handler.notifyStart() def notifyEnd(self): if hasattr(handler, "notifyEnd"): handler.notifyEnd() def handleJumpEventMessage(self, message): if hasattr(handler, "handleJumpEvent"): event = JumpEvent() event.ParseFromString(message[:]) handler.handleJumpEvent(event) def handleSingEventMessage(self, message): if hasattr(handler, "handleSingEvent"): event = SingEvent() event.ParseFromString(message[:]) handler.handleSingEvent(event) def handleSpeakEventMessage(self, message): if hasattr(handler, "handleSpeakEvent"): event = SpeakEvent() event.ParseFromString(message[:]) handler.handleSpeakEvent(event) impl = jpype.JProxy( "ch.dubernet.demopythonapi.simulation.api.ProtobufEventHandler", inst=ProtobufHandler()) return ProtobufAdapter(impl)
def create_buffered_event_handler(handler, buffer_size): class ProtobufHandler: def notifyStart(self): if hasattr(handler, "notifyStart"): handler.notifyStart() def notifyEnd(self): if hasattr(handler, "notifyEnd"): handler.notifyEnd() def handleEventBuffer(self, message): buffer = EventBuffer() buffer.ParseFromString(message[:]) for event in buffer.events: event_type = event.WhichOneof("event") if event_type == "jumpEvent" and hasattr( handler, "handleJumpEvent"): handler.handleJumpEvent(event.jumpEvent) elif event_type == "singEvent" and hasattr( handler, "handleSingEvent"): handler.handleSingEvent(event.singEvent) elif event_type == "speakEvent" and hasattr( handler, "handleSpeakEvent"): handler.handleSpeakEvent(event.speakEvent) impl = jpype.JProxy( "ch.dubernet.demopythonapi.simulation.api.ProtobufEventBufferHandler", inst=ProtobufHandler()) return ProtobufBufferedAdapter(impl, buffer_size)
def run_simulation(self, sim, listeners=None): """ This is a wrapper to the Simulation.simulate() for running a simulation The optional listeners parameter is a sequence of objects which extend orh.AbstractSimulationListener. """ if listeners == None: # this method takes in a vararg of SimulationListeners, which is just a fancy way of passing in an array, so # we have to pass in an array of length 0 .. listener_array = jpype.JArray( self.orp.simulation.listeners.AbstractSimulationListener, 1)(0) else: listener_array = [ jpype.JProxy( ( self.orp.simulation.listeners.SimulationListener, self.orp.simulation.listeners.SimulationEventListener, self.orp.simulation.listeners. SimulationComputationListener, ), inst=c, ) for c in listeners ] sim.getOptions().randomizeSeed( ) # Need to do this otherwise exact same numbers will be generated for each identical run sim.simulate(listener_array)
def RelationshipType(name): if name in rel_types: return rel_types[name] else: rel_types[name] = type = jpype.JProxy(core.RelationshipType,dict={ 'name': lambda:name }) return type
def StopAtDepth(limit): limit = int(limit) assert limit > 0, "Illegal stop depth." if limit == 1: return core.StopEvaluator.DEPTH_ONE else: return jpype.JProxy(Stop, dict={ 'isStopNode': lambda pos: limit <= pos.depth() })
def new_interface_object(interface_class_name, instance): if interface_class_name is None or interface_class_name == '': raise Exception('interface class name is none') try: jproxy = jpype.JProxy(interface_class_name, inst=instance) return jproxy except Exception as e: print(e) return None
def clone(self): return jpype.JProxy(( jpype.JPackage( "net").sf.openrocket.simulation.listeners.SimulationListener, jpype.JPackage("net").sf.openrocket.simulation.listeners. SimulationEventListener, jpype.JPackage("net").sf.openrocket.simulation.listeners. SimulationComputationListener, jpype.java.lang.Cloneable, ), inst=copy(self))
def setSTDOUT(self): if self.JavaRootPath is None or not self.isJVMRunning: return None # updated to @JImplements stdoutPipe = jpype.JProxy( "com.github.skiller9090.stdredirect.PythonPipe", inst=sys.stdout) # stderrPipe = jpype.JProxy("com.github.skiller9090.stdredirect.PythonPipe", inst=sys.stderr) out_stream = jpype.JClass( "com.github.skiller9090.stdredirect.PythonPrintStream")() out_stream.setPythonStdout(stdoutPipe) # err_stream = jpype.JClass("com.github.skiller9090.stdredirect.PythonOutputStream")() # err_stream.setPythonStdout(stderrPipe) ps = jpype.JClass("java.io.PrintStream") jpype.java.lang.System.setOut(ps(out_stream))
def _init_logs(): """ Initialize Java logging. Is called by :func:`jvm`. """ appender = jclass('PythonBridgeAppender') # ``bridge`` is a static property of PythonBridge class. # So there will be only one JavaLoggingBridge for all loggers. appender.bridge = jpype.JProxy('org.gem.log.PythonBridge', inst=JavaLoggingBridge()) props = jclass("Properties")() props.setProperty('log4j.rootLogger', 'debug, pythonbridge') props.setProperty('log4j.appender.pythonbridge', 'org.gem.log.PythonBridgeAppender') jpype.JClass("org.apache.log4j.PropertyConfigurator").configure(props)
def main(self): # Load the template document. doc = self.Document(self.dataDir + "Template.doc") # Setup mail merge event handler to do the custom work. c = HandleMergeField() proxy = jpype.JProxy("com.aspose.words.IFieldMergingCallback", inst=c) doc.getMailMerge().setFieldMergingCallback(proxy) # This is the data for mail merge. fieldNames = ["RecipientName", "SenderName", "FaxNumber", "PhoneNumber", "Subject", "Body", "Urgent", "ForReview", "PleaseComment"] fieldValues = ["Josh", "Jenny", "123456789", "", "Hello", "Test message 1", True, False, True] # Execute the mail merge. doc.getMailMerge().execute(fieldNames, fieldValues) # Save the finished document. doc.save(self.dataDir + "Template Out.doc")
def testProxy(self): p = jpype.JProxy([self._intf], dict={'call': proxy}) r = self._test().callProxy(p, "roundtrip") self.assertEqual(r, "roundtrip") self.assertIsInstance(r, str)
def render_text(self, outfd, data): j_test_path = '-Djava.class.path=/root/JDI.jar' jpype.startJVM(jpype.getDefaultJVMPath(), j_test_path) tasks = self.calculate() if len(tasks) > 0: task = tasks[0] else: jpype.shutdownJVM() raise Exception("no task or wrong pid") # configuration fnames = ['func1', 'func2'] vnames = [['x', 'y'], ['x', 'y']] vtypes = [[1, 1], [2, 2]] # ssh hostname = '10.108.166.165' port = 22 username = '******' password = '******' cmd = 'java -jar pyagent.jar ' + str(task.pid) ssh_res = ssh_cmd(hostname=hostname, port=port, username=username, password=password, cmd=cmd) if 'yes' not in ssh_res: print ssh_res raise Exception("no task or wrong pid") libnames = [] libbases = [] libs = [] name_set = set() for vma in task.get_proc_maps(): fname = vma.vm_name(task) if fname == "Anonymous Mapping": fname = "" if len(fname) > 0 and fname not in name_set: name_set.add(fname) lib = Library() lib.base = vma.vm_start lib.name = fname libnames.append(str(lib.name)) libbases.append(long(lib.base)) libs.append(lib) for lib in libs: if ".so" in lib.name or "java" in lib.name: print "base:", lib.base, "name:", lib.name threadsId = [] for thread in task.threads(): threadsId.append(long(thread.pid)) self.libnames = libnames self.libbases = libbases self.threadsId = threadsId self.currentTask = task self.libs = libs self.symbolDict = {} symbol = volatility.plugins.linux.java.readelf.read_sym_offset( "/usr/local/development/jdk1.7.0_79/jre/lib/amd64/server/libjvm.so" ) self.symbolDict[ "/usr/local/development/jdk1.7.0_79/jre/lib/amd64/server/libjvm.so"] = symbol PyDump = jpype.JPackage('sun.tools.python').PyDump self.PyDump = PyDump method_dict = { 'getThreadsId': self.getThreadsId, 'getLibName': self.getLibName, 'getLibBase': self.getLibBase, 'lookUpByName': self.lookUpByName, 'readBytesFromProcess': self.readBytesFromProcess } jp = jpype.JProxy( 'sun.jvm.hotspot.debugger.linux.PythonMethodInterface', dict=method_dict) # java init PyDump.initVM(jp, int(task.pid)) first_fp = PyDump.initJavaFirstFPAddress("main", True) # event self.event_front_1 = '<xml type="event" name="' self.event_front_2 = '">' self.event_middle_1 = '<' self.event_middle_2 = '>' self.event_middle_3 = '</' self.event_middle_4 = '>' self.event_end = '</xml>\r\n\r\n' tcpSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) tcpSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) tcpSocket.bind(('', 6666)) tcpSocket.listen(5) while True: try: print "waiting for connection..." client, addr = tcpSocket.accept() print "...connected from:", addr while True: time.sleep(1) for result in self.getEvent(first_fp, fnames, vnames, vtypes): if result is not None: print result client.sendall(result) except Exception, e: print repr(e) finally:
def __new__(cls, *args, **kwargs): inst = super(InterfaceProxy, cls).__new__(cls, *args, **kwargs) inst.__init__(*args, **kwargs) return jpype.JProxy((interface, ), inst=inst)
def __init__(self): self.stop = jpype.JProxy(Stop, inst=self) self.returnable = jpype.JProxy(Returnable, inst=self)
def render_text(self, outfd, data): j_test_path = '-Djava.class.path=/root/JDI-old.jar' jpype.startJVM(jpype.getDefaultJVMPath(), j_test_path) tasks = self.calculate() if len(tasks) > 0: task = tasks[0] else: jpype.shutdownJVM() raise Exception("no task or wrong pid") libnames = [] libbases = [] libs = [] name_set = set() for vma in task.get_proc_maps(): fname = vma.vm_name(task) if fname == "Anonymous Mapping": fname = "" if len(fname) > 0 and fname not in name_set: name_set.add(fname) lib = Library() lib.base = vma.vm_start lib.name = fname libnames.append(str(lib.name)) libbases.append(long(lib.base)) libs.append(lib) for lib in libs: if ".so" in lib.name or "java" in lib.name: print "base:", lib.base, "name:", lib.name threadsId = [] for thread in task.threads(): threadsId.append(long(thread.pid)) self.libnames = libnames self.libbases = libbases self.threadsId = threadsId self.currentTask = task self.libs = libs self.symbolDict = {} self.total_time = 0 self.rr_time = 0 symbol = volatility.plugins.linux.java.readelf.read_sym_offset( "/usr/local/development/jdk1.7.0_79/jre/lib/amd64/server/libjvm.so" ) self.symbolDict[ "/usr/local/development/jdk1.7.0_79/jre/lib/amd64/server/libjvm.so"] = symbol j_frames = jpype.JPackage('sun.tools.jdi').Frames method_dict = { 'getThreadsId': self.getThreadsId, 'getLibName': self.getLibName, 'getLibBase': self.getLibBase, 'lookUpByName': self.lookUpByName, 'readBytesFromProcess': self.readBytesFromProcess } jp = jpype.JProxy( 'sun.jvm.hotspot.debugger.linux.PythonMethodInterface', dict=method_dict) j_frames.init(str(task.pid), jp, 1, 'func4') print "real read time is", self.rr_time print "read time is", self.total_time cmd = raw_input() while "q" not in cmd: res = j_frames.getThread('func4') if res == 0: print "not contains" cmd = raw_input() continue self.total_time = 0 self.rr_time = 0 t1 = time.time() j_frames.pythonTest(str(cmd), 'func4') t2 = time.time() print "real read time is", self.rr_time print "read time is", self.total_time print "time is", t2 - t1 cmd = raw_input() jpype.shutdownJVM()
def ConnectIP(self): try: #create a socket RValue = False self._connected = False #s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) hostname = socket.gethostname() localIP = socket.gethostbyname(hostname) remoteIP = self.__ipIP localEP = Global.InetSocketAddress(localIP, 0) remoteEP = Global.InetSocketAddress(remoteIP, int(self.__ipPort)) self.__KNXNetworkLinkIP = Global.KNXNetworkLinkIP( Global.KNXNetworkLinkIP.TUNNEL, localEP, remoteEP, False, Global.TPSettings(True)) #ip tunnel connection self.__KNXConnection = Global.KNXnetIPTunnel( Global.KNXnetIPTunnel.LINK_LAYER, localEP, remoteEP, False) #create a JProxy to integrate the Java interface KNXListener d = { 'frameReceived': self.frameReceived, 'connectionClosed': self.connectionClosed, } proxy = jpype.JProxy(Global.KNXListener, dict=d) self.__KNXConnection.addConnectionListener(proxy) if self.__KNXConnection.getState() == Global.KNXnetIPConnection.OK: RValue = True self._connected = True else: RValue = False self._connected = False return RValue except jpype.JavaException, ex: error = "" self._connected = False if jpype.JavaException.javaClass(ex) is Global.KNXException: error = "Allg. Socket-Verbindungsfehler : " + str( jpype.JavaException.message(ex)) elif jpype.JavaException.javaClass( ex) is Global.KNXTimeoutException: error = "Fehler beim Verbindungsaufbau : " + str( jpype.JavaException.message(ex)) elif jpype.JavaException.javaClass( ex) is Global.KNXRemoteException: error = "Fehler beim Remote-Server : " + str( jpype.JavaException.message(ex)) elif jpype.JavaException.javaClass( ex) is Global.KNXInvalidResponseException: error = "Falsches Format bei der Antwort : " + str( jpype.JavaException.message(ex)) msgbox = gtk.MessageDialog(parent=self.__parent, buttons=gtk.BUTTONS_OK, flags=gtk.DIALOG_MODAL, type=gtk.MESSAGE_ERROR, message_format=error) msgbox.set_title(Global.ERRORCONNECTIONTITLE) result = msgbox.run() msgbox.destroy()
def render_text(self, outfd, data): # local_conf = Conf() # local_conf.config_no() # local_conf.start() j_test_path = '-Djava.class.path=/home/kong/JavaMemory/JDI/out/artifacts/JDI/JDI.jar' jpype.startJVM(jpype.getDefaultJVMPath(), j_test_path) tasks = self.calculate() if len(tasks) > 0: task = tasks[0] else: jpype.shutdownJVM() raise Exception("no task or wrong pid") # configuration self.fnames = ['add', 'sub'] self.vnames = [['x', 'y'], ['x', 'y']] self.vtypes = [[4, 4], [4, 4]] # ssh hostname = '10.108.164.232' port = 22 username = '******' password = '******' cmd = 'java -jar /home/vm/pyagent.jar ' + str(task.pid) ssh_res = ssh_cmd(hostname=hostname, port=port, username=username, password=password, cmd=cmd) if 'yes' not in ssh_res: print ssh_res raise Exception("no task or wrong pid") libnames = [] libbases = [] libs = [] name_set = set() for vma in task.get_proc_maps(): fname = vma.vm_name(task) if fname == "Anonymous Mapping": fname = "" if len(fname) > 0 and fname not in name_set: name_set.add(fname) lib = Library() lib.base = vma.vm_start lib.name = fname libnames.append(str(lib.name)) libbases.append(long(lib.base)) libs.append(lib) for lib in libs: if ".so" in lib.name or "java" in lib.name: print "base:", lib.base, "name:", lib.name threadsId = [] for thread in task.threads(): threadsId.append(long(thread.pid)) self.libnames = libnames self.libbases = libbases self.threadsId = threadsId self.currentTask = task self.libs = libs self.symbolDict = {} # symbol = volatility.plugins.linux.java.readelf.read_sym_offset("/usr/local/development/jdk1.7.0_79/jre/lib/amd64/server/libjvm.so") # self.symbolDict["/usr/local/development/jdk1.7.0_79/jre/lib/amd64/server/libjvm.so"] = symbol symbol = volatility.plugins.linux.java.readelf.read_sym_offset( "/home/kong/JavaMemory/jdk1.7.0_79/jre/lib/amd64/server/libjvm.so") self.symbolDict["/home/vm/jdk1.7.0_79/jre/lib/amd64/server/libjvm.so"] = symbol PyDump = jpype.JPackage('sun.tools.python').PyDump self.PyDump = PyDump method_dict = { 'getThreadsId': self.getThreadsId, 'getLibName': self.getLibName, 'getLibBase': self.getLibBase, 'lookUpByName': self.lookUpByName, 'readBytesFromProcess': self.readBytesFromProcess } jp = jpype.JProxy('sun.jvm.hotspot.debugger.linux.PythonMethodInterface', dict = method_dict) # java init PyDump.initVM(jp, int(task.pid)) self.first_fp_list = [] for index in range(1, 11): threadName = 'http-nio-8080-exec-' + str(index) first_fp = PyDump.initJavaFirstFPAddress(threadName, True) self.first_fp_list.append(first_fp) print threadName, first_fp # event self.event_front_1 = '<xml type="event" name="' self.event_front_2 = '">' self.event_middle_1 = '<' self.event_middle_2 = '>' self.event_middle_3 = '</' self.event_middle_4 = '>' self.event_end = '</xml>\r\n\r\n' self.client = None # tcpSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # tcpSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # tcpSocket.bind(('', 6666)) # tcpSocket.listen(5) # while True: # try: # print "waiting for connection..." # client, addr = tcpSocket.accept() # print "...connected from:", addr # while True: # time.sleep(1) # for result in self.getEvent(first_fp, fnames, vnames, vtypes): # if result is not None: # print result # client.sendall(result) # except Exception, e: # print repr(e) # finally: # client.close() # tcpSocket.close() # self.conf = Conf() # self.conf.config_c(self.run_command, self.stop_command) # self.conf.start() count = 10 while count > 0: print "#######################" for first_fp in self.first_fp_list: inf = self.getEvent(first_fp, self.fnames, self.vnames, self.vtypes, self.client) count -= 1 PyDump.stop() jpype.shutdownJVM()
def render_text(self, outfd, data): # local_conf = Conf() # local_conf.config_no() # local_conf.start() print ">>>>>> render_test >>>>>>" # start JVM, j_test_path is param represent DLL j_test_path = '-Djava.class.path=/home/kong/JavaMemory/JDI/out/artifacts/JDI/JDI.jar' jpype.startJVM(jpype.getDefaultJVMPath(), j_test_path) # tasks 表示被监控程序的进程Id(JVM) tasks = self.calculate() if len(tasks) > 0: # task = tasks[0] task = tasks[-1] print "task.pid is ", task.pid else: jpype.shutdownJVM() raise Exception("no task or wrong pid") # configuration self.fnames = ['func1', 'func2', 'func3', 'func4'] self.vnames = [['x', 'y'], ['x', 'y'], ['x', 'y'], ['x', 'y']] self.vtypes = [[1, 1], [2, 2], [3, 3], [4, 4]] # ssh hostname = '10.108.164.232' port = 22 username = '******' password = '******' cmd = 'java -jar /home/vm/pyagent.jar ' + str(task.pid) ssh_res = ssh_cmd(hostname=hostname, port=port, username=username, password=password, cmd=cmd) if 'yes' not in ssh_res: print ssh_res.decode() raise Exception("no task or wrong pid") else: print 'pyagent.jar return yes' libnames = [] # 共享库名称 libbases = [] # 共享库起始地址 libs = [] name_set = set() # 获取共享库函数在进程中的虚拟地址映射 # vma 虚拟内存空间 for vma in task.get_proc_maps(): fname = vma.vm_name(task) if fname == "Anonymous Mapping": fname = "" if len(fname) > 0 and fname not in name_set: name_set.add(fname) lib = Library() lib.base = vma.vm_start lib.name = fname libnames.append(str(lib.name)) libbases.append(long(lib.base)) libs.append(lib) for lib in libs: if ".so" in lib.name or "java" in lib.name: print "base:", hex(lib.base), "name:", lib.name # 获取子线程tid threadsId = [] for thread in task.threads(): threadsId.append(long(thread.pid)) print threadsId self.libnames = libnames self.libbases = libbases self.threadsId = threadsId self.currentTask = task self.libs = libs self.symbolDict = {} # read elf function, symbol represent share lib offset symbol = volatility.plugins.linux.java.readelf.read_sym_offset("/home/kong/JavaMemory/jdk1.7.0_79/jre/lib/amd64/server/libjvm.so") self.symbolDict["/home/vm/jdk1.7.0_79/jre/lib/amd64/server/libjvm.so"] = symbol # java interface for python PyDump = jpype.JPackage('sun.tools.python').PyDump self.PyDump = PyDump # python interface for java method_dict = { 'getThreadsId': self.getThreadsId, 'getLibName': self.getLibName, 'getLibBase': self.getLibBase, 'lookUpByName': self.lookUpByName, 'readBytesFromProcess': self.readBytesFromProcess } jp = jpype.JProxy('sun.jvm.hotspot.debugger.linux.PythonMethodInterface', dict = method_dict) # java init PyDump.initVM(jp, int(task.pid)) # self.first_fp = PyDump.initJavaFirstFPAddress("testBusyThread", True) self.first_fp = PyDump.initJavaFirstFPAddress("main", True) print 'first_fp:', hex(self.first_fp) # event self.event_front_1 = '<xml type="event"' self.event_front_2 = '">' self.event_middle_1 = '<' self.event_middle_2 = '>' self.event_middle_3 = '</' self.event_middle_4 = '>' self.event_end = '</xml>\r\n\r\n' self.client = None print "===== START =====", os.getpid() # d1wait = datetime.datetime.now() # tcpSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # tcpSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # tcpSocket.bind(('', 6666)) # tcpSocket.listen(5) # try: # print "waiting for connection..." # self.client, addr = tcpSocket.accept() # print "...connected from:", addr # # self.conf = Conf() # # self.conf.config(self.run_command, self.stop_command) # # self.conf.start() # except Exception, e: # print repr(e) count = 10 while count > 0: print "#######################" try: time.sleep(0.1) time_start = time.clock() result = self.getEvent(self.first_fp, self.fnames, self.vnames, self.vtypes, self.client) time_end = time.clock() print "start, end: ", time_start, ",", time_end print "Durning: ", (time_end - time_start) * 1000, "ms" count -= 1 except Exception, e: print repr(e)
def EwakstarDoer_ConfSearchFactory(func): # convert the python lambda to a JVM interface implementation return jpype.JProxy(jvm.c.java.util.function.Function, dict={'apply': func})
def get_proxy(self, supertype, instance): return jpype.JProxy(supertype, inst=instance)
if __name__ == '__main__': jpype.startJVM(classpath=['test/classes', 'project/jpype_java/dist/*'], convertStrings=True) print() kB = (1024 / 8) MB = (1024**2 / 8) fixture = JClass("jpype.common.Fixture")() for i in range(trials): x = np.arange(int(10 * kB), dtype=np.int64) interface = jpype.JProxy( "java.io.Serializable", dict={'callback': DestructionTracker(i, x).callback}) interface_container = fixture.callObject(interface) if (i % 1000) == 0: stats = _jpype.gcStats() print( "created=", DestructionTracker.init_calls, " destroyed=", DestructionTracker.del_calls, " delta=", DestructionTracker.init_calls - DestructionTracker.del_calls, " current=", stats['current'], " min=",
def render_text(self, outfd, data): local_conf = Conf() local_conf.config_no() local_conf.start() # start JVM, j_test_path is param represent DLL j_test_path = '-Djava.class.path=/home/kong/java memory/JDI.jar' jpype.startJVM(jpype.getDefaultJVMPath(), j_test_path) tasks = self.calculate() if len(tasks) > 0: task = tasks[0] else: jpype.shutdownJVM() raise Exception("no task or wrong pid") # configuration self.fnames = ['func1', 'func2', 'func3', 'func4'] self.vnames = [['x', 'y'], ['x', 'y'], ['x', 'y'], ['x', 'y']] self.vtypes = [[1, 1], [2, 2], [3, 3], [4, 4]] # ssh # hostname = '10.108.164.67' # port = 22 # username = '******' # password = '******' # # cmd = 'java -jar pyagent.jar ' + str(task.pid) # ssh_res = ssh_cmd(hostname=hostname, port=port, username=username, password=password, cmd=cmd) # if 'yes' not in ssh_res: # print ssh_res # raise Exception("no task or wrong pid") libnames = [] # 共享库名称 libbases = [] # 共享库起始地址 libs = [] name_set = set() # 获取共享库函数在进程中的虚拟地址映射 # vma 虚拟内存空间 for vma in task.get_proc_maps(): fname = vma.vm_name(task) if fname == "Anonymous Mapping": fname = "" if len(fname) > 0 and fname not in name_set: name_set.add(fname) lib = Library() lib.base = vma.vm_start lib.name = fname libnames.append(str(lib.name)) libbases.append(long(lib.base)) libs.append(lib) for lib in libs: if ".so" in lib.name or "java" in lib.name: print "base:", lib.base, "name:", lib.name # 获取子线程tid threadsId = [] for thread in task.threads(): threadsId.append(long(thread.pid)) self.libnames = libnames self.libbases = libbases self.threadsId = threadsId self.currentTask = task self.libs = libs self.symbolDict = {} # read elf function, symbol represent share lib offset symbol = volatility.plugins.linux.java.readelf.read_sym_offset( "/home/kong/java memory/jdk1.7.0_79/jre/lib/amd64/server/libjvm.so" ) self.symbolDict[ "/home/vm/jdk1.7.0_79/jre/lib/amd64/server/libjvm.so"] = symbol # java interface for python PyDump = jpype.JPackage('sun.tools.python').PyDump self.PyDump = PyDump # python interface for java method_dict = { 'getThreadsId': self.getThreadsId, 'getLibName': self.getLibName, 'getLibBase': self.getLibBase, 'lookUpByName': self.lookUpByName, 'readBytesFromProcess': self.readBytesFromProcess } jp = jpype.JProxy( 'sun.jvm.hotspot.debugger.linux.PythonMethodInterface', dict=method_dict) # java init PyDump.initVM(jp, int(task.pid)) self.first_fp = PyDump.initJavaFirstFPAddress("main", True) print 'first_fp:', self.first_fp # event self.event_front_1 = '<xml type="event"' self.event_front_2 = '">' self.event_middle_1 = '<' self.event_middle_2 = '>' self.event_middle_3 = '</' self.event_middle_4 = '>' self.event_end = '</xml>\r\n\r\n' self.client = None # tcpSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # tcpSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # tcpSocket.bind(('', 6666)) # tcpSocket.listen(5) try: print "waiting for connection..." # self.client, addr = tcpSocket.accept() # print "...connected from:", addr self.conf = Conf() self.conf.config(self.run_command, self.stop_command) self.conf.start() except Exception, e: print repr(e)
def _KStarConfSearchFactory(func): # convert the python lambda to a JVM interface implementation return jpype.JProxy(jvm.getInnerClass(c.kstar.KStar, 'ConfSearchFactory'), dict={'make': func})
def render_text(self, outfd, data): j_test_path = '-Djava.class.path=/root/JDI.jar' jpype.startJVM(jpype.getDefaultJVMPath(), j_test_path) tasks = self.calculate() if len(tasks) > 0: task = tasks[0] else: jpype.shutdownJVM() raise Exception("no task or wrong pid") # ssh hostname = '10.108.166.165' port = 22 username = '******' password = '******' cmd = 'java -jar pyagent.jar ' + str(task.pid) ssh_res = ssh_cmd(hostname=hostname, port=port, username=username, password=password, cmd=cmd) if 'yes' not in ssh_res: print ssh_res raise Exception("wrong ssh") libnames = [] libbases = [] libs = [] name_set = set() for vma in task.get_proc_maps(): fname = vma.vm_name(task) if fname == "Anonymous Mapping": fname = "" if len(fname) > 0 and fname not in name_set: name_set.add(fname) lib = Library() lib.base = vma.vm_start lib.name = fname libnames.append(str(lib.name)) libbases.append(long(lib.base)) libs.append(lib) for lib in libs: if ".so" in lib.name or "java" in lib.name: print "base:", lib.base, "name:", lib.name threadsId = [] for thread in task.threads(): threadsId.append(long(thread.pid)) self.libnames = libnames self.libbases = libbases self.threadsId = threadsId self.currentTask = task self.libs = libs self.symbolDict = {} symbol = volatility.plugins.linux.java.readelf.read_sym_offset( "/usr/local/development/jdk1.7.0_79/jre/lib/amd64/server/libjvm.so" ) self.symbolDict[ "/usr/local/development/jdk1.7.0_79/jre/lib/amd64/server/libjvm.so"] = symbol PyDump = jpype.JPackage('sun.tools.python').PyDump self.PyDump = PyDump method_dict = { 'getThreadsId': self.getThreadsId, 'getLibName': self.getLibName, 'getLibBase': self.getLibBase, 'lookUpByName': self.lookUpByName, 'readBytesFromProcess': self.readBytesFromProcess } jp = jpype.JProxy( 'sun.jvm.hotspot.debugger.linux.PythonMethodInterface', dict=method_dict) fpAddress = 0 spAddress = 0 first_fp = 0 print "input:" cmd = raw_input() vm_state = False while "q" not in cmd: if "1" in cmd: if vm_state: print "input:" cmd = raw_input() continue PyDump.initVM(jp, int(task.pid)) print "init VM" vm_state = True elif "2" in cmd: fpAddress = PyDump.initJavaLastFPAddress("main", True) spAddress = PyDump.initJavaLastSPAddress("main", True) print "get the address of last fp and sp" elif "3" in cmd: try: if fpAddress != 0 and spAddress != 0: print fpAddress, spAddress t1 = time.time() fp = self.readAddressByAddress(fpAddress) print time.time() - t1 fp = self.readAddressByAddress(fpAddress) print time.time() - t1 sp = self.readAddressByAddress(spAddress) print time.time() - t1 res = self.readMemory(sp, 1000)[0] fp = self.readAddressByAddress(fpAddress) print time.time() - t1 for i in range(5): print hex(fp), hex(sp) local = res[fp - 48] print "locals:", for j in range(5): print res[local - j * 8], print sp = fp + 16 fp = res[fp] else: print "failed" except Exception, e: print "except:", repr(e) elif "4" in cmd: if not vm_state: PyDump.initVM(jp, int(task.pid)) vm_state = True first_fp = PyDump.initJavaFirstFPAddress("main", True) PyDump.clear() print "get the address of first fp" print first_fp