mailing list of musl libc
 help / color / mirror / code / Atom feed
* fwrite() - possible division by zero
@ 2018-02-14 18:24 Geraldo Netto
  2018-02-14 19:39 ` Markus Wichmann
  0 siblings, 1 reply; 9+ messages in thread
From: Geraldo Netto @ 2018-02-14 18:24 UTC (permalink / raw)
  To: musl

[-- Attachment #1: Type: text/plain, Size: 805 bytes --]

Dear Friends,

I was playing with musl and I think I may have found an issue on fwrite():

This is the original code:

size_t fwrite(const void *restrict src, size_t size, size_t nmemb,
FILE *restrict f)
{
    size_t k, l = size*nmemb;
    if (!size) nmemb = 0;
    FLOCK(f);
    k = __fwritex(src, l, f);
    FUNLOCK(f);
    return k==l ? nmemb : k/size;
}


It seems we need to check the variable size on return because if size is zero
We'll have a division by zero and a segmentation fault

I'm sending the attached patch that changes the return as follows:

return k==l ? nmemb : (size != 0) ? k/size : k;


I don't know if this is the correct approach, so, feel free to
change/let me know how to fix :)
Hope it helps


Kind Regards,

Geraldo Netto
Sapere Aude => Non dvcor, dvco
http://exdev.sf.net/

[-- Attachment #2: 0001-fwrite-avoid-segmentation-fault-when-size-0.patch --]
[-- Type: application/octet-stream, Size: 774 bytes --]

From b1679c6aa916eafe0a490a246b3e6889ce98ac72 Mon Sep 17 00:00:00 2001
From: geraldo netto <geraldonetto@gmail.com>
Date: Wed, 14 Feb 2018 16:19:46 -0200
Subject: [PATCH] fwrite: avoid segmentation fault when size = 0

Signed-off-by: geraldo netto <geraldonetto@gmail.com>
---
 src/stdio/fwrite.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/stdio/fwrite.c b/src/stdio/fwrite.c
index 7a567b2..16d2041 100644
--- a/src/stdio/fwrite.c
+++ b/src/stdio/fwrite.c
@@ -32,7 +32,7 @@ size_t fwrite(const void *restrict src, size_t size, size_t nmemb, FILE *restric
 	FLOCK(f);
 	k = __fwritex(src, l, f);
 	FUNLOCK(f);
-	return k==l ? nmemb : k/size;
+	return k==l ? nmemb : (size != 0) ? k/size : k;
 }
 
 weak_alias(fwrite, fwrite_unlocked);
-- 
2.7.4


^ permalink raw reply	[flat|nested] 9+ messages in thread

end of thread, other threads:[~2018-02-16  2:58 UTC | newest]

Thread overview: 9+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2018-02-14 18:24 fwrite() - possible division by zero Geraldo Netto
2018-02-14 19:39 ` Markus Wichmann
2018-02-14 19:48   ` Andrew Bell
2018-02-14 20:07     ` Markus Wichmann
2018-02-14 20:11       ` Andrew Bell
2018-02-14 21:15         ` Szabolcs Nagy
2018-02-14 21:47           ` Andrew Bell
2018-02-15  4:20             ` Rich Felker
2018-02-16  2:58               ` Geraldo Netto

Code repositories for project(s) associated with this public inbox

	https://git.vuxu.org/mirror/musl/

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).