bind/java: fix misuse of mem_ensure.

mem_ensure is to ensure the remaining space in buffer
is large enough to hold extra size bytes. We've been passing
the target capacity instead of the number of extra bytes we
need.

Change-Id: Ic6f6ddb4ad22cbcdbc44eb4a58e6a415ae771fb2
Reviewed-on: https://go-review.googlesource.com/12578
Reviewed-by: David Crawshaw <crawshaw@golang.org>
This commit is contained in:
Hyang-Ah (Hana) Kim 2015-07-23 13:18:49 -04:00 committed by Hyang-Ah Hana Kim
parent 354c023467
commit c039090cf1
1 changed files with 12 additions and 7 deletions

View File

@ -56,14 +56,23 @@ static mem *mem_ensure(mem *m, uint32_t size) {
m->buf = NULL; m->buf = NULL;
m->pinned = NULL; m->pinned = NULL;
} }
uint32_t cap = m->cap;
if (m->cap > m->off+size) { if (m->cap > m->off+size) {
return m; return m;
} }
m->buf = (uint8_t*)realloc((void*)m->buf, m->off+size); if (cap == 0) {
cap = 64;
}
// TODO(hyangah): consider less aggressive allocation such as
// cap += max(pow2round(size), 64)
while (cap < m->off+size) {
cap *= 2;
}
m->buf = (uint8_t*)realloc((void*)m->buf, cap);
if (m->buf == NULL) { if (m->buf == NULL) {
LOG_FATAL("mem_ensure realloc failed, off=%d, size=%d", m->off, size); LOG_FATAL("mem_ensure realloc failed, off=%d, size=%d", m->off, size);
} }
m->cap = m->off+size; m->cap = cap;
return m; return m;
} }
@ -108,11 +117,7 @@ uint8_t *mem_write(JNIEnv *env, jobject obj, uint32_t size, uint32_t alignment)
LOG_FATAL("write can only append to seq, size: (off=%d, len=%d, size=%d", m->off, m->len, size); LOG_FATAL("write can only append to seq, size: (off=%d, len=%d, size=%d", m->off, m->len, size);
} }
uint32_t offset = align(m->off, alignment); uint32_t offset = align(m->off, alignment);
uint32_t cap = m->cap; m = mem_ensure(m, offset - m->off + size);
while (offset+size > cap) {
cap *= 2;
}
m = mem_ensure(m, cap);
uint8_t *res = m->buf+offset; uint8_t *res = m->buf+offset;
m->off = offset+size; m->off = offset+size;
m->len = offset+size; m->len = offset+size;