Skip to content

Document that custom finalizers must not resurrect their argument - #13732

Merged
gasche merged 1 commit into
ocaml:trunkfrom
jberdine:custom_final_doc
Jan 24, 2025
Merged

gasche merged 1 commit into
ocaml:trunkfrom
jberdine:custom_final_doc

Conversation

@jberdine

Copy link
Copy Markdown
Contributor

Perhaps I am mistaken, but my understanding of the runtime implementation is
that there is no provision for custom block finalizers to resurrect their
arguments. In particular, if a custom block allocated in the minor heap dies
before being promoted, its finalizer will be run immediately after exiting
the STW barrier, when the minor GC has just finished. If a finalizer makes
its custom block live again at this point (e.g. storing it into a global
root), there is no further marking done, and the custom block will not be
promoted, and be in danger of being overwritten in the minor heap.

To wit:

> cat dodgy.c
#include <caml/custom.h>
#include <caml/memory.h>
#include <caml/mlvalues.h>

static value global = Val_none;

value init(value _unit) {
  caml_register_global_root(&global);
  return Val_unit;
}

typedef struct _block {
  int data;
} block;

static void finalize_block (value v) {
  global = v;
}

static struct custom_operations custom_ops = {
  NULL,
  finalize_block,
  custom_compare_default,
  custom_hash_default,
  custom_serialize_default,
  custom_deserialize_default,
  custom_compare_ext_default,
  custom_fixed_length_default
};

value box (value v) {
  int n = Int_val(v);
  value b = caml_alloc_custom(&custom_ops, sizeof(block), 0, 1);
  ((block*)Data_custom_val(b))->data = n;
  return b;
}

value get (value _unit) {
  if (global == Val_none) {
    return Val_int(0);
  } else {
    return Val_int(((block*)Data_custom_val(global))->data);
  }
}

> cat dodgy.ml
type t

external init : unit -> unit = "init"
external box : int -> t = "box"
external get : unit -> int = "get"

;;
init () ;
for i = 1 to 100000 do
  let _ = box i in
  ()
done ;
Gc.full_major () ;
Printf.eprintf "got %i\n" (get ())

> ocamlc -custom dodgy.c dodgy.ml && ./a.out
zsh: segmentation fault  ./a.out

Note that this crashes with 4.14, but I have not seen this crash with
trunk. If the analysis above is incorrect and this should be safe now, I am
happy to revise this PR to document that instead.

@gadmm

gadmm commented Jan 15, 2025 •

Copy link
Copy Markdown
Contributor

More generally, is a custom finalizer allowed to mutate the OCaml heap? Access it?

@jberdine

Copy link
Copy Markdown
Contributor Author

If the docs stated something as strong as the OCaml heap cannot be mutated, then it would seem understandable for users to interpret that as also banning calling caml_remove_global_root and caml_remove_generational_global_root. Whether those functions mutate "OCaml heap" is perhaps an implementation detail that the docs are better to avoid.

However, your question makes me think that it would probably be better to state something stronger than in the current PR. Perhaps: "Every OCaml heap value that is dead when a custom block finalizer is called must still be dead when it returns." The aim here is to make it clear that adding any marking work is prohibited, and it is not specific to the finalized block itself, those just happen to be the dead values user code gets to see.

@stedolan

Copy link
Copy Markdown
Contributor

Custom block finalisers run under extremely harsh constraints. They cannot access the OCaml heap, mutate the OCaml heap, release the runtime lock, or do almost anything else. They can safely call caml_remove_(generational_)global_root, but that's about it.

The reason is that custom block finalisers run synchronously inside the GC when the heap is in an invalid state. If you access the heap from a custom block finaliser, you'll see very weird states such as objects that are halfway through being promoted from the minor to the major heap and are partially overwritten. Nearly the only thing that you can safely do is access the bytes of the custom block being finalised.

This API is hard to use correctly. In particular, I think it's a mistake for finalize to take a value: most of the things you can do with a value cannot be done inside finalize. Rather, it would be better if it took a void* (the result of Data_custom_val(v)), which is the piece of memory it's expected to finalize.

(None of the above is particularly different between OCaml 4 and OCaml 5)

@stedolan

Copy link
Copy Markdown
Contributor

but I have not seen this crash with trunk

I think that's because your loop is only allocating boxes, so dangling pointers into the minor heap have a pretty good chance of hitting something of the right type, because the minor heap only contains boxes. Try this instead:

init () ;
for i = 1 to 100000 do
  let _ = box i in
  Printf.eprintf "got %i\n" (get ())
done

@gadmm

gadmm commented Jan 22, 2025 •

Copy link
Copy Markdown
Contributor

Must not access the OCaml heap sounds a better description than the current PR.

(None of the above is particularly different between OCaml 4 and OCaml 5)

There is one minor difference from the point of view of caml_remove_global_root and caml_remove_generational_global_root: it does not need the runtime lock in OCaml 5. So it can run from any thread in any circumstance. This means that there is nothing exceptional about it for custom finalizers (whereas it used to be a special exception for custom finalizers in OCaml 4).

Edit: it is not true that caml_remove_generational_global_root, which uses classify_gc_root before taking the roots lock, can be used without the runtime lock... but then if it is safe to call it from a custom finalizer then there is a complex invariant which is not documented.

@jberdine

Copy link
Copy Markdown
Contributor Author

Thanks, I will revise based on these comments and update this PR. My understanding is that caml_remove_generational_global_root was made safe to call from custom block finalizers by #13584.

I agree that it would be better if these finalizers received just the result of Data_custom_val. There is no way to make that change due to backward compatibility desires though, or am I overlooking something?

Signed-off-by: Josh Berdine <josh@berdine.net>
@jberdine

Copy link
Copy Markdown
Contributor Author

I have pushed a new version with I think improved clarity based on the discussion here.

While working on the wording of this I encountered another question: the manual currently states

[finalizers] must not allocate on the Caml heap, or call OCaml code or allow it to be called (for example, they should not call caml_release_runtime_system()"

while other custom block operations also have the prohibition to not allocate or call OCaml code, but do not explicitly mention the "allow it to be called" phrase. My expectation is that that clarification is also applicable to the other custom operations. The current state of this PR is based on this, but if this is wrong I am happy to revise.

@gasche gasche left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! The extra information looks fine to me, so I propose to go ahead and merge. If one of the experts around wants to suggest reformulations, this can go in a follow-up PR.

@gasche
gasche merged commit c82ce40 into ocaml:trunk Jan 24, 2025
@jberdine
jberdine deleted the custom_final_doc branch January 28, 2025 22:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants