Fix get_magic() handling of short reads.
[oota-llvm.git] / lib / Support / DataStream.cpp
index fa8edc729c95c2384478f0d0f03e442ae8dd6cfc..7815d08092e0e0448e9a03045aec354c342464d7 100644 (file)
@@ -1,4 +1,4 @@
-//===--- llvm/Support/DataStream.cpp - Lazy streamed Data               ---===//
+//===--- llvm/Support/DataStream.cpp - Lazy streamed data -----------------===//
 //
 //                     The LLVM Compiler Infrastructure
 //
 //===----------------------------------------------------------------------===//
 
 #define DEBUG_TYPE "Data-stream"
-#include "llvm/ADT/Statistic.h"
 #include "llvm/Support/DataStream.h"
+#include "llvm/ADT/Statistic.h"
+#include "llvm/Support/Program.h"
 #include "llvm/Support/system_error.h"
-#include <string>
 #include <cerrno>
 #include <cstdio>
+#include <string>
 #if !defined(_MSC_VER) && !defined(__MINGW32__)
 #include <unistd.h>
 #else
@@ -48,8 +49,6 @@ DataStreamer::~DataStreamer() {}
 
 namespace {
 
-const static error_code success;
-
 // Very simple stream backed by a file. Mostly useful for stdin and debugging;
 // actual file access is probably still best done with mmap.
 class DataFileStreamer : public DataStreamer {
@@ -59,22 +58,26 @@ public:
   virtual ~DataFileStreamer() {
     close(Fd);
   }
-  virtual size_t GetBytes(unsigned char *buf, size_t len) {
+  virtual size_t GetBytes(unsigned char *buf, size_t len) LLVM_OVERRIDE {
     NumStreamFetches++;
     return read(Fd, buf, len);
   }
 
   error_code OpenFile(const std::string &Filename) {
+    if (Filename == "-") {
+      Fd = 0;
+      sys::ChangeStdinToBinary();
+      return error_code::success();
+    }
+  
     int OpenFlags = O_RDONLY;
 #ifdef O_BINARY
     OpenFlags |= O_BINARY;  // Open input file in binary mode on win32.
 #endif
-    if (Filename == "-")
-      Fd = 0;
-    else
-      Fd = ::open(Filename.c_str(), OpenFlags);
-    if (Fd == -1) return error_code(errno, posix_category());
-      return success;
+    Fd = ::open(Filename.c_str(), OpenFlags);
+    if (Fd == -1)
+      return error_code(errno, posix_category());
+    return error_code::success();
   }
 };
 
@@ -84,8 +87,7 @@ namespace llvm {
 DataStreamer *getDataFileStreamer(const std::string &Filename,
                                   std::string *StrError) {
   DataFileStreamer *s = new DataFileStreamer();
-  error_code e = s->OpenFile(Filename);
-  if (e != success) {
+  if (error_code e = s->OpenFile(Filename)) {
     *StrError = std::string("Could not open ") + Filename + ": " +
         e.message() + "\n";
     return NULL;