ui_access

source of pkg::alloy::objc

1// Objective-C from Alloy (PLAN.md, F7), the package2// `pkg::alloy::objc`: the runtime's C functions, loaded while running, for3// AppKit and Metal on Apple systems.4// Every message is `objc_msgSend` read as the method's exact C prototype5// (F0 question 4), so arguments pass as the method declares them:6//7// ```text8// const set_frame = o.send<extern (c_pointer, c_pointer, Rect, bool)>();9// set_frame(window, o.sel(&"setFrame:display:"), frame, true);10// ```11//12// Classes the system calls back into are made while running, their13// methods C functions (lambdas capturing nothing) or blocks holding the14// Alloy value they reach, and their objects may keep a `c_pointer` of15// their own in an instance variable. Blocks, the callbacks some16// APIs take, are built in the blocks ABI's layout as global blocks, which17// the runtime never copies. On Linux the same functions come from18// GNUstep's runtime (libobjc2), which the tests run this module against.19//20// ## How it was built21//22// Notes kept from each stage as it was finished, the sizes and numbers23// of their day; what changed since is in REVIEW.md and the history.24//25// Built in F7a inside `window` and moved here in F7b: see pkg::alloy::window's notes.2627import std::ffi;28import std::option;29import std::string;30import std::process;3132// The runtime's functions, and `objc_msgSend`'s addresses, read as a33// prototype per call.34exp type Objc = struct {35    exp library: Library,36    exp message: c_pointer, // objc_msgSend37    exp message_struct: c_pointer, // objc_msgSend_stret on x86-64, objc_msgSend on ARM6438    exp get_class: extern (c_string) -> c_pointer,39    exp register_selector: extern (c_string) -> c_pointer,40    exp allocate_class: extern (c_pointer, c_string, c_size) -> c_pointer,41    exp register_class: extern (c_pointer),42    exp add_method: extern (c_pointer, c_pointer, c_pointer, c_string) -> bool,43    exp add_ivar: extern (c_pointer, c_string, c_size, u8, c_string) -> bool,44    exp instance_variable: extern (c_pointer, c_string) -> c_pointer,45    exp ivar_offset: extern (c_pointer) -> c_ssize,46    exp class_of: extern (c_pointer) -> c_pointer,47    exp get_protocol: extern (c_string) -> c_pointer,48    exp add_protocol: extern (c_pointer, c_pointer) -> bool,49    exp pool_push: extern () -> c_pointer,50    exp pool_pop: extern (c_pointer),51    exp global_block: c_pointer, // _NSConcreteGlobalBlock's address52    exp block_method: extern (c_pointer) -> c_pointer, // imp_implementationWithBlock53    exp block_of: extern (c_pointer) -> c_pointer, // imp_getBlock54    exp implementation: extern (c_pointer, c_pointer) -> c_pointer, // class_getMethodImplementation55};5657// The runtime, or None where it cannot be loaded.58exp fn Objc::load() -> Option<Objc> {59    const path: &[u8] = if (60        target() == "macos-arm64" || target() == "macos-x86_64"61    ) &"/usr/lib/libobjc.A.dylib" else &"libobjc.so.4.6";62    const library = if (Library::open(&path) is ::Some |l|) l else {63        return ::None;64    };65    const message = address_of(&library, &"objc_msgSend");66    // a result too large for registers comes through objc_msgSend_stret67    // on x86-64 (System V's memory class); ARM64's objc_msgSend takes the68    // result's address in x8 itself69    const message_struct = if (70        target() == "macos-arm64" || target() == "linux-aarch64"71    ) message else address_of(&library, &"objc_msgSend_stret");72    return ::Some(Objc {73        .library = library,74        .message = message,75        .message_struct = message_struct,76        .get_class = required(&library, &"objc_getClass"),77        .register_selector = required(&library, &"sel_registerName"),78        .allocate_class = required(&library, &"objc_allocateClassPair"),79        .register_class = required(&library, &"objc_registerClassPair"),80        .add_method = required(&library, &"class_addMethod"),81        .add_ivar = required(&library, &"class_addIvar"),82        .instance_variable = required(&library, &"class_getInstanceVariable"),83        .ivar_offset = required(&library, &"ivar_getOffset"),84        .class_of = required(&library, &"object_getClass"),85        .get_protocol = required(&library, &"objc_getProtocol"),86        .add_protocol = required(&library, &"class_addProtocol"),87        .pool_push = required(&library, &"objc_autoreleasePoolPush"),88        .pool_pop = required(&library, &"objc_autoreleasePoolPop"),89        .global_block = address_of(&library, &"_NSConcreteGlobalBlock"),90        .block_method = required(&library, &"imp_implementationWithBlock"),91        .block_of = required(&library, &"imp_getBlock"),92        .implementation = required(&library, &"class_getMethodImplementation")93    });94}9596// The library's function of that name, as the C prototype `F`; a library97// lacking it is older than any this package supports.98exp fn required<F: CFunction>(library: &Library, name: &[u8]) -> F {99    if (library.symbol<F>(&name) is ::Some |move f|) {100        return move f;101    }102    const message = f"pkg::alloy::objc: the system library lacks {name}";103    panic message.view();104}105106// The text with a NUL after it, for C.107fn c_text_of(text: &[u8]) -> String {108    var out = String::from(&text);109    out.push(0);110    return move out;111}112113// The address of a library's symbol, a function or data; 0 when it has114// none. Data symbols (`_NSConcreteGlobalBlock`, AppKit's string115// constants) come through `symbol` read as a function, whose value is116// the address alone.117exp fn address_of(library: &Library, name: &[u8]) -> c_pointer {118    if (library.symbol<extern ()>(&name) is ::Some |f|) {119        return copy f as c_pointer;120    }121    return 0;122}123124// The value a data symbol holds, a pointer: AppKit's `NSString *`125// constants, 0 when the library has no such symbol.126exp fn pointer_at(library: &Library, name: &[u8]) -> c_pointer {127    const at = address_of(&library, &name);128    return if (at == 0) 0 else at.view<c_pointer>(1)[0];129}130131// `objc_msgSend` as the prototype `F`, whose first two parameters are the132// receiver and the selector.133exp fn send<F: CFunction>(self o: &Objc) -> F {134    return copy o.message as F;135}136137// `objc_msgSend` for a method returning a struct larger than 16 bytes138// (`NSRect`), as the prototype `F`.139exp fn send_struct<F: CFunction>(self o: &Objc) -> F {140    return copy o.message_struct as F;141}142143// The selector of the name, `setFrame:display:`. Names shorter than 128144// bytes, every one used, take their NUL in a buffer on the stack, so no145// message allocates.146exp fn sel(self o: &Objc, name: &[u8]) -> c_pointer {147    if (name.length() < SHORT) {148        var buffer: [u8 : SHORT] = [0 : SHORT];149        buffer[..name.length()] = name;150        return o.register_selector(&buffer[..name.length() + 1]);151    }152    return o.register_selector(&c_text_of(&name).view());153}154155// The class of the name, 0 when none is loaded.156exp fn class(self o: &Objc, name: &[u8]) -> c_pointer {157    if (name.length() < SHORT) {158        var buffer: [u8 : SHORT] = [0 : SHORT];159        buffer[..name.length()] = name;160        return o.get_class(&buffer[..name.length() + 1]);161    }162    return o.get_class(&c_text_of(&name).view());163}164165const SHORT: u64 = 128;166167/* --- Messages most calls need --- */168169// A message taking nothing and giving an object: `[x alloc]`, `[x init]`.170exp fn call(self o: &Objc, receiver: c_pointer, selector: &[u8]) -> c_pointer {171    return o.send<extern (c_pointer, c_pointer) -> c_pointer>()(receiver, o.sel(&selector));172}173174// A message taking an object and giving one.175exp fn call_with(176    self o: &Objc,177    receiver: c_pointer,178    selector: &[u8],179    argument: c_pointer180) -> c_pointer {181    return o.send<extern (c_pointer, c_pointer, c_pointer) -> c_pointer>()(182        receiver,183        o.sel(&selector),184        argument185    );186}187188// A message taking an integer (`NSInteger`, `NSUInteger`, a `BOOL`189// widened) and giving an object or nothing.190exp fn call_integer(191    self o: &Objc,192    receiver: c_pointer,193    selector: &[u8],194    argument: u64195) -> c_pointer {196    return o.send<extern (c_pointer, c_pointer, u64) -> c_pointer>()(197        receiver,198        o.sel(&selector),199        argument200    );201}202203// A message taking a `BOOL`.204exp fn call_bool(self o: &Objc, receiver: c_pointer, selector: &[u8], argument: bool) {205    o.send<extern (c_pointer, c_pointer, bool)>()(receiver, o.sel(&selector), argument);206}207208// A message giving an integer (`NSInteger`, `NSUInteger`).209exp fn integer(self o: &Objc, receiver: c_pointer, selector: &[u8]) -> u64 {210    return o.send<extern (c_pointer, c_pointer) -> u64>()(receiver, o.sel(&selector));211}212213// A message giving a `BOOL`.214exp fn boolean(self o: &Objc, receiver: c_pointer, selector: &[u8]) -> bool {215    return o.send<extern (c_pointer, c_pointer) -> bool>()(receiver, o.sel(&selector));216}217218// A message giving a `double` (`CGFloat`, `NSTimeInterval`).219exp fn number(self o: &Objc, receiver: c_pointer, selector: &[u8]) -> f64 {220    return o.send<extern (c_pointer, c_pointer) -> f64>()(receiver, o.sel(&selector));221}222223// `[[class alloc] init]`.224exp fn make(self o: &Objc, class: c_pointer) -> c_pointer {225    return o.call(o.call(class, &"alloc"), &"init");226}227228exp fn release(self o: &Objc, object: c_pointer) {229    if (object != 0) {230        o.send<extern (c_pointer, c_pointer)>()(object, o.sel(&"release"));231    }232}233234// An autoreleased NSString of the UTF-8 text.235exp fn string(self o: &Objc, text: &[u8]) -> c_pointer {236    const class = o.class(&"NSString");237    const f = o.send<extern (c_pointer, c_pointer, c_string) -> c_pointer>();238    return f(class, o.sel(&"stringWithUTF8String:"), &c_text_of(&text).view());239}240241// An NSString's text as UTF-8; empty for nil.242exp fn text_of(self o: &Objc, string: c_pointer) -> String {243    if (string == 0) {244        return String::empty();245    }246    const at = o.call(string, &"UTF8String");247    if (at == 0) {248        return String::empty();249    }250    return String::from(&at.c_text());251}252253/* --- Classes made while running --- */254255// A new class of the name below the superclass, to give methods and256// register; the class already registered under that name when there is257// one (a second window in the same process), which `is_new` tells.258exp type NewClass = struct {259    exp class: c_pointer,260    exp is_new: bool,261};262263exp fn subclass(self o: &Objc, name: &[u8], superclass: c_pointer) -> NewClass {264    const made = o.allocate_class(superclass, &c_text_of(&name).view(), 0);265    if (made == 0) {266        return NewClass { .class = o.class(&name), .is_new = false };267    }268    return NewClass { .class = made, .is_new = true };269}270271// Adds the method, a C function taking the receiver and the selector272// first, whose types are written as the runtime encodes them (`v@:@`).273exp fn method<F: CFunction>(self o: &Objc, class: c_pointer, selector: &[u8], types: &[u8], f: F) {274    o.add_method(class, o.sel(&selector), copy f as c_pointer, &c_text_of(&types).view());275}276277// Adds the method as a block holding `state`: the block's function is278// called with the block, the receiver and the method's arguments (no279// selector), and reads the state back with `block_state`. A class's280// methods reach the Alloy value that made it this way. Gives the block,281// which `free_block` frees once the class is no longer used; a class282// made for the process keeps its blocks.283exp fn method_with<F: CFunction>(284    self o: &Objc,285    class: c_pointer,286    selector: &[u8],287    types: &[u8],288    invoke: F,289    state: c_pointer290) -> c_pointer {291    const block = o.block(copy invoke, state);292    o.add_method(class, o.sel(&selector), o.block_method(block), &c_text_of(&types).view());293    return block;294}295296// Adds the instance variable holding the object's Alloy state, before297// the class is registered.298exp fn add_state(self o: &Objc, class: c_pointer) {299    // a pointer: 8 bytes aligned to 8 (log2 3), encoded `^v`300    o.add_ivar(class, &"alloy", 8, 3, &"^v");301}302303exp fn adopt(self o: &Objc, class: c_pointer, protocol: &[u8]) {304    const p = o.get_protocol(&c_text_of(&protocol).view());305    if (p != 0) {306        o.add_protocol(class, p);307    }308}309310// Where an object's state lies in it.311fn state_offset(self o: &Objc, object: c_pointer) -> u64 {312    const ivar = o.instance_variable(o.class_of(object), &"alloy");313    if (ivar == 0) {314        panic "pkg::alloy::objc: an object without Alloy state";315    }316    return o.ivar_offset(ivar) to u64;317}318319// The state kept in an object of a class `add_state` gave a place for.320exp fn state(self o: &Objc, object: c_pointer) -> c_pointer {321    return (object + o.state_offset(object) to c_pointer).view<c_pointer>(1)[0];322}323324exp fn set_state(self o: &Objc, object: c_pointer, state: c_pointer) {325    (object + o.state_offset(object) to c_pointer).view_var<c_pointer>(1)[0] = state;326}327328/* --- Blocks --- */329330extern malloc(size: c_size) -> c_pointer;331extern free(memory: c_pointer);332333// A block in the blocks ABI's layout (the isa, flags, the function called334// with the block first, a descriptor) with the descriptor after it and335// the state its function reads back (`block_state`). Global blocks are336// never copied nor released by the runtime; one lives in C's heap until337// `free_block`, so the methods of a class made once stay valid as long338// as the process.339type Block = struct {340    isa: c_pointer,341    flags: i32,342    reserved: i32,343    invoke: c_pointer,344    descriptor: c_pointer,345    state: c_pointer,346    // the descriptor: reserved, the block's size, its signature347    descriptor_reserved: c_ulong,348    descriptor_size: c_ulong,349    descriptor_signature: c_pointer,350};351352// BLOCK_IS_GLOBAL, BLOCK_USE_STRET, BLOCK_HAS_SIGNATURE353const BLOCK_IS_GLOBAL: i32 = 1 << 28;354const BLOCK_USE_STRET: i32 = 1 << 29;355const BLOCK_HAS_SIGNATURE: i32 = 1 << 30;356357// A block calling `invoke` with itself and the arguments the caller358// passes, holding `state`.359exp fn block<F: CFunction>(self o: &Objc, invoke: F, state: c_pointer) -> c_pointer {360    return o.make_block(copy invoke as c_pointer, state, &"");361}362363// A block whose function gives a struct too large for registers, which364// x86-64 returns through memory: the block says so (BLOCK_USE_STRET and365// its signature, as clang writes them), so a method made of it is called366// through objc_msgSend_stret. `signature` is the block's type encoding.367exp fn struct_block<F: CFunction>(368    self o: &Objc,369    invoke: F,370    state: c_pointer,371    signature: &[u8]372) -> c_pointer {373    return o.make_block(copy invoke as c_pointer, state, &signature);374}375376fn make_block(self o: &Objc, invoke: c_pointer, state: c_pointer, signature: &[u8]) -> c_pointer {377    const at = malloc(Block.size() to c_size);378    var flags = BLOCK_IS_GLOBAL;379    var text: c_pointer = 0;380    if (signature.length() > 0) {381        text = lasting(signature.length() to u64 + 1);382        text.view_var<u8>(signature.length())[..] = signature;383        flags |= BLOCK_HAS_SIGNATURE;384        if (target() == "macos-x86_64" || target() == "linux-x86_64") {385            flags |= BLOCK_USE_STRET;386        }387    }388    // the descriptor after the block's 40 bytes389    at.view_var<Block>(1)[0] = Block {390        .isa = o.global_block,391        .flags = flags,392        .reserved = 0,393        .invoke = invoke,394        .descriptor = at + 40 to c_pointer,395        .state = state,396        .descriptor_reserved = 0,397        .descriptor_size = 40 to c_ulong,398        .descriptor_signature = text399    };400    return at;401}402403// A block's type encoding from a method's (`{CGRect=...}@:{_NSRange=QQ}`404// gives `{CGRect=...}@?@{_NSRange=QQ}`): the block, then the receiver,405// with no selector.406exp fn block_signature(method_types: &[u8]) -> String {407    var out = String::empty();408    for ([..method_types.length()]) |k| {409        if (k + 1 < method_types.length() && method_types[k..k + 2] == "@:" && out.length() > 0) {410            out.append(&"@?@");411            out.append(&method_types[k + 2..]);412            return move out;413        }414        out.push(method_types[k]);415    }416    return move out;417}418419// Adds the method as a block, as `method_with`, for one returning a420// struct larger than 16 bytes (`NSRect`).421exp fn struct_method_with<F: CFunction>(422    self o: &Objc,423    class: c_pointer,424    selector: &[u8],425    types: &[u8],426    invoke: F,427    state: c_pointer428) -> c_pointer {429    const signature = block_signature(&types);430    const block = o.struct_block(copy invoke, state, &signature.view());431    o.add_method(class, o.sel(&selector), o.block_method(block), &c_text_of(&types).view());432    return block;433}434435// `BOOL`'s type encoding: `B` on ARM64, where it is C's bool, `c` on436// x86-64, where it is a signed char.437exp fn bool_code() -> &[u8] {438    return if (target() == "macos-arm64" || target() == "linux-aarch64") &"B" else &"c";439}440441// The state a block holds, read by its function.442exp fn block_state(block: c_pointer) -> c_pointer {443    return block.view<Block>(1)[0].state;444}445446// Frees a block `block` made, once nothing calls it any more.447exp fn free_block(block: c_pointer) {448    free(block);449}450451// The block a method `method_with` added runs, 0 for another kind.452exp fn method_block(self o: &Objc, class: c_pointer, selector: &[u8]) -> c_pointer {453    return o.block_of(o.implementation(class, o.sel(&selector)));454}455456// C's heap, for values the runtime holds past what Alloy's ownership457// sees: zeroed bytes, never freed.458exp fn lasting(size: u64) -> c_pointer {459    const at = malloc(size to c_size);460    const bytes = &var at.view_var<u8>(size);461    for ([..size]) |k| {462        bytes[k] = 0;463    }464    return at;465}