From cc0d1ec0760237fd8f67c10c5922b5e31064f753 Mon Sep 17 00:00:00 2001
From: Justine Tunney <jtunney@gmail.com>
Date: Wed, 27 Apr 2022 20:18:34 -0700
Subject: [PATCH] Fix some bugs

- addr2line backtrace should continue on eintr
- lua crashes if we try to iterate a non-table
---
 libc/log/backtrace2.greg.c        | 12 +++++++++++-
 third_party/linenoise/linenoise.c |  2 +-
 third_party/lua/lrepl.c           | 18 ++++++++++--------
 3 files changed, 22 insertions(+), 10 deletions(-)

diff --git a/libc/log/backtrace2.greg.c b/libc/log/backtrace2.greg.c
index 359a7580a..61f0f8666 100644
--- a/libc/log/backtrace2.greg.c
+++ b/libc/log/backtrace2.greg.c
@@ -116,7 +116,17 @@ static int PrintBacktraceUsingAddr2line(int fd, const struct StackFrame *bp) {
     _exit(127);
   }
   close(pipefds[1]);
-  while ((got = read(pipefds[0], buf, kBacktraceBufSize)) > 0) {
+  for (;;) {
+    got = read(pipefds[0], buf, kBacktraceBufSize);
+    if (!got) break;
+    if (got == -1 && errno == EINTR) {
+      errno = 0;
+      continue;
+    }
+    if (got == -1) {
+      kprintf("error reading backtrace %m\n");
+      break;
+    }
     p1 = buf;
     p3 = p1 + got;
     /*
diff --git a/third_party/linenoise/linenoise.c b/third_party/linenoise/linenoise.c
index 2eac70d57..8c713720d 100644
--- a/third_party/linenoise/linenoise.c
+++ b/third_party/linenoise/linenoise.c
@@ -1834,7 +1834,7 @@ void linenoiseEnd(struct linenoiseState *l) {
 }
 
 static int CompareStrings(const void *a, const void *b) {
-  return strcasecmp(*(const char **)a, *(const char **)b);
+  return strcmp(*(const char **)a, *(const char **)b);
 }
 
 /**
diff --git a/third_party/lua/lrepl.c b/third_party/lua/lrepl.c
index 5bdd29561..5f343f36f 100644
--- a/third_party/lua/lrepl.c
+++ b/third_party/lua/lrepl.c
@@ -140,18 +140,20 @@ void lua_readline_completions (const char *p, linenoiseCompletions *c) {
   }
 
   // search final object
-  lua_pushnil(L);
-  while (lua_next(L, -2)) {
-    if (lua_type(L, -2) == LUA_TSTRING) {
-      name = lua_tostring(L, -2);
-      if (startswithi(name, a)) {
-        lua_readline_addcompletion(c, xasprintf("%.*s%s", a - p, p, name));
+  if (lua_type(L, -1) == LUA_TTABLE) {
+    lua_pushnil(L);
+    while (lua_next(L, -2)) {
+      if (lua_type(L, -2) == LUA_TSTRING) {
+        name = lua_tostring(L, -2);
+        if (startswithi(name, a)) {
+          lua_readline_addcompletion(c, xasprintf("%.*s%s", a - p, p, name));
+        }
       }
+      lua_pop(L, 1);
     }
-    lua_pop(L, 1);
   }
 
-  lua_pop(L, 1);
+  lua_pop(L, 1); // pop table
 
   for (i = 0; i < ARRAYLEN(kKeywordHints); ++i) {
     if (startswithi(kKeywordHints[i], p)) {