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