-
Notifications
You must be signed in to change notification settings - Fork 44
Description
When using ion-c from C++ there is not a straightforward way to assign C++ string literals (which are const) to ION_STRING values.
This results in some gymnastics to remove the const from C++ strings which can lead to more complexities around writing data. One example is when writing struct fields, the ION_STRING value for the field name is captured by the writer and held until the value is written. This requires the user to keep the bytes in memory for the field name, until the value is written. This is neither documented, nor intuitive.
An example of what a user might do:
ION_STRING fieldname = { 0 };
char name_non_const[] = "field_name"; // This will copy the bytes, and eliminate the const.
ion_string_assign_cstr(&fieldname, name_non_const, strlen(name_non_const));
ion_writer_write_field_name(writer, &fieldname); // writer will now hold onto the bytes of name_non_const.In non-trivial cases this pattern might be abstracted into a function or macro to perform the copy and write. If that is the case, the storage for name_non_const could inadvertently go out of scope, leading to memory safety issues when the writer finally does write the field's value.
Potential Solutions
We have two potential solutions. The first would be to do a proper const-correctness pass on the ION_STRING API, in order to better support C++ users. Initial investigation into this suggests that it might be more problematic than expected. There are places where the string is modified (null termination added, despite ION_STRING documented to not be null terminated).
The second solution would be to add a new function that provides either an equivalent to ion_string_assign_cstr, with a const char* argument, or a function to copy a const string into an ION_STRING. We would need to verify that any of the functions that modify an ION_STRING's value are limited to functions that manage their own allocations, and won't try to modify the literal data.
We also need to make sure that we know, and can document any paths where ion-c might free the data associated with an ION_STRING.