aboutsummaryrefslogtreecommitdiffhomepage
path: root/builder/elfpatch.go
blob: 6a407db6fc09cd2c207be621c79e59032d2d1b1d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package builder

import (
	"debug/elf"
	"fmt"
	"os"
)

func getElfSectionData(executable string, sectionName string) ([]byte, elf.FileHeader, error) {
	elfFile, err := elf.Open(executable)
	if err != nil {
		return nil, elf.FileHeader{}, err
	}
	defer elfFile.Close()

	section := elfFile.Section(sectionName)
	if section == nil {
		return nil, elf.FileHeader{}, fmt.Errorf("could not find %s section", sectionName)
	}

	data, err := section.Data()

	return data, elfFile.FileHeader, err
}

func replaceElfSection(executable string, sectionName string, data []byte) error {
	fp, err := os.OpenFile(executable, os.O_RDWR, 0)
	if err != nil {
		return err
	}
	defer fp.Close()

	elfFile, err := elf.Open(executable)
	if err != nil {
		return err
	}
	defer elfFile.Close()

	section := elfFile.Section(sectionName)
	if section == nil {
		return fmt.Errorf("could not find %s section", sectionName)
	}

	// Implicitly check for compressed sections
	if section.Size != section.FileSize {
		return fmt.Errorf("expected section %s to have identical size and file size, got %d and %d", sectionName, section.Size, section.FileSize)
	}

	// Only permit complete replacement of section
	if section.Size != uint64(len(data)) {
		return fmt.Errorf("expected section %s to have size %d, was actually %d", sectionName, len(data), section.Size)
	}

	// Write the replacement section data
	_, err = fp.WriteAt(data, int64(section.Offset))
	return err
}