├── .gitignore ├── LICENSE ├── README.md ├── doc.go ├── dwarf_helpers.go ├── go.mod ├── go.sum ├── helpers.go ├── helpers_test.go ├── process_go17_darwin.go ├── process_go17_other.go ├── process_go18.go ├── reflect_helpers.go ├── troop.go ├── troop_call.go ├── troop_globals.go ├── troop_test.go └── troop_types.go /.gitignore: -------------------------------------------------------------------------------- 1 | goof.test 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2017 Jeff Wendling 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Goof 2 | 3 | Goof lets you call functions in your binary with just the string of their 4 | name. How? 5 | 6 | ```go 7 | var troop goof.Troop 8 | out, err := troop.Call("fmt.Fprintf", os.Stdout, "hello %s", []interface{}{"world"}) 9 | if err != nil { // some error calling the function 10 | return err 11 | } 12 | n, err := out[0].(int), out[1].(error) 13 | if err != nil { 14 | return err 15 | } 16 | fmt.Printf("wrote %d bytes\n", n) 17 | ``` 18 | 19 | Caveat: you have to have called `fmt.Fprintf` elsewhere in your binary. 20 | 21 | Goof lets you get access to globals in your binary with just the string of 22 | their name. How? 23 | 24 | ```go 25 | var troop goof.Troop 26 | rv, err := troop.Global("net/http.DefaultServeMux") 27 | if err != nil { // couldn't find it 28 | return err 29 | } 30 | // rv contains an addressable reflect.Value of the default ServeMux! 31 | ``` 32 | 33 | Caveat: the global must be used elsewhere in the binary somehow. 34 | 35 | Goof lets you get access to all of the `reflect.Type`s in your binary. How? 36 | 37 | ```go 38 | var troop goof.Troop 39 | types, err := troop.Types() 40 | if err != nil { // something went wrong getting them 41 | return err 42 | } 43 | for _, typ := range types { 44 | fmt.Println(typ) 45 | } 46 | ``` 47 | 48 | Caveat: the types must be possible outputs to `reflect.TypeOf(val)` in your binary. 49 | 50 | ## Usage 51 | 52 | You should probably just make a single `Troop` in your binary and use that 53 | everywhere since it does a lot of caching and work on first use. 54 | 55 | ## How? 56 | 57 | It loads up the dwarf information of any binary it's loaded in and then does 58 | a bunch of unsafe tom foolery to perform these dirty deeds. How unsafe is it? 59 | 60 | - Reusing needles unsafe. 61 | - Jumping into a shark tank with a steak swimming suit unsafe. 62 | - Carnival ride unsafe. 63 | - Driving on the wrong side of the highway blindfolded unsafe. 64 | 65 | ## Should I use this? 66 | 67 | Do you really have to ask? OF COURSE! If you do, please let me know what terrible 68 | idea this enabled. I'm very interested. 69 | 70 | ## Testimonials 71 | 72 | > "I can't wait to get some goof in my [manhole](https://github.com/jtolds/go-manhole)!" - [@jtolds](https://github.com/jtolds) 73 | 74 | > "README is hilarious :joy:" 75 | 76 | > "Now I just need to come up with something horrendously risky to use this for..." 77 | -------------------------------------------------------------------------------- /doc.go: -------------------------------------------------------------------------------- 1 | // package goof is something you should never import. 2 | package goof 3 | -------------------------------------------------------------------------------- /dwarf_helpers.go: -------------------------------------------------------------------------------- 1 | package goof 2 | 3 | import ( 4 | "debug/dwarf" 5 | "encoding/binary" 6 | "unsafe" 7 | 8 | "github.com/zeebo/errs" 9 | ) 10 | 11 | func dwarfTypeName(dtyp dwarf.Type) string { 12 | // for some reason the debug/dwarf package doesn't set the Name field 13 | // on the common type for struct fields. what is this misery? 14 | switch dtyp := dtyp.(type) { 15 | case *dwarf.StructType: 16 | return dtyp.StructName 17 | default: 18 | return dtyp.Common().Name 19 | } 20 | } 21 | 22 | func getFunctionArgTypes(data *dwarf.Data, entry *dwarf.Entry) ( 23 | []dwarf.Type, error) { 24 | 25 | reader := data.Reader() 26 | 27 | reader.Seek(entry.Offset) 28 | _, err := reader.Next() 29 | if err != nil { 30 | return nil, err 31 | } 32 | 33 | var args []dwarf.Type 34 | for { 35 | child, err := reader.Next() 36 | if err != nil { 37 | return nil, err 38 | } 39 | if child == nil || child.Tag == 0 { 40 | break 41 | } 42 | 43 | if child.Tag != dwarf.TagFormalParameter { 44 | continue 45 | } 46 | 47 | dtyp, err := entryType(data, child) 48 | if err != nil { 49 | return nil, err 50 | } 51 | 52 | args = append(args, dtyp) 53 | } 54 | 55 | return args, nil 56 | } 57 | 58 | func entryType(data *dwarf.Data, entry *dwarf.Entry) (dwarf.Type, error) { 59 | off, ok := entry.Val(dwarf.AttrType).(dwarf.Offset) 60 | if !ok { 61 | return nil, errs.New("unable to find type offset for entry") 62 | } 63 | return data.Type(off) 64 | } 65 | 66 | func entryLocation(data *dwarf.Data, entry *dwarf.Entry) (uint64, error) { 67 | loc, ok := entry.Val(dwarf.AttrLocation).([]byte) 68 | if !ok { 69 | return 0, errs.New("unable to find location for entry") 70 | } 71 | if len(loc) == 0 { 72 | return 0, errs.New("location had no data") 73 | } 74 | 75 | // only support this opcode. did you know dwarf location information is 76 | // a stack based programming language with opcodes and stuff? i wonder 77 | // how many interpreters for that have code execution bugs in them. 78 | if loc[0] != 0x03 { 79 | return 0, errs.New("can't interpret location information") 80 | } 81 | 82 | // oh man let's also just assume that the dwarf info is written in the 83 | // same order as the host! WHAT COULD GO WRONG?! 84 | switch len(loc) - 1 { 85 | case 4: 86 | return uint64(hostOrder.Uint32(loc[1:])), nil 87 | case 8: 88 | return uint64(hostOrder.Uint64(loc[1:])), nil 89 | default: 90 | return 0, errs.New("what kind of computer is this?") 91 | } 92 | } 93 | 94 | var hostOrder binary.ByteOrder 95 | 96 | func init() { 97 | i := 1 98 | data := (*[4]byte)(unsafe.Pointer(&i)) 99 | 100 | if data[0] == 0 { 101 | hostOrder = binary.BigEndian 102 | } else { 103 | hostOrder = binary.LittleEndian 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/zeebo/goof 2 | 3 | go 1.19 4 | 5 | require github.com/zeebo/errs v1.3.0 6 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/zeebo/errs v1.1.1 h1:Cs5Noqj/tj3Ql/hLkD9WdumKlssx/IN2zr7CRGNOKZA= 2 | github.com/zeebo/errs v1.1.1/go.mod h1:Yj8dHrUQwls1bF3dr/vcSIu+qf4mI7idnTcHfoACc6I= 3 | github.com/zeebo/errs v1.3.0 h1:hmiaKqgYZzcVgRL1Vkc1Mn2914BbzB0IBxs+ebeutGs= 4 | github.com/zeebo/errs v1.3.0/go.mod h1:sgbWHsvVuTPHcqJJGQ1WhI5KbWlHYz+2+2C/LSEtCw4= 5 | -------------------------------------------------------------------------------- /helpers.go: -------------------------------------------------------------------------------- 1 | package goof 2 | 3 | import ( 4 | "unsafe" 5 | ) 6 | 7 | func makeInterface(typ, val unsafe.Pointer) interface{} { 8 | return *(*interface{})(unsafe.Pointer(&[2]unsafe.Pointer{typ, val})) 9 | } 10 | 11 | func dataPtr(val interface{}) unsafe.Pointer { 12 | return (*[2]unsafe.Pointer)(unsafe.Pointer(&val))[1] 13 | } 14 | -------------------------------------------------------------------------------- /helpers_test.go: -------------------------------------------------------------------------------- 1 | package goof 2 | 3 | import ( 4 | "os" 5 | "os/exec" 6 | "reflect" 7 | "strings" 8 | "testing" 9 | ) 10 | 11 | const importPath = "github.com/zeebo/goof" 12 | 13 | var troop Troop 14 | 15 | type suite struct{} 16 | 17 | func Test(t *testing.T) { 18 | // normal test invocations don't come with dwarf info, so we can't actually 19 | // run the tests :( 20 | // 21 | // it's ok. skip it here and hope TestCompile checks it. 22 | if err := troop.check(); err != nil { 23 | t.Log("skipping test due to error:", troop.check()) 24 | t.SkipNow() 25 | } 26 | 27 | // this way we don't have to remember to add the tests to this function 28 | // to run. 29 | s := reflect.TypeOf(suite{}) 30 | for i := 0; i < s.NumMethod(); i++ { 31 | method := s.Method(i) 32 | if !strings.HasPrefix(method.Name, "Test") { 33 | continue 34 | } 35 | t.Run(method.Name[4:], func(t *testing.T) { 36 | method.Func.Call([]reflect.Value{ 37 | reflect.ValueOf(suite{}), 38 | reflect.ValueOf(t), 39 | }) 40 | }) 41 | } 42 | } 43 | 44 | // TestCompile tries to actually run the tests on an environment that can 45 | // compile the test. HEH. 46 | func TestCompile(t *testing.T) { 47 | if os.Getenv("GOOF_SKIP_COMPILE") != "" { 48 | t.SkipNow() 49 | } 50 | if err := exec.Command("go", "test", "-c", importPath).Run(); err != nil { 51 | t.Logf("skipping compile test due to error: %v", err) 52 | t.SkipNow() 53 | } 54 | cmd := exec.Command("./goof.test", "-test.v") 55 | cmd.Env = append(cmd.Env, "GOOF_SKIP_COMPILE=true") 56 | output, err := cmd.CombinedOutput() 57 | if err != nil { 58 | t.Logf("%s", output) 59 | t.Fatal(err) 60 | } 61 | t.Log("\n" + string(output)) 62 | } 63 | -------------------------------------------------------------------------------- /process_go17_darwin.go: -------------------------------------------------------------------------------- 1 | //go:build !go1.8 && darwin 2 | // +build !go1.8,darwin 3 | 4 | package goof 5 | 6 | import ( 7 | "debug/dwarf" 8 | "debug/macho" 9 | "unsafe" 10 | 11 | "github.com/zeebo/errs" 12 | ) 13 | 14 | // #include 15 | // #include 16 | import "C" 17 | 18 | func openProc() (*dwarf.Data, error) { 19 | const bufsize = 4096 20 | 21 | buf := (*C.char)(C.malloc(bufsize)) 22 | defer C.free(unsafe.Pointer(buf)) 23 | 24 | size := C.uint32_t(bufsize) 25 | if rc := C._NSGetExecutablePath(buf, &size); rc != 0 { 26 | return nil, errs.New("error in cgo call to get path: %d", rc) 27 | } 28 | 29 | fh, err := macho.Open(C.GoString(buf)) 30 | if err != nil { 31 | return nil, errs.Wrap(err) 32 | } 33 | defer fh.Close() 34 | 35 | dwarf, err := fh.DWARF() 36 | return dwarf, errs.Wrap(err) 37 | } 38 | -------------------------------------------------------------------------------- /process_go17_other.go: -------------------------------------------------------------------------------- 1 | //go:build !go1.8 && !darwin 2 | // +build !go1.8,!darwin 3 | 4 | package goof 5 | 6 | import ( 7 | "debug/dwarf" 8 | "debug/elf" 9 | 10 | "github.com/zeebo/errs" 11 | ) 12 | 13 | func openProc() (*dwarf.Data, error) { 14 | fh, err := elf.Open("/proc/self/exe") 15 | if err != nil { 16 | return nil, errs.Wrap(err) 17 | } 18 | defer fh.Close() 19 | 20 | data, err := fh.DWARF() 21 | return data, errs.Wrap(err) 22 | } 23 | -------------------------------------------------------------------------------- /process_go18.go: -------------------------------------------------------------------------------- 1 | //go:build go1.8 2 | // +build go1.8 3 | 4 | package goof 5 | 6 | import ( 7 | "debug/dwarf" 8 | "debug/elf" 9 | "debug/macho" 10 | "debug/pe" 11 | "io" 12 | "os" 13 | "runtime" 14 | 15 | "github.com/zeebo/errs" 16 | ) 17 | 18 | func openProc() (*dwarf.Data, error) { 19 | path, err := os.Executable() 20 | if err != nil { 21 | return nil, errs.Wrap(err) 22 | } 23 | 24 | var fh interface { 25 | io.Closer 26 | DWARF() (*dwarf.Data, error) 27 | } 28 | 29 | switch runtime.GOOS { 30 | case "linux": 31 | fh, err = elf.Open(path) 32 | case "darwin": 33 | fh, err = macho.Open(path) 34 | case "windows": 35 | fh, err = pe.Open(path) 36 | default: 37 | return nil, errs.New("unknown goos: %q", runtime.GOOS) 38 | } 39 | if err != nil { 40 | return nil, errs.Wrap(err) 41 | } 42 | defer fh.Close() 43 | 44 | data, err := fh.DWARF() 45 | return data, errs.Wrap(err) 46 | } 47 | -------------------------------------------------------------------------------- /reflect_helpers.go: -------------------------------------------------------------------------------- 1 | package goof 2 | 3 | import ( 4 | "fmt" 5 | "path" 6 | "reflect" 7 | "strings" 8 | "unsafe" 9 | ) 10 | 11 | func ifaces(values []reflect.Value) []interface{} { 12 | out := make([]interface{}, 0, len(values)) 13 | for _, value := range values { 14 | out = append(out, value.Interface()) 15 | } 16 | return out 17 | } 18 | 19 | func reflectCanBeNil(rtyp reflect.Type) bool { 20 | switch rtyp.Kind() { 21 | case reflect.Interface, 22 | reflect.Ptr, 23 | reflect.Map, 24 | reflect.Chan, 25 | reflect.Slice: 26 | return true 27 | } 28 | return false 29 | } 30 | 31 | func typesByString(types []reflect.Type) sortTypesByString { 32 | cache := make([]string, 0, len(types)) 33 | for _, typ := range types { 34 | cache = append(cache, typ.String()) 35 | } 36 | return sortTypesByString{ 37 | types: types, 38 | cache: cache, 39 | } 40 | } 41 | 42 | type sortTypesByString struct { 43 | types []reflect.Type 44 | cache []string 45 | } 46 | 47 | func (s sortTypesByString) Len() int { return len(s.types) } 48 | 49 | func (s sortTypesByString) Less(i, j int) bool { 50 | return s.cache[i] < s.cache[j] 51 | } 52 | 53 | func (s sortTypesByString) Swap(i, j int) { 54 | s.cache[i], s.cache[j] = s.cache[j], s.cache[i] 55 | s.types[i], s.types[j] = s.types[j], s.types[i] 56 | } 57 | 58 | var ( 59 | unsafePointerType = reflect.TypeOf((*unsafe.Pointer)(nil)).Elem() 60 | ) 61 | 62 | // dwarfName does a best effort to return the dwarf entry name for the reflect 63 | // type so that we can map between them. here's hoping it doesn't do it wrong 64 | func dwarfName(rtyp reflect.Type) (out string) { 65 | pkg_path := rtyp.PkgPath() 66 | name := rtyp.Name() 67 | 68 | switch { 69 | // this type's PkgPath returns "" instead of "unsafe". hah. 70 | case rtyp == unsafePointerType: 71 | return "unsafe.Pointer" 72 | 73 | case pkg_path != "": 74 | // this is crazy, but sometimes a dot is encoded as %2e, but only when 75 | // it's in the last path component. i wonder if this is sufficient. 76 | if strings.Contains(pkg_path, "/") { 77 | dir := path.Dir(pkg_path) 78 | base := strings.Replace(path.Base(pkg_path), ".", "%2e", -1) 79 | pkg_path = dir + "/" + base 80 | } 81 | 82 | return pkg_path + "." + name 83 | 84 | case name != "": 85 | return name 86 | 87 | default: 88 | switch rtyp.Kind() { 89 | case reflect.Ptr: 90 | return "*" + dwarfName(rtyp.Elem()) 91 | 92 | case reflect.Slice: 93 | return "[]" + dwarfName(rtyp.Elem()) 94 | 95 | case reflect.Array: 96 | return fmt.Sprintf("[%d]%s", 97 | rtyp.Len(), 98 | dwarfName(rtyp.Elem())) 99 | 100 | case reflect.Map: 101 | return fmt.Sprintf("map[%s]%s", 102 | dwarfName(rtyp.Key()), 103 | dwarfName(rtyp.Elem())) 104 | 105 | case reflect.Chan: 106 | prefix := "chan" 107 | switch rtyp.ChanDir() { 108 | case reflect.SendDir: 109 | prefix = "chan<-" 110 | case reflect.RecvDir: 111 | prefix = "<-chan" 112 | } 113 | return fmt.Sprintf("%s %s", 114 | prefix, 115 | dwarfName(rtyp.Elem())) 116 | 117 | // TODO: func, struct 118 | 119 | default: 120 | // oh well. this sometimes works. 121 | return rtyp.String() 122 | } 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /troop.go: -------------------------------------------------------------------------------- 1 | package goof 2 | 3 | import ( 4 | "debug/dwarf" 5 | "reflect" 6 | "sync" 7 | ) 8 | 9 | type Troop struct { 10 | once sync.Once 11 | err error 12 | data *dwarf.Data 13 | types map[string]reflect.Type 14 | globals map[string]reflect.Value 15 | functions map[string]functionCacheEntry 16 | failures map[string]error 17 | } 18 | 19 | type functionCacheEntry struct { 20 | pc uint64 21 | dtypes []dwarf.Type 22 | } 23 | 24 | func (t *Troop) init() { 25 | t.data, t.err = openProc() 26 | if t.err != nil { 27 | return 28 | } 29 | 30 | t.failures = make(map[string]error) 31 | 32 | t.types = make(map[string]reflect.Type) 33 | t.err = t.addTypes() 34 | if t.err != nil { 35 | return 36 | } 37 | 38 | t.globals = make(map[string]reflect.Value) 39 | t.err = t.addGlobals() 40 | if t.err != nil { 41 | return 42 | } 43 | 44 | t.functions = make(map[string]functionCacheEntry) 45 | t.err = t.addFunctions() 46 | if t.err != nil { 47 | return 48 | } 49 | } 50 | 51 | func (t *Troop) check() error { 52 | t.once.Do(t.init) 53 | return t.err 54 | } 55 | -------------------------------------------------------------------------------- /troop_call.go: -------------------------------------------------------------------------------- 1 | package goof 2 | 3 | import ( 4 | "debug/dwarf" 5 | "reflect" 6 | "sort" 7 | "unsafe" 8 | 9 | "github.com/zeebo/errs" 10 | ) 11 | 12 | func (t *Troop) addFunctions() error { 13 | reader := t.data.Reader() 14 | 15 | for { 16 | entry, err := reader.Next() 17 | if err != nil { 18 | return errs.Wrap(err) 19 | } 20 | if entry == nil { 21 | break 22 | } 23 | 24 | if entry.Tag != dwarf.TagSubprogram { 25 | continue 26 | } 27 | 28 | name, ok := entry.Val(dwarf.AttrName).(string) 29 | if !ok { 30 | continue 31 | } 32 | 33 | pc, ok := entry.Val(dwarf.AttrLowpc).(uint64) 34 | if !ok { 35 | continue 36 | } 37 | 38 | dtypes, err := getFunctionArgTypes(t.data, entry) 39 | if err != nil { 40 | continue 41 | } 42 | 43 | _, err = t.findDwarfTypes(dtypes) 44 | if err != nil { 45 | continue 46 | } 47 | 48 | t.functions[name] = functionCacheEntry{ 49 | pc: pc, 50 | dtypes: dtypes, 51 | } 52 | } 53 | 54 | return nil 55 | } 56 | 57 | func (t *Troop) Functions() ([]string, error) { 58 | if err := t.check(); err != nil { 59 | return nil, err 60 | } 61 | 62 | out := make([]string, 0, len(t.functions)) 63 | for name := range t.functions { 64 | out = append(out, name) 65 | } 66 | sort.Strings(out) 67 | return out, nil 68 | } 69 | 70 | func (t *Troop) Call(name string, args ...interface{}) ([]interface{}, error) { 71 | if err := t.check(); err != nil { 72 | return nil, err 73 | } 74 | 75 | // and so it begins. find the function, the pc, and the types of the args 76 | // and return values. we don't know which is which, but we assume the 77 | // caller passed the appropriate things. 78 | entry, ok := t.functions[name] 79 | if !ok { 80 | return nil, errs.New("call %s: unknown or uncallable function", name) 81 | } 82 | pc, dtypes := entry.pc, entry.dtypes 83 | 84 | // make sure they didn't pass more arguments than total types 85 | num_results := len(dtypes) - len(args) 86 | if num_results < 0 { 87 | return nil, errs.New("call %s: too many args", name) 88 | } 89 | 90 | // build the arguments, checking consistency and doing hacks to make it 91 | // nice to use. 92 | in, in_types, err := t.buildArguments(args, dtypes[:len(args)]) 93 | if err != nil { 94 | return nil, errs.New("call %s: %v", name, err) 95 | } 96 | 97 | // the rest must be the return values, RIGHT? LOL 98 | out_types, err := t.findDwarfTypes(dtypes[len(args):]) 99 | if err != nil { 100 | return nil, errs.New("call %s: %v", name, err) 101 | } 102 | 103 | // make it happen 104 | fn_typ := reflect.FuncOf(in_types, out_types, false) 105 | fn := reflect.ValueOf(makeInterface(dataPtr(fn_typ), unsafe.Pointer(&pc))) 106 | return ifaces(fn.Call(in)), nil 107 | } 108 | 109 | func (t *Troop) buildArguments(args []interface{}, dtypes []dwarf.Type) ( 110 | []reflect.Value, []reflect.Type, error) { 111 | 112 | if len(args) != len(dtypes) { 113 | return nil, nil, errs.New("number of arguments does not match") 114 | } 115 | 116 | // so I want the Call signatrue to have args passed as ...interface{} 117 | // because that makes the api nice: taking a reflect.Value is hard for the 118 | // consumer. 119 | // 120 | // Unfortunately, that means that if you pass an interface type in, they 121 | // get down-casted to just interface{}. Doubly unfortunately, the itab 122 | // pointer was lost when the value was converted to an interface{} instead 123 | // of whatever interface it was in the first place. 124 | // 125 | // So let's just look and see if we can find the interface type in the 126 | // types map based on the dwarf type. If not, shoot. Hopefully that's 127 | // rare! Maybe we can expose a CallReflect api that can get around this. 128 | // 129 | // Heh. 130 | 131 | in_types := make([]reflect.Type, 0, len(args)) 132 | in := make([]reflect.Value, 0, len(args)) 133 | 134 | for i, arg := range args { 135 | dtyp := dtypes[i] 136 | 137 | val, err := t.constructValue(arg, dtyp) 138 | if err != nil { 139 | return nil, nil, errs.New("arg %d: %v", i, err) 140 | } 141 | 142 | in_types = append(in_types, val.Type()) 143 | in = append(in, val) 144 | } 145 | 146 | return in, in_types, nil 147 | } 148 | 149 | func (t *Troop) constructValue(arg interface{}, dtyp dwarf.Type) ( 150 | val reflect.Value, err error) { 151 | 152 | rtyp, err := t.consistentValue(arg, dtyp) 153 | if err != nil { 154 | return val, err 155 | } 156 | if arg == nil { 157 | return reflect.New(rtyp).Elem(), nil 158 | } 159 | return reflect.ValueOf(arg).Convert(rtyp), nil 160 | } 161 | 162 | func (t *Troop) consistentValue(arg interface{}, dtyp dwarf.Type) ( 163 | reflect.Type, error) { 164 | 165 | rtyp, err := t.findDwarfType(dtyp) 166 | if err != nil { 167 | return nil, err 168 | } 169 | if arg == nil { 170 | if !reflectCanBeNil(rtyp) { 171 | return nil, errs.New("passing nil to non-nillable type: %v", 172 | rtyp) 173 | } 174 | return rtyp, nil 175 | } 176 | if !reflect.TypeOf(arg).ConvertibleTo(rtyp) { 177 | return nil, errs.New("cannot convert %v to %T", rtyp, arg) 178 | } 179 | return rtyp, nil 180 | } 181 | -------------------------------------------------------------------------------- /troop_globals.go: -------------------------------------------------------------------------------- 1 | package goof 2 | 3 | import ( 4 | "debug/dwarf" 5 | "reflect" 6 | "regexp" 7 | "sort" 8 | "strings" 9 | "unsafe" 10 | 11 | "github.com/zeebo/errs" 12 | ) 13 | 14 | var statictmpRe = regexp.MustCompile(`statictmp_\d+$`) 15 | 16 | func (t *Troop) addGlobals() error { 17 | reader := t.data.Reader() 18 | 19 | for { 20 | entry, err := reader.Next() 21 | if err != nil { 22 | return errs.Wrap(err) 23 | } 24 | if entry == nil { 25 | break 26 | } 27 | 28 | if entry.Tag != dwarf.TagVariable { 29 | continue 30 | } 31 | 32 | name, ok := entry.Val(dwarf.AttrName).(string) 33 | if !ok { 34 | continue 35 | } 36 | 37 | // filter out some values that aren't useful and just clutter stuff 38 | if strings.Contains(name, "·") { 39 | continue 40 | } 41 | if statictmpRe.MatchString(name) { 42 | continue 43 | } 44 | 45 | loc, err := entryLocation(t.data, entry) 46 | if err != nil { 47 | continue 48 | } 49 | 50 | dtyp, err := entryType(t.data, entry) 51 | if err != nil { 52 | continue 53 | } 54 | 55 | dname := dwarfTypeName(dtyp) 56 | if dname == "" || dname == "" { 57 | continue 58 | } 59 | 60 | rtyp := t.types[dname] 61 | if rtyp == nil { 62 | continue 63 | } 64 | 65 | ptr := unsafe.Pointer(uintptr(loc)) 66 | t.globals[name] = reflect.NewAt(rtyp, ptr).Elem() 67 | } 68 | 69 | return nil 70 | } 71 | 72 | func (t *Troop) Globals() ([]string, error) { 73 | if err := t.check(); err != nil { 74 | return nil, err 75 | } 76 | out := make([]string, 0, len(t.globals)) 77 | for name := range t.globals { 78 | out = append(out, name) 79 | } 80 | sort.Strings(out) 81 | return out, nil 82 | } 83 | 84 | func (t *Troop) Global(name string) (reflect.Value, error) { 85 | if err := t.check(); err != nil { 86 | return reflect.Value{}, t.err 87 | } 88 | return t.globals[name], nil 89 | } 90 | -------------------------------------------------------------------------------- /troop_test.go: -------------------------------------------------------------------------------- 1 | package goof 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "os" 7 | "testing" 8 | ) 9 | 10 | //go:noinline 11 | func Barf(err error) int { 12 | if err != nil { 13 | return len(err.Error()) 14 | } 15 | return 5 16 | } 17 | 18 | // no dead code elim 19 | func init() { Barf(nil) } 20 | 21 | func (suite) TestCall(t *testing.T) { 22 | symbol := fmt.Sprintf("%s.Barf", importPath) 23 | if _, err := troop.Call(symbol, errors.New("hi")); err != nil { 24 | t.Fatal(err) 25 | } 26 | if _, err := troop.Call(symbol, nil); err != nil { 27 | t.Fatal(err) 28 | } 29 | } 30 | 31 | func (suite) TestCallFprintf(t *testing.T) { 32 | fmt.Fprintf(os.Stdout, "hello world %d\n", 2) 33 | if _, err := troop.Call("fmt.Fprintf", os.Stdout, "hello world %d\n", []interface{}{2}); err != nil { 34 | t.Fatal(err) 35 | } 36 | } 37 | 38 | func (suite) TestCallFailures(t *testing.T) { 39 | symbol := fmt.Sprintf("%s.Barf", importPath) 40 | type is []interface{} 41 | 42 | cases := []struct { 43 | name string 44 | args []interface{} 45 | }{ 46 | {symbol, is{nil, nil}}, // too many args 47 | {symbol, is{false}}, // wrong arg kind 48 | {symbol, is{"hello", 2}}, // wrong arg kind 49 | } 50 | 51 | for i, c := range cases { 52 | out, err := troop.Call(c.name, c.args...) 53 | if err == nil { 54 | t.Logf("%d: %+v", i, c) 55 | t.Errorf("expected an error. out: %#v", out) 56 | } 57 | } 58 | } 59 | 60 | func (suite) TestGlobals(t *testing.T) { 61 | troop_rv, err := troop.Global(fmt.Sprintf("%s.troop", importPath)) 62 | if err != nil { 63 | t.Fatal(err) 64 | } 65 | troop2 := troop_rv.Addr().Interface().(*Troop) 66 | if troop2 != &troop { 67 | t.Fatal("got a different troop") 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /troop_types.go: -------------------------------------------------------------------------------- 1 | package goof 2 | 3 | import ( 4 | "debug/dwarf" 5 | "fmt" 6 | "reflect" 7 | "sort" 8 | "strings" 9 | "unsafe" 10 | 11 | "github.com/zeebo/errs" 12 | ) 13 | 14 | func (t *Troop) typelinks() ([]unsafe.Pointer, [][]uint32, error) { 15 | reader := t.data.Reader() 16 | for { 17 | entry, err := reader.Next() 18 | if err != nil { 19 | return nil, nil, errs.Wrap(err) 20 | } else if entry == nil { 21 | break 22 | } else if entry.Tag != dwarf.TagSubprogram { 23 | continue 24 | } 25 | name, ok := entry.Val(dwarf.AttrName).(string) 26 | if !ok || name != "reflect.typelinks" { 27 | continue 28 | } 29 | pc, ok := entry.Val(dwarf.AttrLowpc).(uint64) 30 | if !ok { 31 | continue 32 | } 33 | fn_typ := reflect.FuncOf(nil, []reflect.Type{ 34 | reflect.TypeOf([]unsafe.Pointer(nil)), 35 | reflect.TypeOf([][]uint32(nil)), 36 | }, false) 37 | fn := reflect.ValueOf(makeInterface(dataPtr(fn_typ), unsafe.Pointer(&pc))) 38 | out := ifaces(fn.Call(nil)) 39 | if len(out) != 2 { 40 | return nil, nil, errs.New("wrong number of output results: %d", len(out)) 41 | } 42 | sections, ok := out[0].([]unsafe.Pointer) 43 | if !ok { 44 | return nil, nil, errs.New("wrong type of sections: %T", out[0]) 45 | } 46 | offsets, ok := out[1].([][]uint32) 47 | if !ok { 48 | return nil, nil, errs.New("wrong type of offsets: %T", out[1]) 49 | } 50 | return sections, offsets, nil 51 | } 52 | return nil, nil, errs.New("unable to find reflect.typelinks") 53 | } 54 | 55 | func (t *Troop) addTypes() error { 56 | sections, offset, err := t.typelinks() 57 | if err != nil { 58 | return err 59 | } 60 | for i, offs := range offset { 61 | section := sections[i] 62 | for _, off := range offs { 63 | ptr := unsafe.Pointer(uintptr(section) + uintptr(off)) 64 | typ := reflect.TypeOf(makeInterface(ptr, nil)) 65 | t.addType(typ) 66 | } 67 | } 68 | 69 | // special cased types 70 | t.types["*void"] = unsafePointerType 71 | t.types["**void"] = reflect.PtrTo(unsafePointerType) 72 | 73 | return nil 74 | } 75 | 76 | func (t *Troop) addType(typ reflect.Type) { 77 | name := dwarfName(typ) 78 | if _, ok := t.types[name]; ok { 79 | return 80 | } 81 | t.types[name] = typ 82 | 83 | defer func() { 84 | if r := recover(); r != nil { 85 | t.failures[name] = fmt.Errorf("failed to add type %q (%v): %v", name, typ, r) 86 | } 87 | }() 88 | 89 | switch typ.Kind() { 90 | case reflect.Ptr, reflect.Chan, reflect.Slice, reflect.Array: 91 | t.addType(typ.Elem()) 92 | 93 | case reflect.Map: 94 | t.addType(typ.Key()) 95 | t.addType(typ.Elem()) 96 | 97 | case reflect.Func: 98 | for i := 0; i < typ.NumIn(); i++ { 99 | t.addType(typ.In(i)) 100 | } 101 | for i := 0; i < typ.NumOut(); i++ { 102 | t.addType(typ.Out(i)) 103 | } 104 | 105 | case reflect.Struct: 106 | for i := 0; i < typ.NumField(); i++ { 107 | t.addType(typ.Field(i).Type) 108 | } 109 | for i := 0; i < typ.NumMethod(); i++ { 110 | t.addType(typ.Method(i).Type) 111 | } 112 | 113 | case reflect.Interface: 114 | for i := 0; i < typ.NumMethod(); i++ { 115 | t.addType(typ.Method(i).Type) 116 | } 117 | } 118 | } 119 | 120 | func (t *Troop) Types() ([]reflect.Type, error) { 121 | if err := t.check(); err != nil { 122 | return nil, err 123 | } 124 | out := make([]reflect.Type, 0, len(t.types)) 125 | for _, typ := range t.types { 126 | out = append(out, typ) 127 | } 128 | sort.Sort(typesByString(out)) 129 | return out, nil 130 | } 131 | 132 | func (t *Troop) Type(name string) (reflect.Type, error) { 133 | if err := t.check(); err != nil { 134 | return nil, err 135 | } 136 | 137 | entry, ok := t.types[name] 138 | if !ok { 139 | return nil, errs.New("type %s: unknown type", name) 140 | } 141 | 142 | return entry, nil 143 | } 144 | 145 | func (t *Troop) findDwarfTypes(dtypes []dwarf.Type) ([]reflect.Type, error) { 146 | out_types := make([]reflect.Type, 0, len(dtypes)) 147 | for _, dtyp := range dtypes { 148 | typ, err := t.findDwarfType(dtyp) 149 | if err != nil { 150 | return nil, err 151 | } 152 | out_types = append(out_types, typ) 153 | } 154 | return out_types, nil 155 | } 156 | 157 | func (t *Troop) findDwarfType(dtyp dwarf.Type) (reflect.Type, error) { 158 | // TODO(jeff): we can synthesize some of these dwarf types at runtime, 159 | // but hopefully we got enough of them when we loaded up all of the 160 | // types. The problematic types are: 1. named types, 2. recursive types. 161 | var dname string 162 | switch dtyp := dtyp.(type) { 163 | case *dwarf.StructType: 164 | if dtyp.StructName != "" { 165 | dname = dtyp.StructName 166 | } else { 167 | dname = dtyp.Defn() 168 | } 169 | default: 170 | dname = dtyp.String() 171 | } 172 | 173 | // heh this is super hacky, but what isn't!? 174 | if strings.HasPrefix(dname, "*struct ") && 175 | !strings.HasPrefix(dname, "*struct {") { 176 | 177 | dname = "*" + dname[len("*struct "):] 178 | } 179 | 180 | typ, ok := t.types[dname] 181 | if !ok { 182 | return nil, errs.New("dwarf type %q unknown", dname) 183 | } 184 | return typ, nil 185 | } 186 | --------------------------------------------------------------------------------