misc: Merge branch 'release-staging-v20.0.0.0' into develop
[gem5.git] / src / base / output.cc
1 /*
2 * Copyright (c) 2015 ARM Limited
3 * Copyright (c) 2020 Barkhausen Institut
4 * All rights reserved
5 *
6 * The license below extends only to copyright in the software and shall
7 * not be construed as granting a license to any other intellectual
8 * property including but not limited to intellectual property relating
9 * to a hardware implementation of the functionality of the software
10 * licensed hereunder. You may use the software subject to the license
11 * terms below provided that you ensure that this notice is replicated
12 * unmodified and in its entirety in all distributions of the software,
13 * modified or unmodified, in source code or in binary form.
14 *
15 * Copyright (c) 2013 Andreas Sandberg
16 * Copyright (c) 2005 The Regents of The University of Michigan
17 * All rights reserved.
18 *
19 * Redistribution and use in source and binary forms, with or without
20 * modification, are permitted provided that the following conditions are
21 * met: redistributions of source code must retain the above copyright
22 * notice, this list of conditions and the following disclaimer;
23 * redistributions in binary form must reproduce the above copyright
24 * notice, this list of conditions and the following disclaimer in the
25 * documentation and/or other materials provided with the distribution;
26 * neither the name of the copyright holders nor the names of its
27 * contributors may be used to endorse or promote products derived from
28 * this software without specific prior written permission.
29 *
30 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
31 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
32 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
33 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
34 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
35 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
36 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
37 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
38 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
39 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
40 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
41 */
42
43 #include "base/output.hh"
44
45 #include <dirent.h>
46 #include <sys/stat.h>
47 #include <sys/types.h>
48 #include <unistd.h>
49 #include <zfstream.h>
50
51 #include <cassert>
52 #include <cerrno>
53 #include <climits>
54 #include <cstdlib>
55 #include <fstream>
56
57 #include "base/logging.hh"
58
59 using namespace std;
60
61 OutputDirectory simout;
62
63
64 OutputStream::OutputStream(const std::string &name, std::ostream *stream)
65 : _name(name), _stream(stream)
66 {
67 }
68
69 OutputStream::~OutputStream()
70 {
71 }
72
73 void
74 OutputStream::relocate(const OutputDirectory &dir)
75 {
76 }
77
78 template<class StreamType>
79 OutputFile<StreamType>::OutputFile(const OutputDirectory &dir,
80 const std::string &name,
81 std::ios_base::openmode mode,
82 bool recreateable)
83 : OutputStream(name, new stream_type_t()),
84 _mode(mode), _recreateable(recreateable),
85 _fstream(static_cast<stream_type_t *>(_stream))
86 {
87 _fstream->open(dir.resolve(_name).c_str(), _mode);
88
89 assert(_fstream->is_open());
90 }
91
92 template<class StreamType>
93 OutputFile<StreamType>::~OutputFile()
94 {
95 if (_fstream->is_open())
96 _fstream->close();
97 }
98
99 template<class StreamType>
100 void
101 OutputFile<StreamType>::relocate(const OutputDirectory &dir)
102 {
103 if (_recreateable) {
104 _fstream->close();
105 _fstream->open(dir.resolve(_name).c_str(), _mode);
106 }
107 }
108
109 OutputStream OutputDirectory::stdout("stdout", &cout);
110 OutputStream OutputDirectory::stderr("stderr", &cerr);
111
112 /**
113 * @file This file manages creating / deleting output files for the simulator.
114 */
115 OutputDirectory::OutputDirectory()
116 {}
117
118 OutputDirectory::OutputDirectory(const std::string &name)
119 {
120 setDirectory(name);
121 }
122
123 OutputDirectory::~OutputDirectory()
124 {
125 for (auto& f: files) {
126 if (f.second)
127 delete f.second;
128 }
129 }
130
131 OutputStream *
132 OutputDirectory::checkForStdio(const string &name)
133 {
134 if (name == "cerr" || name == "stderr")
135 return &stderr;
136
137 if (name == "cout" || name == "stdout")
138 return &stdout;
139
140 return NULL;
141 }
142
143 void
144 OutputDirectory::close(OutputStream *file)
145 {
146 if (file == &stdout || file == &stderr) {
147 file->stream()->flush();
148 return;
149 }
150
151 auto i = files.find(file->name());
152 if (i == files.end())
153 fatal("Attempted to close an unregistred file stream");
154
155 files.erase(i);
156
157 delete file;
158 }
159
160 void
161 OutputDirectory::setDirectory(const string &d)
162 {
163 const string old_dir(dir);
164
165 dir = d;
166
167 // guarantee that directory ends with a path separator
168 if (dir[dir.size() - 1] != PATH_SEPARATOR)
169 dir += PATH_SEPARATOR;
170
171 // Try to create the directory. If it already exists, that's ok;
172 // otherwise, fail if we couldn't create it.
173 if ((mkdir(dir.c_str(), 0755) != 0) && (errno != EEXIST))
174 fatal("Failed to create new output subdirectory '%s'\n", dir);
175
176 // Check if we need to recreate anything
177 if (!old_dir.empty()) {
178 // Recreate output files
179 for (file_map_t::iterator i = files.begin(); i != files.end(); ++i) {
180 i->second->relocate(*this);
181 }
182
183 // Relocate sub-directories
184 for (dir_map_t::iterator i = dirs.begin(); i != dirs.end(); ++i) {
185 i->second->setDirectory(dir + PATH_SEPARATOR + i->first);
186 }
187 }
188
189 }
190
191 const string &
192 OutputDirectory::directory() const
193 {
194 if (dir.empty())
195 panic("Output directory not set!");
196
197 return dir;
198 }
199
200 string
201 OutputDirectory::resolve(const string &name) const
202 {
203 return !isAbsolute(name) ? dir + name : name;
204 }
205
206 OutputStream *
207 OutputDirectory::create(const string &name, bool binary, bool no_gz)
208 {
209 OutputStream *file = checkForStdio(name);
210 if (file)
211 return file;
212
213 const ios_base::openmode mode(
214 ios::trunc | (binary ? ios::binary : (ios::openmode)0));
215 const bool recreateable(!isAbsolute(name));
216
217 return open(name, mode, recreateable, no_gz);
218 }
219
220 OutputStream *
221 OutputDirectory::open(const std::string &name,
222 ios_base::openmode mode,
223 bool recreateable,
224 bool no_gz)
225 {
226 OutputStream *os;
227
228 if (!no_gz && name.find(".gz", name.length() - 3) < name.length()) {
229 // Although we are creating an output stream, we still need to pass the
230 // correct mode for gzofstream as this used directly to set the file
231 // mode.
232 mode |= std::ios::out;
233 os = new OutputFile<gzofstream>(*this, name, mode, recreateable);
234 } else {
235 os = new OutputFile<ofstream>(*this, name, mode, recreateable);
236 }
237
238 files[name] = os;
239
240 return os;
241 }
242
243 OutputStream *
244 OutputDirectory::find(const string &name) const
245 {
246 OutputStream *file = checkForStdio(name);
247 if (file)
248 return file;
249
250 auto i = files.find(name);
251 if (i != files.end())
252 return (*i).second;
253
254 return NULL;
255 }
256
257
258 OutputStream *
259 OutputDirectory::findOrCreate(const std::string &name, bool binary)
260 {
261 OutputStream *os(find(name));
262 if (os)
263 return os;
264 else
265 return create(name, binary);
266 }
267
268 bool
269 OutputDirectory::isFile(const string &name) const
270 {
271 // definitely a file if in our data structure
272 if (find(name) != NULL) return true;
273
274 struct stat st_buf;
275 int st = stat(name.c_str(), &st_buf);
276 return (st == 0) && S_ISREG(st_buf.st_mode);
277 }
278
279 OutputDirectory *
280 OutputDirectory::createSubdirectory(const string &name)
281 {
282 const string new_dir = resolve(name);
283 if (new_dir.find(directory()) == string::npos)
284 fatal("Attempting to create subdirectory not in m5 output dir\n");
285
286 OutputDirectory *dir(new OutputDirectory(new_dir));
287 dirs[name] = dir;
288
289 return dir;
290 }
291
292 void
293 OutputDirectory::remove(const string &name, bool recursive)
294 {
295 const string fname = resolve(name);
296
297 if (fname.find(directory()) == string::npos)
298 fatal("Attempting to remove file/dir not in output dir\n");
299
300 if (isFile(fname)) {
301 // close and release file if we have it open
302 auto i = files.find(fname);
303 if (i != files.end()) {
304 delete i->second;
305 files.erase(i);
306 }
307
308 if (::remove(fname.c_str()) != 0)
309 fatal("Could not erase file '%s'\n", fname);
310 } else {
311 // assume 'name' is a directory
312 if (recursive) {
313 DIR *subdir = opendir(fname.c_str());
314
315 // silently ignore removal request for non-existent directory
316 if ((!subdir) && (errno == ENOENT))
317 return;
318
319 // fail on other errors
320 if (!subdir) {
321 perror("opendir");
322 fatal("Error opening directory for recursive removal '%s'\n",
323 fname);
324 }
325
326 struct dirent *de = readdir(subdir);
327 while (de != NULL) {
328 // ignore files starting with a '.'; user must delete those
329 // manually if they really want to
330 if (de->d_name[0] != '.')
331 remove(name + PATH_SEPARATOR + de->d_name, recursive);
332
333 de = readdir(subdir);
334 }
335
336 closedir(subdir);
337 }
338
339 // try to force recognition that we deleted the files in the directory
340 sync();
341
342 if (::remove(fname.c_str()) != 0) {
343 perror("Warning! 'remove' failed. Could not erase directory.");
344 }
345 }
346 }