Skip to content

Commit

Permalink
Merge pull request #131 from neil4/direct-savestates
Browse files Browse the repository at this point in the history
Avoid malloc & memcpy in retro_serialize
  • Loading branch information
LibretroAdmin authored Apr 1, 2023
2 parents 14c08b8 + 26bcce6 commit f97cec6
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 11 deletions.
24 changes: 14 additions & 10 deletions libretro.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1922,6 +1922,7 @@ size_t retro_serialize_size(void)
StateMem st;

st.data = NULL;
st.data_frontend = NULL;
st.loc = 0;
st.len = 0;
st.malloced = 0;
Expand All @@ -1948,22 +1949,24 @@ size_t retro_serialize_size(void)
bool retro_serialize(void *data, size_t size)
{
StateMem st;
bool ret = false;
uint8_t *_dat = (uint8_t *)malloc(size);
bool ret = false;

if (!_dat)
return false;

/* Mednafen can realloc the buffer so we need to ensure this is safe. */
st.data = _dat;
st.data_frontend = (uint8_t*)data;
st.data = st.data_frontend;
st.loc = 0;
st.len = 0;
st.malloced = size;

/* MDFNSS_SaveSM will malloc separate memory for st.data to complete
* the save if the passed-in size is too small */
ret = MDFNSS_SaveSM(&st, 0, 0, NULL, NULL, NULL);

memcpy(data, st.data, size);
free(st.data);
if (st.data != st.data_frontend)
{
log_cb(RETRO_LOG_WARN, "Save state size has increased\n");
free(st.data);
ret = false;
}

return ret;
}
Expand All @@ -1972,7 +1975,8 @@ bool retro_unserialize(const void *data, size_t size)
{
StateMem st;

st.data = (uint8_t *)data;
st.data_frontend = (uint8_t*)data;
st.data = st.data_frontend;
st.loc = 0;
st.len = size;
st.malloced = 0;
Expand Down
11 changes: 10 additions & 1 deletion mednafen/state.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,16 @@ static int32_t smem_write(StateMem *st, void *buffer, uint32_t len)

while(newsize < (len + st->loc))
newsize *= 2;
st->data = (uint8_t *)realloc(st->data, newsize);

// Don't realloc data_frontend memory
if (st->data == st->data_frontend && st->data != NULL )
{
st->data = (uint8_t *)malloc(newsize);
memcpy(st->data, st->data_frontend, st->malloced);
}
else
st->data = (uint8_t *)realloc(st->data, newsize);

st->malloced = newsize;
}
memcpy(st->data + st->loc, buffer, len);
Expand Down
1 change: 1 addition & 0 deletions mednafen/state.h
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
typedef struct
{
uint8_t *data;
uint8_t *data_frontend; // never realloc'd
uint32_t loc;
uint32_t len;
uint32_t malloced;
Expand Down

0 comments on commit f97cec6

Please sign in to comment.