mongodb: fixes crash when the return of `mongoc_cursor_current` was freed
authorAlexandre Terrasa <alexandre@moz-code.org>
Sun, 29 Nov 2015 20:35:14 +0000 (15:35 -0500)
committerAlexandre Terrasa <alexandre@moz-code.org>
Sun, 29 Nov 2015 20:35:14 +0000 (15:35 -0500)
As explained by the documentation (that I should have read more thoroughly...),
`bson_t` structures allocated by the `mongoc_cursor_current` function should not be freed by the user.

Before this commit, the `bson_t` returned by `mongoc_cursor_current` where left as this then freed
by the nit GC.

This commit makes the `current` method to return a copy of the `bson_t` struct so
it can be freed safely by the GC later.

And... this is why I fear and hate the C programming language... :)

Signed-off-by: Alexandre Terrasa <alexandre@moz-code.org>

lib/mongodb/mongodb.nit
lib/mongodb/native_mongodb.nit

index 6a8727e..889fc2e 100644 (file)
@@ -110,7 +110,6 @@ private class BSON
        fun to_json: JsonObject do
                var json = to_s.parse_json
                if json isa JsonParseError then
-                       print to_s
                        print json.message
                        sys.exit 1
                end
index d25a9ac..c28a218 100644 (file)
@@ -506,7 +506,12 @@ extern class NativeMongoCursor `{ mongoc_cursor_t* `}
        # Wrapper for `mongoc_cursor_current()`.
        #
        # Fetches the cursors current document or NULL if there has been an error.
-       fun current: NativeBSON `{ return (bson_t*) mongoc_cursor_current(self); `}
+       fun current: NativeBSON `{
+               // As said in documentation, BSON objects should not be freed manually.
+               bson_t* bson = (bson_t*) mongoc_cursor_current(self);
+               // Copy BSON so we can let the GC free it automatically.
+               return bson_copy(bson);
+       `}
 
        # Wrapper for `mongoc_cursor_next()`.
        #