浏览代码

hexdump: Improve error handling

In particular, hexdump can now handle read errors and reads that
completely fill up the buffer.
Ben Wiederhake 3 年之前
父节点
当前提交
c706b2c142
共有 1 个文件被更改,包括 10 次插入4 次删除
  1. 10 4
      Userland/Utilities/hexdump.cpp

+ 10 - 4
Userland/Utilities/hexdump.cpp

@@ -62,8 +62,10 @@ int main(int argc, char** argv)
     size_t contents_size = 0;
 
     int nread;
-    do {
+    while (true) {
         nread = file->read(&contents[contents_size], BUFSIZ - contents_size);
+        if (nread <= 0)
+            break;
         contents_size += nread;
         // Print as many complete lines as we can (possibly none).
         size_t offset;
@@ -71,9 +73,13 @@ int main(int argc, char** argv)
             print_line(&contents[offset], LINE_LENGTH_BYTES);
         }
         contents_size -= offset;
-        // Regions cannot overlap due to above static_assert.
-        memcpy(&contents[0], &contents[offset], contents_size);
-    } while (nread);
+        VERIFY(contents_size < LINE_LENGTH_BYTES);
+        // If we managed to make the buffer exactly full, &contents[BUFSIZ] would blow up.
+        if (contents_size > 0) {
+            // Regions cannot overlap due to above static_assert.
+            memcpy(&contents[0], &contents[offset], contents_size);
+        }
+    }
     VERIFY(contents_size <= LINE_LENGTH_BYTES - 1);
     if (contents_size > 0)
         print_line(&contents[0], contents_size);