serialize.hh revision 9554:406fbcf60223
1/*
2 * Copyright (c) 2002-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 *          Erik Hallnor
30 *          Steve Reinhardt
31 */
32
33/* @file
34 * Serialization Interface Declarations
35 */
36
37#ifndef __SERIALIZE_HH__
38#define __SERIALIZE_HH__
39
40
41#include <iostream>
42#include <list>
43#include <map>
44#include <vector>
45
46#include "base/types.hh"
47
48class IniFile;
49class Serializable;
50class Checkpoint;
51class SimObject;
52
53/** The current version of the checkpoint format.
54 * This should be incremented by 1 and only 1 for every new version, where a new
55 * version is defined as a checkpoint created before this version won't work on
56 * the current version until the checkpoint format is updated. Adding a new
57 * SimObject shouldn't cause the version number to increase, only changes to
58 * existing objects such as serializing/unserializing more state, changing sizes
59 * of serialized arrays, etc. */
60static const uint64_t gem5CheckpointVersion = 0x0000000000000005;
61
62template <class T>
63void paramOut(std::ostream &os, const std::string &name, const T &param);
64
65template <class T>
66void paramIn(Checkpoint *cp, const std::string &section,
67             const std::string &name, T &param);
68
69template <class T>
70bool optParamIn(Checkpoint *cp, const std::string &section,
71             const std::string &name, T &param);
72
73template <class T>
74void arrayParamOut(std::ostream &os, const std::string &name,
75                   const T *param, unsigned size);
76
77template <class T>
78void arrayParamOut(std::ostream &os, const std::string &name,
79                   const std::vector<T> &param);
80
81template <class T>
82void arrayParamOut(std::ostream &os, const std::string &name,
83                   const std::list<T> &param);
84
85template <class T>
86void arrayParamIn(Checkpoint *cp, const std::string &section,
87                  const std::string &name, T *param, unsigned size);
88
89template <class T>
90void arrayParamIn(Checkpoint *cp, const std::string &section,
91                  const std::string &name, std::vector<T> &param);
92
93template <class T>
94void arrayParamIn(Checkpoint *cp, const std::string &section,
95                  const std::string &name, std::list<T> &param);
96
97void
98objParamIn(Checkpoint *cp, const std::string &section,
99           const std::string &name, SimObject * &param);
100
101template <typename T>
102void fromInt(T &t, int i)
103{
104    t = (T)i;
105}
106
107template <typename T>
108void fromSimObject(T &t, SimObject *s)
109{
110    t = dynamic_cast<T>(s);
111}
112
113//
114// These macros are streamlined to use in serialize/unserialize
115// functions.  It's assumed that serialize() has a parameter 'os' for
116// the ostream, and unserialize() has parameters 'cp' and 'section'.
117#define SERIALIZE_SCALAR(scalar)        paramOut(os, #scalar, scalar)
118
119#define UNSERIALIZE_SCALAR(scalar)      paramIn(cp, section, #scalar, scalar)
120#define UNSERIALIZE_OPT_SCALAR(scalar)      optParamIn(cp, section, #scalar, scalar)
121
122// ENUMs are like SCALARs, but we cast them to ints on the way out
123#define SERIALIZE_ENUM(scalar)          paramOut(os, #scalar, (int)scalar)
124
125#define UNSERIALIZE_ENUM(scalar)                \
126 do {                                           \
127    int tmp;                                    \
128    paramIn(cp, section, #scalar, tmp);         \
129    fromInt(scalar, tmp);                    \
130  } while (0)
131
132#define SERIALIZE_ARRAY(member, size)           \
133        arrayParamOut(os, #member, member, size)
134
135#define UNSERIALIZE_ARRAY(member, size)         \
136        arrayParamIn(cp, section, #member, member, size)
137
138#define SERIALIZE_OBJPTR(objptr)        paramOut(os, #objptr, (objptr)->name())
139
140#define UNSERIALIZE_OBJPTR(objptr)                      \
141  do {                                                  \
142    SimObject *sptr;                                    \
143    objParamIn(cp, section, #objptr, sptr);             \
144    fromSimObject(objptr, sptr);                        \
145  } while (0)
146
147/**
148 * Basic support for object serialization.
149 *
150 * @note Many objects that support serialization need to be put in a
151 * consistent state when serialization takes place. We refer to the
152 * action of forcing an object into a consistent state as
153 * 'draining'. Objects that need draining inherit from Drainable. See
154 * Drainable for more information.
155 */
156class Serializable
157{
158  protected:
159    void nameOut(std::ostream &os);
160    void nameOut(std::ostream &os, const std::string &_name);
161
162  public:
163    Serializable();
164    virtual ~Serializable();
165
166    // manditory virtual function, so objects must provide names
167    virtual const std::string name() const = 0;
168
169    virtual void serialize(std::ostream &os);
170    virtual void unserialize(Checkpoint *cp, const std::string &section);
171
172    static Serializable *create(Checkpoint *cp, const std::string &section);
173
174    static int ckptCount;
175    static int ckptMaxCount;
176    static int ckptPrevCount;
177    static void serializeAll(const std::string &cpt_dir);
178    static void unserializeGlobals(Checkpoint *cp);
179};
180
181void debug_serialize(const std::string &cpt_dir);
182
183//
184// A SerializableBuilder serves as an evaluation context for a set of
185// parameters that describe a specific instance of a Serializable.  This
186// evaluation context corresponds to a section in the .ini file (as
187// with the base ParamContext) plus an optional node in the
188// configuration hierarchy (the configNode member) for resolving
189// Serializable references.  SerializableBuilder is an abstract superclass;
190// derived classes specialize the class for particular subclasses of
191// Serializable (e.g., BaseCache).
192//
193// For typical usage, see the definition of
194// SerializableClass::createObject().
195//
196class SerializableBuilder
197{
198  public:
199
200    SerializableBuilder() {}
201
202    virtual ~SerializableBuilder() {}
203
204    // Create the actual Serializable corresponding to the parameter
205    // values in this context.  This function is overridden in derived
206    // classes to call a specific constructor for a particular
207    // subclass of Serializable.
208    virtual Serializable *create() = 0;
209};
210
211//
212// An instance of SerializableClass corresponds to a class derived from
213// Serializable.  The SerializableClass instance serves to bind the string
214// name (found in the config file) to a function that creates an
215// instance of the appropriate derived class.
216//
217// This would be much cleaner in Smalltalk or Objective-C, where types
218// are first-class objects themselves.
219//
220class SerializableClass
221{
222  public:
223
224    // Type CreateFunc is a pointer to a function that creates a new
225    // simulation object builder based on a .ini-file parameter
226    // section (specified by the first string argument), a unique name
227    // for the object (specified by the second string argument), and
228    // an optional config hierarchy node (specified by the third
229    // argument).  A pointer to the new SerializableBuilder is returned.
230    typedef Serializable *(*CreateFunc)(Checkpoint *cp,
231                                        const std::string &section);
232
233    static std::map<std::string,CreateFunc> *classMap;
234
235    // Constructor.  For example:
236    //
237    // SerializableClass baseCacheSerializableClass("BaseCacheSerializable",
238    //                         newBaseCacheSerializableBuilder);
239    //
240    SerializableClass(const std::string &className, CreateFunc createFunc);
241
242    // create Serializable given name of class and pointer to
243    // configuration hierarchy node
244    static Serializable *createObject(Checkpoint *cp,
245                                      const std::string &section);
246};
247
248//
249// Macros to encapsulate the magic of declaring & defining
250// SerializableBuilder and SerializableClass objects
251//
252
253#define REGISTER_SERIALIZEABLE(CLASS_NAME, OBJ_CLASS)                      \
254SerializableClass the##OBJ_CLASS##Class(CLASS_NAME,                        \
255                                         OBJ_CLASS::createForUnserialize);
256
257class Checkpoint
258{
259  private:
260
261    IniFile *db;
262
263  public:
264    Checkpoint(const std::string &cpt_dir);
265    ~Checkpoint();
266
267    const std::string cptDir;
268
269    bool find(const std::string &section, const std::string &entry,
270              std::string &value);
271
272    bool findObj(const std::string &section, const std::string &entry,
273                 SimObject *&value);
274
275    bool sectionExists(const std::string &section);
276
277    // The following static functions have to do with checkpoint
278    // creation rather than restoration.  This class makes a handy
279    // namespace for them though.  Currently no Checkpoint object is
280    // created on serialization (only unserialization) so we track the
281    // directory name as a global.  It would be nice to change this
282    // someday
283
284  private:
285    // current directory we're serializing into.
286    static std::string currentDirectory;
287
288  public:
289    // Set the current directory.  This function takes care of
290    // inserting curTick() if there's a '%d' in the argument, and
291    // appends a '/' if necessary.  The final name is returned.
292    static std::string setDir(const std::string &base_name);
293
294    // Export current checkpoint directory name so other objects can
295    // derive filenames from it (e.g., memory).  The return value is
296    // guaranteed to end in '/' so filenames can be directly appended.
297    // This function is only valid while a checkpoint is being created.
298    static std::string dir();
299
300    // Filename for base checkpoint file within directory.
301    static const char *baseFilename;
302};
303
304#endif // __SERIALIZE_HH__
305