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