Skip to content

Commit

Permalink
Fix possible segfault when creating new PG::Result
Browse files Browse the repository at this point in the history
Initialize connection and typemap prior to any object allocations, to make sure valid objects are marked.

This regression was introduced in commit 5061020 while introducing write barriers.
However it is not necessary to use RB_OBJ_WRITE when the "old" object (1st argument) is not yet created or immediately after it was created.
The initial assignment can and must be done before processing the typemap as it was before the above commit.

Fixes ged#530
  • Loading branch information
larskanis committed Apr 27, 2023
1 parent 2b87db5 commit 38b4318
Showing 1 changed file with 5 additions and 3 deletions.
8 changes: 5 additions & 3 deletions ext/pg_result.c
Original file line number Diff line number Diff line change
Expand Up @@ -208,12 +208,16 @@ pg_new_result2(PGresult *result, VALUE rb_pgconn)

this = (t_pg_result *)xmalloc(sizeof(*this) + sizeof(*this->fnames) * nfields);
this->pgresult = result;
/* Initialize connection and typemap prior to any object allocations,
* to make sure valid objects are marked. */
this->connection = rb_pgconn;
this->typemap = pg_typemap_all_strings;
this->p_typemap = RTYPEDDATA_DATA( this->typemap );
this->nfields = -1;
this->tuple_hash = Qnil;
this->field_map = Qnil;
this->flags = 0;
self = TypedData_Wrap_Struct(rb_cPGresult, &pgresult_type, this);
RB_OBJ_WRITE(self, &this->connection, rb_pgconn);

if( result ){
t_pg_connection *p_conn = pg_get_connection(rb_pgconn);
Expand All @@ -227,8 +231,6 @@ pg_new_result2(PGresult *result, VALUE rb_pgconn)
this->p_typemap = RTYPEDDATA_DATA( this->typemap );
this->flags = p_conn->flags;
} else {
RB_OBJ_WRITE(self, &this->typemap, pg_typemap_all_strings);
this->p_typemap = RTYPEDDATA_DATA( this->typemap );
this->enc_idx = rb_locale_encindex();
}

Expand Down

0 comments on commit 38b4318

Please sign in to comment.