about summary refs log tree commit diff stats
path: root/adapter/protocol
diff options
context:
space:
mode:
authorbptato <nincsnevem662@gmail.com>2024-08-26 22:35:34 +0200
committerbptato <nincsnevem662@gmail.com>2024-08-26 22:37:38 +0200
commit494c0cc92d84162b68aa7f3c79a99b2262eadc6f (patch)
tree8793b60a98f3061603745b8e760599719ffd4811 /adapter/protocol
parent672d18b026cca0c910f55e552fdc0a735871c790 (diff)
downloadchawan-494c0cc92d84162b68aa7f3c79a99b2262eadc6f.tar.gz
stbi, jebp: use read/write instead of fread/fwrite
glibc likes to do weird things (such as calling stat) when you use
fread(3) and friends, so try to use functions that are more likely to
just do a single syscall.

Also, copy over some more paranoid read/write procedures to http.
Diffstat (limited to 'adapter/protocol')
-rw-r--r--adapter/protocol/http.nim18
1 files changed, 15 insertions, 3 deletions
diff --git a/adapter/protocol/http.nim b/adapter/protocol/http.nim
index d00479e4..69542288 100644
--- a/adapter/protocol/http.nim
+++ b/adapter/protocol/http.nim
@@ -23,8 +23,20 @@ type
     earlyhint: EarlyHintState
     slist: curl_slist
 
+const STDIN_FILENO = 0
+const STDOUT_FILENO = 1
+
+proc writeAll(data: pointer; size: int) =
+  var n = 0
+  while n < size:
+    let i = write(STDOUT_FILENO, addr cast[ptr UncheckedArray[uint8]](data)[n],
+      int(size) - n)
+    assert i >= 0
+    n += i
+
 proc puts(s: string) =
-  discard write(1, unsafeAddr s[0], s.len)
+  if s.len > 0:
+    writeAll(unsafeAddr s[0], s.len)
 
 proc curlWriteHeader(p: cstring; size, nitems: csize_t; userdata: pointer):
     csize_t {.cdecl.} =
@@ -63,12 +75,12 @@ proc curlWriteHeader(p: cstring; size, nitems: csize_t; userdata: pointer):
 # From the documentation: size is always 1.
 proc curlWriteBody(p: cstring; size, nmemb: csize_t; userdata: pointer):
     csize_t {.cdecl.} =
-  return csize_t(write(stdout.getFileHandle(), p, int(nmemb)))
+  return csize_t(write(STDOUT_FILENO, p, int(nmemb)))
 
 # From the documentation: size is always 1.
 proc readFromStdin(p: pointer; size, nitems: csize_t; userdata: pointer):
     csize_t {.cdecl.} =
-  return csize_t(read(0, p, int(nitems)))
+  return csize_t(read(STDIN_FILENO, p, int(nitems)))
 
 proc curlPreRequest(clientp: pointer; conn_primary_ip, conn_local_ip: cstring;
     conn_primary_port, conn_local_port: cint): cint {.cdecl.} =