Shenghou Ma | 2fc67e7 | 2015-11-01 04:18:58 -0500 | [diff] [blame] | 1 | // Copyright 2016 The Go Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
Russ Cox | d4b2638 | 2021-02-19 18:35:10 -0500 | [diff] [blame] | 5 | //go:build linux || netbsd || (js && wasm) |
Shenghou Ma | 2fc67e7 | 2015-11-01 04:18:58 -0500 | [diff] [blame] | 6 | |
| 7 | package os |
| 8 | |
| 9 | import ( |
| 10 | "errors" |
| 11 | "runtime" |
| 12 | ) |
| 13 | |
Egon Elbre | cfe5d79 | 2021-04-20 17:38:54 +0300 | [diff] [blame] | 14 | func executable() (string, error) { |
Shenghou Ma | 2fc67e7 | 2015-11-01 04:18:58 -0500 | [diff] [blame] | 15 | var procfn string |
| 16 | switch runtime.GOOS { |
| 17 | default: |
| 18 | return "", errors.New("Executable not implemented for " + runtime.GOOS) |
David Crawshaw | 8a2c34e | 2016-11-28 17:23:12 -0500 | [diff] [blame] | 19 | case "linux", "android": |
Shenghou Ma | 2fc67e7 | 2015-11-01 04:18:58 -0500 | [diff] [blame] | 20 | procfn = "/proc/self/exe" |
| 21 | case "netbsd": |
| 22 | procfn = "/proc/curproc/exe" |
Shenghou Ma | 2fc67e7 | 2015-11-01 04:18:58 -0500 | [diff] [blame] | 23 | } |
Egon Elbre | cfe5d79 | 2021-04-20 17:38:54 +0300 | [diff] [blame] | 24 | path, err := Readlink(procfn) |
Shenghou Ma | 2fc67e7 | 2015-11-01 04:18:58 -0500 | [diff] [blame] | 25 | |
Egon Elbre | cfe5d79 | 2021-04-20 17:38:54 +0300 | [diff] [blame] | 26 | // When the executable has been deleted then Readlink returns a |
| 27 | // path appended with " (deleted)". |
| 28 | return stringsTrimSuffix(path, " (deleted)"), err |
| 29 | } |
| 30 | |
| 31 | // stringsTrimSuffix is the same as strings.TrimSuffix. |
| 32 | func stringsTrimSuffix(s, suffix string) string { |
| 33 | if len(s) >= len(suffix) && s[len(s)-len(suffix):] == suffix { |
| 34 | return s[:len(s)-len(suffix)] |
| 35 | } |
| 36 | return s |
Shenghou Ma | 2fc67e7 | 2015-11-01 04:18:58 -0500 | [diff] [blame] | 37 | } |