hare

[hare] The Hare programming language
git clone https://git.torresjrjr.com/hare.git
Log | Files | Refs | README | LICENSE

self+freebsd.ha (1115B)


      1 // SPDX-License-Identifier: MPL-2.0
      2 // (c) Hare authors <https://harelang.org>
      3 
      4 use errors;
      5 use fs;
      6 use io;
      7 use os;
      8 use path;
      9 use rt;
     10 use types::c;
     11 
     12 // Opens the executing process's binary image.
     13 export fn self() (image | io::error | fs::error) = {
     14 	// 1: sysctl
     15 	let buf: [path::MAX * 2 + 1]u8 = [0...];
     16 	let pathsz = len(buf);
     17 	match (rt::sysctlbyname("kern.proc.pathname",
     18 			&buf[0], &pathsz, null, 0)) {
     19 	case rt::errno => void;
     20 	case void =>
     21 		const file = os::open(c::tostr(&buf[0]: *const c::char)!)?;
     22 		match (open(file)) {
     23 		case let img: image =>
     24 			return img;
     25 		case let err: io::error =>
     26 			return err;
     27 		case errors::invalid =>
     28 			abort("Running program image is not a valid ELF file");
     29 		};
     30 	};
     31 
     32 	// 2. procfs (not mounted by default, but better than step 3)
     33 	match (os::open("/proc/curproc/exe")) {
     34 	case let file: io::file =>
     35 		match (open(file)) {
     36 		case let img: image =>
     37 			return img;
     38 		case let err: io::error =>
     39 			return err;
     40 		case errors::invalid =>
     41 			abort("Running program image is not a valid ELF file");
     42 		};
     43 	case => void;
     44 	};
     45 
     46 	// 3. Fallback (os::args[0])
     47 	return self_argv();
     48 };