serialize.hh revision 12452:ad4adeb441d0
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) 2002-2005 The Regents of The University of Michigan
15 * All rights reserved.
16 *
17 * Redistribution and use in source and binary forms, with or without
18 * modification, are permitted provided that the following conditions are
19 * met: redistributions of source code must retain the above copyright
20 * notice, this list of conditions and the following disclaimer;
21 * redistributions in binary form must reproduce the above copyright
22 * notice, this list of conditions and the following disclaimer in the
23 * documentation and/or other materials provided with the distribution;
24 * neither the name of the copyright holders nor the names of its
25 * contributors may be used to endorse or promote products derived from
26 * this software without specific prior written permission.
27 *
28 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
29 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
31 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
32 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
33 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
34 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
38 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 *
40 * Authors: Nathan Binkert
41 *          Erik Hallnor
42 *          Steve Reinhardt
43 *          Andreas Sandberg
44 */
45
46/* @file
47 * Serialization Interface Declarations
48 */
49
50#ifndef __SERIALIZE_HH__
51#define __SERIALIZE_HH__
52
53
54#include <iostream>
55#include <list>
56#include <map>
57#include <stack>
58#include <set>
59#include <vector>
60
61#include "base/bitunion.hh"
62
63class CheckpointIn;
64class IniFile;
65class Serializable;
66class SimObject;
67class SimObjectResolver;
68
69typedef std::ostream CheckpointOut;
70
71
72template <class T>
73void paramOut(CheckpointOut &cp, const std::string &name, const T &param);
74
75template <typename T>
76void
77paramOut(CheckpointOut &cp, const std::string &name, const BitUnionType<T> &p)
78{
79    paramOut(cp, name, static_cast<BitUnionBaseType<T> >(p));
80}
81
82template <class T>
83void paramIn(CheckpointIn &cp, const std::string &name, T &param);
84
85template <typename T>
86void
87paramIn(CheckpointIn &cp, const std::string &name, BitUnionType<T> &p)
88{
89    BitUnionBaseType<T> b;
90    paramIn(cp, name, b);
91    p = b;
92}
93
94template <class T>
95bool optParamIn(CheckpointIn &cp, const std::string &name, T &param,
96                bool warn = true);
97
98template <typename T>
99bool
100optParamIn(CheckpointIn &cp, const std::string &name,
101           BitUnionType<T> &p, bool warn = true)
102{
103    BitUnionBaseType<T> b;
104    if (optParamIn(cp, name, b, warn)) {
105        p = b;
106        return true;
107    } else {
108        return false;
109    }
110}
111
112template <class T>
113void arrayParamOut(CheckpointOut &cp, const std::string &name,
114                   const T *param, unsigned size);
115
116template <class T>
117void arrayParamOut(CheckpointOut &cp, const std::string &name,
118                   const std::vector<T> &param);
119
120template <class T>
121void arrayParamOut(CheckpointOut &cp, const std::string &name,
122                   const std::list<T> &param);
123
124template <class T>
125void arrayParamOut(CheckpointOut &cp, const std::string &name,
126                   const std::set<T> &param);
127
128template <class T>
129void arrayParamIn(CheckpointIn &cp, const std::string &name,
130                  T *param, unsigned size);
131
132template <class T>
133void arrayParamIn(CheckpointIn &cp, const std::string &name,
134                  std::vector<T> &param);
135
136template <class T>
137void arrayParamIn(CheckpointIn &cp, const std::string &name,
138                  std::list<T> &param);
139
140template <class T>
141void arrayParamIn(CheckpointIn &cp, const std::string &name,
142                  std::set<T> &param);
143
144void
145objParamIn(CheckpointIn &cp, const std::string &name, SimObject * &param);
146
147//
148// These macros are streamlined to use in serialize/unserialize
149// functions.  It's assumed that serialize() has a parameter 'os' for
150// the ostream, and unserialize() has parameters 'cp' and 'section'.
151#define SERIALIZE_SCALAR(scalar)        paramOut(cp, #scalar, scalar)
152
153#define UNSERIALIZE_SCALAR(scalar)      paramIn(cp, #scalar, scalar)
154#define UNSERIALIZE_OPT_SCALAR(scalar)      optParamIn(cp, #scalar, scalar)
155
156// ENUMs are like SCALARs, but we cast them to ints on the way out
157#define SERIALIZE_ENUM(scalar)          paramOut(cp, #scalar, (int)scalar)
158
159#define UNSERIALIZE_ENUM(scalar)                        \
160    do {                                                \
161        int tmp;                                        \
162        paramIn(cp, #scalar, tmp);                      \
163        scalar = static_cast<decltype(scalar)>(tmp);    \
164    } while (0)
165
166#define SERIALIZE_ARRAY(member, size)           \
167        arrayParamOut(cp, #member, member, size)
168
169#define UNSERIALIZE_ARRAY(member, size)         \
170        arrayParamIn(cp, #member, member, size)
171
172#define SERIALIZE_CONTAINER(member)             \
173        arrayParamOut(cp, #member, member)
174
175#define UNSERIALIZE_CONTAINER(member)           \
176        arrayParamIn(cp, #member, member)
177
178#define SERIALIZE_EVENT(event) event.serializeSection(cp, #event);
179
180#define UNSERIALIZE_EVENT(event)                        \
181    do {                                                \
182        event.unserializeSection(cp, #event);           \
183        eventQueue()->checkpointReschedule(&event);     \
184    } while (0)
185
186#define SERIALIZE_OBJ(obj) obj.serializeSection(cp, #obj)
187#define UNSERIALIZE_OBJ(obj) obj.unserializeSection(cp, #obj)
188
189#define SERIALIZE_OBJPTR(objptr)        paramOut(cp, #objptr, (objptr)->name())
190
191#define UNSERIALIZE_OBJPTR(objptr)                      \
192    do {                                                \
193        SimObject *sptr;                                \
194        objParamIn(cp, #objptr, sptr);                  \
195        objptr = dynamic_cast<decltype(objptr)>(sptr);  \
196    } while (0)
197
198/**
199 * Basic support for object serialization.
200 *
201 * Objects that support serialization should derive from this
202 * class. Such objects can largely be divided into two categories: 1)
203 * True SimObjects (deriving from SimObject), and 2) child objects
204 * (non-SimObjects).
205 *
206 * SimObjects are serialized automatically into their own sections
207 * automatically by the SimObject base class (see
208 * SimObject::serializeAll().
209 *
210 * SimObjects can contain other serializable objects that are not
211 * SimObjects. Much like normal serialized members are not serialized
212 * automatically, these objects will not be serialized automatically
213 * and it is expected that the objects owning such serializable
214 * objects call the required serialization/unserialization methods on
215 * child objects. The preferred method to serialize a child object is
216 * to call serializeSection() on the child, which serializes the
217 * object into a new subsection in the current section. Another option
218 * is to call serialize() directly, which serializes the object into
219 * the current section. The latter is not recommended as it can lead
220 * to naming clashes between objects.
221 *
222 * @note Many objects that support serialization need to be put in a
223 * consistent state when serialization takes place. We refer to the
224 * action of forcing an object into a consistent state as
225 * 'draining'. Objects that need draining inherit from Drainable. See
226 * Drainable for more information.
227 */
228class Serializable
229{
230  protected:
231    /**
232     * Scoped checkpoint section helper class
233     *
234     * This helper class creates a section within a checkpoint without
235     * the need for a separate serializeable object. It is mainly used
236     * within the Serializable class when serializing or unserializing
237     * section (see serializeSection() and unserializeSection()). It
238     * can also be used to maintain backwards compatibility in
239     * existing code that serializes structs that are not inheriting
240     * from Serializable into subsections.
241     *
242     * When the class is instantiated, it appends a name to the active
243     * path in a checkpoint. The old path is later restored when the
244     * instance is destroyed. For example, serializeSection() could be
245     * implemented by instantiating a ScopedCheckpointSection and then
246     * calling serialize() on an object.
247     */
248    class ScopedCheckpointSection {
249      public:
250        template<class CP>
251        ScopedCheckpointSection(CP &cp, const char *name) {
252            pushName(name);
253            nameOut(cp);
254        }
255
256        template<class CP>
257        ScopedCheckpointSection(CP &cp, const std::string &name) {
258            pushName(name.c_str());
259            nameOut(cp);
260        }
261
262        ~ScopedCheckpointSection();
263
264        ScopedCheckpointSection() = delete;
265        ScopedCheckpointSection(const ScopedCheckpointSection &) = delete;
266        ScopedCheckpointSection &operator=(
267            const ScopedCheckpointSection &) = delete;
268        ScopedCheckpointSection &operator=(
269            ScopedCheckpointSection &&) = delete;
270
271      private:
272        void pushName(const char *name);
273        void nameOut(CheckpointOut &cp);
274        void nameOut(CheckpointIn &cp) {};
275    };
276
277  public:
278    Serializable();
279    virtual ~Serializable();
280
281    /**
282     * Serialize an object
283     *
284     * Output an object's state into the current checkpoint section.
285     *
286     * @param cp Checkpoint state
287     */
288    virtual void serialize(CheckpointOut &cp) const = 0;
289
290    /**
291     * Unserialize an object
292     *
293     * Read an object's state from the current checkpoint section.
294     *
295     * @param cp Checkpoint state
296     */
297    virtual void unserialize(CheckpointIn &cp) = 0;
298
299    /**
300     * Serialize an object into a new section
301     *
302     * This method creates a new section in a checkpoint and calls
303     * serialize() to serialize the current object into that
304     * section. The name of the section is appended to the current
305     * checkpoint path.
306     *
307     * @param cp Checkpoint state
308     * @param name Name to append to the active path
309     */
310    void serializeSection(CheckpointOut &cp, const char *name) const;
311
312    void serializeSection(CheckpointOut &cp, const std::string &name) const {
313        serializeSection(cp, name.c_str());
314    }
315
316    /**
317     * Unserialize an a child object
318     *
319     * This method loads a child object from a checkpoint. The object
320     * name is appended to the active path to form a fully qualified
321     * section name and unserialize() is called.
322     *
323     * @param cp Checkpoint state
324     * @param name Name to append to the active path
325     */
326    void unserializeSection(CheckpointIn &cp, const char *name);
327
328    void unserializeSection(CheckpointIn &cp, const std::string &name) {
329        unserializeSection(cp, name.c_str());
330    }
331
332    /** Get the fully-qualified name of the active section */
333    static const std::string &currentSection();
334
335    static int ckptCount;
336    static int ckptMaxCount;
337    static int ckptPrevCount;
338    static void serializeAll(const std::string &cpt_dir);
339    static void unserializeGlobals(CheckpointIn &cp);
340
341  private:
342    static std::stack<std::string> path;
343};
344
345void debug_serialize(const std::string &cpt_dir);
346
347
348class CheckpointIn
349{
350  private:
351
352    IniFile *db;
353
354    SimObjectResolver &objNameResolver;
355
356  public:
357    CheckpointIn(const std::string &cpt_dir, SimObjectResolver &resolver);
358    ~CheckpointIn();
359
360    const std::string cptDir;
361
362    bool find(const std::string &section, const std::string &entry,
363              std::string &value);
364
365    bool findObj(const std::string &section, const std::string &entry,
366                 SimObject *&value);
367
368
369    bool entryExists(const std::string &section, const std::string &entry);
370    bool sectionExists(const std::string &section);
371
372    // The following static functions have to do with checkpoint
373    // creation rather than restoration.  This class makes a handy
374    // namespace for them though.  Currently no Checkpoint object is
375    // created on serialization (only unserialization) so we track the
376    // directory name as a global.  It would be nice to change this
377    // someday
378
379  private:
380    // current directory we're serializing into.
381    static std::string currentDirectory;
382
383  public:
384    // Set the current directory.  This function takes care of
385    // inserting curTick() if there's a '%d' in the argument, and
386    // appends a '/' if necessary.  The final name is returned.
387    static std::string setDir(const std::string &base_name);
388
389    // Export current checkpoint directory name so other objects can
390    // derive filenames from it (e.g., memory).  The return value is
391    // guaranteed to end in '/' so filenames can be directly appended.
392    // This function is only valid while a checkpoint is being created.
393    static std::string dir();
394
395    // Filename for base checkpoint file within directory.
396    static const char *baseFilename;
397};
398
399#endif // __SERIALIZE_HH__
400