1/*
2 * Copyright 2012, 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#include "bcc/Support/OutputFile.h"
18
19#include <cstdlib>
20
21#include <llvm/Support/raw_ostream.h>
22
23#include "bcc/Support/Log.h"
24
25using namespace bcc;
26
27OutputFile::OutputFile(const std::string &pFilename, unsigned pFlags)
28  : super(pFilename, pFlags) { }
29
30ssize_t OutputFile::write(const void *pBuf, size_t count) {
31  if ((mFD < 0) || hasError()) {
32    return -1;
33  }
34
35  if ((count <= 0) || (pBuf == NULL)) {
36    // Keep safe and issue a warning.
37    ALOGW("OutputFile::write: count = %zu, buffer = %p", count, pBuf);
38    return 0;
39  }
40
41  while (count > 0) {
42    ssize_t write_size = ::write(mFD, pBuf, count);
43
44    if (write_size > 0) {
45      return write_size;
46    } else if ((errno == EAGAIN) || (errno == EINTR)) {
47      // If the errno is EAGAIN or EINTR, then we try to write again.
48      //
49      // Fall-through
50    } else {
51      detectError();
52      return -1;
53    }
54  }
55  // unreachable
56  return 0;
57}
58
59void OutputFile::truncate() {
60  if (mFD < 0) {
61    return;
62  }
63
64  do {
65    if (::ftruncate(mFD, 0) == 0) {
66      return;
67    }
68  } while (errno == EINTR);
69  detectError();
70
71  return;
72}
73
74llvm::raw_fd_ostream *OutputFile::dup() {
75  int newfd;
76
77  do {
78    newfd = ::dup(mFD);
79    if (newfd < 0) {
80      if (errno != EINTR) {
81        detectError();
82        return NULL;
83      }
84      // EINTR
85      continue;
86    }
87    // dup() returns ok.
88    break;
89  } while (true);
90
91  llvm::raw_fd_ostream *result =
92      new (std::nothrow) llvm::raw_fd_ostream(newfd, /* shouldClose */true);
93
94  if (result == NULL) {
95    mError = std::make_error_code(std::errc::not_enough_memory);
96  }
97
98  return result;
99}
100