Skip to content

Proposal: Ability to append functions to .init_array/.fini_array #23574

Open

Description

@alexrp

In certain specialized scenarios such as #20382, it's important to be able to designate constructor/destructor (henceforth init/fini) functions. Init functions allow running initialization code before main() in the case of a program, or when a shared library is loaded and thus before any exported functions are invoked. Conversely, fini functions allow running cleanup after main() returns in the case of a program, or when a shared library is unloaded.

To make this functionality available in Zig, I propose the following:

@appendInitFiniArray(comptime ptr: *const anyopaque, comptime options: std.builtin.InitFiniOptions) void;

// std.builtin
const InitFiniOptions = struct {
    array: enum { init, fini },
    priority: i32 = std.math.maxInt(u16),
};

This builtin function appends ptr to the designated array (.init_array/.fini_array) or the equivalent for the object format.

  • ptr must be comptime-known and resolve to a function with the signature fn () callconv(.c) void.
  • priority can be any i32, but it should be documented that priorities in the range 0 through 100 tend to be used for low-level libraries like libc. That's why C compilers default priority to 65535, which seems sensible for us to do, too.
  • It is valid to append the same ptr multiple times, even with the same priority value, though obviously not particularly sensible.
    • I see no point in attempting to prevent this in Sema as there are ways to circumvent it at link time anyway, and doing so is perfectly valid at the object format level.
  • The language reference should strongly discourage using this builtin function as a general-purpose initialization/cleanup mechanism, since doing so does not lead to particularly idiomatic Zig code. Basically, if you don't know whether you need @appendInitFiniArray(), you don't.
    • That's also part of why I chose this name, rather than the relatively innocent-sounding __attribute__((constructor))/__attribute__((destructor)) in GCC/Clang.

Example usage:

comptime {
    @appendInitFiniArray(&ctor, .{ .array = .init });
    @appendInitFiniArray(&dtor, .{ .array = .fini });
}

fn ctor() callconv(.c) void {
    // ...
}

fn dtor() callconv(.c) void {
    // ...
}

Activity

  1. added
    proposal
    on Apr 15, 2025
  2. added this to the 0.16.0 milestone on Apr 15, 2025
  3. self-assigned this
    on Apr 15, 2025
  4. alexrp commented on Apr 15, 2025

    @alexrp
    MemberAuthor

    I don't know that I would categorize it as "for C compatibility". It's an object format feature that happens to be used by C/C++, but use cases for it don't necessarily have anything to do with C. We already have partial support for it in libc-less Zig due to fuzzing, for example:

    zig/lib/std/start.zig

    Lines 571 to 583 in 76da028

    const opt_init_array_start = @extern([*]*const fn () callconv(.c) void, .{
    .name = "__init_array_start",
    .linkage = .weak,
    });
    const opt_init_array_end = @extern([*]*const fn () callconv(.c) void, .{
    .name = "__init_array_end",
    .linkage = .weak,
    });
    if (opt_init_array_start) |init_array_start| {
    const init_array_end = opt_init_array_end.?;
    const slice = init_array_start[0 .. init_array_end - init_array_start];
    for (slice) |func| func();
    }

    Note that the callconv(.c) requirement isn't there because we necessarily specifically need the C calling convention; rather, it's just that there are some callconv(.auto) features that don't make sense in this context.

  5. added
    enhancement
    on Apr 15, 2025
  6. removed their assignment
    on May 2, 2025
  7. rootbeer commented on May 11, 2025

    @rootbeer
    Contributor

    I think the missing __cxa_finalize would also explain the root of the bug in #17908 (comment)?

  8. alexrp commented on May 11, 2025

    @alexrp
    MemberAuthor

    Sounds likely.

  9. alexrp commented on May 14, 2025

    @alexrp
    MemberAuthor

    Just reproducing some discussion from Zulip here:

    @jacobly0 rightly pointed out that it's possible to implement this builtin in userland with some helper functions in the standard library to abstract over the different object formats.

    However, I think a weakness of that approach is that, when using the C backend, builtin.ofmt == .c, so you can't directly figure out what object format you're ultimately compiling to. OTOH, with this proposal, the C backend would just lower @appendInitFiniArray to __attribute__((constructor)) or __attribute__((destructor)).

    That said, I could see an argument that we should just not have ObjectFormat.c and instead rely on builtin.zig_backend == .stage2_c for detecting the C backend in Zig code. We'd then require that the C code we generate actually gets compiled to the object format that was specified (or more likely picked by default) when invoking the Zig compiler. This would require a new command line flag to actually pick the C backend.

  10. modified the milestones: upcoming, urgent on Jun 26, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementproposal

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions