Browse Source

Fix panic in fwrite

lmiskiew 6 years ago
parent
commit
5b6b11cb65

+ 5 - 2
src/header/stdio/mod.rs

@@ -562,11 +562,14 @@ pub unsafe extern "C" fn funlockfile(file: *mut FILE) {
 pub unsafe extern "C" fn fwrite(
     ptr: *const c_void,
     size: size_t,
-    count: size_t,
+    nitems: size_t,
     stream: *mut FILE,
 ) -> size_t {
+    if size == 0 || nitems == 0 {
+        return 0
+    }
     let mut stream = (*stream).lock();
-    let buf = slice::from_raw_parts_mut(ptr as *mut u8, size as usize * count as usize);
+    let buf = slice::from_raw_parts_mut(ptr as *mut u8, size as usize * nitems as usize);
     let mut written = 0;
     while written < buf.len() {
         match stream.write(&mut buf[written..]) {

+ 1 - 0
tests/Makefile

@@ -23,6 +23,7 @@ EXPECT_BINS=\
 	stdio/all \
 	stdio/buffer \
 	stdio/fgets \
+	stdio/fputs \
 	stdio/fread \
 	stdio/freopen \
 	stdio/fseek \

+ 0 - 0
tests/expected/stdio/fputs.stderr


+ 0 - 0
tests/expected/stdio/fputs.stdout


+ 11 - 0
tests/stdio/fputs.c

@@ -0,0 +1,11 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <errno.h>
+
+int main(int argc, char ** argv) {
+	FILE *f = fopen("stdio/fputs.out", "w");
+	char *in = "Hello World!";
+	fputs(in, f); // calls fwrite, helpers::fwritex, internal::to_write and internal::stdio_write
+	fclose(f);
+	return 0;
+}

+ 1 - 0
tests/stdio/fputs.out

@@ -0,0 +1 @@
+Hello World!

+ 15 - 2
tests/stdio/fwrite.c

@@ -4,8 +4,21 @@
 
 int main(int argc, char ** argv) {
 	FILE *f = fopen("stdio/fwrite.out", "w");
-	char *in = "Hello World!";
-	fputs(in, f); // calls fwrite, helpers::fwritex, internal::to_write and internal::stdio_write
+	const char ptr[] = "Hello World!";
+
+	if (fwrite(ptr, 0, 17, f)) {
+		return -1;
+	}
+
+	if (fwrite(ptr, 7, 0, f)) {
+		return -1;
+	}
+
+	if (fwrite(ptr, 0, 0, f)) {
+		return -1;
+	}
+
+	fwrite(ptr, sizeof(ptr), 1, f);
 	fclose(f);
 	return 0;
 }

BIN
tests/stdio/fwrite.out