Home | History | Annotate | Download | only in libmemunreachable
      1 /*
      2  * Copyright (C) 2015 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 // Copied from system/extras/memory_replay/LineBuffer.cpp
     18 // TODO(ccross): find a way to share between libmemunreachable and memory_replay?
     19 
     20 #include <errno.h>
     21 #include <string.h>
     22 #include <unistd.h>
     23 
     24 #include "LineBuffer.h"
     25 
     26 LineBuffer::LineBuffer(int fd, char* buffer, size_t buffer_len) : fd_(fd), buffer_(buffer), buffer_len_(buffer_len) {
     27 }
     28 
     29 bool LineBuffer::GetLine(char** line, size_t* line_len) {
     30   while (true) {
     31     if (bytes_ > 0) {
     32       char* newline = reinterpret_cast<char*>(memchr(buffer_ + start_, '\n', bytes_));
     33       if (newline != nullptr) {
     34         *newline = '\0';
     35         *line = buffer_ + start_;
     36         start_ = newline - buffer_ + 1;
     37         bytes_ -= newline - *line + 1;
     38         *line_len = newline - *line;
     39         return true;
     40       }
     41     }
     42     if (start_ > 0) {
     43       // Didn't find anything, copy the current to the front of the buffer.
     44       memmove(buffer_, buffer_ + start_, bytes_);
     45       start_ = 0;
     46     }
     47     ssize_t bytes = TEMP_FAILURE_RETRY(read(fd_, buffer_ + bytes_, buffer_len_ - bytes_ - 1));
     48     if (bytes <= 0) {
     49       if (bytes_ > 0) {
     50         // The read data might not contain a nul terminator, so add one.
     51         buffer_[bytes_] = '\0';
     52         *line = buffer_ + start_;
     53         *line_len = bytes_;
     54         bytes_ = 0;
     55         start_ = 0;
     56         return true;
     57       }
     58       return false;
     59     }
     60     bytes_ += bytes;
     61   }
     62 }
     63