assembly - Self modifying code always segmentation faults on Linux -


i found article self modifying code , tried examples, segmentation faults. fas can understand, there violation in memory permissions. code segment (r)ead/e(x)ecute , attempt of writting results fault. there way test program either changing memory permissions @ runtime or before? i'm using linux , example written in gas assembly.

.extern memcpy .section .data string:         .asciz  "whatever" string_end: .section .bss         .lcomm buf, string_end-string .section .text .globl main main:         call changer         mov $string, %edx label:         push string_end-string         push $buf         push $string         call memcpy changer:         mov $offset_to_write, %esi         mov $label, %edi         mov $0xb, %ecx loop1:         lodsb         stosb         loop loop1         ret offset_to_write:         push 0         call exit end: 

so after modification suggested osgx here working code.(actually if assemble&link&run crashes if watch using gdb modifies code!)

.extern memcpy .section .data string:         .asciz  "giorgos" string_end: .section .bss         .lcomm buf, string_end-string .section .text .globl main main:         lea (main), %esi                # start of memory region                                         # change permissions (smc-enabled)         andl $0xfffff000, %esi          # align start of pagesize         pushl   $7                      # permissions==r|w|x         pushl   $4096                   # page size         pushl   %esi                    # computed start address         call    mprotect          call    changer                 # function smc         mov     $string, %edx label:         push    string_end-string       # code overridden         push    $buf                    # , never executed!         push    $string         call    memcpy changer:         mov     $offset_to_write, %esi  # simple copy bytes algorithm         mov     $label, %edi         mov     $0xb, %ecx loop1:         lodsb         stosb         loop    loop1         ret offset_to_write:                        # these instructions         push    $0                      # executed         call    exit end: 

you should change memory access permissions in runtime.

#include <sys/mman.h>  void *addr  = get_address_of_instruction_pointer(); int  length = 4096;   /* size of page */  if (mprotect(addr, length, prot_read | prot_write | prot_exec) == 0) {     /* current code page writable , code allowed execution */ } 

Comments

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -