Skip to content

Commit 26c9363

Browse files
committed
Ensuring string values are zero-terminated.
This helps when some code requires a string value to be zero-terminated to avoid copying and adding \0 byte. It adds small overhead (less than 3% in worst case of an empty string value) to existing sizeof(njs_value_t) + sizeof(njs_string_t) = 32.
1 parent e981736 commit 26c9363

File tree

3 files changed

+8
-2
lines changed

3 files changed

+8
-2
lines changed

src/njs_scope.c

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -199,7 +199,7 @@ njs_scope_value_index(njs_vm_t *vm, const njs_value_t *src, njs_uint_t runtime,
199199
+ njs_string_map_size(length);
200200
}
201201

202-
value_size += sizeof(njs_string_t) + size;
202+
value_size += sizeof(njs_string_t) + size + 1;
203203
}
204204

205205
value_size += sizeof(njs_index_t);
@@ -221,6 +221,8 @@ njs_scope_value_index(njs_vm_t *vm, const njs_value_t *src, njs_uint_t runtime,
221221
string->length = src->string.data->length;
222222
string->size = src->string.data->size;
223223

224+
string->start[size] = '\0';
225+
224226
memcpy(string->start, start, size);
225227
}
226228

src/njs_string.c

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,7 @@ njs_string_new(njs_vm_t *vm, njs_value_t *value, const u_char *start,
147147
}
148148

149149

150+
/* Underlying string data is zero-terminated. */
150151
u_char *
151152
njs_string_alloc(njs_vm_t *vm, njs_value_t *value, uint64_t size,
152153
uint64_t length)
@@ -172,7 +173,7 @@ njs_string_alloc(njs_vm_t *vm, njs_value_t *value, uint64_t size,
172173
total = size;
173174
}
174175

175-
string = njs_mp_alloc(vm->mem_pool, sizeof(njs_string_t) + total);
176+
string = njs_mp_alloc(vm->mem_pool, sizeof(njs_string_t) + total + 1);
176177

177178
if (njs_fast_path(string != NULL)) {
178179
value->string.data = string;
@@ -181,6 +182,8 @@ njs_string_alloc(njs_vm_t *vm, njs_value_t *value, uint64_t size,
181182
string->size = size;
182183
string->length = length;
183184

185+
string->start[size] = '\0';
186+
184187
if (map_offset != 0) {
185188
map = (uint32_t *) (string->start + map_offset);
186189
map[0] = 0;

src/njs_value.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -517,6 +517,7 @@ typedef struct {
517517
njs_assert((value)->string.data != NULL); \
518518
(str)->length = (value)->string.data->size; \
519519
(str)->start = (u_char *) (value)->string.data->start; \
520+
njs_assert((str)->start[(str)->length] == '\0'); \
520521
} while (0)
521522

522523

0 commit comments

Comments
 (0)