serialize.cc revision 6225
1955SN/A/*
2955SN/A * Copyright (c) 2002-2005 The Regents of The University of Michigan
31762SN/A * All rights reserved.
4955SN/A *
5955SN/A * Redistribution and use in source and binary forms, with or without
6955SN/A * modification, are permitted provided that the following conditions are
7955SN/A * met: redistributions of source code must retain the above copyright
8955SN/A * notice, this list of conditions and the following disclaimer;
9955SN/A * redistributions in binary form must reproduce the above copyright
10955SN/A * notice, this list of conditions and the following disclaimer in the
11955SN/A * documentation and/or other materials provided with the distribution;
12955SN/A * neither the name of the copyright holders nor the names of its
13955SN/A * contributors may be used to endorse or promote products derived from
14955SN/A * this software without specific prior written permission.
15955SN/A *
16955SN/A * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17955SN/A * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18955SN/A * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19955SN/A * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20955SN/A * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21955SN/A * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22955SN/A * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23955SN/A * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24955SN/A * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25955SN/A * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26955SN/A * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27955SN/A *
282665Ssaidi@eecs.umich.edu * Authors: Nathan Binkert
292665Ssaidi@eecs.umich.edu *          Erik Hallnor
30955SN/A *          Steve Reinhardt
31955SN/A */
32955SN/A
334202Sbinkertn@umich.edu#include <sys/time.h>
344202Sbinkertn@umich.edu#include <sys/types.h>
35955SN/A#include <sys/stat.h>
36955SN/A#include <errno.h>
37955SN/A
38955SN/A#include <fstream>
394202Sbinkertn@umich.edu#include <list>
40955SN/A#include <string>
414202Sbinkertn@umich.edu#include <vector>
424202Sbinkertn@umich.edu
434202Sbinkertn@umich.edu#include "base/inifile.hh"
444202Sbinkertn@umich.edu#include "base/misc.hh"
454202Sbinkertn@umich.edu#include "base/output.hh"
464202Sbinkertn@umich.edu#include "base/str.hh"
474202Sbinkertn@umich.edu#include "base/trace.hh"
484202Sbinkertn@umich.edu#include "sim/eventq.hh"
494202Sbinkertn@umich.edu#include "sim/serialize.hh"
504202Sbinkertn@umich.edu#include "sim/sim_events.hh"
51955SN/A#include "sim/sim_exit.hh"
524202Sbinkertn@umich.edu#include "sim/sim_object.hh"
534202Sbinkertn@umich.edu
54955SN/A// For stat reset hack
552667Sstever@eecs.umich.edu#include "sim/stat_control.hh"
562667Sstever@eecs.umich.edu
572667Sstever@eecs.umich.eduusing namespace std;
582667Sstever@eecs.umich.edu
592667Sstever@eecs.umich.eduextern SimObject *resolveSimObject(const string &);
602667Sstever@eecs.umich.edu
612037SN/A//
622037SN/A// The base implementations use to_number for parsing and '<<' for
632037SN/A// displaying, suitable for integer types.
644202Sbinkertn@umich.edu//
654202Sbinkertn@umich.edutemplate <class T>
664202Sbinkertn@umich.edubool
674202Sbinkertn@umich.eduparseParam(const string &s, T &value)
684202Sbinkertn@umich.edu{
694202Sbinkertn@umich.edu    return to_number(s, value);
704202Sbinkertn@umich.edu}
714202Sbinkertn@umich.edu
724202Sbinkertn@umich.edutemplate <class T>
734202Sbinkertn@umich.eduvoid
744202Sbinkertn@umich.edushowParam(ostream &os, const T &value)
754202Sbinkertn@umich.edu{
764202Sbinkertn@umich.edu    os << value;
771858SN/A}
781858SN/A
791858SN/A//
801085SN/A// Template specializations:
81955SN/A// - char (8-bit integer)
82955SN/A// - floating-point types
83955SN/A// - bool
84955SN/A// - string
851108SN/A//
86955SN/A
87955SN/A// Treat 8-bit ints (chars) as ints on output, not as chars
88955SN/Atemplate <>
89955SN/Avoid
90955SN/AshowParam(ostream &os, const char &value)
91955SN/A{
92955SN/A    os << (int)value;
93955SN/A}
94955SN/A
95955SN/A
96955SN/Atemplate <>
97955SN/Avoid
98955SN/AshowParam(ostream &os, const unsigned char &value)
99955SN/A{
100955SN/A    os << (unsigned int)value;
101955SN/A}
1022655Sstever@eecs.umich.edu
1032655Sstever@eecs.umich.edu
1042655Sstever@eecs.umich.edu// Use sscanf() for FP types as to_number() only handles integers
1052655Sstever@eecs.umich.edutemplate <>
1062655Sstever@eecs.umich.edubool
1072655Sstever@eecs.umich.eduparseParam(const string &s, float &value)
1082655Sstever@eecs.umich.edu{
1092655Sstever@eecs.umich.edu    return (sscanf(s.c_str(), "%f", &value) == 1);
1102655Sstever@eecs.umich.edu}
1112655Sstever@eecs.umich.edu
1122655Sstever@eecs.umich.edutemplate <>
1132655Sstever@eecs.umich.edubool
1142655Sstever@eecs.umich.eduparseParam(const string &s, double &value)
1152655Sstever@eecs.umich.edu{
1162655Sstever@eecs.umich.edu    return (sscanf(s.c_str(), "%lf", &value) == 1);
1172655Sstever@eecs.umich.edu}
1184007Ssaidi@eecs.umich.edu
1194007Ssaidi@eecs.umich.edutemplate <>
1204007Ssaidi@eecs.umich.edubool
1214007Ssaidi@eecs.umich.eduparseParam(const string &s, bool &value)
1222655Sstever@eecs.umich.edu{
1232655Sstever@eecs.umich.edu    const string &ls = to_lower(s);
1242655Sstever@eecs.umich.edu
1252655Sstever@eecs.umich.edu    if (ls == "true") {
1262655Sstever@eecs.umich.edu        value = true;
127955SN/A        return true;
1283918Ssaidi@eecs.umich.edu    }
1293918Ssaidi@eecs.umich.edu
1303918Ssaidi@eecs.umich.edu    if (ls == "false") {
1313918Ssaidi@eecs.umich.edu        value = false;
1323918Ssaidi@eecs.umich.edu        return true;
1333918Ssaidi@eecs.umich.edu    }
1343918Ssaidi@eecs.umich.edu
1353918Ssaidi@eecs.umich.edu    return false;
1363918Ssaidi@eecs.umich.edu}
1373918Ssaidi@eecs.umich.edu
1383918Ssaidi@eecs.umich.edu// Display bools as strings
1393918Ssaidi@eecs.umich.edutemplate <>
1403918Ssaidi@eecs.umich.eduvoid
1413918Ssaidi@eecs.umich.edushowParam(ostream &os, const bool &value)
1423940Ssaidi@eecs.umich.edu{
1433940Ssaidi@eecs.umich.edu    os << (value ? "true" : "false");
1443940Ssaidi@eecs.umich.edu}
1453942Ssaidi@eecs.umich.edu
1463940Ssaidi@eecs.umich.edu
1473515Ssaidi@eecs.umich.edu// String requires no processing to speak of
1483918Ssaidi@eecs.umich.edutemplate <>
1493918Ssaidi@eecs.umich.edubool
1503515Ssaidi@eecs.umich.eduparseParam(const string &s, string &value)
1512655Sstever@eecs.umich.edu{
1523918Ssaidi@eecs.umich.edu    value = s;
1533619Sbinkertn@umich.edu    return true;
154955SN/A}
155955SN/A
1562655Sstever@eecs.umich.eduint Serializable::ckptMaxCount = 0;
1573918Ssaidi@eecs.umich.eduint Serializable::ckptCount = 0;
1583619Sbinkertn@umich.eduint Serializable::ckptPrevCount = -1;
159955SN/A
160955SN/Avoid
1612655Sstever@eecs.umich.eduSerializable::nameOut(ostream &os)
1623918Ssaidi@eecs.umich.edu{
1633619Sbinkertn@umich.edu    os << "\n[" << name() << "]\n";
164955SN/A}
165955SN/A
1662655Sstever@eecs.umich.eduvoid
1673918Ssaidi@eecs.umich.eduSerializable::nameOut(ostream &os, const string &_name)
1683683Sstever@eecs.umich.edu{
1692655Sstever@eecs.umich.edu    os << "\n[" << _name << "]\n";
1701869SN/A}
1711869SN/A
172template <class T>
173void
174paramOut(ostream &os, const string &name, const T &param)
175{
176    os << name << "=";
177    showParam(os, param);
178    os << "\n";
179}
180
181template <class T>
182void
183arrayParamOut(ostream &os, const string &name, const vector<T> &param)
184{
185    int size = param.size();
186    os << name << "=";
187    if (size > 0)
188        showParam(os, param[0]);
189    for (int i = 1; i < size; ++i) {
190        os << " ";
191        showParam(os, param[i]);
192    }
193    os << "\n";
194}
195
196
197template <class T>
198void
199paramIn(Checkpoint *cp, const string &section, const string &name, T &param)
200{
201    string str;
202    if (!cp->find(section, name, str) || !parseParam(str, param)) {
203        fatal("Can't unserialize '%s:%s'\n", section, name);
204    }
205}
206
207
208template <class T>
209void
210arrayParamOut(ostream &os, const string &name, const T *param, int size)
211{
212    os << name << "=";
213    if (size > 0)
214        showParam(os, param[0]);
215    for (int i = 1; i < size; ++i) {
216        os << " ";
217        showParam(os, param[i]);
218    }
219    os << "\n";
220}
221
222
223template <class T>
224void
225arrayParamIn(Checkpoint *cp, const string &section, const string &name,
226             T *param, int size)
227{
228    string str;
229    if (!cp->find(section, name, str)) {
230        fatal("Can't unserialize '%s:%s'\n", section, name);
231    }
232
233    // code below stolen from VectorParam<T>::parse().
234    // it would be nice to unify these somehow...
235
236    vector<string> tokens;
237
238    tokenize(tokens, str, ' ');
239
240    // Need this if we were doing a vector
241    // value.resize(tokens.size());
242
243    if (tokens.size() != size) {
244        fatal("Array size mismatch on %s:%s'\n", section, name);
245    }
246
247    for (int i = 0; i < tokens.size(); i++) {
248        // need to parse into local variable to handle vector<bool>,
249        // for which operator[] returns a special reference class
250        // that's not the same as 'bool&', (since it's a packed
251        // vector)
252        T scalar_value;
253        if (!parseParam(tokens[i], scalar_value)) {
254            string err("could not parse \"");
255
256            err += str;
257            err += "\"";
258
259            fatal(err);
260        }
261
262        // assign parsed value to vector
263        param[i] = scalar_value;
264    }
265}
266
267template <class T>
268void
269arrayParamIn(Checkpoint *cp, const string &section,
270             const string &name, vector<T> &param)
271{
272    string str;
273    if (!cp->find(section, name, str)) {
274        fatal("Can't unserialize '%s:%s'\n", section, name);
275    }
276
277    // code below stolen from VectorParam<T>::parse().
278    // it would be nice to unify these somehow...
279
280    vector<string> tokens;
281
282    tokenize(tokens, str, ' ');
283
284    // Need this if we were doing a vector
285    // value.resize(tokens.size());
286
287    param.resize(tokens.size());
288
289    for (int i = 0; i < tokens.size(); i++) {
290        // need to parse into local variable to handle vector<bool>,
291        // for which operator[] returns a special reference class
292        // that's not the same as 'bool&', (since it's a packed
293        // vector)
294        T scalar_value;
295        if (!parseParam(tokens[i], scalar_value)) {
296            string err("could not parse \"");
297
298            err += str;
299            err += "\"";
300
301            fatal(err);
302        }
303
304        // assign parsed value to vector
305        param[i] = scalar_value;
306    }
307}
308
309
310
311void
312objParamIn(Checkpoint *cp, const string &section,
313           const string &name, SimObject * &param)
314{
315    if (!cp->findObj(section, name, param)) {
316        fatal("Can't unserialize '%s:%s'\n", section, name);
317    }
318}
319
320
321#define INSTANTIATE_PARAM_TEMPLATES(type)                               \
322template void                                                           \
323paramOut(ostream &os, const string &name, type const &param);           \
324template void                                                           \
325paramIn(Checkpoint *cp, const string &section,                          \
326        const string &name, type & param);                              \
327template void                                                           \
328arrayParamOut(ostream &os, const string &name,                          \
329              type const *param, int size);                             \
330template void                                                           \
331arrayParamIn(Checkpoint *cp, const string &section,                     \
332             const string &name, type *param, int size);                \
333template void                                                           \
334arrayParamOut(ostream &os, const string &name,                          \
335              const vector<type> &param);                               \
336template void                                                           \
337arrayParamIn(Checkpoint *cp, const string &section,                     \
338             const string &name, vector<type> &param);
339
340INSTANTIATE_PARAM_TEMPLATES(signed char)
341INSTANTIATE_PARAM_TEMPLATES(unsigned char)
342INSTANTIATE_PARAM_TEMPLATES(signed short)
343INSTANTIATE_PARAM_TEMPLATES(unsigned short)
344INSTANTIATE_PARAM_TEMPLATES(signed int)
345INSTANTIATE_PARAM_TEMPLATES(unsigned int)
346INSTANTIATE_PARAM_TEMPLATES(signed long)
347INSTANTIATE_PARAM_TEMPLATES(unsigned long)
348INSTANTIATE_PARAM_TEMPLATES(signed long long)
349INSTANTIATE_PARAM_TEMPLATES(unsigned long long)
350INSTANTIATE_PARAM_TEMPLATES(bool)
351INSTANTIATE_PARAM_TEMPLATES(float)
352INSTANTIATE_PARAM_TEMPLATES(double)
353INSTANTIATE_PARAM_TEMPLATES(string)
354
355
356/////////////////////////////
357
358/// Container for serializing global variables (not associated with
359/// any serialized object).
360class Globals : public Serializable
361{
362  public:
363    const string name() const;
364    void serialize(ostream &os);
365    void unserialize(Checkpoint *cp);
366};
367
368/// The one and only instance of the Globals class.
369Globals globals;
370
371const string
372Globals::name() const
373{
374    return "Globals";
375}
376
377void
378Globals::serialize(ostream &os)
379{
380    nameOut(os);
381    SERIALIZE_SCALAR(curTick);
382
383    nameOut(os, "MainEventQueue");
384    mainEventQueue.serialize(os);
385}
386
387void
388Globals::unserialize(Checkpoint *cp)
389{
390    const string &section = name();
391    UNSERIALIZE_SCALAR(curTick);
392
393    mainEventQueue.unserialize(cp, "MainEventQueue");
394}
395
396Serializable::Serializable()
397{
398}
399
400Serializable::~Serializable()
401{
402}
403
404void
405Serializable::serialize(ostream &os)
406{
407}
408
409void
410Serializable::unserialize(Checkpoint *cp, const string &section)
411{
412}
413
414void
415Serializable::serializeAll(const string &cpt_dir)
416{
417    setCheckpointDir(cpt_dir);
418    string dir = Checkpoint::dir();
419    if (mkdir(dir.c_str(), 0775) == -1 && errno != EEXIST)
420            fatal("couldn't mkdir %s\n", dir);
421
422    string cpt_file = dir + Checkpoint::baseFilename;
423    ofstream outstream(cpt_file.c_str());
424    time_t t = time(NULL);
425    if (!outstream.is_open())
426        fatal("Unable to open file %s for writing\n", cpt_file.c_str());
427    outstream << "// checkpoint generated: " << ctime(&t);
428
429    globals.serialize(outstream);
430    SimObject::serializeAll(outstream);
431}
432
433void
434Serializable::unserializeAll(const string &cpt_dir)
435{
436    setCheckpointDir(cpt_dir);
437    string dir = Checkpoint::dir();
438    string cpt_file = dir + Checkpoint::baseFilename;
439    string section = "";
440
441    DPRINTFR(Config, "Loading checkpoint dir '%s'\n",
442             dir);
443    Checkpoint *cp = new Checkpoint(dir, section);
444    unserializeGlobals(cp);
445    SimObject::unserializeAll(cp);
446}
447
448void
449Serializable::unserializeGlobals(Checkpoint *cp)
450{
451    globals.unserialize(cp);
452}
453
454const char *Checkpoint::baseFilename = "m5.cpt";
455
456static string checkpointDirBase;
457
458void
459setCheckpointDir(const string &name)
460{
461    checkpointDirBase = name;
462    if (checkpointDirBase[checkpointDirBase.size() - 1] != '/')
463        checkpointDirBase += "/";
464}
465
466string
467Checkpoint::dir()
468{
469    // use csprintf to insert curTick into directory name if it
470    // appears to have a format placeholder in it.
471    return (checkpointDirBase.find("%") != string::npos) ?
472        csprintf(checkpointDirBase, curTick) : checkpointDirBase;
473}
474
475void
476debug_serialize(const string &cpt_dir)
477{
478    Serializable::serializeAll(cpt_dir);
479}
480
481
482////////////////////////////////////////////////////////////////////////
483//
484// SerializableClass member definitions
485//
486////////////////////////////////////////////////////////////////////////
487
488// Map of class names to SerializableBuilder creation functions.
489// Need to make this a pointer so we can force initialization on the
490// first reference; otherwise, some SerializableClass constructors
491// may be invoked before the classMap constructor.
492map<string, SerializableClass::CreateFunc> *SerializableClass::classMap = 0;
493
494// SerializableClass constructor: add mapping to classMap
495SerializableClass::SerializableClass(const string &className,
496                                     CreateFunc createFunc)
497{
498    if (classMap == NULL)
499        classMap = new map<string, SerializableClass::CreateFunc>();
500
501    if ((*classMap)[className])
502        fatal("Error: simulation object class %s redefined\n", className);
503
504    // add className --> createFunc to class map
505    (*classMap)[className] = createFunc;
506}
507
508//
509//
510Serializable *
511SerializableClass::createObject(Checkpoint *cp, const string &section)
512{
513    string className;
514
515    if (!cp->find(section, "type", className)) {
516        fatal("Serializable::create: no 'type' entry in section '%s'.\n",
517              section);
518    }
519
520    CreateFunc createFunc = (*classMap)[className];
521
522    if (createFunc == NULL) {
523        fatal("Serializable::create: no create function for class '%s'.\n",
524              className);
525    }
526
527    Serializable *object = createFunc(cp, section);
528
529    assert(object != NULL);
530
531    return object;
532}
533
534
535Serializable *
536Serializable::create(Checkpoint *cp, const string &section)
537{
538    Serializable *object = SerializableClass::createObject(cp, section);
539    object->unserialize(cp, section);
540    return object;
541}
542
543
544Checkpoint::Checkpoint(const string &cpt_dir, const string &path)
545    : db(new IniFile), basePath(path), cptDir(cpt_dir)
546{
547    string filename = cpt_dir + "/" + Checkpoint::baseFilename;
548    if (!db->load(filename)) {
549        fatal("Can't load checkpoint file '%s'\n", filename);
550    }
551}
552
553
554bool
555Checkpoint::find(const string &section, const string &entry, string &value)
556{
557    return db->find(section, entry, value);
558}
559
560
561bool
562Checkpoint::findObj(const string &section, const string &entry,
563                    SimObject *&value)
564{
565    string path;
566
567    if (!db->find(section, entry, path))
568        return false;
569
570    value = resolveSimObject(path);
571    return true;
572}
573
574
575bool
576Checkpoint::sectionExists(const string &section)
577{
578    return db->sectionExists(section);
579}
580