1// Copyright 2017 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15// This tool extracts ELF LOAD segments from our linker binary, and produces an
16// assembly file and linker script which will embed those segments as sections
17// in another binary.
18package main
19
20import (
21	"bytes"
22	"debug/elf"
23	"flag"
24	"fmt"
25	"io"
26	"io/ioutil"
27	"log"
28	"os"
29	"strconv"
30)
31
32func main() {
33	var asmPath string
34	var scriptPath string
35
36	flag.StringVar(&asmPath, "s", "", "Path to save the assembly file")
37	flag.StringVar(&scriptPath, "T", "", "Path to save the linker script")
38	flag.Parse()
39
40	f, err := os.Open(flag.Arg(0))
41	if err != nil {
42		log.Fatalf("Error opening %q: %v", flag.Arg(0), err)
43	}
44	defer f.Close()
45
46	ef, err := elf.NewFile(f)
47	if err != nil {
48		log.Fatalf("Unable to read elf file: %v", err)
49	}
50
51	asm := &bytes.Buffer{}
52	script := &bytes.Buffer{}
53	baseLoadAddr := uint64(0x1000)
54	load := 0
55
56	fmt.Fprintln(asm, ".globl __dlwrap_linker_offset")
57	fmt.Fprintf(asm, ".set __dlwrap_linker_offset, 0x%x\n", baseLoadAddr)
58
59	fmt.Fprintln(script, "ENTRY(__dlwrap__start)")
60	fmt.Fprintln(script, "SECTIONS {")
61
62	progsWithFlagsCount := make(map[string]int)
63
64	for _, prog := range ef.Progs {
65		if prog.Type != elf.PT_LOAD {
66			continue
67		}
68
69		progName := progNameFromFlags(prog.Flags, progsWithFlagsCount)
70		sectionName := ".linker_" + progName
71		symName := "__dlwrap_linker_" + progName
72
73		flags := ""
74		if prog.Flags&elf.PF_W != 0 {
75			flags += "w"
76		}
77		if prog.Flags&elf.PF_X != 0 {
78			flags += "x"
79		}
80		fmt.Fprintf(asm, ".section %s, \"a%s\"\n", sectionName, flags)
81
82		if load == 0 {
83			fmt.Fprintln(asm, ".globl __dlwrap_linker")
84			fmt.Fprintln(asm, "__dlwrap_linker:")
85			fmt.Fprintln(asm)
86		}
87
88		fmt.Fprintf(asm, ".globl %s\n%s:\n\n", symName, symName)
89
90		fmt.Fprintf(script, "  %s 0x%x : {\n", sectionName, baseLoadAddr+prog.Vaddr)
91		fmt.Fprintf(script, "    KEEP(*(%s));\n", sectionName)
92		fmt.Fprintln(script, "  }")
93
94		buffer, _ := ioutil.ReadAll(prog.Open())
95		bytesToAsm(asm, buffer)
96
97		// Fill in zeros for any BSS sections. It would be nice to keep
98		// this as a true BSS, but ld/gold isn't preserving those,
99		// instead combining the segments with the following segment,
100		// and BSS only exists at the end of a LOAD segment.  The
101		// linker doesn't use a lot of BSS, so this isn't a huge
102		// problem.
103		if prog.Memsz > prog.Filesz {
104			fmt.Fprintf(asm, ".fill 0x%x, 1, 0\n", prog.Memsz-prog.Filesz)
105		}
106		fmt.Fprintln(asm)
107
108		load += 1
109	}
110
111	fmt.Fprintln(asm, ".globl __dlwrap_linker_end")
112	fmt.Fprintln(asm, "__dlwrap_linker_end:")
113	fmt.Fprintln(asm)
114
115	fmt.Fprintln(asm, `.section .note.android.embedded_linker,"a",%note`)
116
117	// Discard the PT_INTERP section so that the linker doesn't need to be passed the
118	// --no-dynamic-linker flag.
119	fmt.Fprintln(script, "  /DISCARD/ : { *(.interp) }")
120
121	fmt.Fprintln(script, "}")
122	fmt.Fprintln(script, "INSERT BEFORE .note.android.embedded_linker;")
123
124	if asmPath != "" {
125		if err := ioutil.WriteFile(asmPath, asm.Bytes(), 0777); err != nil {
126			log.Fatalf("Unable to write %q: %v", asmPath, err)
127		}
128	}
129
130	if scriptPath != "" {
131		if err := ioutil.WriteFile(scriptPath, script.Bytes(), 0777); err != nil {
132			log.Fatalf("Unable to write %q: %v", scriptPath, err)
133		}
134	}
135}
136
137func bytesToAsm(asm io.Writer, buf []byte) {
138	for i, b := range buf {
139		if i%64 == 0 {
140			if i != 0 {
141				fmt.Fprint(asm, "\n")
142			}
143			fmt.Fprint(asm, ".byte ")
144		} else {
145			fmt.Fprint(asm, ",")
146		}
147		fmt.Fprintf(asm, "%d", b)
148	}
149	fmt.Fprintln(asm)
150}
151
152func progNameFromFlags(flags elf.ProgFlag, progsWithFlagsCount map[string]int) string {
153	s := ""
154	if flags&elf.PF_R != 0 {
155		s += "r"
156	}
157	if flags&elf.PF_W != 0 {
158		s += "w"
159	}
160	if flags&elf.PF_X != 0 {
161		s += "x"
162	}
163
164	count := progsWithFlagsCount[s]
165	count++
166	progsWithFlagsCount[s] = count
167
168	if count > 1 {
169		s += strconv.Itoa(count)
170	}
171
172	return s
173}
174