[LTP] [PATCH v2 15/15] ujson: writer: Flush buffer before direct writes

Andrea Cervesato andrea.cervesato@suse.de
Tue Oct 13 14:02:11 CEST 2026


From: Andrea Cervesato <andrea.cervesato@suse.com>

out_writer_file() writes chunks larger than a quarter of its buffer
directly to the file, bypassing data still sitting in the buffer. Any
string longer than 256 bytes was therefore written before the preceding
output, producing corrupted JSON. Flush the buffer first.

Fixes: c50a0e0751c8 ("libs: Vendor ujson library")
Signed-off-by: Andrea Cervesato <andrea.cervesato@suse.com>
---
 libs/ujson/ujson_writer.c | 12 +++++++++++-
 1 file changed, 11 insertions(+), 1 deletion(-)

diff --git a/libs/ujson/ujson_writer.c b/libs/ujson/ujson_writer.c
index ac21ab442..7874735a1 100644
--- a/libs/ujson/ujson_writer.c
+++ b/libs/ujson/ujson_writer.c
@@ -402,6 +402,9 @@ struct json_writer_file {
 
 static int out_writer_file_write(ujson_writer *self, int fd, const char *buf, ssize_t buf_len)
 {
+	if (!buf_len)
+		return 0;
+
 	do {
 		ssize_t ret = write(fd, buf, buf_len);
 		if (ret < 0) {
@@ -434,8 +437,15 @@ static int out_writer_file(ujson_writer *self, const char *buf, size_t buf_len)
 	size_t buf_size = sizeof(writer_file->buf);
 	size_t buf_avail = buf_size - writer_file->buf_used;
 
-	if (buf_len > buf_size/4)
+	if (buf_len > buf_size / 4) {
+		if (out_writer_file_write(self, writer_file->fd,
+					  writer_file->buf, writer_file->buf_used))
+			return 1;
+
+		writer_file->buf_used = 0;
+
 		return out_writer_file_write(self, writer_file->fd, buf, buf_len);
+	}
 
 	if (buf_len >= buf_avail) {
 		if (out_writer_file_write(self, writer_file->fd,

-- 
2.51.0



More information about the ltp mailing list