@@ -53,12 +53,11 @@ class MemoryMappedSource::Impl {
5353 Status Open (const std::string& path, MemorySource::AccessMode mode) {
5454 if (is_open_) { return Status::IOError (" A file is already open" ); }
5555
56- path_ = path;
57- int prot_flag = PROT_READ;
56+ prot_flags = PROT_READ;
5857
5958 if (mode == MemorySource::READ_WRITE) {
6059 file_ = fopen (path.c_str (), " r+b" );
61- prot_flag |= PROT_WRITE;
60+ prot_flags |= PROT_WRITE;
6261 } else {
6362 file_ = fopen (path.c_str (), " rb" );
6463 }
@@ -75,13 +74,13 @@ class MemoryMappedSource::Impl {
7574 fseek (file_, 0L , SEEK_SET);
7675 is_open_ = true ;
7776
78- data_ = reinterpret_cast <uint8_t *>(
79- mmap (nullptr , size_, prot_flag, MAP_SHARED, fileno (file_), 0 ));
80- if (data_ == nullptr ) {
81- std::stringstream ss;
77+ void * result = mmap (nullptr , size_, prot_flags, MAP_SHARED, fileno (file_), 0 );
78+ if (result == MAP_FAILED) {
79+ std::stringstream ss ;
8280 ss << " Memory mapping file failed, errno: " << errno;
8381 return Status::IOError (ss.str ());
8482 }
83+ data_ = reinterpret_cast <uint8_t *>(result);
8584
8685 return Status::OK ();
8786 }
@@ -90,11 +89,13 @@ class MemoryMappedSource::Impl {
9089
9190 uint8_t * data () { return data_; }
9291
92+ bool writable () { return (prot_flags & PROT_WRITE) == PROT_WRITE; }
93+
9394 private:
94- std::string path_;
9595 FILE* file_;
9696 int64_t size_;
9797 bool is_open_;
98+ uint8_t prot_flags;
9899
99100 // The memory map
100101 uint8_t * data_;
@@ -135,6 +136,9 @@ Status MemoryMappedSource::ReadAt(
135136}
136137
137138Status MemoryMappedSource::Write (int64_t position, const uint8_t * data, int64_t nbytes) {
139+ if (!impl_->writable ()) {
140+ return Status::IOError (" Unable to write" );
141+ }
138142 if (position < 0 || position >= impl_->size ()) {
139143 return Status::Invalid (" position is out of bounds" );
140144 }
0 commit comments