github.com/agiledragon/gomonkey/v2@v2.11.1-0.20240427155748-d56c6823ec17/modify_binary_linux.go (about)

     1  package gomonkey
     2  
     3  import "syscall"
     4  
     5  func modifyBinary(target uintptr, bytes []byte) {
     6  	function := entryAddress(target, len(bytes))
     7  	err := mprotectCrossPage(target, len(bytes), syscall.PROT_READ|syscall.PROT_WRITE|syscall.PROT_EXEC)
     8  	if err != nil {
     9  		panic(err)
    10  	}
    11  	copy(function, bytes)
    12  	err = mprotectCrossPage(target, len(bytes), syscall.PROT_READ|syscall.PROT_EXEC)
    13  	if err != nil {
    14  		panic(err)
    15  	}
    16  }
    17  
    18  func mprotectCrossPage(addr uintptr, length int, prot int) error {
    19  	pageSize := syscall.Getpagesize()
    20  	for p := pageStart(addr); p < addr+uintptr(length); p += uintptr(pageSize) {
    21  		page := entryAddress(p, pageSize)
    22  		if err := syscall.Mprotect(page, prot); err != nil {
    23  			return err
    24  		}
    25  	}
    26  	return nil
    27  }