def endExecution(self): LittleAction.endExecution(self) if self.workslot.building.money >=0: print self.people.name, " recupere ", self.workslot.building.money self.people.money += self.workslot.building.money self.workslot.building.money = 0. else: toGive = max(min (-self.workslot.building.money, self.people.money - 5.) , 0.) print self.people.name, " donne ", toGive self.people.money -= toGive self.workslot.building.money += toGive for o in self.workslot.building.wantObjects.keys(): utils.addToDict(self.workslot.building.wantToBuy, o, self.workslot.building.wantObjects[o]*24/self.workslot.building.lastManaged) self.workslot.building.wantObjects = {} for o in self.workslot.building.wantToBuy.keys(): self.workslot.building.wantToBuy[o] *= 0.9 cost = 0. for c in self.workslot.building.costs.values(): cost -= c print self.workslot.building.name," : couts ",cost," en ",self.workslot.building.lastManaged," heures" profit = 0. for p in self.workslot.building.profits.values(): profit += p print self.workslot.building.name," : profits ",profit," en ",self.workslot.building.lastManaged," heures" if profit != 0: diff = (profit - 1.3*cost)/profit else: diff = 1 if diff > 1.: diff = 1. if diff < -1: diff = -1. print diff for c in self.workslot.building.costs.keys(): val = utils.getDict(self.workslot.building.prices, c)*(1+0.1*diff) utils.addToDict(self.workslot.building.prices, c, min(-0.1, val)) for p in self.workslot.building.profits.keys(): val = utils.getDict(self.workslot.building.prices, p)*(1-0.1*diff) utils.addToDict(self.workslot.building.prices, p, max(0.1, val)) self.workslot.building.costs = {} self.workslot.building.profits = {} self.workslot.building.lastManaged = 0
def getPossibleActions(self, actionType=[]): if self.occupied: return [] if "constructing" in self.types : if(actionType==[] or "work" in actionType or "build" in actionType): recipe = allRecipes["build"] meanTime = (recipe.timeMax - recipe.timeMin)/2. price=int(10*self.building.prices["basePrice"]*meanTime)/10. act = LittleWorkAction(workslot=self, type="build" ) act.price = -price return [act] return [] actions = [] for type in self.types: if type not in workSlotTypes.keys(): #~ print "no actions for workslot type ",type continue else: for a in workSlotTypes[type].recipes: recipe = allRecipes[a] if actionType != []: #~ print "recipe ",a, "action types ",actionType if a in specialWorks and a not in actionType: #~ print "special, not here" continue if a not in specialWorks and a not in actionType and "work" not in actionType: #~ print "not special, not here" continue meanTime = (recipe.timeMax - recipe.timeMin)/2. price=int(10*self.building.prices["basePrice"]*meanTime)/10. if a == "sleep": act = LittleSleepAction(workslot=self) #~ act.price = price act.price = max(utils.getDict(self.building.prices, "sleep"), 0.1) elif a == "eat": act = LittleEatAction(workslot=self) act.price = max(utils.getDict(self.building.prices, "eat"), 0.1) #~ act.price = price else: act = LittleWorkAction(workslot=self, type=a) act.price = -int(10*self.building.prices["basePrice"]*meanTime)/10. if act.canExecute(): actions.append(act) return actions
def test_should_create_task_with_authorized_request(self): newUser = self.createUser(self.user) newUserLogin = self.loginUser(self.user) response = getDict(newUserLogin.content) newTask = self.createTask( token = response['access'], task = json.dumps({ 'title': 'Title task', 'content':'Content task', }) ) responseTask = getDict(newTask.content) self.assertEqual(newTask.status_code, 201)
def register(request): requiredParams = [ 'email', 'username', 'password', ] code = _validate(request, requiredParams) if code != 200: return HttpResponse(status=code) else: params = getDict(request.body) try: u = User.objects.create_user( username = params['username'].lower(), email = params['email'], password = params['password'], ) u.save() return HttpResponse(status = 201) except Exception as e: return HttpResponse( status = 400, content_type = 'application/json', content = json.dumps({ 'detail' : 'invalid parameters', }) )
def test_should_be_allowed_to_delete_tasks(self): newUser = self.createUser(self.user) newUserLogin = self.loginUser(self.user) response = getDict(newUserLogin.content) newTask = self.createTask( token = response['access'], task = json.dumps({ 'title': 'Title', 'content': 'Content', }), ) taskID = 1 # Remove task deletedTask = self.makeRequest.delete( path = self.tasksPath + str(taskID) + '/', HTTP_AUTHORIZATION = 'Bearer ' + response['access'], ) self.assertEqual(deletedTask.status_code, 200) # Try to find task with id that doesn't exists anymore # And should throw error 404 task = self.makeRequest.get( path = self.tasksPath + str(taskID) + '/', HTTP_AUTHORIZATION = 'Bearer ' + response['access'], ) self.assertEqual(task.status_code, 404)
def test_should_throw_error_on_update_inexistent_task(self): newUser = self.createUser(self.user) newUserLogin = self.loginUser(self.user) response = getDict(newUserLogin.content) newTask = self.createTask( token = response['access'], task = json.dumps({ 'title': 'Title task', 'content': 'Content task', }), ) taskID = 1 updatedTask = self.makeRequest.patch( path = self.tasksPath + str(taskID + 1) + '/', content_type = self.contentType, data = json.dumps({ 'content': 'new content', 'title': 'new title', }), HTTP_AUTHORIZATION = 'Bearer ' + response['access'], ) self.assertEqual(updatedTask.status_code, 404)
def getPossibleActions(self, isOwner=False, actionTypes=[]): #~ print self.owner actions = [] for s in self.workSlots: actions = actions + s.getPossibleActions(actionTypes) if isOwner and (actionTypes == [] or "manage" in actionTypes): if len(self.workSlots) == 0: print "can't manage without workslots !" else: #~ print "manage action possible" actions.append(LittleManageAction(workslot=self.workSlots[0])) reallyWantToBuy = copy.deepcopy(self.wantToBuy) if actionTypes == [] or "buy" in actionTypes: for o in self.objects.keys(): if utils.getDict(self.wantToBuy, o) > self.objects[o]: #~ if o in reallyWantToBuy.keys() and reallyWantToBuy[o] > 0: #~ reallyWantToBuy[o] -=1 #~ else: #~ print "can sell ",o actions.append(LittleBuyAction(workslot=self.workSlots[0], object=o)) #~ print len(actions)," possible actions for type ",actionTypes," in ",self.name return actions
def _validate(request, requiredParams, email=True): """ this method return 200 if: - method is POST and - contentType is application/json and - has all required params and - email is well formated """ if request.method == 'POST': try: body = getDict(request.body) except: return 400 if ( request.content_type == 'application/json' and hasRequiredParams(body, requiredParams) ): if email: try: validate_email(body['email']) except: return 400 return 200 else: return 400 else: return 404
def main(): """ This function will parse argments, prepare data and prepare pretrained embedding """ args = parser.parse_args() global_config = configs.__dict__[args.config]() if args.epoch_num != None: global_config.epoch_num = args.epoch_num print("net_name: ", args.model_name) net = models.__dict__[args.model_name](global_config) # get word_dict word_dict = utils.getDict(data_type="quora_question_pairs") # get reader train_reader, dev_reader, test_reader = utils.prepare_data( "quora_question_pairs", word_dict=word_dict, batch_size=global_config.batch_size, buf_size=800000, duplicate_data=global_config.duplicate_data, use_pad=(not global_config.use_lod_tensor)) # load pretrained_word_embedding if global_config.use_pretrained_word_embedding: word2vec = Glove840B_300D( filepath=os.path.join(DATA_DIR, "glove.840B.300d.txt"), keys=set(word_dict.keys())) pretrained_word_embedding = utils.get_pretrained_word_embedding( word2vec=word2vec, word2id=word_dict, config=global_config) print("pretrained_word_embedding to be load:", pretrained_word_embedding) else: pretrained_word_embedding = None # define optimizer optimizer = utils.getOptimizer(global_config) # use cuda or not if not global_config.has_member('use_cuda'): if 'CUDA_VISIBLE_DEVICES' in os.environ and os.environ[ 'CUDA_VISIBLE_DEVICES'] != '': global_config.use_cuda = True else: global_config.use_cuda = False global_config.list_config() train_and_evaluate( train_reader, dev_reader, test_reader, net, optimizer, global_config, pretrained_word_embedding, use_cuda=global_config.use_cuda, parallel=False)
def test_should_get_all_tasks_with_authorized_request(self): newUser = self.createUser(self.user) newUserLogin = self.loginUser(self.user) response = getDict(newUserLogin.content) Tasks = [ { 'title': 'Task title 1', 'content': 'Task content' }, { 'title': 'Task title 2', 'content': 'Task content' }, { 'title': 'Task title 3', 'content': 'Task content' }, { 'title': 'Task title 4', 'content': 'Task content' }, { 'title': 'Task title 5', 'content': 'Task content' }, ] for task in Tasks: newTask = self.createTask( token = response['access'], task = json.dumps(task), ) self.assertEqual(newTask.status_code, 201) allTasks = self.makeRequest.get( path = self.tasksPath, content_type = self.contentType, HTTP_AUTHORIZATION = 'Bearer ' + response['access'], ) response = getDict(allTasks.content) self.assertEqual(allTasks.status_code, 200) self.assertIsInstance(response, list)
def test_should_throw_error_on_get_inexistent_task(self): newUser = self.createUser(self.user) newUserLogin = self.loginUser(self.user) response = getDict(newUserLogin.content) task = self.makeRequest.get( path = self.tasksPath + '1/', content_type = self.contentType, HTTP_AUTHORIZATION = 'Bearer ' + response['access'], ) self.assertEqual(task.status_code, 404)
def decode(filename): # Getting the huffman tree of the file and the compressed file's file pointer dict, input = utils.getDict(filename[:-4] + ".du") # Manipulating strings to generate the new name of the decompressed file compressedFilename = filename[:-4] extension = filename[-4:] decompressedFilename = compressedFilename + "Decompressed" + extension # Reading the artifitial bits of the last byte of the compressed file artifitialBits = int.from_bytes(input.read(1), "big") # Auxiliary variables buffer = 0 buffer2 = 0 key = "" # Start writing the decompressed file and reading the content of the compressed one output = open(decompressedFilename, "wb") buffer = input.read(1) if buffer: while True: buffer2 = input.read(1) # If the second read was not sucessful, it means that buffer contains the last byte of the compressed file if not buffer2: bitArray = (BitArray(buffer)).bin # In this case, we just read the bits that we know are useful for i in range(0, len(bitArray) - artifitialBits): key += str(bitArray[i]) if key in dict: output.write(dict[key]) key = "" break else: # If buffer2 contains a byte, we are not at the end of the compressed file for bit in (BitArray(buffer)).bin: key += str(bit) # Check if the accumulated bits form a known key in the tree if key in dict: output.write(dict[key]) key = "" buffer = buffer2 return decompressedFilename
def test_should_throw_error_on_delete_tasks_without_login(self): newUser = self.createUser(self.user) newUserLogin = self.loginUser(self.user) response = getDict(newUserLogin.content) newTask = self.createTask( token = response['access'], task = json.dumps({ 'title': 'Title task', 'content': 'Content task', }), ) taskID = 1 deletedTask = self.makeRequest.delete( path = self.tasksPath + str(taskID) + '/', content_type = self.contentType, ) self.assertEqual(deletedTask.status_code, 401)
def test_should_throw_error_on_create_task_with_wrong_parametters(self): newUser = self.createUser(self.user) newUserLogin = self.loginUser(self.user) response = getDict(newUserLogin.content) badTasks = [ { # empty }, { # no title 'content': 'no title' }, { # no content 'title': 'no content', } ] for task in badTasks: newTask = self.createTask( token = response['access'], task = task, ) self.assertEqual(newTask.status_code, 400)
def search(request): if request.GET.get('term'): term = request.GET['term'].lower() inverseIndex = utils.getDict() retrievedDocs = utils.getSearchList(term) if len(retrievedDocs) > 10: retrievedDocs = retrievedDocs[10:] docs = [] for doc in retrievedDocs: try: retrieved = Document.objects.get(name=doc) docs.append(retrieved) except Exception: pass if len(docs) > 0: context = {'docs': docs} else: context = {'noneFound': "No Documents Found"} return render(request, 'search.html', context) return render(request, 'search.html')
# -*- encoding:utf8 -*- import torch import torch.autograd as autograd import utils as u import model datas = ["I am test sentence one", "You are the one he like", "I like eating"] mydict = u.getDict(datas) batch_size = 2 time_step = 5 embed_dim = 3 hidden_dim = 4 sentences = u.load_set(datas, mydict) paded_sents, masks = u.padding_and_generate_mask(sentences, time_step) LSTM = model.myLSTM(embed_dim, hidden_dim, len(mydict)) for s, m in u.batch_iter(paded_sents, masks, batch_size): s = autograd.Variable(torch.LongTensor(s), requires_grad=False) print s m = autograd.Variable(torch.FloatTensor(m), requires_grad=False) final_h = LSTM(s, m, time_step, batch_size) print final_h print '-' * 80
def createISymbolsNode(sample, symbolsList, path, baseAddr, nindsym): endian = utils.getEndianFormat(sample) sections = utils.getSections(sample) is64 = utils.is64Bit(sample) count = 0 inSymbols = {} addr = baseAddr offset = 0 while count < nindsym: desc = [] nsect = len(sections) while nsect > 0: nsect -= 1 section = sections[nsect] flag = section.flags # print(section.reserved1) if (flag & SECTION_TYPE != S_SYMBOL_STUBS \ and flag & SECTION_TYPE != S_LAZY_SYMBOL_POINTERS \ and flag & SECTION_TYPE != S_LAZY_DYLIB_SYMBOL_POINTERS \ and flag & SECTION_TYPE != S_NON_LAZY_SYMBOL_POINTERS) \ or section.reserved1 > count: #section type or indirect symbol index mismatch continue nsect = 0 #calculate stub or pointer length if section.reserved2 > 0: length = section.reserved2 else: if is64: length = 8 else: length = 4 #calculate indirect value location indirectOffset = section.offset + (count - section.reserved1) * length #read indirect symbol index byte, indirectIndex = ReadWrite.readInt32(path, endian, offset) offset += byte if indirectIndex & (INDIRECT_SYMBOL_LOCAL | INDIRECT_SYMBOL_ABS) == 0: if indirectIndex >= len(symbolsList): raise Exception("index is out of range " + str(indirectIndex)) symbolName = utils.getSymbolByIndex(symbolsList, indirectIndex) description = "Symbol" value = symbolName desc.append(utils.getDict(description, value)) else: description = "Symbol" value = [] if indirectIndex == INDIRECT_SYMBOL_LOCAL: value.append("80000000 INDIRECT_SYMBOL_LOCAL") elif indirectIndex == INDIRECT_SYMBOL_ABS: value.append("40000000 INDIRECT_SYMBOL_ABS") else: value.append("80000000 INDIRECT_SYMBOL_LOCAL") value.append("40000000 INDIRECT_SYMBOL_ABS") desc.append(utils.getDict(description, value)) description = "Section" value = "(" + section.segname.rstrip( '\x00') + "," + section.sectname.rstrip('\x00') + ")" desc.append(utils.getDict(description, value)) description = "Indirect Address" value = hex(indirectOffset).rstrip("L") + "($+" + str( indirectOffset - section.offset) + ")" desc.append(utils.getDict(description, value)) inSymbols[hex(addr)] = desc addr += byte count += 1 inSymbols = collections.OrderedDict(sorted(inSymbols.items())) return inSymbols
def createSymbolsNode(sample, strs, path, baseAddr, baseStrAddr, nsym): endian = utils.getEndianFormat(sample) frameworks = utils.getAllFrameworks(sample) sections = utils.getSections(sample) count = 0 symbols = {} addr = baseAddr offset = 0 while count < nsym: count += 1 byte, data = ReadWrite.readInt32(path, endian, offset) offset += byte description = "String Table Index" value = strs.get(hex(baseStrAddr + data).rstrip("L")) if value is None: value = "" symbols[hex(addr)] = utils.getDict(description, value) addr += byte byte, n_type = ReadWrite.readInt8(path, endian, offset) offset += byte types = [] description = "Type" if n_type & N_STAB: types.append("E0 N_STAB") else: if n_type & N_TYPE == N_UNDF: types.append("00 N_UNDF") elif n_type & N_TYPE == N_ABS: types.append("02 N_ABS") elif n_type & N_TYPE == N_SECT: types.append("0E N_SECT") elif n_type & N_TYPE == N_PBUD: types.append("0C N_PBUD") elif n_type & N_TYPE == N_INDR: types.append("0A N_INDR") if n_type & N_PEXT: types.append("10 N_PEXT") if n_type & N_EXT: types.append("01 N_EXT") symbols[hex(addr)] = utils.getDict(description, types) addr += byte byte, n_sect = ReadWrite.readInt8(path, endian, offset) offset += byte section = utils.getSectionByIndex(sections, n_sect) description = "Section Index" if n_sect == NO_SECT or section is None: value = "NO_SECT" else: value = str(n_sect) + "(" + section.segname.rstrip( '\x00') + "," + section.sectname.rstrip('\x00') + ")" symbols[hex(addr)] = utils.getDict(description, value) addr += byte byte, n_desc = ReadWrite.readInt16(path, endian, offset) offset += byte descriptions = [] description = "Description" if n_type & N_STAB == 0 and n_type & N_TYPE == N_UNDF or n_type & N_TYPE == N_PBUD and n_type & N_EXT: if n_desc & REFERENCE_TYPE == REFERENCE_FLAG_UNDEFINED_NON_LAZY: descriptions.append("0 REFERENCE_FLAG_UNDEFINED_NON_LAZY") elif n_desc & REFERENCE_TYPE == REFERENCE_FLAG_UNDEFINED_LAZY: descriptions.append("1 REFERENCE_FLAG_UNDEFINED_LAZY") elif n_desc & REFERENCE_TYPE == REFERENCE_FLAG_DEFINED: descriptions.append("2 REFERENCE_FLAG_DEFINED") elif n_desc & REFERENCE_TYPE == REFERENCE_FLAG_PRIVATE_DEFINED: descriptions.append("3 REFERENCE_FLAG_PRIVATE_DEFINED") elif n_desc & REFERENCE_TYPE == REFERENCE_FLAG_PRIVATE_UNDEFINED_NON_LAZY: descriptions.append( "4 REFERENCE_FLAG_PRIVATE_UNDEFINED_NON_LAZY") elif n_desc & REFERENCE_TYPE == REFERENCE_FLAG_PRIVATE_UNDEFINED_LAZY: descriptions.append("5 REFERENCE_FLAG_PRIVATE_UNDEFINED_LAZY") else: descriptions.append(n_desc & REFERENCE_TYPE, "???") libOrdinal = get_library_ordinal(n_desc) framework = frameworks.get(libOrdinal) if framework is None: descriptions.append("Library Ordinal " + str(libOrdinal)) else: descriptions.append("Library Ordinal " + str(libOrdinal) + "(" + framework + ")") if n_desc & N_ARM_THUMB_DEF == N_ARM_THUMB_DEF: descriptions.append("0008 N_ARM_THUMB_DEF") if n_desc & REFERENCED_DYNAMICALLY == REFERENCED_DYNAMICALLY: descriptions.append("0010 REFERENCED_DYNAMICALLY") if n_desc & N_NO_DEAD_STRIP == N_NO_DEAD_STRIP: descriptions.append("0020 N_NO_DEAD_STRIP") if n_desc & N_WEAK_REF == N_WEAK_REF: descriptions.append("0040 N_WEAK_REF") if n_type & N_TYPE == N_UNDF: if n_desc & N_REF_TO_WEAK == N_REF_TO_WEAK: descriptions.append("0080 N_REF_TO_WEAK") else: if n_desc & N_WEAK_DEF == N_WEAK_DEF: descriptions.append("0080 N_WEAK_DEF") if n_desc & N_SYMBOL_RESOLVER == N_SYMBOL_RESOLVER: descriptions.append("0100 N_SYMBOL_RESOLVER") symbols[hex(addr)] = utils.getDict(description, descriptions) addr += byte byte, n_value = ReadWrite.readInt32(path, endian, offset) offset += byte if n_type & N_TYPE == N_SECT: description = "Value" if n_type & N_STAB or section is None: if n_value == 0: value = "0" else: value = n_value else: value = str(n_value) + "(s+" + str(n_value - section.addr) + ")" else: description = "Value" value = n_value symbols[hex(addr)] = utils.getDict(description, value) addr += byte symbols = collections.OrderedDict(sorted(symbols.items())) return symbols
def test_should_login_with_email_and_password(self): newUser = self.createUser(self.user) sessionUser = self.loginUser(self.user) response = getDict(sessionUser.content) self.assertIsNot(response['access'], '') self.assertIsNot(response['refresh'], '')
def test_should_be_allowed_to_update_tasks(self): newUser = self.createUser(self.user) newUserLogin = self.loginUser(self.user) response = getDict(newUserLogin.content) oldTitle = 'Title task' oldContent = 'Content task' newTitle = 'Title updated' newContent = 'Content updated' newTask = self.createTask( token = response['access'], task = json.dumps({ 'title': oldTitle, 'content': oldContent, }) ) responseTask = getDict(newTask.content) taskID = 1 # Send empty data updatedTaskEmpty = self.makeRequest.patch( path = self.tasksPath + str(taskID) +'/', content_type = self.contentType, HTTP_AUTHORIZATION = 'Bearer ' + response['access'], ) responseTaskEmpty = getDict(updatedTaskEmpty.content) self.assertEqual(updatedTaskEmpty.status_code, 200) self.assertEqual(responseTaskEmpty['content'], oldContent) self.assertEqual(responseTaskEmpty['title'], oldTitle) # Update only title updatedTaskTitle = self.makeRequest.patch( path = self.tasksPath + str(taskID) + '/', content_type = self.contentType, data = json.dumps({ 'title': newTitle }), HTTP_AUTHORIZATION = 'Bearer ' + response['access'], ) responseTaskTitle = getDict(updatedTaskTitle.content) self.assertEqual(updatedTaskTitle.status_code, 200) self.assertEqual(responseTaskTitle['title'], newTitle) # Update only content updatedTaskContent = self.makeRequest.patch( path = self.tasksPath + str(taskID) + '/', content_type = self.contentType, data = json.dumps({ 'content': newContent }), HTTP_AUTHORIZATION = 'Bearer ' + response['access'], ) responseTaskContent = getDict(updatedTaskContent.content) self.assertEqual(updatedTaskContent.status_code, 200) self.assertEqual(responseTaskContent['content'], newContent) # Update both updatedTask = self.makeRequest.patch( path = self.tasksPath + str(taskID) + '/', content_type = self.contentType, data = json.dumps({ 'content': oldContent, 'title': oldTitle, }), HTTP_AUTHORIZATION = 'Bearer ' + response['access'], ) responseTaskBoth = getDict(updatedTask.content) self.assertEqual(updatedTask.status_code, 200) self.assertEqual(responseTaskBoth['content'], oldContent) self.assertEqual(responseTaskBoth['title'], oldTitle)
def createRebaseNode(sample, path, baseAddr): endian = utils.getEndianFormat(sample) length = os.path.getsize(path) opcodes = {} actions = [] offset = 0 addr = baseAddr address = 0 scale = 0 typeValue = 0 while offset < length: byte, data = ReadWrite.readInt8(path, endian, offset) offset += byte opcode = data & REBASE_OPCODE_MASK immediate = data & REBASE_IMMEDIATE_MASK if opcode == REBASE_OPCODE_DONE: description = "REBASE_OPCODE_DONE" value = "" opcodes[hex(addr)] = utils.getDict(description, value) addr += byte elif opcode == REBASE_OPCODE_SET_TYPE_IMM: typeValue = immediate typeString = "" if typeValue == REBASE_TYPE_POINTER: typeString = "REBASE_TYPE_POINTER" elif typeValue == REBASE_TYPE_TEXT_ABSOLUTE32: typeString = "REBASE_TYPE_TEXT_ABSOLUTE32" elif typeValue == REBASE_TYPE_TEXT_PCREL32: typeString = "REBASE_TYPE_TEXT_PCREL32" else: typeString = "Unknown" description = "REBASE_OPCODE_SET_TYPE_IMM" value = "type (" + str(typeValue) + "," + typeString + ")" opcodes[hex(addr)] = utils.getDict(description, value) addr += byte elif opcode == REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: segmentIndex = immediate description = "REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB" value = "segment (" + str(segmentIndex) + ")" opcodes[hex(addr)] = utils.getDict(description, value) addr += byte if offset >= length: break newByte, newData = ReadWrite.read_uleb128(path, offset) offset += newByte description = "uleb128" value = "offset (" + str(newData) + ")" opcodes[hex(addr)] = utils.getDict(description, value) addr += newByte segments = utils.getSegments(sample) if segmentIndex > len(segments): raise Exception("index is out of range " + str(segmentIndex)) elif opcode == REBASE_OPCODE_ADD_ADDR_ULEB: description = "REBASE_OPCODE_ADD_ADDR_ULEB" value = "" opcodes[hex(addr)] = utils.getDict(description, value) addr += byte if offset >= length: break newByte, newData = ReadWrite.read_uleb128(path, offset) offset += newByte description = "uleb128" value = "offset (" + str(newData) + ")" opcodes[hex(addr)] = utils.getDict(description, value) addr += newByte elif opcode == REBASE_OPCODE_ADD_ADDR_IMM_SCALED: scale = immediate description = "REBASE_OPCODE_ADD_ADDR_IMM_SCALED" value = "scale (" + str(scale) + ")" opcodes[hex(addr)] = utils.getDict(description, "") addr += byte elif opcode == REBASE_OPCODE_DO_REBASE_IMM_TIMES: count = immediate description = "REBASE_OPCODE_DO_REBASE_IMM_TIMES" value = "count (" + str(count) + ")" opcodes[hex(addr)] = utils.getDict(description, value) addr += byte elif opcode == REBASE_OPCODE_DO_REBASE_ULEB_TIMES: description = "REBASE_OPCODE_DO_REBASE_ULEB_TIMES" value = "" opcodes[hex(addr)] = utils.getDict(description, value) addr += byte if offset >= length: break newByte, newData = ReadWrite.read_uleb128(path, offset) offset += newByte description = "uleb128" value = "count (" + str(newData) + ")" opcodes[hex(addr)] = utils.getDict(description, value) addr += newByte elif opcode == REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB: description = "REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB" value = "" opcodes[hex(addr)] = utils.getDict(description, value) addr += byte if offset >= length: break newByte, newData = ReadWrite.read_uleb128(path, offset) offset += newByte description = "uleb128" value = "offset (" + str(newData) + ")" opcodes[hex(addr)] = utils.getDict(description, value) addr += newByte elif opcode == REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB: description = "REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB" value = "" opcodes[hex(addr)] = utils.getDict(description, value) addr += byte if offset >= length: break newByte, newData = ReadWrite.read_uleb128(path, offset) offset += newByte description = "uleb128" value = "count (" + str(newData) + ")" opcodes[hex(addr)] = utils.getDict(description, value) addr += newByte if offset >= length: break newByte, skip = ReadWrite.read_uleb128(path, offset) offset += newByte description = "uleb128" value = "skip (" + str(skip) + ")" opcodes[hex(addr)] = utils.getDict(description, value) addr += newByte else: addr += byte return opcodes
def printSymbols(filePath, path, baseAddr): endian = utils.getEndianFormat(filePath) length = os.path.getsize(path) opcodes = {} offset = 0 addr = baseAddr while offset < length: byte, terminalSize = ReadWrite.readInt8(path, endian, offset) offset += byte description = "Terminal Size" value = str(terminalSize) opcodes[hex(addr)] = utils.getDict(description, value) addr += byte if terminalSize != 0 and offset < length: byte, flags = ReadWrite.read_uleb128(path, offset) offset += byte value = [] if (flags & EXPORT_SYMBOL_FLAGS_KIND_MASK ) == EXPORT_SYMBOL_FLAGS_KIND_REGULAR: value.append("00 EXPORT_SYMBOL_FLAGS_KIND_REGULAR") if (flags & EXPORT_SYMBOL_FLAGS_KIND_MASK ) == EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL: value.append("01 EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL") if flags & EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION: value.append("04 EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION") if flags & EXPORT_SYMBOL_FLAGS_REEXPORT: value.append("08 EXPORT_SYMBOL_FLAGS_REEXPORT") if flags & EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER: value.append("10 EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER") description = "Flags" opcodes[hex(addr)] = utils.getDict(description, value) addr += byte if offset >= length: break byte, offsets = ReadWrite.read_uleb128(path, offset) offset += byte description = "Symbol Offset" value = hex(offsets) opcodes[hex(addr)] = utils.getDict(description, value) addr += byte if offset >= length: break byte, childCount = ReadWrite.readInt8(path, endian, offset) offset += byte if terminalSize == 0 and childCount == 0: break description = "Child Count" value = str(childCount) opcodes[hex(addr)] = utils.getDict(description, value) addr += byte while childCount > 0 and offset < length: byte, label = ReadWrite.readString(path, offset) offset += byte description = "Node Label" value = label opcodes[hex(addr)] = utils.getDict(description, value) addr += byte if offset >= length: break byte, skip = ReadWrite.read_uleb128(path, offset) offset += byte description = "Next Node" value = hex(baseAddr + skip) opcodes[hex(addr)] = utils.getDict(description, value) addr += byte childCount -= 1 return opcodes
def createBindingNode(filePath, path, baseAddr): endian = utils.getEndianFormat(filePath) length = os.path.getsize(path) opcodes = {} offset = 0 addr = baseAddr while offset < length: byte, data = ReadWrite.readInt8(path, endian, offset) offset += byte opcode = data & BIND_OPCODE_MASK immediate = data & BIND_IMMEDIATE_MASK if opcode == BIND_OPCODE_DONE: description = "BIND_OPCODE_DONE" value = "" opcodes[hex(addr)] = utils.getDict(description, value) addr += byte elif opcode == BIND_OPCODE_SET_DYLIB_ORDINAL_IMM: libOrdinal = immediate description = "BIND_OPCODE_SET_DYLIB_ORDINAL_IMM" value = "dylib (" + str(libOrdinal) + ")" opcodes[hex(addr)] = utils.getDict(description, value) addr += byte elif opcode == BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB: description = "BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB" value = "" opcodes[hex(addr)] = utils.getDict(description, value) addr += byte if offset >= length: break newByte, libOrdinal = ReadWrite.read_uleb128(path, offset) offset += newByte description = "uleb128" value = "dylib (" + str(libOrdinal) + ")" opcodes[hex(addr)] = utils.getDict(description, value) addr += newByte elif opcode == BIND_OPCODE_SET_DYLIB_SPECIAL_IMM: #Special means negative if immediate == 0: libOrdinal = 0 else: signExtended = immediate | BIND_OPCODE_MASK #This sign extends the value libOrdinal = signExtended description = "BIND_OPCODE_SET_DYLIB_SPECIAL_IMM" value = "dylib (" + str(libOrdinal) + ")" opcodes[hex(addr)] = utils.getDict(description, value) addr += byte elif opcode == BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM: symbolFlags = immediate description = "BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM" value = "flags (" + str(symbolFlags) + ")" opcodes[hex(addr)] = utils.getDict(description, value) addr += byte if offset >= length: break newByte, symbolName = ReadWrite.readString(path, offset) offset += newByte description = "string" value = "name (" + symbolName + ")" opcodes[hex(addr)] = utils.getDict(description, value) addr += newByte elif opcode == BIND_OPCODE_SET_TYPE_IMM: typeValue = immediate description = "BIND_OPCODE_SET_TYPE_IMM" typeString = "" if typeValue == BIND_TYPE_POINTER: typeString = "BIND_TYPE_POINTER" elif typeValue == BIND_TYPE_TEXT_ABSOLUTE32: typeString = "BIND_TYPE_TEXT_ABSOLUTE32" elif typeValue == BIND_TYPE_TEXT_PCREL32: typeString = "BIND_TYPE_TEXT_PCREL32" else: typeString = "???" value = "type (" + typeString + ")" opcodes[hex(addr)] = utils.getDict(description, typeString) addr += byte elif opcode == BIND_OPCODE_SET_ADDEND_SLEB: description = "BIND_OPCODE_SET_ADDEND_SLEB" value = "" opcodes[hex(addr)] = utils.getDict(description, value) addr += byte if offset >= length: break newByte, addend = ReadWrite.read_uleb128(path, offset) offset += newByte description = "sleb128" value = "addend (" + str(addend) + ")" opcodes[hex(addr)] = utils.getDict(description, value) addr += newByte elif opcode == BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: segmentIndex = immediate description = "BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB" value = "segment (" + str(segmentIndex) + ")" opcodes[hex(addr)] = utils.getDict(description, value) addr += byte if offset >= length: break newByte, val = ReadWrite.read_uleb128(path, offset) offset += newByte description = "uleb128" value = "offset (" + str(val) + ")" opcodes[hex(addr)] = utils.getDict(description, value) addr += newByte elif opcode == BIND_OPCODE_ADD_ADDR_ULEB: description = "BIND_OPCODE_ADD_ADDR_ULEB" value = "" opcodes[hex(addr)] = utils.getDict(description, value) addr += byte if offset >= length: break newByte, val = ReadWrite.read_uleb128(path, offset) offset += newByte description = "uleb128" value = "offset (" + str(val) + ")" opcodes[hex(addr)] = utils.getDict(description, value) addr += newByte elif opcode == BIND_OPCODE_DO_BIND: description = "BIND_OPCODE_DO_BIND" value = "" opcodes[hex(addr)] = utils.getDict(description, value) addr += byte elif opcode == BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB: description = "BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB" value = "" opcodes[hex(addr)] = utils.getDict(description, value) addr += byte if offset >= length: break newByte, val = ReadWrite.read_uleb128(path, offset) offset += newByte description = "uleb128" value = "offset (" + str(val) + ")" opcodes[hex(addr)] = utils.getDict(description, value) addr += newByte elif opcode == BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED: scale = immediate description = "BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED" value = "scale (" + str(scale) + ")" opcodes[hex(addr)] = utils.getDict(description, value) addr += byte elif opcode == BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB: description = "BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB" value = "" opcodes[hex(addr)] = utils.getDict(description, value) addr += byte if offset >= length: break newByte, count = ReadWrite.read_uleb128(path, offset) offset += newByte description = "uleb128" value = "count (" + str(count) + ")" opcodes[hex(addr)] = utils.getDict(description, value) addr += newByte if offset >= length: break newByte, skip = ReadWrite.read_uleb128(path, offset) offset += newByte description = "uleb128" value = "skip (" + str(skip) + ")" opcodes[hex(addr)] = utils.getDict(description, value) addr += newByte else: addr += byte return opcodes