serialize.cc revision 1638
1/*
2 * Copyright (c) 2002-2004 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
29#include <sys/time.h>
30#include <sys/types.h>
31#include <sys/stat.h>
32#include <errno.h>
33
34#include <fstream>
35#include <list>
36#include <string>
37#include <vector>
38
39#include "base/inifile.hh"
40#include "base/misc.hh"
41#include "base/output.hh"
42#include "base/str.hh"
43#include "base/trace.hh"
44#include "sim/config_node.hh"
45#include "sim/eventq.hh"
46#include "sim/param.hh"
47#include "sim/serialize.hh"
48#include "sim/sim_events.hh"
49#include "sim/sim_exit.hh"
50#include "sim/sim_object.hh"
51
52using namespace std;
53
54int Serializable::maxCount;
55int Serializable::count;
56
57void
58Serializable::nameOut(ostream &os)
59{
60    os << "\n[" << name() << "]\n";
61}
62
63void
64Serializable::nameOut(ostream &os, const string &_name)
65{
66    os << "\n[" << _name << "]\n";
67}
68
69template <class T>
70void
71paramOut(ostream &os, const std::string &name, const T &param)
72{
73    os << name << "=";
74    showParam(os, param);
75    os << "\n";
76}
77
78
79template <class T>
80void
81paramIn(Checkpoint *cp, const std::string &section,
82        const std::string &name, T &param)
83{
84    std::string str;
85    if (!cp->find(section, name, str) || !parseParam(str, param)) {
86        fatal("Can't unserialize '%s:%s'\n", section, name);
87    }
88}
89
90
91template <class T>
92void
93arrayParamOut(ostream &os, const std::string &name,
94              const T *param, int size)
95{
96    os << name << "=";
97    if (size > 0)
98        showParam(os, param[0]);
99    for (int i = 1; i < size; ++i) {
100        os << " ";
101        showParam(os, param[i]);
102    }
103    os << "\n";
104}
105
106
107template <class T>
108void
109arrayParamIn(Checkpoint *cp, const std::string &section,
110             const std::string &name, T *param, int size)
111{
112    std::string str;
113    if (!cp->find(section, name, str)) {
114        fatal("Can't unserialize '%s:%s'\n", section, name);
115    }
116
117    // code below stolen from VectorParam<T>::parse().
118    // it would be nice to unify these somehow...
119
120    vector<string> tokens;
121
122    tokenize(tokens, str, ' ');
123
124    // Need this if we were doing a vector
125    // value.resize(tokens.size());
126
127    if (tokens.size() != size) {
128        fatal("Array size mismatch on %s:%s'\n", section, name);
129    }
130
131    for (int i = 0; i < tokens.size(); i++) {
132        // need to parse into local variable to handle vector<bool>,
133        // for which operator[] returns a special reference class
134        // that's not the same as 'bool&', (since it's a packed
135        // vector)
136        T scalar_value;
137        if (!parseParam(tokens[i], scalar_value)) {
138            string err("could not parse \"");
139
140            err += str;
141            err += "\"";
142
143            fatal(err);
144        }
145
146        // assign parsed value to vector
147        param[i] = scalar_value;
148    }
149}
150
151
152void
153objParamIn(Checkpoint *cp, const std::string &section,
154           const std::string &name, Serializable * &param)
155{
156    if (!cp->findObj(section, name, param)) {
157        fatal("Can't unserialize '%s:%s'\n", section, name);
158    }
159}
160
161
162#define INSTANTIATE_PARAM_TEMPLATES(type)				\
163template void								\
164paramOut(ostream &os, const std::string &name, type const &param);	\
165template void								\
166paramIn(Checkpoint *cp, const std::string &section,			\
167        const std::string &name, type & param);				\
168template void								\
169arrayParamOut(ostream &os, const std::string &name,			\
170              type const *param, int size);				\
171template void								\
172arrayParamIn(Checkpoint *cp, const std::string &section,		\
173             const std::string &name, type *param, int size);
174
175
176INSTANTIATE_PARAM_TEMPLATES(int8_t)
177INSTANTIATE_PARAM_TEMPLATES(uint8_t)
178INSTANTIATE_PARAM_TEMPLATES(int16_t)
179INSTANTIATE_PARAM_TEMPLATES(uint16_t)
180INSTANTIATE_PARAM_TEMPLATES(int32_t)
181INSTANTIATE_PARAM_TEMPLATES(uint32_t)
182INSTANTIATE_PARAM_TEMPLATES(int64_t)
183INSTANTIATE_PARAM_TEMPLATES(uint64_t)
184INSTANTIATE_PARAM_TEMPLATES(bool)
185INSTANTIATE_PARAM_TEMPLATES(string)
186
187
188/////////////////////////////
189
190/// Container for serializing global variables (not associated with
191/// any serialized object).
192class Globals : public Serializable
193{
194  public:
195    const string name() const;
196    void serialize(ostream &os);
197    void unserialize(Checkpoint *cp);
198};
199
200/// The one and only instance of the Globals class.
201Globals globals;
202
203const string
204Globals::name() const
205{
206    return "Globals";
207}
208
209void
210Globals::serialize(ostream &os)
211{
212    nameOut(os);
213    SERIALIZE_SCALAR(curTick);
214
215    nameOut(os, "MainEventQueue");
216    mainEventQueue.serialize(os);
217}
218
219void
220Globals::unserialize(Checkpoint *cp)
221{
222    const string &section = name();
223    UNSERIALIZE_SCALAR(curTick);
224
225    mainEventQueue.unserialize(cp, "MainEventQueue");
226}
227
228void
229Serializable::serializeAll()
230{
231    if (maxCount && count++ > maxCount)
232        exitNow("Maximum number of checkpoints dropped", 0);
233
234    string dir = Checkpoint::dir();
235    if (mkdir(dir.c_str(), 0775) == -1 && errno != EEXIST)
236            fatal("couldn't mkdir %s\n", dir);
237
238    string cpt_file = dir + Checkpoint::baseFilename;
239    ofstream outstream(cpt_file.c_str());
240    time_t t = time(NULL);
241    outstream << "// checkpoint generated: " << ctime(&t);
242
243    globals.serialize(outstream);
244    SimObject::serializeAll(outstream);
245}
246
247
248void
249Serializable::unserializeGlobals(Checkpoint *cp)
250{
251    globals.unserialize(cp);
252}
253
254
255class SerializeEvent : public Event
256{
257  protected:
258    Tick repeat;
259
260  public:
261    SerializeEvent(Tick _when, Tick _repeat);
262    virtual void process();
263    virtual void serialize(std::ostream &os)
264    {
265        panic("Cannot serialize the SerializeEvent");
266    }
267
268};
269
270SerializeEvent::SerializeEvent(Tick _when, Tick _repeat)
271    : Event(&mainEventQueue, Serialize_Pri), repeat(_repeat)
272{
273    setFlags(AutoDelete);
274    schedule(_when);
275}
276
277void
278SerializeEvent::process()
279{
280    Serializable::serializeAll();
281    if (repeat)
282        schedule(curTick + repeat);
283}
284
285const char *Checkpoint::baseFilename = "m5.cpt";
286
287static string checkpointDirBase;
288
289string
290Checkpoint::dir()
291{
292    // use csprintf to insert curTick into directory name if it
293    // appears to have a format placeholder in it.
294    return (checkpointDirBase.find("%") != string::npos) ?
295        csprintf(checkpointDirBase, curTick) : checkpointDirBase;
296}
297
298void
299Checkpoint::setup(Tick when, Tick period)
300{
301    new SerializeEvent(when, period);
302}
303
304class SerializeParamContext : public ParamContext
305{
306  private:
307    SerializeEvent *event;
308
309  public:
310    SerializeParamContext(const string &section);
311    ~SerializeParamContext();
312    void checkParams();
313};
314
315SerializeParamContext serialParams("serialize");
316
317Param<string> serialize_dir(&serialParams, "dir",
318                            "dir to stick checkpoint in "
319                            "(sprintf format with cycle #)");
320
321Param<Counter> serialize_cycle(&serialParams,
322                                "cycle",
323                                "cycle to serialize",
324                                0);
325
326Param<Counter> serialize_period(&serialParams,
327                                "period",
328                                "period to repeat serializations",
329                                0);
330
331Param<int> serialize_count(&serialParams, "count",
332                           "maximum number of checkpoints to drop");
333
334SerializeParamContext::SerializeParamContext(const string &section)
335    : ParamContext(section), event(NULL)
336{ }
337
338SerializeParamContext::~SerializeParamContext()
339{
340}
341
342void
343SerializeParamContext::checkParams()
344{
345    checkpointDirBase = simout.resolve(serialize_dir);
346
347    // guarantee that directory ends with a '/'
348    if (checkpointDirBase[checkpointDirBase.size() - 1] != '/')
349        checkpointDirBase += "/";
350
351    if (serialize_cycle > 0)
352        Checkpoint::setup(serialize_cycle, serialize_period);
353
354    Serializable::maxCount = serialize_count;
355}
356
357void
358debug_serialize()
359{
360    Serializable::serializeAll();
361}
362
363void
364debug_serialize(Tick when)
365{
366    new SerializeEvent(when, 0);
367}
368
369////////////////////////////////////////////////////////////////////////
370//
371// SerializableClass member definitions
372//
373////////////////////////////////////////////////////////////////////////
374
375// Map of class names to SerializableBuilder creation functions.
376// Need to make this a pointer so we can force initialization on the
377// first reference; otherwise, some SerializableClass constructors
378// may be invoked before the classMap constructor.
379map<string,SerializableClass::CreateFunc> *SerializableClass::classMap = 0;
380
381// SerializableClass constructor: add mapping to classMap
382SerializableClass::SerializableClass(const string &className,
383                                       CreateFunc createFunc)
384{
385    if (classMap == NULL)
386        classMap = new map<string,SerializableClass::CreateFunc>();
387
388    if ((*classMap)[className])
389    {
390        cerr << "Error: simulation object class " << className << " redefined"
391             << endl;
392        fatal("");
393    }
394
395    // add className --> createFunc to class map
396    (*classMap)[className] = createFunc;
397}
398
399
400//
401//
402Serializable *
403SerializableClass::createObject(Checkpoint *cp,
404                                 const std::string &section)
405{
406    string className;
407
408    if (!cp->find(section, "type", className)) {
409        fatal("Serializable::create: no 'type' entry in section '%s'.\n",
410              section);
411    }
412
413    CreateFunc createFunc = (*classMap)[className];
414
415    if (createFunc == NULL) {
416        fatal("Serializable::create: no create function for class '%s'.\n",
417              className);
418    }
419
420    Serializable *object = createFunc(cp, section);
421
422    assert(object != NULL);
423
424    return object;
425}
426
427
428Serializable *
429Serializable::create(Checkpoint *cp, const std::string &section)
430{
431    Serializable *object = SerializableClass::createObject(cp, section);
432    object->unserialize(cp, section);
433    return object;
434}
435
436
437Checkpoint::Checkpoint(const std::string &cpt_dir, const std::string &path,
438                       const ConfigNode *_configNode)
439    : db(new IniFile), basePath(path), configNode(_configNode), cptDir(cpt_dir)
440{
441    string filename = cpt_dir + "/" + Checkpoint::baseFilename;
442    if (!db->load(filename)) {
443        fatal("Can't load checkpoint file '%s'\n", filename);
444    }
445}
446
447
448bool
449Checkpoint::find(const std::string &section, const std::string &entry,
450                 std::string &value)
451{
452    return db->find(section, entry, value);
453}
454
455
456bool
457Checkpoint::findObj(const std::string &section, const std::string &entry,
458                    Serializable *&value)
459{
460    string path;
461
462    if (!db->find(section, entry, path))
463        return false;
464
465    if ((value = configNode->resolveSimObject(path)) != NULL)
466        return true;
467
468    if ((value = objMap[path]) != NULL)
469        return true;
470
471    return false;
472}
473
474
475bool
476Checkpoint::sectionExists(const std::string &section)
477{
478    return db->sectionExists(section);
479}
480