Version française
Home     About     Download     Resources     Contact us    

This site is updated infrequently. For up-to-date information, please visit the new OCaml website at

Browse thread
When can we ignore CAMLparam and CAMLreturn?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Jianzhou Zhao <jianzhou@s...>
Subject: When can we ignore CAMLparam and CAMLreturn?
Hi All,

Here is the code from LLVM-OCaml bindings.

/* llvalue -> GenericValue.t array -> ExecutionEngine.t -> GenericValue.t */
CAMLprim value llvm_ee_run_function(LLVMValueRef F, value Args,
                                   LLVMExecutionEngineRef EE) {
 unsigned NumArgs;
 LLVMGenericValueRef Result, *GVArgs;
 unsigned I;

 NumArgs = Wosize_val(Args);
 GVArgs = (LLVMGenericValueRef*) malloc(NumArgs * sizeof(LLVMGenericValueRef));
 for (I = 0; I != NumArgs; ++I)
   GVArgs[I] = Genericvalue_val(Field(Args, I));

 Result = LLVMRunFunction(EE, F, NumArgs, GVArgs);

 return alloc_generic_value(Result);

In this code,  GenericValue.t is an Ocaml value with custom_operations
(say finalizing, hashing, serializing or deserializing a C type) as
shown in the below.

 #define Genericvalue_val(v)  (*(LLVMGenericValueRef *)(Data_custom_val(v)))

 static void llvm_finalize_generic_value(value GenVal) {

 static struct custom_operations generic_value_ops = {
   (char *) "LLVMGenericValue",

 static value alloc_generic_value(LLVMGenericValueRef Ref) {
   value Val = alloc_custom(&generic_value_ops,
sizeof(LLVMGenericValueRef), 0, 1);
   Genericvalue_val(Val) = Ref;
   return Val;

The 'llvm_ee_run_function' does not protect the Args parameter by
CAMLparam with CAMLreturn. Is this safe in this case, because we
allocated a GVArgs? The Ocaml manual suggests to use CAMLparam for any
value parameters
( In
the other LLVM bindings files, the code sometimes also ignores
CAMLparam and CAMLreturn if Caml "value" refers to unit or string. Is
it also safe? for example.

/* string -> lltype -> llmodule -> llvalue */
CAMLprim LLVMValueRef llvm_define_function(value Name, LLVMTypeRef Ty,
LLVMModuleRef M) {
   LLVMValueRef Fn = LLVMAddFunction(M, String_val(Name), Ty);
   LLVMAppendBasicBlockInContext(LLVMGetTypeContext(Ty), Fn, "entry");
   return Fn;

I have been working on extending this Ocaml bindings, but got some
inconsistent results at runtime. I used Valgrind to check my program,
it reports some invalid writes or reads in C overlapping with some
memory space managed by Ocaml, but the report is not detailed enough.
so I doubt if the binding code does any thing wrong. Is there any tool
to help analyzing if the code manages memory between C and OCaml
bindings correctly?