serialize.hh revision 13107:8fa5f70698a2
1/*
2 * Copyright (c) 2015, 2018 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 <algorithm>
55#include <iostream>
56#include <list>
57#include <map>
58#include <stack>
59#include <set>
60#include <vector>
61
62#include "base/bitunion.hh"
63
64class CheckpointIn;
65class IniFile;
66class Serializable;
67class SimObject;
68class SimObjectResolver;
69
70typedef std::ostream CheckpointOut;
71
72
73template <class T>
74void paramOut(CheckpointOut &cp, const std::string &name, const T &param);
75
76template <typename T>
77void
78paramOut(CheckpointOut &cp, const std::string &name, const BitUnionType<T> &p)
79{
80    paramOut(cp, name, static_cast<BitUnionBaseType<T> >(p));
81}
82
83template <class T>
84void paramIn(CheckpointIn &cp, const std::string &name, T &param);
85
86template <typename T>
87void
88paramIn(CheckpointIn &cp, const std::string &name, BitUnionType<T> &p)
89{
90    BitUnionBaseType<T> b;
91    paramIn(cp, name, b);
92    p = b;
93}
94
95template <class T>
96bool optParamIn(CheckpointIn &cp, const std::string &name, T &param,
97                bool warn = true);
98
99template <typename T>
100bool
101optParamIn(CheckpointIn &cp, const std::string &name,
102           BitUnionType<T> &p, bool warn = true)
103{
104    BitUnionBaseType<T> b;
105    if (optParamIn(cp, name, b, warn)) {
106        p = b;
107        return true;
108    } else {
109        return false;
110    }
111}
112
113template <class T>
114void arrayParamOut(CheckpointOut &cp, const std::string &name,
115                   const T *param, unsigned size);
116
117template <class T>
118void arrayParamOut(CheckpointOut &cp, const std::string &name,
119                   const std::vector<T> &param);
120
121template <class T>
122void arrayParamOut(CheckpointOut &cp, const std::string &name,
123                   const std::list<T> &param);
124
125template <class T>
126void arrayParamOut(CheckpointOut &cp, const std::string &name,
127                   const std::set<T> &param);
128
129template <class T>
130void arrayParamIn(CheckpointIn &cp, const std::string &name,
131                  T *param, unsigned size);
132
133template <class T>
134void arrayParamIn(CheckpointIn &cp, const std::string &name,
135                  std::vector<T> &param);
136
137template <class T>
138void arrayParamIn(CheckpointIn &cp, const std::string &name,
139                  std::list<T> &param);
140
141template <class T>
142void arrayParamIn(CheckpointIn &cp, const std::string &name,
143                  std::set<T> &param);
144
145void
146objParamIn(CheckpointIn &cp, const std::string &name, SimObject * &param);
147
148template <class T>
149static void
150arrayParamOut(CheckpointOut &cp, const std::string &name,
151              const BitUnionType<T> *param, unsigned size)
152{
153    // We copy the array into a vector. This is needed since we cannot
154    // directly typecast a pointer to BitUnionType<T> into a pointer
155    // of BitUnionBaseType<T> but we can typecast BitUnionType<T>
156    // to BitUnionBaseType<T> since we overloaded the typecast operator
157    std::vector<BitUnionBaseType<T>> bitunion_vec(param, param + size);
158
159    arrayParamOut(cp, name, bitunion_vec);
160}
161
162template <class T>
163static void
164arrayParamIn(CheckpointIn &cp, const std::string &name,
165             BitUnionType<T> *param, unsigned size)
166{
167    std::vector<BitUnionBaseType<T>> bitunion_vec(size);
168
169    arrayParamIn(cp, name, bitunion_vec);
170    std::copy(bitunion_vec.begin(), bitunion_vec.end(), param);
171}
172
173//
174// These macros are streamlined to use in serialize/unserialize
175// functions.  It's assumed that serialize() has a parameter 'os' for
176// the ostream, and unserialize() has parameters 'cp' and 'section'.
177#define SERIALIZE_SCALAR(scalar)        paramOut(cp, #scalar, scalar)
178
179#define UNSERIALIZE_SCALAR(scalar)      paramIn(cp, #scalar, scalar)
180#define UNSERIALIZE_OPT_SCALAR(scalar)      optParamIn(cp, #scalar, scalar)
181
182// ENUMs are like SCALARs, but we cast them to ints on the way out
183#define SERIALIZE_ENUM(scalar)          paramOut(cp, #scalar, (int)scalar)
184
185#define UNSERIALIZE_ENUM(scalar)                        \
186    do {                                                \
187        int tmp;                                        \
188        paramIn(cp, #scalar, tmp);                      \
189        scalar = static_cast<decltype(scalar)>(tmp);    \
190    } while (0)
191
192#define SERIALIZE_ARRAY(member, size)           \
193        arrayParamOut(cp, #member, member, size)
194
195#define UNSERIALIZE_ARRAY(member, size)         \
196        arrayParamIn(cp, #member, member, size)
197
198#define SERIALIZE_CONTAINER(member)             \
199        arrayParamOut(cp, #member, member)
200
201#define UNSERIALIZE_CONTAINER(member)           \
202        arrayParamIn(cp, #member, member)
203
204#define SERIALIZE_EVENT(event) event.serializeSection(cp, #event);
205
206#define UNSERIALIZE_EVENT(event)                        \
207    do {                                                \
208        event.unserializeSection(cp, #event);           \
209        eventQueue()->checkpointReschedule(&event);     \
210    } while (0)
211
212#define SERIALIZE_OBJ(obj) obj.serializeSection(cp, #obj)
213#define UNSERIALIZE_OBJ(obj) obj.unserializeSection(cp, #obj)
214
215#define SERIALIZE_OBJPTR(objptr)        paramOut(cp, #objptr, (objptr)->name())
216
217#define UNSERIALIZE_OBJPTR(objptr)                      \
218    do {                                                \
219        SimObject *sptr;                                \
220        objParamIn(cp, #objptr, sptr);                  \
221        objptr = dynamic_cast<decltype(objptr)>(sptr);  \
222    } while (0)
223
224/**
225 * Basic support for object serialization.
226 *
227 * Objects that support serialization should derive from this
228 * class. Such objects can largely be divided into two categories: 1)
229 * True SimObjects (deriving from SimObject), and 2) child objects
230 * (non-SimObjects).
231 *
232 * SimObjects are serialized automatically into their own sections
233 * automatically by the SimObject base class (see
234 * SimObject::serializeAll().
235 *
236 * SimObjects can contain other serializable objects that are not
237 * SimObjects. Much like normal serialized members are not serialized
238 * automatically, these objects will not be serialized automatically
239 * and it is expected that the objects owning such serializable
240 * objects call the required serialization/unserialization methods on
241 * child objects. The preferred method to serialize a child object is
242 * to call serializeSection() on the child, which serializes the
243 * object into a new subsection in the current section. Another option
244 * is to call serialize() directly, which serializes the object into
245 * the current section. The latter is not recommended as it can lead
246 * to naming clashes between objects.
247 *
248 * @note Many objects that support serialization need to be put in a
249 * consistent state when serialization takes place. We refer to the
250 * action of forcing an object into a consistent state as
251 * 'draining'. Objects that need draining inherit from Drainable. See
252 * Drainable for more information.
253 */
254class Serializable
255{
256  protected:
257    /**
258     * Scoped checkpoint section helper class
259     *
260     * This helper class creates a section within a checkpoint without
261     * the need for a separate serializeable object. It is mainly used
262     * within the Serializable class when serializing or unserializing
263     * section (see serializeSection() and unserializeSection()). It
264     * can also be used to maintain backwards compatibility in
265     * existing code that serializes structs that are not inheriting
266     * from Serializable into subsections.
267     *
268     * When the class is instantiated, it appends a name to the active
269     * path in a checkpoint. The old path is later restored when the
270     * instance is destroyed. For example, serializeSection() could be
271     * implemented by instantiating a ScopedCheckpointSection and then
272     * calling serialize() on an object.
273     */
274    class ScopedCheckpointSection {
275      public:
276        template<class CP>
277        ScopedCheckpointSection(CP &cp, const char *name) {
278            pushName(name);
279            nameOut(cp);
280        }
281
282        template<class CP>
283        ScopedCheckpointSection(CP &cp, const std::string &name) {
284            pushName(name.c_str());
285            nameOut(cp);
286        }
287
288        ~ScopedCheckpointSection();
289
290        ScopedCheckpointSection() = delete;
291        ScopedCheckpointSection(const ScopedCheckpointSection &) = delete;
292        ScopedCheckpointSection &operator=(
293            const ScopedCheckpointSection &) = delete;
294        ScopedCheckpointSection &operator=(
295            ScopedCheckpointSection &&) = delete;
296
297      private:
298        void pushName(const char *name);
299        void nameOut(CheckpointOut &cp);
300        void nameOut(CheckpointIn &cp) {};
301    };
302
303  public:
304    Serializable();
305    virtual ~Serializable();
306
307    /**
308     * Serialize an object
309     *
310     * Output an object's state into the current checkpoint section.
311     *
312     * @param cp Checkpoint state
313     */
314    virtual void serialize(CheckpointOut &cp) const = 0;
315
316    /**
317     * Unserialize an object
318     *
319     * Read an object's state from the current checkpoint section.
320     *
321     * @param cp Checkpoint state
322     */
323    virtual void unserialize(CheckpointIn &cp) = 0;
324
325    /**
326     * Serialize an object into a new section
327     *
328     * This method creates a new section in a checkpoint and calls
329     * serialize() to serialize the current object into that
330     * section. The name of the section is appended to the current
331     * checkpoint path.
332     *
333     * @param cp Checkpoint state
334     * @param name Name to append to the active path
335     */
336    void serializeSection(CheckpointOut &cp, const char *name) const;
337
338    void serializeSection(CheckpointOut &cp, const std::string &name) const {
339        serializeSection(cp, name.c_str());
340    }
341
342    /**
343     * Unserialize an a child object
344     *
345     * This method loads a child object from a checkpoint. The object
346     * name is appended to the active path to form a fully qualified
347     * section name and unserialize() is called.
348     *
349     * @param cp Checkpoint state
350     * @param name Name to append to the active path
351     */
352    void unserializeSection(CheckpointIn &cp, const char *name);
353
354    void unserializeSection(CheckpointIn &cp, const std::string &name) {
355        unserializeSection(cp, name.c_str());
356    }
357
358    /** Get the fully-qualified name of the active section */
359    static const std::string &currentSection();
360
361    static int ckptCount;
362    static int ckptMaxCount;
363    static int ckptPrevCount;
364    static void serializeAll(const std::string &cpt_dir);
365    static void unserializeGlobals(CheckpointIn &cp);
366
367  private:
368    static std::stack<std::string> path;
369};
370
371void debug_serialize(const std::string &cpt_dir);
372
373
374class CheckpointIn
375{
376  private:
377
378    IniFile *db;
379
380    SimObjectResolver &objNameResolver;
381
382  public:
383    CheckpointIn(const std::string &cpt_dir, SimObjectResolver &resolver);
384    ~CheckpointIn();
385
386    const std::string cptDir;
387
388    bool find(const std::string &section, const std::string &entry,
389              std::string &value);
390
391    bool findObj(const std::string &section, const std::string &entry,
392                 SimObject *&value);
393
394
395    bool entryExists(const std::string &section, const std::string &entry);
396    bool sectionExists(const std::string &section);
397
398    // The following static functions have to do with checkpoint
399    // creation rather than restoration.  This class makes a handy
400    // namespace for them though.  Currently no Checkpoint object is
401    // created on serialization (only unserialization) so we track the
402    // directory name as a global.  It would be nice to change this
403    // someday
404
405  private:
406    // current directory we're serializing into.
407    static std::string currentDirectory;
408
409  public:
410    // Set the current directory.  This function takes care of
411    // inserting curTick() if there's a '%d' in the argument, and
412    // appends a '/' if necessary.  The final name is returned.
413    static std::string setDir(const std::string &base_name);
414
415    // Export current checkpoint directory name so other objects can
416    // derive filenames from it (e.g., memory).  The return value is
417    // guaranteed to end in '/' so filenames can be directly appended.
418    // This function is only valid while a checkpoint is being created.
419    static std::string dir();
420
421    // Filename for base checkpoint file within directory.
422    static const char *baseFilename;
423};
424
425#endif // __SERIALIZE_HH__
426