misc: Changed gem5 version info for gem5 20.2 dev
[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 std::string resolved_path = dir.resolve(_name);
88
89 _fstream->open(resolved_path.c_str(), _mode);
90
91 panic_if(!_fstream->is_open(), "Failed to open \"%s\"\n", resolved_path);
92 }
93
94 template<class StreamType>
95 OutputFile<StreamType>::~OutputFile()
96 {
97 if (_fstream->is_open())
98 _fstream->close();
99 }
100
101 template<class StreamType>
102 void
103 OutputFile<StreamType>::relocate(const OutputDirectory &dir)
104 {
105 if (_recreateable) {
106 _fstream->close();
107 _fstream->open(dir.resolve(_name).c_str(), _mode);
108 }
109 }
110
111 OutputStream OutputDirectory::stdout("stdout", &cout);
112 OutputStream OutputDirectory::stderr("stderr", &cerr);
113
114 /**
115 * @file This file manages creating / deleting output files for the simulator.
116 */
117 OutputDirectory::OutputDirectory()
118 {}
119
120 OutputDirectory::OutputDirectory(const std::string &name)
121 {
122 setDirectory(name);
123 }
124
125 OutputDirectory::~OutputDirectory()
126 {
127 for (auto& f: files) {
128 if (f.second)
129 delete f.second;
130 }
131 }
132
133 OutputStream *
134 OutputDirectory::checkForStdio(const string &name)
135 {
136 if (name == "cerr" || name == "stderr")
137 return &stderr;
138
139 if (name == "cout" || name == "stdout")
140 return &stdout;
141
142 return NULL;
143 }
144
145 void
146 OutputDirectory::close(OutputStream *file)
147 {
148 if (file == &stdout || file == &stderr) {
149 file->stream()->flush();
150 return;
151 }
152
153 auto i = files.find(file->name());
154 if (i == files.end())
155 fatal("Attempted to close an unregistred file stream");
156
157 files.erase(i);
158
159 delete file;
160 }
161
162 void
163 OutputDirectory::setDirectory(const string &d)
164 {
165 const string old_dir(dir);
166
167 dir = d;
168
169 // guarantee that directory ends with a path separator
170 if (dir[dir.size() - 1] != PATH_SEPARATOR)
171 dir += PATH_SEPARATOR;
172
173 // Try to create the directory. If it already exists, that's ok;
174 // otherwise, fail if we couldn't create it.
175 if ((mkdir(dir.c_str(), 0755) != 0) && (errno != EEXIST))
176 fatal("Failed to create new output subdirectory '%s'\n", dir);
177
178 // Check if we need to recreate anything
179 if (!old_dir.empty()) {
180 // Recreate output files
181 for (file_map_t::iterator i = files.begin(); i != files.end(); ++i) {
182 i->second->relocate(*this);
183 }
184
185 // Relocate sub-directories
186 for (dir_map_t::iterator i = dirs.begin(); i != dirs.end(); ++i) {
187 i->second->setDirectory(dir + PATH_SEPARATOR + i->first);
188 }
189 }
190
191 }
192
193 const string &
194 OutputDirectory::directory() const
195 {
196 if (dir.empty())
197 panic("Output directory not set!");
198
199 return dir;
200 }
201
202 string
203 OutputDirectory::resolve(const string &name) const
204 {
205 return !isAbsolute(name) ? dir + name : name;
206 }
207
208 OutputStream *
209 OutputDirectory::create(const string &name, bool binary, bool no_gz)
210 {
211 OutputStream *file = checkForStdio(name);
212 if (file)
213 return file;
214
215 const ios_base::openmode mode(
216 ios::trunc | (binary ? ios::binary : (ios::openmode)0));
217 const bool recreateable(!isAbsolute(name));
218
219 return open(name, mode, recreateable, no_gz);
220 }
221
222 OutputStream *
223 OutputDirectory::open(const std::string &name,
224 ios_base::openmode mode,
225 bool recreateable,
226 bool no_gz)
227 {
228 OutputStream *os;
229
230 if (!no_gz && name.find(".gz", name.length() - 3) < name.length()) {
231 // Although we are creating an output stream, we still need to pass the
232 // correct mode for gzofstream as this used directly to set the file
233 // mode.
234 mode |= std::ios::out;
235 os = new OutputFile<gzofstream>(*this, name, mode, recreateable);
236 } else {
237 os = new OutputFile<ofstream>(*this, name, mode, recreateable);
238 }
239
240 files[name] = os;
241
242 return os;
243 }
244
245 OutputStream *
246 OutputDirectory::find(const string &name) const
247 {
248 OutputStream *file = checkForStdio(name);
249 if (file)
250 return file;
251
252 auto i = files.find(name);
253 if (i != files.end())
254 return (*i).second;
255
256 return NULL;
257 }
258
259
260 OutputStream *
261 OutputDirectory::findOrCreate(const std::string &name, bool binary)
262 {
263 OutputStream *os(find(name));
264 if (os)
265 return os;
266 else
267 return create(name, binary);
268 }
269
270 bool
271 OutputDirectory::isFile(const string &name) const
272 {
273 // definitely a file if in our data structure
274 if (find(name) != NULL) return true;
275
276 struct stat st_buf;
277 int st = stat(name.c_str(), &st_buf);
278 return (st == 0) && S_ISREG(st_buf.st_mode);
279 }
280
281 OutputDirectory *
282 OutputDirectory::createSubdirectory(const string &name)
283 {
284 const string new_dir = resolve(name);
285 if (new_dir.find(directory()) == string::npos)
286 fatal("Attempting to create subdirectory not in m5 output dir\n");
287
288 OutputDirectory *dir(new OutputDirectory(new_dir));
289 dirs[name] = dir;
290
291 return dir;
292 }
293
294 void
295 OutputDirectory::remove(const string &name, bool recursive)
296 {
297 const string fname = resolve(name);
298
299 if (fname.find(directory()) == string::npos)
300 fatal("Attempting to remove file/dir not in output dir\n");
301
302 if (isFile(fname)) {
303 // close and release file if we have it open
304 auto i = files.find(fname);
305 if (i != files.end()) {
306 delete i->second;
307 files.erase(i);
308 }
309
310 if (::remove(fname.c_str()) != 0)
311 fatal("Could not erase file '%s'\n", fname);
312 } else {
313 // assume 'name' is a directory
314 if (recursive) {
315 DIR *subdir = opendir(fname.c_str());
316
317 // silently ignore removal request for non-existent directory
318 if ((!subdir) && (errno == ENOENT))
319 return;
320
321 // fail on other errors
322 if (!subdir) {
323 perror("opendir");
324 fatal("Error opening directory for recursive removal '%s'\n",
325 fname);
326 }
327
328 struct dirent *de = readdir(subdir);
329 while (de != NULL) {
330 // ignore files starting with a '.'; user must delete those
331 // manually if they really want to
332 if (de->d_name[0] != '.')
333 remove(name + PATH_SEPARATOR + de->d_name, recursive);
334
335 de = readdir(subdir);
336 }
337
338 closedir(subdir);
339 }
340
341 // try to force recognition that we deleted the files in the directory
342 sync();
343
344 if (::remove(fname.c_str()) != 0) {
345 perror("Warning! 'remove' failed. Could not erase directory.");
346 }
347 }
348 }