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 #include "android-base/test_utils.h"
18 
19 #include <fcntl.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <sys/stat.h>
23 #include <unistd.h>
24 
25 #include <string>
26 
27 #include <android-base/file.h>
28 #include <android-base/logging.h>
29 
CapturedStdFd(int std_fd)30 CapturedStdFd::CapturedStdFd(int std_fd) : std_fd_(std_fd), old_fd_(-1) {
31   Start();
32 }
33 
~CapturedStdFd()34 CapturedStdFd::~CapturedStdFd() {
35   if (old_fd_ != -1) {
36     Stop();
37   }
38 }
39 
fd() const40 int CapturedStdFd::fd() const {
41   return temp_file_.fd;
42 }
43 
str()44 std::string CapturedStdFd::str() {
45   std::string result;
46   CHECK_EQ(0, TEMP_FAILURE_RETRY(lseek(fd(), 0, SEEK_SET)));
47   android::base::ReadFdToString(fd(), &result);
48   return result;
49 }
50 
Reset()51 void CapturedStdFd::Reset() {
52   // Do not reset while capturing.
53   CHECK_EQ(-1, old_fd_);
54   CHECK_EQ(0, TEMP_FAILURE_RETRY(lseek(fd(), 0, SEEK_SET)));
55   CHECK_EQ(0, ftruncate(fd(), 0));
56 }
57 
Start()58 void CapturedStdFd::Start() {
59 #if defined(_WIN32)
60   // On Windows, stderr is often buffered, so make sure it is unbuffered so
61   // that we can immediately read back what was written to stderr.
62   if (std_fd_ == STDERR_FILENO) CHECK_EQ(0, setvbuf(stderr, nullptr, _IONBF, 0));
63 #endif
64   old_fd_ = dup(std_fd_);
65   CHECK_NE(-1, old_fd_);
66   CHECK_NE(-1, dup2(fd(), std_fd_));
67 }
68 
Stop()69 void CapturedStdFd::Stop() {
70   CHECK_NE(-1, old_fd_);
71   CHECK_NE(-1, dup2(old_fd_, std_fd_));
72   close(old_fd_);
73   old_fd_ = -1;
74   // Note: cannot restore prior setvbuf() setting.
75 }
76