Best Python code snippet using avocado_python
main.py
Source:main.py  
...9    elf = ELF(infile)1011    # add imported function from external library12    elf.add_imported_library('lib_x64_library.so')13    elf.add_imported_symbol('export_function', '_export_function', 'lib_x64_library.so')1415    elf.add_data('constdata', 'C' * 5 + '\x00')16    elf.add_pointer('constdata_pointer', 'constdata')17    elf.add_code('pointer_verifier', """18        push rdi19        mov rdi, qword ptr [constdata_pointer]20        call qword ptr [_puts]21        pop rdi22        ret23    """)24    elf.add_init_function('pointer_verifier')2526    elf.add_tls_bss_data('tls_bss_long', 0x4, 'tls_bss_long_offset')27    elf.add_tls_bss_data('tls_bss_char_array', 0x100, 'tls_bss_char_array_offset')2829    elf.add_imported_symbol('puts', '_puts')30    elf.add_data('init_message', 'Hello From Init Array\x00')31    elf.add_code("new_init_function", """32        push rdi33        lea rdi, byte ptr [init_message]34        call qword ptr [_puts]35        pop rdi36        ret37    """)38    elf.add_init_function("new_init_function")3940    # hook function_2, call export_function41    elf.patch_code(fromwhere=0x40068C,42                   towhere=0x400697,43                   label='patch_40068C',44                   code="""45                        call qword ptr [_export_function]46                        push rbp47                        mov rbp, rsp48                        lea rdi, [_commandline]49                        """)50    elf.add_data('_commandline', '/bin/sh')5152    # .text:00000000004006E2    lea     rdi, aParent    ; "parent"53    # .text:00000000004006E9    call    _puts54    # .text:00000000004006EE    lea     rax, function_355    elf.insert_code(where=0x4006e9, label="patch_4006e9", code="""56    add rdi, 1  # rdi -> "arent"57    """, nbound=0x4006ee)5859    # .text:0000000000400678    lea     rdi, a255s      ; "%255s"60    # .text:000000000040067F    mov     eax, 061    elf.insert_code(where=0x400678, label="patch_400678", code="""62    lea rdi, [_commandline]63    call 0x40054064    xor rax, rax65    leave66    ret67    """, nbound=0x40067f)6869    # add imported function from libc70    elf.add_imported_symbol('getpid', '_getpid')7172    # data and code manipulate73    elf.add_data('global_data', 'A' * 0x20)7475    # x64 has problems with direct addressing76    elf.add_code('entry1',77                 """78                 mov rax, [global_data2222]79                 mov rbx, [entry2]80                 mov rax, [_getpid]81                 """)8283    elf.add_code('entry2',84                 """85                 mov rax, [global_data]86                 mov rbx, [entry1]87                 mov rcx, [_getpid]88                 """)8990    elf.add_data('global_data2222', 'B' * 0x20)9192    elf.add_code('entry3',93                 """94                 lea rcx, [global_data2222]95                 mov rax, [global_data2222]96                 mov rbx, [entry1]97                 mov rcx, [entry2]98                 mov rcx, [entry3]99                 mov rcx, [_getppid]100                 """)101102    elf.add_imported_symbol('getppid', '_getppid')103104    elf.add_code('entry4',105                 """106                 mov rcx, [_getppid]107                 """)108109    elf.save(outfile)110111112def test_386(infile, outfile):113    elf = ELF(infile)114115    # add imported function from external library116    elf.add_imported_library('lib_x86_library.so')117    elf.add_imported_symbol('export_function', '_export_function', 'lib_x86_library.so')118119    elf.add_tls_bss_data('tls_bss_long', 0x4, 'tls_bss_long_offset')120    elf.add_tls_bss_data('tls_bss_char_array', 0x100, 'tls_bss_char_array_offset')121122    elf.add_data('constdata', 'C' * 5 + '\x00')123    elf.add_pointer('constdata_pointer', 'constdata')124    elf.add_code('pointer_verifier', """125        mov eax, dword ptr [constdata_pointer]126        push eax127        call dword ptr [_puts]128        add esp, 4129        ret130    """)131    elf.add_init_function('pointer_verifier')132133    elf.add_imported_symbol('puts', '_puts')134    elf.add_data('init_message', 'Hello From Init Array\x00')135    elf.add_code("new_init_function", """136        push edi137        lea edi, byte ptr [init_message]138        push edi139        call dword ptr [_puts]140        add esp, 4141        pop edi142        ret143    """)144    elf.add_init_function("new_init_function")145146    # hook function_2, call export_function147    elf.patch_code(fromwhere=0x0804857C,148                   towhere=0x08048583,149                   label='patch_804857C',150                   code="""151                        call dword ptr[_export_function]152                        push ebp153                        mov ebp, esp154                        push ebx155                        sub esp, 4156                        """)157158    # .text:0804860B    lea     eax, (aParent - 804A000h)[ebx] ; "parent"159    # .text:08048611    push    eax             ; s160    # .text:08048612    call    _puts161    # .text:08048617    add     esp, 10h162    elf.insert_code(where=0x08048611, label="patch_08048611", code="""163    add eax, 1  # eax -> "arent"164    """, nbound=0x08048617)165166    # add imported function from libc167    elf.add_imported_symbol('getpid', '_getpid')168169    # data and code manipulate170    elf.add_data('global_data', 'A' * 0x20)171172    elf.add_code('entry1',173                 """174                 mov eax, [global_data2222]175                 mov ebx, [entry2]176                 mov ecx, [_getpid]177                 """)178179    elf.add_code('entry2',180                 """181                 mov eax, [global_data]182                 mov ebx, [entry1]183                 mov ecx, [_getpid]184                 """)185186    elf.add_data('global_data2222', 'B' * 0x20)187188    elf.add_code('entry3',189                 """190                 mov eax, [global_data2222]191                 mov ebx, [entry1]192                 mov ebx, [entry2]193                 mov ebx, [entry3]194                 mov ecx, [_getppid]195                 """)196197    elf.add_imported_symbol('getppid', '_getppid')198199    elf.add_code('entry4',200                 """201                 mov ecx, [_getppid]202                 """)203204    elf.save(outfile)205206207def test_arm(infile, outfile):208    elf = ELF(infile)209210    # add imported function from external library211    elf.add_imported_library('lib_arm_library.so')212    elf.add_imported_symbol('export_function', '_export_function', 'lib_arm_library.so')213214    elf.add_tls_bss_data('tls_bss_long', 0x4, 'tls_bss_long_offset')215    elf.add_tls_bss_data('tls_bss_char_array', 0x100, 'tls_bss_char_array_offset')216217    elf.add_data('constdata', 'C' * 5 + '\x00')218    elf.add_pointer('constdata_pointer', 'constdata')219    elf.add_code('pointer_verifier', """        220        stmfd sp!, {r0, r3, lr}221        ldr r0, =constdata_pointer222        ldr r0, [r0]223        ldr r3, =_puts224        ldr r3, [r3]225        blx r3226        ldmfd sp!, {r0, r3, pc}227    """)228    elf.add_init_function('pointer_verifier')229230    elf.add_imported_symbol('puts', '_puts')231    elf.add_data('init_message', 'Hello From Init Array\x00')232    elf.add_code("new_init_function", """233        stmfd sp!, {r0, r3, lr}234        ldr r0, =init_message235        ldr r3, =_puts236        ldr r3, [r3]237        blx r3238        ldmfd sp!, {r0, r3, pc}239    """)240    elf.add_init_function("new_init_function")241242    # hook function_2, call export_function243    elf.insert_code(where=0x10610, label="patch_10610", code="""244    stmfd sp!, {r3, lr}245    ldr r3, =_export_function246    ldr r3, [r3, #0x0]247    blx r3248    ldmfd sp!, {r3, lr}249    """)250251    # test pc-related instruction wrap252    elf.insert_code(where=0x10684, label="patch_10684", code="nop")253254    # add imported function from libc255    elf.add_imported_symbol('getpid', '_getpid')256257    # data and code manipulate258    elf.add_data('global_data', 'A' * 0x20)259260    elf.add_code('entry1',261                 """262                 ldr r1, =global_data2222263                 ldr r1, =entry2264                 ldr r1, =_getpid265                 """)266267    elf.add_code('entry2',268                 """269                 ldr r1, =global_data270                 ldr r1, =entry1271                 ldr r1, =_getpid272                 """)273274    elf.add_data('global_data2222', 'B' * 0x20)275276    elf.add_code('entry3',277                 """278                 ldr r1, =global_data2222279                 ldr r1, =entry1280                 ldr r1, =entry2281                 ldr r1, =entry3282                 ldr r1, =_getppid283                 """)284285    elf.add_imported_symbol('getppid', '_getppid')286287    elf.add_code('entry4',288                 """289                 ldr r1, =_getppid290                 """)291292    elf.save(outfile)293294295def test_arm_pie(infile, outfile):296    elf = ELF(infile)297298    elf.add_imported_symbol('puts', '_puts', 'libc.so.0')299300    elf.add_data('init_message', 'Hello From Init Array\x00')301    elf.add_code("new_init_function", """302        stmfd sp!, {r0, r3, lr}303        ldr r0, =init_message304        ldr r3, =_puts305        ldr r3, [r3]306        blx r3307        ldmfd sp!, {r0, r3, pc}308    """)309    elf.add_init_function("new_init_function")310311    # hook function_2, call export_function312    elf.insert_code(where=0x90c, label="patch_90c", code="""313        stmfd sp!, {r0, r3}314        ldr r0, =init_message315        ldr r3, =5316        ldr r3, =_puts317        ldr r3, [r3]318        ldmfd sp!, {r0, r3}319    """)320321    # hook function_2, call export_function322    elf.insert_code(where=0x920, label="patch_920", code="""323        stmfd sp!, {r0, r3}324        ldr r0, =init_message325        ldr r3, =5326        ldr r3, =_puts327        ldr r3, [r3]328        ldmfd sp!, {r0, r3}329    """)330331    # test pc-related instruction wrap332    elf.insert_code(where=0x8C4, label="patch_8C4", code="nop")333334    trampoline_template_with_tls = """335    stmfd sp!, {{r0 - r4}}      @ save registers336    ldr r0, =afl_prev_loc_offset337    ldr r1, [r0]                @ afl_prev_loc offset338    mrc p15, 0, r0, c13, c0, 3  @ tls pointer339    ldrh r2, [r0, r1]           @ load afl_prev_loc, zero-extended340    movw r4, #{magic:#x}        @ cur_loc, zero-extended341    eor r2, r2, r4              @ afl_prev_loc ^ cur_loc342    ldr r3, =shm_pointer343    ldr r3, [r3]                @ shm_pointer344    ldrb r4, [r3, r2]345    add r4, r4, #1              @ shm[xored] += 1346    strb r4, [r3, r2]347    movw r2, #{magic_shift:#x}  @ cur_loc >> 1348    strh r2, [r0, r1]           @ afl_prev_loc = cur_loc >> 1349    ldmfd sp!, {{r0 - r4}}      @ restore registers350    """351352    afl_init = """353    stmfd sp!, {lr}354    ldr r3, =afl_init_entry355    ldr r3, [r3]356    blx r3                  @ call afl_init_entry(r0, r1, r2)357    ldr r3, =shm_pointer358    str r0, [r3]            @ save shm_pointer359    ldmfd sp!, {pc}360    """361362    init_entry = 'afl_manual_init'363    elf.add_imported_symbol(init_entry, 'afl_init_entry', 'libaflinit.so')364365    # avoid write to invalid address before initialization complete366    elf.add_data('afl_area_initial', '\x00' * 0x10000)367    elf.add_pointer('shm_pointer', 'afl_area_initial')368369    elf.add_code('afl_init', afl_init)370    elf.add_init_function('afl_init')371372    elf.add_tls_bss_data('afl_prev_loc', 4, 'afl_prev_loc_offset')373    trampoline_template = trampoline_template_with_tls374375    for index, bb in enumerate([0x938, 0x8E8]):376        magic = bb * 0xdeadbeef % 2 ** 16377        trampoline = trampoline_template.format(magic=magic, magic_shift=magic >> 1)378        elf.insert_code(where=bb, label="patch_%#x" % bb, code=trampoline)379380    elf.save(outfile)381382383def test_arm_afl(target, output, daemon_mode, disable_tls, bbs):384    import sys385    import datetime386387    def die(s):388        sys.stdout.write(s + '\n') or exit()389390    def log(s):391        sys.stdout.write(s + '\n')392393    def tlog(msg):394        log('%s %s' % (str(datetime.datetime.now()), msg))395396    trampoline_template_with_tls = """397    stmfd sp!, {{r0 - r4}}      @ save registers398    ldr r0, =afl_prev_loc_offset399    ldr r1, [r0]                @ afl_prev_loc offset400    mrc p15, 0, r0, c13, c0, 3  @ tls pointer401    ldrh r2, [r0, r1]           @ load afl_prev_loc, zero-extended402    movw r4, #{magic:#x}        @ cur_loc, zero-extended403    eor r2, r2, r4              @ afl_prev_loc ^ cur_loc404    ldr r3, =shm_pointer405    ldr r3, [r3]                @ shm_pointer406    ldrb r4, [r3, r2]407    add r4, r4, #1              @ shm[xored] += 1408    strb r4, [r3, r2]409    movw r2, #{magic_shift:#x}  @ cur_loc >> 1410    strh r2, [r0, r1]           @ afl_prev_loc = cur_loc >> 1411    ldmfd sp!, {{r0 - r4}}      @ restore registers412    """413414    trampoline_template_single_thread = """415    stmfd sp!, {{r0, r2 - r4}}  @ save registers416    ldr r0, =afl_prev_loc417    ldrh r2, [r0]               @ load afl_prev_loc, zero-extended418    movw r4, #{magic:#x}        @ cur_loc, zero-extended419    eor r2, r2, r4              @ afl_prev_loc ^ cur_loc420    ldr r3, =shm_pointer421    ldr r3, [r3]                @ shm_pointer422    ldrb r4, [r3, r2]423    add r4, r4, #1              @ shm[xored] += 1424    strb r4, [r3, r2]425    movw r2, #{magic_shift:#x}  @ cur_loc >> 1426    strh r2, [r0]               @ afl_prev_loc = cur_loc >> 1427    ldmfd sp!, {{r0, r2 - r4}}  @ restore registers428    """429430    afl_init = """431    stmfd sp!, {lr}432    ldr r3, =afl_init_entry433    ldr r3, [r3]434    blx r3                  @ call afl_init_entry(r0, r1, r2)435    ldr r3, =shm_pointer436    str r0, [r3]            @ save shm_pointer437    ldmfd sp!, {pc}438    """439440    # it is okay we have duplicate magics, since what we actually need is making441    # magic1 ^ magic2 unique. it helps nothing by making magic itself unique.442    # magics = []443    from zlib import crc32444445    def new_magic(seed):446        return crc32(str(seed)) % 2 ** 16447448    elf = ELF(target)449450    tlog('Start patching for %s' % target)451452    if (not elf.check_imported_library('libc.so.6') and453            not elf.check_imported_library('libc.so.0')):454        die('The binary does not have libc.so.6/0 imported.')455456    if daemon_mode == 'desock':457        init_entry = 'afl_manual_init'458        elf.add_imported_library('libdesock.so')459    elif daemon_mode == 'client':460        init_entry = 'afl_manual_init_daemon'461    else:462        init_entry = 'afl_manual_init'463    elf.add_imported_symbol(init_entry, 'afl_init_entry', 'libaflinit.so')464465    # avoid write to invalid address before initialization complete466    elf.add_data('afl_area_initial', '\x00' * 0x10000)467    elf.add_pointer('shm_pointer', 'afl_area_initial')468469    elf.add_code('afl_init', afl_init)470    elf.add_init_function('afl_init')471472    if disable_tls:473        elf.add_data('afl_prev_loc', '\x00' * 4)474        trampoline_template = trampoline_template_single_thread475    else:476        elf.add_tls_bss_data('afl_prev_loc', 4, 'afl_prev_loc_offset')477        trampoline_template = trampoline_template_with_tls
...module.py
Source:module.py  
...88            # to the directory structure89            module_path = statement.module.replace(".", os.path.sep)90            imported_path = os.path.join(imported_path, module_path)91        return imported_path92    def add_imported_symbol(self, statement):93        """94        Keeps track of symbol names and importable entities95        """96        for index, name in enumerate(statement.names):97            final_name = self._get_name_from_alias_statement(name)98            imported_symbol = ImportedSymbol.from_statement(99                statement, os.path.abspath(self.path), index100            )101            self.imported_symbols[final_name] = imported_symbol102    @staticmethod103    def _get_name_from_alias_statement(alias):104        """Returns the aliased name or original one."""105        return alias.asname if alias.asname else alias.name106    def _handle_import_from(self, statement, interesting_klass):107        self.add_imported_symbol(statement)108        if interesting_klass in [name.name for name in statement.names]:109            self.interesting_klass_found = True110        if statement.module != self.module:111            return112        name = get_statement_import_as(statement).get(self.klass, None)113        if name is not None:114            self.klass_imports.add(name)115    @staticmethod116    def _all_module_level_names(full_module_name):117        result = []118        components = full_module_name.split(".")[:-1]119        for topmost in range(len(components)):120            result.append(".".join(components[-topmost:]))121            components.pop()122        return result123    def _handle_import(self, statement):124        self.add_imported_symbol(statement)125        imported_as = get_statement_import_as(statement)126        name = imported_as.get(self.module, None)127        if name is not None:128            self.mod_imports.add(name)129        for as_name in imported_as.values():130            for mod_name in self._all_module_level_names(as_name):131                if mod_name == self.module:132                    self.mod_imports.add(mod_name)133    def iter_classes(self, interesting_klass=None):134        """135        Iterate through classes and keep track of imported avocado statements136        """137        for statement in self.mod.body:138            # Looking for a 'from <module> import <klass>'...test_safeloader_module.py
Source:test_safeloader_module.py  
...16    def test_add_imported_symbols_from_module(self):17        import_stm = ast.ImportFrom(18            module="foo", names=[ast.Name(name="bar", asname=None)]19        )20        self.module.add_imported_symbol(import_stm)21        self.assertEqual(self.module.imported_symbols["bar"].module_path, "foo")22        self.assertEqual(self.module.imported_symbols["bar"].symbol, "bar")23    def test_add_imported_object_from_module_asname(self):24        import_stm = ast.ImportFrom(25            module="foo", names=[ast.Name(name="bar", asname="baz")]26        )27        self.module.add_imported_symbol(import_stm)28        self.assertEqual(self.module.imported_symbols["baz"].module_path, "foo")29        self.assertEqual(self.module.imported_symbols["baz"].symbol, "bar")30    def test_is_not_avocado_test(self):31        self.assertFalse(self.module.is_matching_klass(ast.ClassDef()))32    def test_is_not_avocado_tests(self):33        for klass in self.module.iter_classes():34            self.assertFalse(self.module.is_matching_klass(klass))35class PythonModuleTest(unittest.TestCase):36    """37    Has tests based on other Python source code files38    """39    def test_is_avocado_test(self):40        passtest_path = os.path.join(BASEDIR, "examples", "tests", "passtest.py")41        passtest_module = PythonModule(passtest_path)...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
