output.cc revision 11259:4006183015a1
1/*
2 * Copyright (c) 2005 The Regents of The University of Michigan
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
7 * met: redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer;
9 * redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution;
12 * neither the name of the copyright holders nor the names of its
13 * contributors may be used to endorse or promote products derived from
14 * this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 *
28 * Authors: Nathan Binkert
29 *          Chris Emmons
30 */
31
32#include <sys/stat.h>
33#include <sys/types.h>
34#include <dirent.h>
35#include <unistd.h>
36
37#include <cassert>
38#include <cerrno>
39#include <climits>
40#include <cstdlib>
41#include <fstream>
42
43#include <gzstream.hh>
44
45#include "base/misc.hh"
46#include "base/output.hh"
47
48using namespace std;
49
50OutputDirectory simout;
51
52/**
53 * @file This file manages creating / deleting output files for the simulator.
54 */
55OutputDirectory::OutputDirectory()
56{}
57
58OutputDirectory::~OutputDirectory()
59{
60    for (map_t::iterator i = files.begin(); i != files.end(); i++) {
61        if (i->second)
62            delete i->second;
63    }
64}
65
66std::ostream *
67OutputDirectory::checkForStdio(const string &name) const
68{
69    if (name == "cerr" || name == "stderr")
70        return &cerr;
71
72    if (name == "cout" || name == "stdout")
73        return &cout;
74
75    return NULL;
76}
77
78ostream *
79OutputDirectory::openFile(const string &filename,
80                          ios_base::openmode mode, bool no_gz)
81{
82    bool gz = !no_gz;
83    gz = gz && filename.find(".gz", filename.length()-3) < filename.length();
84    if (gz) {
85        ogzstream *file = new ogzstream(filename.c_str(), mode);
86        if (!file->is_open())
87            fatal("Cannot open file %s", filename);
88        assert(files.find(filename) == files.end());
89        files[filename] = file;
90        return file;
91    } else {
92        ofstream *file = new ofstream(filename.c_str(), mode);
93        if (!file->is_open())
94            fatal("Cannot open file %s", filename);
95        assert(files.find(filename) == files.end());
96        files[filename] = file;
97        return file;
98    }
99}
100
101void
102OutputDirectory::close(ostream *openStream) {
103    map_t::iterator i;
104    for (i = files.begin(); i != files.end(); i++) {
105        if (i->second != openStream)
106            continue;
107
108        ofstream *fs = dynamic_cast<ofstream*>(i->second);
109        if (fs) {
110            fs->close();
111            delete i->second;
112            break;
113        } else {
114            ogzstream *gfs = dynamic_cast<ogzstream*>(i->second);
115            if (gfs) {
116                gfs->close();
117                delete i->second;
118                break;
119            }
120        }
121    }
122
123    if (i == files.end())
124        fatal("Attempted to close an unregistred file stream");
125
126    files.erase(i);
127}
128
129void
130OutputDirectory::setDirectory(const string &d)
131{
132    if (!dir.empty())
133        panic("Output directory already set!\n");
134
135    dir = d;
136
137    // guarantee that directory ends with a path separator
138    if (dir[dir.size() - 1] != PATH_SEPARATOR)
139        dir += PATH_SEPARATOR;
140}
141
142const string &
143OutputDirectory::directory() const
144{
145    if (dir.empty())
146        panic("Output directory not set!");
147
148    return dir;
149}
150
151string
152OutputDirectory::resolve(const string &name) const
153{
154    return (name[0] != PATH_SEPARATOR) ? dir + name : name;
155}
156
157ostream *
158OutputDirectory::create(const string &name, bool binary, bool no_gz)
159{
160    ostream *file = checkForStdio(name);
161    if (file)
162        return file;
163
164    string filename = resolve(name);
165    ios_base::openmode mode =
166        ios::trunc | (binary ? ios::binary : (ios::openmode)0);
167    file = openFile(filename, mode, no_gz);
168
169    return file;
170}
171
172ostream *
173OutputDirectory::find(const string &name) const
174{
175    ostream *file = checkForStdio(name);
176    if (file)
177        return file;
178
179    const string filename = resolve(name);
180    map_t::const_iterator i = files.find(filename);
181    if (i != files.end())
182        return (*i).second;
183
184    return NULL;
185}
186
187bool
188OutputDirectory::isFile(const std::ostream *os)
189{
190    return os && os != &cerr && os != &cout;
191}
192
193bool
194OutputDirectory::isFile(const string &name) const
195{
196    // definitely a file if in our data structure
197    if (find(name) != NULL) return true;
198
199    struct stat st_buf;
200    int st = stat(name.c_str(), &st_buf);
201    return (st == 0) && S_ISREG(st_buf.st_mode);
202}
203
204string
205OutputDirectory::createSubdirectory(const string &name) const
206{
207    const string new_dir = resolve(name);
208    if (new_dir.find(directory()) == string::npos)
209        fatal("Attempting to create subdirectory not in m5 output dir\n");
210
211    // if it already exists, that's ok; otherwise, fail if we couldn't create
212    if ((mkdir(new_dir.c_str(), 0755) != 0) && (errno != EEXIST))
213        fatal("Failed to create new output subdirectory '%s'\n", new_dir);
214
215    return name + PATH_SEPARATOR;
216}
217
218void
219OutputDirectory::remove(const string &name, bool recursive)
220{
221    const string fname = resolve(name);
222
223    if (fname.find(directory()) == string::npos)
224        fatal("Attempting to remove file/dir not in output dir\n");
225
226    if (isFile(fname)) {
227        // close and release file if we have it open
228        map_t::iterator itr = files.find(fname);
229        if (itr != files.end()) {
230            delete itr->second;
231            files.erase(itr);
232        }
233
234        if (::remove(fname.c_str()) != 0)
235            fatal("Could not erase file '%s'\n", fname);
236    } else {
237        // assume 'name' is a directory
238        if (recursive) {
239            DIR *subdir = opendir(fname.c_str());
240
241            // silently ignore removal request for non-existent directory
242            if ((!subdir) && (errno == ENOENT))
243                return;
244
245            // fail on other errors
246            if (!subdir) {
247                perror("opendir");
248                fatal("Error opening directory for recursive removal '%s'\n",
249                    fname);
250            }
251
252            struct dirent *de = readdir(subdir);
253            while (de != NULL) {
254                // ignore files starting with a '.'; user must delete those
255                //   manually if they really want to
256                if (de->d_name[0] != '.')
257                    remove(name + PATH_SEPARATOR + de->d_name, recursive);
258
259                de = readdir(subdir);
260            }
261
262            closedir(subdir);
263        }
264
265        // try to force recognition that we deleted the files in the directory
266        sync();
267
268        if (::remove(fname.c_str()) != 0) {
269            perror("Warning!  'remove' failed.  Could not erase directory.");
270        }
271    }
272}
273