<commit_before>/*
 * Copyright (c) 2011 ARM Limited
 * All rights reserved
 *
 * The license below extends only to copyright in the software and shall
 * not be construed as granting a license to any other intellectual
 * property including but not limited to intellectual property relating
 * to a hardware implementation of the functionality of the software
 * licensed hereunder.  You may use the software subject to the license
 * terms below provided that you ensure that this notice is replicated
 * unmodified and in its entirety in all distributions of the software,
 * modified or unmodified, in source code or in binary form.
 *
 * Copyright (c) 2006 The Regents of The University of Michigan
 * Copyright (c) 2010 Advanced Micro Devices, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Ali Saidi
 *          Steve Reinhardt
 */

/**
 * @file
 * Definition of the Packet Class, a packet is a transaction occuring
 * between a single level of the memory heirarchy (ie L1->L2).
 */

#include <cstring>
#include <iostream>

#include "base/cprintf.hh"
#include "base/misc.hh"
#include "base/trace.hh"
#include "mem/packet.hh"

using namespace std;

// The one downside to bitsets is that static initializers can get ugly.
#define SET1(a1)                     (1 << (a1))
#define SET2(a1, a2)                 (SET1(a1) | SET1(a2))
#define SET3(a1, a2, a3)             (SET2(a1, a2) | SET1(a3))
#define SET4(a1, a2, a3, a4)         (SET3(a1, a2, a3) | SET1(a4))
#define SET5(a1, a2, a3, a4, a5)     (SET4(a1, a2, a3, a4) | SET1(a5))
#define SET6(a1, a2, a3, a4, a5, a6) (SET5(a1, a2, a3, a4, a5) | SET1(a6))

const MemCmd::CommandInfo
MemCmd::commandInfo[] =
{
    /* InvalidCmd */
    { 0, InvalidCmd, "InvalidCmd" },
    /* ReadReq */
    { SET3(IsRead, IsRequest, NeedsResponse), ReadResp, "ReadReq" },
    /* ReadResp */
    { SET3(IsRead, IsResponse, HasData), InvalidCmd, "ReadResp" },
    /* ReadRespWithInvalidate */
    { SET4(IsRead, IsResponse, HasData, IsInvalidate),
            InvalidCmd, "ReadRespWithInvalidate" },
    /* WriteReq */
    { SET5(IsWrite, NeedsExclusive, IsRequest, NeedsResponse, HasData),
            WriteResp, "WriteReq" },
    /* WriteResp */
    { SET3(IsWrite, NeedsExclusive, IsResponse), InvalidCmd, "WriteResp" },
    /* Writeback */
    { SET4(IsWrite, NeedsExclusive, IsRequest, HasData),
            InvalidCmd, "Writeback" },
    /* SoftPFReq */
    { SET4(IsRead, IsRequest, IsSWPrefetch, NeedsResponse),
            SoftPFResp, "SoftPFReq" },
    /* HardPFReq */
    { SET4(IsRead, IsRequest, IsHWPrefetch, NeedsResponse),
            HardPFResp, "HardPFReq" },
    /* SoftPFResp */
    { SET4(IsRead, IsResponse, IsSWPrefetch, HasData),
            InvalidCmd, "SoftPFResp" },
    /* HardPFResp */
    { SET4(IsRead, IsResponse, IsHWPrefetch, HasData),
            InvalidCmd, "HardPFResp" },
    /* WriteInvalidateReq */
    { SET6(IsWrite, NeedsExclusive, IsInvalidate,
           IsRequest, HasData, NeedsResponse),
            WriteInvalidateResp, "WriteInvalidateReq" },
    /* WriteInvalidateResp */
    { SET3(IsWrite, NeedsExclusive, IsResponse),
            InvalidCmd, "WriteInvalidateResp" },
    /* UpgradeReq */
    { SET5(IsInvalidate, NeedsExclusive, IsUpgrade, IsRequest, NeedsResponse),
            UpgradeResp, "UpgradeReq" },
    /* SCUpgradeReq: response could be UpgradeResp or UpgradeFailResp */
    { SET6(IsInvalidate, NeedsExclusive, IsUpgrade, IsLlsc,
           IsRequest, NeedsResponse),
            UpgradeResp, "SCUpgradeReq" },
    /* UpgradeResp */
    { SET3(NeedsExclusive, IsUpgrade, IsResponse),
            InvalidCmd, "UpgradeResp" },
    /* SCUpgradeFailReq: generates UpgradeFailResp ASAP */
    { SET5(IsInvalidate, NeedsExclusive, IsLlsc,
           IsRequest, NeedsResponse),
            UpgradeFailResp, "SCUpgradeFailReq" },
    /* UpgradeFailResp */
    { SET2(NeedsExclusive, IsResponse),
            InvalidCmd, "UpgradeFailResp" },
    /* ReadExReq */
    { SET5(IsRead, NeedsExclusive, IsInvalidate, IsRequest, NeedsResponse),
            ReadExResp, "ReadExReq" },
    /* ReadExResp */
    { SET4(IsRead, NeedsExclusive, IsResponse, HasData),
            InvalidCmd, "ReadExResp" },
    /* LoadLockedReq: note that we use plain ReadResp as response, so that
     *                we can also use ReadRespWithInvalidate when needed */
    { SET4(IsRead, IsLlsc, IsRequest, NeedsResponse),
            ReadResp, "LoadLockedReq" },
    /* StoreCondReq */
    { SET6(IsWrite, NeedsExclusive, IsLlsc,
           IsRequest, NeedsResponse, HasData),
            StoreCondResp, "StoreCondReq" },
    /* StoreCondFailReq: generates failing StoreCondResp ASAP */
    { SET6(IsWrite, NeedsExclusive, IsLlsc,
           IsRequest, NeedsResponse, HasData),
            StoreCondResp, "StoreCondFailReq" },
    /* StoreCondResp */
    { SET4(IsWrite, NeedsExclusive, IsLlsc, IsResponse),
            InvalidCmd, "StoreCondResp" },
    /* SwapReq -- for Swap ldstub type operations */
    { SET6(IsRead, IsWrite, NeedsExclusive, IsRequest, HasData, NeedsResponse),
        SwapResp, "SwapReq" },
    /* SwapResp -- for Swap ldstub type operations */
    { SET5(IsRead, IsWrite, NeedsExclusive, IsResponse, HasData),
            InvalidCmd, "SwapResp" },
    /* IntReq -- for interrupts */
    { SET4(IsWrite, IsRequest, NeedsResponse, HasData),
        MessageResp, "MessageReq" },
    /* IntResp -- for interrupts */
    { SET2(IsWrite, IsResponse), InvalidCmd, "MessageResp" },
    /* NetworkNackError  -- nacked at network layer (not by protocol) */
    { SET2(IsResponse, IsError), InvalidCmd, "NetworkNackError" },
    /* InvalidDestError  -- packet dest field invalid */
    { SET2(IsResponse, IsError), InvalidCmd, "InvalidDestError" },
    /* BadAddressError   -- memory address invalid */
    { SET2(IsResponse, IsError), InvalidCmd, "BadAddressError" },
    /* FunctionalReadError */
    { SET3(IsRead, IsResponse, IsError), InvalidCmd, "FunctionalReadError" },
    /* FunctionalWriteError */
    { SET3(IsWrite, IsResponse, IsError), InvalidCmd, "FunctionalWriteError" },
    /* PrintReq */
    { SET2(IsRequest, IsPrint), InvalidCmd, "PrintReq" },
    /* Flush Request */
    { SET3(IsRequest, IsFlush, NeedsExclusive), InvalidCmd, "FlushReq" },
};

bool
Packet::checkFunctional(Printable *obj, Addr addr, int size, uint8_t *data)
{
    Addr func_start = getAddr();
    Addr func_end   = getAddr() + getSize() - 1;
    Addr val_start  = addr;
    Addr val_end    = val_start + size - 1;

    if (func_start > val_end || val_start > func_end) {
        // no intersection
        return false;
    }

    // check print first since it doesn't require data
    if (isPrint()) {
        dynamic_cast<PrintReqState*>(senderState)->printObj(obj);
        return false;
    }

    // if there's no data, there's no need to look further
    if (!data) {
        return false;
    }

    // offset of functional request into supplied value (could be
    // negative if partial overlap)
    int offset = func_start - val_start;

    if (isRead()) {
        if (func_start >= val_start && func_end <= val_end) {
            allocate();
            memcpy(getPtr<uint8_t>(), data + offset, getSize());
            return true;
        } else {
            // Offsets and sizes to copy in case of partial overlap
            int func_offset;
            int val_offset;
            int overlap_size;

            // calculate offsets and copy sizes for the two byte arrays
            if (val_start < func_start && val_end <= func_end) {
                val_offset = func_start - val_start;
                func_offset = 0;
                overlap_size = val_end - func_start;
            } else if (val_start >= func_start && val_end > func_end) {
                val_offset = 0;
                func_offset = val_start - func_start;
                overlap_size = func_end - val_start;
            } else if (val_start >= func_start && val_end <= func_end) {
                val_offset = 0;
                func_offset = val_start - func_start;
                overlap_size = size;
            } else {
                panic("BUG: Missed a case for a partial functional request");
            }

            // Figure out how much of the partial overlap should be copied
            // into the packet and not overwrite previously found bytes.
            if (bytesValidStart == 0 && bytesValidEnd == 0) {
                // No bytes have been copied yet, just set indices
                // to found range
                bytesValidStart = func_offset;
                bytesValidEnd = func_offset + overlap_size;
            } else {
                // Some bytes have already been copied. Use bytesValid
                // indices and offset values to figure out how much data
                // to copy and where to copy it to.

                // Indice overlap conditions to check
                int a = func_offset - bytesValidStart;
                int b = (func_offset + overlap_size) - bytesValidEnd;
                int c = func_offset - bytesValidEnd;
                int d = (func_offset + overlap_size) - bytesValidStart;

                if (a >= 0 && b <= 0) {
                    // bytes already in pkt data array are superset of
                    // found bytes, will not copy any bytes
                    overlap_size = 0;
                } else if (a < 0 && d >= 0 && b <= 0) {
                    // found bytes will move bytesValidStart towards 0
                    overlap_size = bytesValidStart - func_offset;
                    bytesValidStart = func_offset;
                } else if (b > 0 && c <= 0 && a >= 0) {
                    // found bytes will move bytesValidEnd
                    // towards end of pkt data array
                    overlap_size =
                        (func_offset + overlap_size) - bytesValidEnd;
                    val_offset += bytesValidEnd - func_offset;
                    func_offset = bytesValidEnd;
                    bytesValidEnd += overlap_size;
                } else if (a < 0 && b > 0) {
                    // Found bytes are superset of copied range. Will move
                    // bytesValidStart towards 0 and bytesValidEnd towards
                    // end of pkt data array.  Need to break copy into two
                    // pieces so as to not overwrite previously found data.

                    // copy the first half
                    uint8_t *dest = getPtr<uint8_t>() + func_offset;
                    uint8_t *src = data + val_offset;
                    memcpy(dest, src, (bytesValidStart - func_offset));

                    // re-calc the offsets and indices to do the copy
                    // required for the second half
                    val_offset += (bytesValidEnd - func_offset);
                    bytesValidStart = func_offset;
                    overlap_size =
                        (func_offset + overlap_size) - bytesValidEnd;
                    func_offset = bytesValidEnd;
                    bytesValidEnd += overlap_size;
                } else if ((c > 0 && b > 0)
                           || (a < 0 && d < 0)) {
                    // region to be copied is discontiguous! Not supported.
                    panic("BUG: Discontiguous bytes found"
                          "for functional copying!");
                }
            }

            assert((bytesValidStart >= 0) && (bytesValidEnd <= getSize()));

            // copy partial data into the packet's data array
            uint8_t *dest = getPtr<uint8_t>() + func_offset;
            uint8_t *src = data + val_offset;
            memcpy(dest, src, overlap_size);

            // check if we're done filling the functional access
            bool done = (bytesValidStart == 0) && (bytesValidEnd == getSize());
            return done;
        }
    } else if (isWrite()) {
        if (offset >= 0) {
            memcpy(data + offset, getPtr<uint8_t>(),
                   (min(func_end, val_end) - func_start) + 1);
        } else {
            // val_start > func_start
            memcpy(data, getPtr<uint8_t>() - offset,
                   (min(func_end, val_end) - val_start) + 1);
        }
    } else {
        panic("Don't know how to handle command %s\n", cmdString());
    }

    // keep going with request by default
    return false;
}

void
Packet::print(ostream &o, const int verbosity, const string &prefix) const
{
    ccprintf(o, "%s[%x:%x] %s\n", prefix,
             getAddr(), getAddr() + getSize() - 1, cmdString());
}

Packet::PrintReqState::PrintReqState(ostream &_os, int _verbosity)
    : curPrefixPtr(new string("")), os(_os), verbosity(_verbosity)
{
    labelStack.push_back(LabelStackEntry("", curPrefixPtr));
}

Packet::PrintReqState::~PrintReqState()
{
    labelStack.pop_back();
    assert(labelStack.empty());
    delete curPrefixPtr;
}

Packet::PrintReqState::
LabelStackEntry::LabelStackEntry(const string &_label, string *_prefix)
    : label(_label), prefix(_prefix), labelPrinted(false)
{
}

void
Packet::PrintReqState::pushLabel(const string &lbl, const string &prefix)
{
    labelStack.push_back(LabelStackEntry(lbl, curPrefixPtr));
    curPrefixPtr = new string(*curPrefixPtr);
    *curPrefixPtr += prefix;
}

void
Packet::PrintReqState::popLabel()
{
    delete curPrefixPtr;
    curPrefixPtr = labelStack.back().prefix;
    labelStack.pop_back();
    assert(!labelStack.empty());
}

void
Packet::PrintReqState::printLabels()
{
    if (!labelStack.back().labelPrinted) {
        LabelStack::iterator i = labelStack.begin();
        LabelStack::iterator end = labelStack.end();
        while (i != end) {
            if (!i->labelPrinted) {
                ccprintf(os, "%s%s\n", *(i->prefix), i->label);
                i->labelPrinted = true;
            }
            i++;
        }
    }
}

void
Packet::PrintReqState::printObj(Printable *obj)
{
    printLabels();
    obj->print(os, verbosity, curPrefix());
}
<commit_msg>Packet: Remove meaningless assert statement<commit_after>/*
 * Copyright (c) 2011 ARM Limited
 * All rights reserved
 *
 * The license below extends only to copyright in the software and shall
 * not be construed as granting a license to any other intellectual
 * property including but not limited to intellectual property relating
 * to a hardware implementation of the functionality of the software
 * licensed hereunder.  You may use the software subject to the license
 * terms below provided that you ensure that this notice is replicated
 * unmodified and in its entirety in all distributions of the software,
 * modified or unmodified, in source code or in binary form.
 *
 * Copyright (c) 2006 The Regents of The University of Michigan
 * Copyright (c) 2010 Advanced Micro Devices, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Ali Saidi
 *          Steve Reinhardt
 */

/**
 * @file
 * Definition of the Packet Class, a packet is a transaction occuring
 * between a single level of the memory heirarchy (ie L1->L2).
 */

#include <cstring>
#include <iostream>

#include "base/cprintf.hh"
#include "base/misc.hh"
#include "base/trace.hh"
#include "mem/packet.hh"

using namespace std;

// The one downside to bitsets is that static initializers can get ugly.
#define SET1(a1)                     (1 << (a1))
#define SET2(a1, a2)                 (SET1(a1) | SET1(a2))
#define SET3(a1, a2, a3)             (SET2(a1, a2) | SET1(a3))
#define SET4(a1, a2, a3, a4)         (SET3(a1, a2, a3) | SET1(a4))
#define SET5(a1, a2, a3, a4, a5)     (SET4(a1, a2, a3, a4) | SET1(a5))
#define SET6(a1, a2, a3, a4, a5, a6) (SET5(a1, a2, a3, a4, a5) | SET1(a6))

const MemCmd::CommandInfo
MemCmd::commandInfo[] =
{
    /* InvalidCmd */
    { 0, InvalidCmd, "InvalidCmd" },
    /* ReadReq */
    { SET3(IsRead, IsRequest, NeedsResponse), ReadResp, "ReadReq" },
    /* ReadResp */
    { SET3(IsRead, IsResponse, HasData), InvalidCmd, "ReadResp" },
    /* ReadRespWithInvalidate */
    { SET4(IsRead, IsResponse, HasData, IsInvalidate),
            InvalidCmd, "ReadRespWithInvalidate" },
    /* WriteReq */
    { SET5(IsWrite, NeedsExclusive, IsRequest, NeedsResponse, HasData),
            WriteResp, "WriteReq" },
    /* WriteResp */
    { SET3(IsWrite, NeedsExclusive, IsResponse), InvalidCmd, "WriteResp" },
    /* Writeback */
    { SET4(IsWrite, NeedsExclusive, IsRequest, HasData),
            InvalidCmd, "Writeback" },
    /* SoftPFReq */
    { SET4(IsRead, IsRequest, IsSWPrefetch, NeedsResponse),
            SoftPFResp, "SoftPFReq" },
    /* HardPFReq */
    { SET4(IsRead, IsRequest, IsHWPrefetch, NeedsResponse),
            HardPFResp, "HardPFReq" },
    /* SoftPFResp */
    { SET4(IsRead, IsResponse, IsSWPrefetch, HasData),
            InvalidCmd, "SoftPFResp" },
    /* HardPFResp */
    { SET4(IsRead, IsResponse, IsHWPrefetch, HasData),
            InvalidCmd, "HardPFResp" },
    /* WriteInvalidateReq */
    { SET6(IsWrite, NeedsExclusive, IsInvalidate,
           IsRequest, HasData, NeedsResponse),
            WriteInvalidateResp, "WriteInvalidateReq" },
    /* WriteInvalidateResp */
    { SET3(IsWrite, NeedsExclusive, IsResponse),
            InvalidCmd, "WriteInvalidateResp" },
    /* UpgradeReq */
    { SET5(IsInvalidate, NeedsExclusive, IsUpgrade, IsRequest, NeedsResponse),
            UpgradeResp, "UpgradeReq" },
    /* SCUpgradeReq: response could be UpgradeResp or UpgradeFailResp */
    { SET6(IsInvalidate, NeedsExclusive, IsUpgrade, IsLlsc,
           IsRequest, NeedsResponse),
            UpgradeResp, "SCUpgradeReq" },
    /* UpgradeResp */
    { SET3(NeedsExclusive, IsUpgrade, IsResponse),
            InvalidCmd, "UpgradeResp" },
    /* SCUpgradeFailReq: generates UpgradeFailResp ASAP */
    { SET5(IsInvalidate, NeedsExclusive, IsLlsc,
           IsRequest, NeedsResponse),
            UpgradeFailResp, "SCUpgradeFailReq" },
    /* UpgradeFailResp */
    { SET2(NeedsExclusive, IsResponse),
            InvalidCmd, "UpgradeFailResp" },
    /* ReadExReq */
    { SET5(IsRead, NeedsExclusive, IsInvalidate, IsRequest, NeedsResponse),
            ReadExResp, "ReadExReq" },
    /* ReadExResp */
    { SET4(IsRead, NeedsExclusive, IsResponse, HasData),
            InvalidCmd, "ReadExResp" },
    /* LoadLockedReq: note that we use plain ReadResp as response, so that
     *                we can also use ReadRespWithInvalidate when needed */
    { SET4(IsRead, IsLlsc, IsRequest, NeedsResponse),
            ReadResp, "LoadLockedReq" },
    /* StoreCondReq */
    { SET6(IsWrite, NeedsExclusive, IsLlsc,
           IsRequest, NeedsResponse, HasData),
            StoreCondResp, "StoreCondReq" },
    /* StoreCondFailReq: generates failing StoreCondResp ASAP */
    { SET6(IsWrite, NeedsExclusive, IsLlsc,
           IsRequest, NeedsResponse, HasData),
            StoreCondResp, "StoreCondFailReq" },
    /* StoreCondResp */
    { SET4(IsWrite, NeedsExclusive, IsLlsc, IsResponse),
            InvalidCmd, "StoreCondResp" },
    /* SwapReq -- for Swap ldstub type operations */
    { SET6(IsRead, IsWrite, NeedsExclusive, IsRequest, HasData, NeedsResponse),
        SwapResp, "SwapReq" },
    /* SwapResp -- for Swap ldstub type operations */
    { SET5(IsRead, IsWrite, NeedsExclusive, IsResponse, HasData),
            InvalidCmd, "SwapResp" },
    /* IntReq -- for interrupts */
    { SET4(IsWrite, IsRequest, NeedsResponse, HasData),
        MessageResp, "MessageReq" },
    /* IntResp -- for interrupts */
    { SET2(IsWrite, IsResponse), InvalidCmd, "MessageResp" },
    /* NetworkNackError  -- nacked at network layer (not by protocol) */
    { SET2(IsResponse, IsError), InvalidCmd, "NetworkNackError" },
    /* InvalidDestError  -- packet dest field invalid */
    { SET2(IsResponse, IsError), InvalidCmd, "InvalidDestError" },
    /* BadAddressError   -- memory address invalid */
    { SET2(IsResponse, IsError), InvalidCmd, "BadAddressError" },
    /* FunctionalReadError */
    { SET3(IsRead, IsResponse, IsError), InvalidCmd, "FunctionalReadError" },
    /* FunctionalWriteError */
    { SET3(IsWrite, IsResponse, IsError), InvalidCmd, "FunctionalWriteError" },
    /* PrintReq */
    { SET2(IsRequest, IsPrint), InvalidCmd, "PrintReq" },
    /* Flush Request */
    { SET3(IsRequest, IsFlush, NeedsExclusive), InvalidCmd, "FlushReq" },
};

bool
Packet::checkFunctional(Printable *obj, Addr addr, int size, uint8_t *data)
{
    Addr func_start = getAddr();
    Addr func_end   = getAddr() + getSize() - 1;
    Addr val_start  = addr;
    Addr val_end    = val_start + size - 1;

    if (func_start > val_end || val_start > func_end) {
        // no intersection
        return false;
    }

    // check print first since it doesn't require data
    if (isPrint()) {
        dynamic_cast<PrintReqState*>(senderState)->printObj(obj);
        return false;
    }

    // if there's no data, there's no need to look further
    if (!data) {
        return false;
    }

    // offset of functional request into supplied value (could be
    // negative if partial overlap)
    int offset = func_start - val_start;

    if (isRead()) {
        if (func_start >= val_start && func_end <= val_end) {
            allocate();
            memcpy(getPtr<uint8_t>(), data + offset, getSize());
            return true;
        } else {
            // Offsets and sizes to copy in case of partial overlap
            int func_offset;
            int val_offset;
            int overlap_size;

            // calculate offsets and copy sizes for the two byte arrays
            if (val_start < func_start && val_end <= func_end) {
                val_offset = func_start - val_start;
                func_offset = 0;
                overlap_size = val_end - func_start;
            } else if (val_start >= func_start && val_end > func_end) {
                val_offset = 0;
                func_offset = val_start - func_start;
                overlap_size = func_end - val_start;
            } else if (val_start >= func_start && val_end <= func_end) {
                val_offset = 0;
                func_offset = val_start - func_start;
                overlap_size = size;
            } else {
                panic("BUG: Missed a case for a partial functional request");
            }

            // Figure out how much of the partial overlap should be copied
            // into the packet and not overwrite previously found bytes.
            if (bytesValidStart == 0 && bytesValidEnd == 0) {
                // No bytes have been copied yet, just set indices
                // to found range
                bytesValidStart = func_offset;
                bytesValidEnd = func_offset + overlap_size;
            } else {
                // Some bytes have already been copied. Use bytesValid
                // indices and offset values to figure out how much data
                // to copy and where to copy it to.

                // Indice overlap conditions to check
                int a = func_offset - bytesValidStart;
                int b = (func_offset + overlap_size) - bytesValidEnd;
                int c = func_offset - bytesValidEnd;
                int d = (func_offset + overlap_size) - bytesValidStart;

                if (a >= 0 && b <= 0) {
                    // bytes already in pkt data array are superset of
                    // found bytes, will not copy any bytes
                    overlap_size = 0;
                } else if (a < 0 && d >= 0 && b <= 0) {
                    // found bytes will move bytesValidStart towards 0
                    overlap_size = bytesValidStart - func_offset;
                    bytesValidStart = func_offset;
                } else if (b > 0 && c <= 0 && a >= 0) {
                    // found bytes will move bytesValidEnd
                    // towards end of pkt data array
                    overlap_size =
                        (func_offset + overlap_size) - bytesValidEnd;
                    val_offset += bytesValidEnd - func_offset;
                    func_offset = bytesValidEnd;
                    bytesValidEnd += overlap_size;
                } else if (a < 0 && b > 0) {
                    // Found bytes are superset of copied range. Will move
                    // bytesValidStart towards 0 and bytesValidEnd towards
                    // end of pkt data array.  Need to break copy into two
                    // pieces so as to not overwrite previously found data.

                    // copy the first half
                    uint8_t *dest = getPtr<uint8_t>() + func_offset;
                    uint8_t *src = data + val_offset;
                    memcpy(dest, src, (bytesValidStart - func_offset));

                    // re-calc the offsets and indices to do the copy
                    // required for the second half
                    val_offset += (bytesValidEnd - func_offset);
                    bytesValidStart = func_offset;
                    overlap_size =
                        (func_offset + overlap_size) - bytesValidEnd;
                    func_offset = bytesValidEnd;
                    bytesValidEnd += overlap_size;
                } else if ((c > 0 && b > 0)
                           || (a < 0 && d < 0)) {
                    // region to be copied is discontiguous! Not supported.
                    panic("BUG: Discontiguous bytes found"
                          "for functional copying!");
                }
            }

            // copy partial data into the packet's data array
            uint8_t *dest = getPtr<uint8_t>() + func_offset;
            uint8_t *src = data + val_offset;
            memcpy(dest, src, overlap_size);

            // check if we're done filling the functional access
            bool done = (bytesValidStart == 0) && (bytesValidEnd == getSize());
            return done;
        }
    } else if (isWrite()) {
        if (offset >= 0) {
            memcpy(data + offset, getPtr<uint8_t>(),
                   (min(func_end, val_end) - func_start) + 1);
        } else {
            // val_start > func_start
            memcpy(data, getPtr<uint8_t>() - offset,
                   (min(func_end, val_end) - val_start) + 1);
        }
    } else {
        panic("Don't know how to handle command %s\n", cmdString());
    }

    // keep going with request by default
    return false;
}

void
Packet::print(ostream &o, const int verbosity, const string &prefix) const
{
    ccprintf(o, "%s[%x:%x] %s\n", prefix,
             getAddr(), getAddr() + getSize() - 1, cmdString());
}

Packet::PrintReqState::PrintReqState(ostream &_os, int _verbosity)
    : curPrefixPtr(new string("")), os(_os), verbosity(_verbosity)
{
    labelStack.push_back(LabelStackEntry("", curPrefixPtr));
}

Packet::PrintReqState::~PrintReqState()
{
    labelStack.pop_back();
    assert(labelStack.empty());
    delete curPrefixPtr;
}

Packet::PrintReqState::
LabelStackEntry::LabelStackEntry(const string &_label, string *_prefix)
    : label(_label), prefix(_prefix), labelPrinted(false)
{
}

void
Packet::PrintReqState::pushLabel(const string &lbl, const string &prefix)
{
    labelStack.push_back(LabelStackEntry(lbl, curPrefixPtr));
    curPrefixPtr = new string(*curPrefixPtr);
    *curPrefixPtr += prefix;
}

void
Packet::PrintReqState::popLabel()
{
    delete curPrefixPtr;
    curPrefixPtr = labelStack.back().prefix;
    labelStack.pop_back();
    assert(!labelStack.empty());
}

void
Packet::PrintReqState::printLabels()
{
    if (!labelStack.back().labelPrinted) {
        LabelStack::iterator i = labelStack.begin();
        LabelStack::iterator end = labelStack.end();
        while (i != end) {
            if (!i->labelPrinted) {
                ccprintf(os, "%s%s\n", *(i->prefix), i->label);
                i->labelPrinted = true;
            }
            i++;
        }
    }
}

void
Packet::PrintReqState::printObj(Printable *obj)
{
    printLabels();
    obj->print(os, verbosity, curPrefix());
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2006 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Ron Dreslinski
 *          Steve Reinhardt
 *          Ali Saidi
 */

/**
 * @file
 * Declaration of the Packet class.
 */

#ifndef __MEM_PACKET_HH__
#define __MEM_PACKET_HH__

#include "mem/request.hh"
#include "sim/host.hh"
#include "sim/root.hh"
#include <list>
#include <cassert>

struct Packet;
typedef Packet* PacketPtr;
typedef uint8_t* PacketDataPtr;
typedef std::list<PacketPtr> PacketList;

//Coherence Flags
#define NACKED_LINE 1 << 0
#define SATISFIED 1 << 1
#define SHARED_LINE 1 << 2
#define CACHE_LINE_FILL 1 << 3
#define COMPRESSED 1 << 4
#define NO_ALLOCATE 1 << 5
#define SNOOP_COMMIT 1 << 6

//For statistics we need max number of commands, hard code it at
//20 for now.  @todo fix later
#define NUM_MEM_CMDS 1 << 9

/**
 * A Packet is used to encapsulate a transfer between two objects in
 * the memory system (e.g., the L1 and L2 cache).  (In contrast, a
 * single Request travels all the way from the requester to the
 * ultimate destination and back, possibly being conveyed by several
 * different Packets along the way.)
 */
class Packet
{
  public:
    /** Temporary FLAGS field until cache gets working, this should be in coherence/sender state. */
    uint64_t flags;

  private:
   /** A pointer to the data being transfered.  It can be differnt
    *    sizes at each level of the heirarchy so it belongs in the
    *    packet, not request. This may or may not be populated when a
    *    responder recieves the packet. If not populated it memory
    *    should be allocated.
    */
    PacketDataPtr data;

    /** Is the data pointer set to a value that shouldn't be freed
     *   when the packet is destroyed? */
    bool staticData;
    /** The data pointer points to a value that should be freed when
     *   the packet is destroyed. */
    bool dynamicData;
    /** the data pointer points to an array (thus delete [] ) needs to
     *   be called on it rather than simply delete.*/
    bool arrayData;

    /** The address of the request.  This address could be virtual or
     *   physical, depending on the system configuration. */
    Addr addr;

     /** The size of the request or transfer. */
    int size;

    /** Device address (e.g., bus ID) of the source of the
     *   transaction. The source is not responsible for setting this
     *   field; it is set implicitly by the interconnect when the
     *   packet * is first sent.  */
    short src;

    /** Device address (e.g., bus ID) of the destination of the
     *   transaction. The special value Broadcast indicates that the
     *   packet should be routed based on its address. This field is
     *   initialized in the constructor and is thus always valid
     *   (unlike * addr, size, and src). */
    short dest;

    /** Are the 'addr' and 'size' fields valid? */
    bool addrSizeValid;
    /** Is the 'src' field valid? */
    bool srcValid;

  public:

    /** Used to calculate latencies for each packet.*/
    Tick time;

    /** The special destination address indicating that the packet
     *   should be routed based on its address. */
    static const short Broadcast = -1;

    /** A pointer to the original request. */
    RequestPtr req;

    /** A virtual base opaque structure used to hold coherence-related
     *    state.  A specific subclass would be derived from this to
     *    carry state specific to a particular coherence protocol.  */
    class CoherenceState {
      public:
        virtual ~CoherenceState() {}
    };

    /** This packet's coherence state.  Caches should use
     *   dynamic_cast<> to cast to the state appropriate for the
     *   system's coherence protocol.  */
    CoherenceState *coherence;

    /** A virtual base opaque structure used to hold state associated
     *    with the packet but specific to the sending device (e.g., an
     *    MSHR).  A pointer to this state is returned in the packet's
     *    response so that the sender can quickly look up the state
     *    needed to process it.  A specific subclass would be derived
     *    from this to carry state specific to a particular sending
     *    device.  */
    class SenderState {
      public:
        virtual ~SenderState() {}
    };

    /** This packet's sender state.  Devices should use dynamic_cast<>
     *   to cast to the state appropriate to the sender. */
    SenderState *senderState;

  private:
    /** List of command attributes. */
    enum CommandAttribute
    {
        IsRead		= 1 << 0,
        IsWrite		= 1 << 1,
        IsPrefetch	= 1 << 2,
        IsInvalidate	= 1 << 3,
        IsRequest	= 1 << 4,
        IsResponse 	= 1 << 5,
        NeedsResponse	= 1 << 6,
        IsSWPrefetch    = 1 << 7,
        IsHWPrefetch    = 1 << 8,
        HasData		= 1 << 9
    };

  public:
    /** List of all commands associated with a packet. */
    enum Command
    {
        InvalidCmd      = 0,
        ReadReq		= IsRead  | IsRequest | NeedsResponse,
        WriteReq	= IsWrite | IsRequest | NeedsResponse,// | HasData,
        WriteReqNoAck	= IsWrite | IsRequest,// | HasData,
        ReadResp	= IsRead  | IsResponse | NeedsResponse,// | HasData,
        WriteResp	= IsWrite | IsResponse | NeedsResponse,
        Writeback       = IsWrite | IsRequest,// | HasData,
        SoftPFReq       = IsRead  | IsRequest | IsSWPrefetch | NeedsResponse,
        HardPFReq       = IsRead  | IsRequest | IsHWPrefetch | NeedsResponse,
        SoftPFResp      = IsRead  | IsResponse | IsSWPrefetch
                                | NeedsResponse,// | HasData,
        HardPFResp      = IsRead  | IsResponse | IsHWPrefetch
                                | NeedsResponse,// | HasData,
        InvalidateReq   = IsInvalidate | IsRequest,
        WriteInvalidateReq = IsWrite | IsInvalidate | IsRequest,// | HasData,
        UpgradeReq      = IsInvalidate | IsRequest | NeedsResponse,
        UpgradeResp     = IsInvalidate | IsResponse | NeedsResponse,
        ReadExReq       = IsRead | IsInvalidate | IsRequest | NeedsResponse,
        ReadExResp      = IsRead | IsInvalidate | IsResponse
                                | NeedsResponse,// | HasData
    };

    /** Return the string name of the cmd field (for debugging and
     *   tracing). */
    const std::string &cmdString() const;

    /** Reutrn the string to a cmd given by idx. */
    const std::string &cmdIdxToString(Command idx);

    /** Return the index of this command. */
    inline int cmdToIndex() const { return (int) cmd; }

    /** The command field of the packet. */
    Command cmd;

    bool isRead() 	 { return (cmd & IsRead)  != 0; }
    bool isWrite()       { return (cmd & IsWrite) != 0; }
    bool isRequest()	 { return (cmd & IsRequest)  != 0; }
    bool isResponse()	 { return (cmd & IsResponse) != 0; }
    bool needsResponse() { return (cmd & NeedsResponse) != 0; }
    bool isInvalidate()  { return (cmd & IsInvalidate) != 0; }
    bool hasData()	 { return (cmd & HasData) != 0; }

    bool isCacheFill() { return (flags & CACHE_LINE_FILL) != 0; }
    bool isNoAllocate() { return (flags & NO_ALLOCATE) != 0; }
    bool isCompressed() { return (flags & COMPRESSED) != 0; }

    bool nic_pkt() { assert("Unimplemented\n" && 0); return false; }

    /** Possible results of a packet's request. */
    enum Result
    {
        Success,
        BadAddress,
        Nacked,
        Unknown
    };

    /** The result of this packet's request. */
    Result result;

    /** Accessor function that returns the source index of the packet. */
    short getSrc() const { assert(srcValid); return src; }
    void setSrc(short _src) { src = _src; srcValid = true; }

    /** Accessor function that returns the destination index of
        the packet. */
    short getDest() const { return dest; }
    void setDest(short _dest) { dest = _dest; }

    Addr getAddr() const { assert(addrSizeValid); return addr; }
    int getSize() const { assert(addrSizeValid); return size; }
    Addr getOffset(int blkSize) const { return addr & (Addr)(blkSize - 1); }

    void addrOverride(Addr newAddr) { assert(addrSizeValid); addr = newAddr; }
    void cmdOverride(Command newCmd) { cmd = newCmd; }

    /** Constructor.  Note that a Request object must be constructed
     *   first, but the Requests's physical address and size fields
     *   need not be valid. The command and destination addresses
     *   must be supplied.  */
    Packet(Request *_req, Command _cmd, short _dest)
        :  data(NULL), staticData(false), dynamicData(false), arrayData(false),
           addr(_req->paddr), size(_req->size), dest(_dest),
           addrSizeValid(_req->validPaddr),
           srcValid(false),
           req(_req), coherence(NULL), senderState(NULL), cmd(_cmd),
           result(Unknown)
    {
        flags = 0;
        time = curTick;
    }

    /** Alternate constructor if you are trying to create a packet with
     *  a request that is for a whole block, not the address from the req.
     *  this allows for overriding the size/addr of the req.*/
    Packet(Request *_req, Command _cmd, short _dest, int _blkSize)
        :  data(NULL), staticData(false), dynamicData(false), arrayData(false),
           addr(_req->paddr & ~(_blkSize - 1)), size(_blkSize),
           dest(_dest),
           addrSizeValid(_req->validPaddr), srcValid(false),
           req(_req), coherence(NULL), senderState(NULL), cmd(_cmd),
           result(Unknown)
    {
        flags = 0;
        time = curTick;
    }

    /** Destructor. */
    ~Packet()
    { deleteData(); }

    /** Reinitialize packet address and size from the associated
     *   Request object, and reset other fields that may have been
     *   modified by a previous transaction.  Typically called when a
     *   statically allocated Request/Packet pair is reused for
     *   multiple transactions. */
    void reinitFromRequest() {
        assert(req->validPaddr);
        addr = req->paddr;
        size = req->size;
        time = req->time;
        addrSizeValid = true;
        result = Unknown;
        if (dynamicData) {
            deleteData();
            dynamicData = false;
            arrayData = false;
        }
    }

    /** Take a request packet and modify it in place to be suitable
     *   for returning as a response to that request.  Used for timing
     *   accesses only.  For atomic and functional accesses, the
     *   request packet is always implicitly passed back *without*
     *   modifying the command or destination fields, so this function
     *   should not be called. */
    void makeTimingResponse() {
        assert(needsResponse());
        assert(isRequest());
        int icmd = (int)cmd;
        icmd &= ~(IsRequest);
        icmd |= IsResponse;
        cmd = (Command)icmd;
        dest = src;
        srcValid = false;
    }

    /** Take a request packet that has been returned as NACKED and modify it so
     * that it can be sent out again. Only packets that need a response can be
     * NACKED, so verify that that is true. */
    void reinitNacked() {
        assert(needsResponse() && result == Nacked);
        dest =  Broadcast;
        result = Unknown;
    }

    /** Set the data pointer to the following value that should not be freed. */
    template <typename T>
    void dataStatic(T *p);

    /** Set the data pointer to a value that should have delete [] called on it.
     */
    template <typename T>
    void dataDynamicArray(T *p);

    /** set the data pointer to a value that should have delete called on it. */
    template <typename T>
    void dataDynamic(T *p);

    /** return the value of what is pointed to in the packet. */
    template <typename T>
    T get();

    /** get a pointer to the data ptr. */
    template <typename T>
    T* getPtr();

    /** set the value in the data pointer to v. */
    template <typename T>
    void set(T v);

    /** delete the data pointed to in the data pointer. Ok to call to matter how
     * data was allocted. */
    void deleteData();

    /** If there isn't data in the packet, allocate some. */
    void allocate();

    /** Do the packet modify the same addresses. */
    bool intersect(Packet *p);
};

bool fixPacket(Packet *func, Packet *timing);
#endif //__MEM_PACKET_HH
<commit_msg>Add in HasData, and move the define of NUM_MEM_CMDS to a more visible location.<commit_after>/*
 * Copyright (c) 2006 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Ron Dreslinski
 *          Steve Reinhardt
 *          Ali Saidi
 */

/**
 * @file
 * Declaration of the Packet class.
 */

#ifndef __MEM_PACKET_HH__
#define __MEM_PACKET_HH__

#include "mem/request.hh"
#include "sim/host.hh"
#include "sim/root.hh"
#include <list>
#include <cassert>

struct Packet;
typedef Packet* PacketPtr;
typedef uint8_t* PacketDataPtr;
typedef std::list<PacketPtr> PacketList;

//Coherence Flags
#define NACKED_LINE 1 << 0
#define SATISFIED 1 << 1
#define SHARED_LINE 1 << 2
#define CACHE_LINE_FILL 1 << 3
#define COMPRESSED 1 << 4
#define NO_ALLOCATE 1 << 5
#define SNOOP_COMMIT 1 << 6

/**
 * A Packet is used to encapsulate a transfer between two objects in
 * the memory system (e.g., the L1 and L2 cache).  (In contrast, a
 * single Request travels all the way from the requester to the
 * ultimate destination and back, possibly being conveyed by several
 * different Packets along the way.)
 */
class Packet
{
  public:
    /** Temporary FLAGS field until cache gets working, this should be in coherence/sender state. */
    uint64_t flags;

  private:
   /** A pointer to the data being transfered.  It can be differnt
    *    sizes at each level of the heirarchy so it belongs in the
    *    packet, not request. This may or may not be populated when a
    *    responder recieves the packet. If not populated it memory
    *    should be allocated.
    */
    PacketDataPtr data;

    /** Is the data pointer set to a value that shouldn't be freed
     *   when the packet is destroyed? */
    bool staticData;
    /** The data pointer points to a value that should be freed when
     *   the packet is destroyed. */
    bool dynamicData;
    /** the data pointer points to an array (thus delete [] ) needs to
     *   be called on it rather than simply delete.*/
    bool arrayData;

    /** The address of the request.  This address could be virtual or
     *   physical, depending on the system configuration. */
    Addr addr;

     /** The size of the request or transfer. */
    int size;

    /** Device address (e.g., bus ID) of the source of the
     *   transaction. The source is not responsible for setting this
     *   field; it is set implicitly by the interconnect when the
     *   packet * is first sent.  */
    short src;

    /** Device address (e.g., bus ID) of the destination of the
     *   transaction. The special value Broadcast indicates that the
     *   packet should be routed based on its address. This field is
     *   initialized in the constructor and is thus always valid
     *   (unlike * addr, size, and src). */
    short dest;

    /** Are the 'addr' and 'size' fields valid? */
    bool addrSizeValid;
    /** Is the 'src' field valid? */
    bool srcValid;

  public:

    /** Used to calculate latencies for each packet.*/
    Tick time;

    /** The special destination address indicating that the packet
     *   should be routed based on its address. */
    static const short Broadcast = -1;

    /** A pointer to the original request. */
    RequestPtr req;

    /** A virtual base opaque structure used to hold coherence-related
     *    state.  A specific subclass would be derived from this to
     *    carry state specific to a particular coherence protocol.  */
    class CoherenceState {
      public:
        virtual ~CoherenceState() {}
    };

    /** This packet's coherence state.  Caches should use
     *   dynamic_cast<> to cast to the state appropriate for the
     *   system's coherence protocol.  */
    CoherenceState *coherence;

    /** A virtual base opaque structure used to hold state associated
     *    with the packet but specific to the sending device (e.g., an
     *    MSHR).  A pointer to this state is returned in the packet's
     *    response so that the sender can quickly look up the state
     *    needed to process it.  A specific subclass would be derived
     *    from this to carry state specific to a particular sending
     *    device.  */
    class SenderState {
      public:
        virtual ~SenderState() {}
    };

    /** This packet's sender state.  Devices should use dynamic_cast<>
     *   to cast to the state appropriate to the sender. */
    SenderState *senderState;

  private:
    /** List of command attributes. */
    // If you add a new CommandAttribute, make sure to increase NUM_MEM_CMDS
    // as well.
    enum CommandAttribute
    {
        IsRead		= 1 << 0,
        IsWrite		= 1 << 1,
        IsPrefetch	= 1 << 2,
        IsInvalidate	= 1 << 3,
        IsRequest	= 1 << 4,
        IsResponse 	= 1 << 5,
        NeedsResponse	= 1 << 6,
        IsSWPrefetch    = 1 << 7,
        IsHWPrefetch    = 1 << 8,
        HasData		= 1 << 9
    };

//For statistics we need max number of commands, hard code it at
//20 for now.  @todo fix later
#define NUM_MEM_CMDS 1 << 10

  public:
    /** List of all commands associated with a packet. */
    enum Command
    {
        InvalidCmd      = 0,
        ReadReq		= IsRead  | IsRequest | NeedsResponse,
        WriteReq	= IsWrite | IsRequest | NeedsResponse | HasData,
        WriteReqNoAck	= IsWrite | IsRequest | HasData,
        ReadResp	= IsRead  | IsResponse | NeedsResponse | HasData,
        WriteResp	= IsWrite | IsResponse | NeedsResponse,
        Writeback       = IsWrite | IsRequest | HasData,
        SoftPFReq       = IsRead  | IsRequest | IsSWPrefetch | NeedsResponse,
        HardPFReq       = IsRead  | IsRequest | IsHWPrefetch | NeedsResponse,
        SoftPFResp      = IsRead  | IsResponse | IsSWPrefetch
                                | NeedsResponse | HasData,
        HardPFResp      = IsRead  | IsResponse | IsHWPrefetch
                                | NeedsResponse | HasData,
        InvalidateReq   = IsInvalidate | IsRequest,
        WriteInvalidateReq = IsWrite | IsInvalidate | IsRequest | HasData,
        UpgradeReq      = IsInvalidate | IsRequest | NeedsResponse,
        UpgradeResp     = IsInvalidate | IsResponse | NeedsResponse,
        ReadExReq       = IsRead | IsInvalidate | IsRequest | NeedsResponse,
        ReadExResp      = IsRead | IsInvalidate | IsResponse
                                | NeedsResponse | HasData
    };

    /** Return the string name of the cmd field (for debugging and
     *   tracing). */
    const std::string &cmdString() const;

    /** Reutrn the string to a cmd given by idx. */
    const std::string &cmdIdxToString(Command idx);

    /** Return the index of this command. */
    inline int cmdToIndex() const { return (int) cmd; }

    /** The command field of the packet. */
    Command cmd;

    bool isRead() 	 { return (cmd & IsRead)  != 0; }
    bool isWrite()       { return (cmd & IsWrite) != 0; }
    bool isRequest()	 { return (cmd & IsRequest)  != 0; }
    bool isResponse()	 { return (cmd & IsResponse) != 0; }
    bool needsResponse() { return (cmd & NeedsResponse) != 0; }
    bool isInvalidate()  { return (cmd & IsInvalidate) != 0; }
    bool hasData()	 { return (cmd & HasData) != 0; }

    bool isCacheFill() { return (flags & CACHE_LINE_FILL) != 0; }
    bool isNoAllocate() { return (flags & NO_ALLOCATE) != 0; }
    bool isCompressed() { return (flags & COMPRESSED) != 0; }

    bool nic_pkt() { assert("Unimplemented\n" && 0); return false; }

    /** Possible results of a packet's request. */
    enum Result
    {
        Success,
        BadAddress,
        Nacked,
        Unknown
    };

    /** The result of this packet's request. */
    Result result;

    /** Accessor function that returns the source index of the packet. */
    short getSrc() const { assert(srcValid); return src; }
    void setSrc(short _src) { src = _src; srcValid = true; }

    /** Accessor function that returns the destination index of
        the packet. */
    short getDest() const { return dest; }
    void setDest(short _dest) { dest = _dest; }

    Addr getAddr() const { assert(addrSizeValid); return addr; }
    int getSize() const { assert(addrSizeValid); return size; }
    Addr getOffset(int blkSize) const { return addr & (Addr)(blkSize - 1); }

    void addrOverride(Addr newAddr) { assert(addrSizeValid); addr = newAddr; }
    void cmdOverride(Command newCmd) { cmd = newCmd; }

    /** Constructor.  Note that a Request object must be constructed
     *   first, but the Requests's physical address and size fields
     *   need not be valid. The command and destination addresses
     *   must be supplied.  */
    Packet(Request *_req, Command _cmd, short _dest)
        :  data(NULL), staticData(false), dynamicData(false), arrayData(false),
           addr(_req->paddr), size(_req->size), dest(_dest),
           addrSizeValid(_req->validPaddr),
           srcValid(false),
           req(_req), coherence(NULL), senderState(NULL), cmd(_cmd),
           result(Unknown)
    {
        flags = 0;
        time = curTick;
    }

    /** Alternate constructor if you are trying to create a packet with
     *  a request that is for a whole block, not the address from the req.
     *  this allows for overriding the size/addr of the req.*/
    Packet(Request *_req, Command _cmd, short _dest, int _blkSize)
        :  data(NULL), staticData(false), dynamicData(false), arrayData(false),
           addr(_req->paddr & ~(_blkSize - 1)), size(_blkSize),
           dest(_dest),
           addrSizeValid(_req->validPaddr), srcValid(false),
           req(_req), coherence(NULL), senderState(NULL), cmd(_cmd),
           result(Unknown)
    {
        flags = 0;
        time = curTick;
    }

    /** Destructor. */
    ~Packet()
    { deleteData(); }

    /** Reinitialize packet address and size from the associated
     *   Request object, and reset other fields that may have been
     *   modified by a previous transaction.  Typically called when a
     *   statically allocated Request/Packet pair is reused for
     *   multiple transactions. */
    void reinitFromRequest() {
        assert(req->validPaddr);
        addr = req->paddr;
        size = req->size;
        time = req->time;
        addrSizeValid = true;
        result = Unknown;
        if (dynamicData) {
            deleteData();
            dynamicData = false;
            arrayData = false;
        }
    }

    /** Take a request packet and modify it in place to be suitable
     *   for returning as a response to that request.  Used for timing
     *   accesses only.  For atomic and functional accesses, the
     *   request packet is always implicitly passed back *without*
     *   modifying the command or destination fields, so this function
     *   should not be called. */
    void makeTimingResponse() {
        assert(needsResponse());
        assert(isRequest());
        int icmd = (int)cmd;
        icmd &= ~(IsRequest);
        icmd |= IsResponse;
        cmd = (Command)icmd;
        dest = src;
        srcValid = false;
    }

    /** Take a request packet that has been returned as NACKED and modify it so
     * that it can be sent out again. Only packets that need a response can be
     * NACKED, so verify that that is true. */
    void reinitNacked() {
        assert(needsResponse() && result == Nacked);
        dest =  Broadcast;
        result = Unknown;
    }

    /** Set the data pointer to the following value that should not be freed. */
    template <typename T>
    void dataStatic(T *p);

    /** Set the data pointer to a value that should have delete [] called on it.
     */
    template <typename T>
    void dataDynamicArray(T *p);

    /** set the data pointer to a value that should have delete called on it. */
    template <typename T>
    void dataDynamic(T *p);

    /** return the value of what is pointed to in the packet. */
    template <typename T>
    T get();

    /** get a pointer to the data ptr. */
    template <typename T>
    T* getPtr();

    /** set the value in the data pointer to v. */
    template <typename T>
    void set(T v);

    /** delete the data pointed to in the data pointer. Ok to call to matter how
     * data was allocted. */
    void deleteData();

    /** If there isn't data in the packet, allocate some. */
    void allocate();

    /** Do the packet modify the same addresses. */
    bool intersect(Packet *p);
};

bool fixPacket(Packet *func, Packet *timing);
#endif //__MEM_PACKET_HH
<|endoftext|>


<commit_before>//
// posix_main.cpp
// ~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2008 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Modifed by Geoff Lawler, SPARTA, inc. 2008.
//

#include <iostream>
#include <string>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <boost/shared_ptr.hpp>
#include "server.h"

#if !defined(_WIN32)

#include <pthread.h>
#include <signal.h>

#include "logger.h"
#include "libconfig.h++"
#include "initConfig.h"
#include "singletonConfig.h"
#include "watcherd.h"

using namespace std;
using namespace watcher;
using namespace libconfig;

int main(int argc, char* argv[])
{
    TRACE_ENTER();

    string configFilename;
    Config &config=SingletonConfig::instance();
    SingletonConfig::lock();
    if (false==initConfig(config, argc, argv, configFilename))
    {
        cerr << "Error reading configuration file, unable to continue." << endl;
        cerr << "Usage: " << basename(argv[0]) << " [-c|--configFile] configfile" << endl;
        return 1;
    }
    SingletonConfig::unlock();

    string logConf("log.properties");
    if (!config.lookupValue("logPropertiesFile", logConf))
    {
        cout << "Unable to find logPropertiesFile setting in the configuration file, using default: " << logConf
             << " and adding it to the configuration file." << endl;
        config.getRoot().add("logPropertiesFile", libconfig::Setting::TypeString)=logConf;
    }

    LOAD_LOG_PROPS(logConf);

    LOG_INFO("Logger initialized from file \"" << logConf << "\"");

    string address("glory");
    string port("8095");
    size_t numThreads;

    if (!config.lookupValue("server", address))
    {
        LOG_INFO("'server' not found in the configuration file, using default: " << address
                << " and adding this to the configuration file.");
        config.getRoot().add("server", libconfig::Setting::TypeString) = address;
    }

    if (!config.lookupValue("port", port))
    {
        LOG_INFO("'port' not found in the configuration file, using default: " << port
                << " and adding this to the configuration file.");
        config.getRoot().add("port", libconfig::Setting::TypeString)=port;
    }

    if (!config.lookupValue("serverThreadNum", numThreads))
    {
        LOG_INFO("'serverThreadNum' not found in the configuration file, using default: " << numThreads
                << " and adding this to the configuration file.")
           config.getRoot().add("serverThreadNum", libconfig::Setting::TypeInt)=static_cast<int>(numThreads);
    }

    WatcherdPtr theWatcherDaemon(new Watcherd);
    try
    {
        theWatcherDaemon->run(address, port, (int)numThreads);
    }
    catch (std::exception &e)
    {
        LOG_FATAL("Caught exception in main(): " << e.what());
        std::cerr << "exception: " << e.what() << "\n";
    }

    // Save any configuration changes made during the run.
    LOG_INFO("Saving last known configuration to " << configFilename);
    SingletonConfig::lock();
    config.writeFile(configFilename.c_str());

    return 0;
}

#endif // !defined(_WIN32)
<commit_msg>add config for sqlite database file<commit_after>//
// posix_main.cpp
// ~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2008 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Modifed by Geoff Lawler, SPARTA, inc. 2008.
//

#include <iostream>
#include <string>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <boost/shared_ptr.hpp>
#include "server.h"

#if !defined(_WIN32)

#include <pthread.h>
#include <signal.h>

#include "logger.h"
#include "libconfig.h++"
#include "initConfig.h"
#include "singletonConfig.h"
#include "watcherd.h"

using namespace std;
using namespace watcher;
using namespace libconfig;

int main(int argc, char* argv[])
{
    TRACE_ENTER();

    string configFilename;
    Config &config=SingletonConfig::instance();
    SingletonConfig::lock();
    if (false==initConfig(config, argc, argv, configFilename))
    {
        cerr << "Error reading configuration file, unable to continue." << endl;
        cerr << "Usage: " << basename(argv[0]) << " [-c|--configFile] configfile" << endl;
        return 1;
    }
    SingletonConfig::unlock();

    string logConf("log.properties");
    if (!config.lookupValue("logPropertiesFile", logConf))
    {
        cout << "Unable to find logPropertiesFile setting in the configuration file, using default: " << logConf
             << " and adding it to the configuration file." << endl;
        config.getRoot().add("logPropertiesFile", libconfig::Setting::TypeString)=logConf;
    }

    LOAD_LOG_PROPS(logConf);

    LOG_INFO("Logger initialized from file \"" << logConf << "\"");

    string address("glory");
    string port("8095");
    size_t numThreads;
    std::string dbPath("event.db");

    if (!config.lookupValue("server", address))
    {
        LOG_INFO("'server' not found in the configuration file, using default: " << address
                << " and adding this to the configuration file.");
        config.getRoot().add("server", libconfig::Setting::TypeString) = address;
    }

    if (!config.lookupValue("port", port))
    {
        LOG_INFO("'port' not found in the configuration file, using default: " << port
                << " and adding this to the configuration file.");
        config.getRoot().add("port", libconfig::Setting::TypeString)=port;
    }

    if (!config.lookupValue("serverThreadNum", numThreads))
    {
        LOG_INFO("'serverThreadNum' not found in the configuration file, using default: " << numThreads
                << " and adding this to the configuration file.")
           config.getRoot().add("serverThreadNum", libconfig::Setting::TypeInt)=static_cast<int>(numThreads);
    }

    if (!config.lookupValue("databasePath", dbPath))
    {
        LOG_INFO("'databasePath' not found in the configuration file, using default: " << dbPath
                << " and adding this to the configuration file.")
           config.getRoot().add("databasePath", libconfig::Setting::TypeString)=dbPath;
    }

    WatcherdPtr theWatcherDaemon(new Watcherd);
    try
    {
        theWatcherDaemon->run(address, port, (int)numThreads);
    }
    catch (std::exception &e)
    {
        LOG_FATAL("Caught exception in main(): " << e.what());
        std::cerr << "exception: " << e.what() << "\n";
    }

    // Save any configuration changes made during the run.
    LOG_INFO("Saving last known configuration to " << configFilename);
    SingletonConfig::lock();
    config.writeFile(configFilename.c_str());

    return 0;
}

#endif // !defined(_WIN32)
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: txtparaimphint.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2004-09-09 10:49:08 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _XMLOFF_TXTPARAIMPHINT_HXX
#define _XMLOFF_TXTPARAIMPHINT_HXX

#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif

#ifndef _SVARRAY_HXX
#include <svtools/svarray.hxx>
#endif

#ifndef _XMLOFF_XMLIMP_HXX
#include "xmlimp.hxx"
#endif
#ifndef _XMLTEXTFRAMECONTEXT_HXX
#include "XMLTextFrameContext.hxx"
#endif
#ifndef _XMLOFF_XMLEVENTSIMPORTCONTEXT_HXX
#include "XMLEventsImportContext.hxx"
#endif

using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::text;
using namespace ::xmloff::token;

// ---------------------------------------------------------------------

#define XML_HINT_STYLE 1
#define XML_HINT_REFERENCE 2
#define XML_HINT_HYPERLINK 3
#define XML_HINT_RUBY 4
#define XML_HINT_INDEX_MARK 5
#define XML_HINT_TEXT_FRAME 6
// --> DVO, OD 2004-07-14 #i26791#
#define XML_HINT_DRAW 7
// <--

class XMLHint_Impl
{
    Reference < XTextRange > xStart;
    Reference < XTextRange > xEnd;

    sal_uInt8 nType;

public:

    XMLHint_Impl( sal_uInt8 nTyp,
                  const Reference < XTextRange > & rS,
                  const Reference < XTextRange > & rE ) :
        nType( nTyp ),
        xStart( rS ),
        xEnd( rE )
    {
    }

    XMLHint_Impl( sal_uInt8 nTyp,
                  const Reference < XTextRange > & rS ) :
        nType( nTyp ),
        xStart( rS )
    {
    }

    virtual ~XMLHint_Impl() {}

    const Reference < XTextRange > & GetStart() const { return xStart; }
    const Reference < XTextRange > & GetEnd() const { return xEnd; }
    void SetEnd( const Reference < XTextRange > & rPos ) { xEnd = rPos; }

    // We don't use virtual methods to differ between the sub classes,
    // because this seems to be to expensive if compared to inline methods.
    sal_uInt8 GetType() const { return nType; }
    sal_Bool IsStyle() { return XML_HINT_STYLE==nType; }
    sal_Bool IsReference() { return XML_HINT_REFERENCE==nType; }
    sal_Bool IsHyperlink() { return XML_HINT_HYPERLINK==nType; }
    sal_Bool IsIndexMark() { return XML_HINT_INDEX_MARK==nType; }
};

class XMLStyleHint_Impl : public XMLHint_Impl
{
    OUString                 sStyleName;

public:

    XMLStyleHint_Impl( const OUString& rStyleName,
                         const Reference < XTextRange > & rPos ) :
        XMLHint_Impl( XML_HINT_STYLE, rPos, rPos ),
        sStyleName( rStyleName )
    {
    }
    virtual ~XMLStyleHint_Impl() {}

    const OUString& GetStyleName() const { return sStyleName; }
};

class XMLReferenceHint_Impl : public XMLHint_Impl
{
    OUString                 sRefName;

public:

    XMLReferenceHint_Impl( const OUString& rRefName,
                             const Reference < XTextRange > & rPos ) :
        XMLHint_Impl( XML_HINT_REFERENCE, rPos, rPos ),
        sRefName( rRefName )
    {
    }

    virtual ~XMLReferenceHint_Impl() {}

    const OUString& GetRefName() const { return sRefName; }
};

class XMLHyperlinkHint_Impl : public XMLHint_Impl
{
    OUString                 sHRef;
    OUString                 sName;
    OUString                 sTargetFrameName;
    OUString                 sStyleName;
    OUString                 sVisitedStyleName;
    XMLEventsImportContext*  pEvents;

public:

    XMLHyperlinkHint_Impl( const Reference < XTextRange > & rPos ) :
        XMLHint_Impl( XML_HINT_HYPERLINK, rPos, rPos ),
        pEvents( NULL )
    {
    }

    virtual ~XMLHyperlinkHint_Impl()
    {
        if (NULL != pEvents)
            pEvents->ReleaseRef();
    }

    void SetHRef( const OUString& s ) { sHRef = s; }
    const OUString& GetHRef() const { return sHRef; }
    void SetName( const OUString& s ) { sName = s; }
    const OUString& GetName() const { return sName; }
    void SetTargetFrameName( const OUString& s ) { sTargetFrameName = s; }
    const OUString& GetTargetFrameName() const { return sTargetFrameName; }
    void SetStyleName( const OUString& s ) { sStyleName = s; }
    const OUString& GetStyleName() const { return sStyleName; }
    void SetVisitedStyleName( const OUString& s ) { sVisitedStyleName = s; }
    const OUString& GetVisitedStyleName() const { return sVisitedStyleName; }
    XMLEventsImportContext* GetEventsContext() const
    {
        return pEvents;
    }
    void SetEventsContext( XMLEventsImportContext* pCtxt )
    {
        pEvents = pCtxt;
        if (pEvents != NULL)
            pEvents->AddRef();
    }
};

class XMLIndexMarkHint_Impl : public XMLHint_Impl
{
    const Reference<beans::XPropertySet> xIndexMarkPropSet;

    const OUString sID;

public:

    XMLIndexMarkHint_Impl( const Reference < beans::XPropertySet > & rPropSet,
                           const Reference < XTextRange > & rPos ) :
        XMLHint_Impl( XML_HINT_INDEX_MARK, rPos, rPos ),
        xIndexMarkPropSet( rPropSet ),
        sID()
    {
    }

    XMLIndexMarkHint_Impl( const Reference < beans::XPropertySet > & rPropSet,
                           const Reference < XTextRange > & rPos,
                           OUString sIDString) :
        XMLHint_Impl( XML_HINT_INDEX_MARK, rPos, rPos ),
        xIndexMarkPropSet( rPropSet ),
        sID(sIDString)
    {
    }

    virtual ~XMLIndexMarkHint_Impl() {}

    const Reference<beans::XPropertySet> & GetMark() const
        { return xIndexMarkPropSet; }
    const OUString& GetID() const { return sID; }
};

class XMLRubyHint_Impl : public XMLHint_Impl
{
    OUString                 sStyleName;
    OUString                 sTextStyleName;
    OUString                 sText;

public:

    XMLRubyHint_Impl( const Reference < XTextRange > & rPos ) :
        XMLHint_Impl( XML_HINT_RUBY, rPos, rPos )
    {
    }

    virtual ~XMLRubyHint_Impl() {}

    void SetStyleName( const OUString& s ) { sStyleName = s; }
    const OUString& GetStyleName() const { return sStyleName; }
    void SetTextStyleName( const OUString& s ) { sTextStyleName = s; }
    const OUString& GetTextStyleName() const { return sTextStyleName; }
    void AppendText( const OUString& s ) { sText += s; }
    const OUString& GetText() const { return sText; }
};

class XMLTextFrameHint_Impl : public XMLHint_Impl
{
    // OD 2004-04-20 #i26791#
    SvXMLImportContextRef xContext;

public:

    XMLTextFrameHint_Impl( SvXMLImportContext* pContext,
                           const Reference < XTextRange > & rPos ) :
        XMLHint_Impl( XML_HINT_TEXT_FRAME, rPos, rPos ),
        xContext( pContext )
    {
    }

    virtual ~XMLTextFrameHint_Impl()
    {
    }

    Reference < XTextContent > GetTextContent() const
    {
        Reference <XTextContent > xTxt;
        SvXMLImportContext *pContext = &xContext;
        if( pContext->ISA( XMLTextFrameContext ) )
            xTxt = PTR_CAST( XMLTextFrameContext, pContext )->GetTextContent();
        else if( pContext->ISA( XMLTextFrameHyperlinkContext ) )
            xTxt = PTR_CAST( XMLTextFrameHyperlinkContext, pContext )
                        ->GetTextContent();

        return xTxt;
    }

    // --> OD 2004-08-24 #i33242#
    Reference < drawing::XShape > GetShape() const
    {
        Reference < drawing::XShape > xShape;
        SvXMLImportContext *pContext = &xContext;
        if( pContext->ISA( XMLTextFrameContext ) )
            xShape = PTR_CAST( XMLTextFrameContext, pContext )->GetShape();
        else if( pContext->ISA( XMLTextFrameHyperlinkContext ) )
            xShape = PTR_CAST( XMLTextFrameHyperlinkContext, pContext )->GetShape();

        return xShape;
    }
    // <--

    sal_Bool IsBoundAtChar() const
    {
        sal_Bool bRet = sal_False;
        SvXMLImportContext *pContext = &xContext;
        if( pContext->ISA( XMLTextFrameContext ) )
            bRet = TextContentAnchorType_AT_CHARACTER ==
                PTR_CAST( XMLTextFrameContext, pContext )
                    ->GetAnchorType();
        else if( pContext->ISA( XMLTextFrameHyperlinkContext ) )
            bRet = TextContentAnchorType_AT_CHARACTER ==
                PTR_CAST( XMLTextFrameHyperlinkContext, pContext )
                    ->GetAnchorType();
        return bRet;
    }
};

// --> DVO, OD 2004-07-14 #i26791#
class XMLDrawHint_Impl : public XMLHint_Impl
{
    SvXMLImportContextRef xContext;

public:

    XMLDrawHint_Impl( SvXMLShapeContext* pContext,
                      const Reference < XTextRange > & rPos ) :
        XMLHint_Impl( XML_HINT_DRAW, rPos, rPos ),
        xContext( pContext )
    {
    }

    virtual ~XMLDrawHint_Impl()
    {
    }

    // --> OD 2004-08-24 #i33242#
    Reference < drawing::XShape > GetShape() const
    {
        return static_cast<SvXMLShapeContext*>(&xContext)->getShape();
    }
    // <--
};
// <--
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.5.264); FILE MERGED 2005/09/05 14:40:10 rt 1.5.264.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: txtparaimphint.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 15:32:05 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _XMLOFF_TXTPARAIMPHINT_HXX
#define _XMLOFF_TXTPARAIMPHINT_HXX

#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif

#ifndef _SVARRAY_HXX
#include <svtools/svarray.hxx>
#endif

#ifndef _XMLOFF_XMLIMP_HXX
#include "xmlimp.hxx"
#endif
#ifndef _XMLTEXTFRAMECONTEXT_HXX
#include "XMLTextFrameContext.hxx"
#endif
#ifndef _XMLOFF_XMLEVENTSIMPORTCONTEXT_HXX
#include "XMLEventsImportContext.hxx"
#endif

using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::text;
using namespace ::xmloff::token;

// ---------------------------------------------------------------------

#define XML_HINT_STYLE 1
#define XML_HINT_REFERENCE 2
#define XML_HINT_HYPERLINK 3
#define XML_HINT_RUBY 4
#define XML_HINT_INDEX_MARK 5
#define XML_HINT_TEXT_FRAME 6
// --> DVO, OD 2004-07-14 #i26791#
#define XML_HINT_DRAW 7
// <--

class XMLHint_Impl
{
    Reference < XTextRange > xStart;
    Reference < XTextRange > xEnd;

    sal_uInt8 nType;

public:

    XMLHint_Impl( sal_uInt8 nTyp,
                  const Reference < XTextRange > & rS,
                  const Reference < XTextRange > & rE ) :
        nType( nTyp ),
        xStart( rS ),
        xEnd( rE )
    {
    }

    XMLHint_Impl( sal_uInt8 nTyp,
                  const Reference < XTextRange > & rS ) :
        nType( nTyp ),
        xStart( rS )
    {
    }

    virtual ~XMLHint_Impl() {}

    const Reference < XTextRange > & GetStart() const { return xStart; }
    const Reference < XTextRange > & GetEnd() const { return xEnd; }
    void SetEnd( const Reference < XTextRange > & rPos ) { xEnd = rPos; }

    // We don't use virtual methods to differ between the sub classes,
    // because this seems to be to expensive if compared to inline methods.
    sal_uInt8 GetType() const { return nType; }
    sal_Bool IsStyle() { return XML_HINT_STYLE==nType; }
    sal_Bool IsReference() { return XML_HINT_REFERENCE==nType; }
    sal_Bool IsHyperlink() { return XML_HINT_HYPERLINK==nType; }
    sal_Bool IsIndexMark() { return XML_HINT_INDEX_MARK==nType; }
};

class XMLStyleHint_Impl : public XMLHint_Impl
{
    OUString                 sStyleName;

public:

    XMLStyleHint_Impl( const OUString& rStyleName,
                         const Reference < XTextRange > & rPos ) :
        XMLHint_Impl( XML_HINT_STYLE, rPos, rPos ),
        sStyleName( rStyleName )
    {
    }
    virtual ~XMLStyleHint_Impl() {}

    const OUString& GetStyleName() const { return sStyleName; }
};

class XMLReferenceHint_Impl : public XMLHint_Impl
{
    OUString                 sRefName;

public:

    XMLReferenceHint_Impl( const OUString& rRefName,
                             const Reference < XTextRange > & rPos ) :
        XMLHint_Impl( XML_HINT_REFERENCE, rPos, rPos ),
        sRefName( rRefName )
    {
    }

    virtual ~XMLReferenceHint_Impl() {}

    const OUString& GetRefName() const { return sRefName; }
};

class XMLHyperlinkHint_Impl : public XMLHint_Impl
{
    OUString                 sHRef;
    OUString                 sName;
    OUString                 sTargetFrameName;
    OUString                 sStyleName;
    OUString                 sVisitedStyleName;
    XMLEventsImportContext*  pEvents;

public:

    XMLHyperlinkHint_Impl( const Reference < XTextRange > & rPos ) :
        XMLHint_Impl( XML_HINT_HYPERLINK, rPos, rPos ),
        pEvents( NULL )
    {
    }

    virtual ~XMLHyperlinkHint_Impl()
    {
        if (NULL != pEvents)
            pEvents->ReleaseRef();
    }

    void SetHRef( const OUString& s ) { sHRef = s; }
    const OUString& GetHRef() const { return sHRef; }
    void SetName( const OUString& s ) { sName = s; }
    const OUString& GetName() const { return sName; }
    void SetTargetFrameName( const OUString& s ) { sTargetFrameName = s; }
    const OUString& GetTargetFrameName() const { return sTargetFrameName; }
    void SetStyleName( const OUString& s ) { sStyleName = s; }
    const OUString& GetStyleName() const { return sStyleName; }
    void SetVisitedStyleName( const OUString& s ) { sVisitedStyleName = s; }
    const OUString& GetVisitedStyleName() const { return sVisitedStyleName; }
    XMLEventsImportContext* GetEventsContext() const
    {
        return pEvents;
    }
    void SetEventsContext( XMLEventsImportContext* pCtxt )
    {
        pEvents = pCtxt;
        if (pEvents != NULL)
            pEvents->AddRef();
    }
};

class XMLIndexMarkHint_Impl : public XMLHint_Impl
{
    const Reference<beans::XPropertySet> xIndexMarkPropSet;

    const OUString sID;

public:

    XMLIndexMarkHint_Impl( const Reference < beans::XPropertySet > & rPropSet,
                           const Reference < XTextRange > & rPos ) :
        XMLHint_Impl( XML_HINT_INDEX_MARK, rPos, rPos ),
        xIndexMarkPropSet( rPropSet ),
        sID()
    {
    }

    XMLIndexMarkHint_Impl( const Reference < beans::XPropertySet > & rPropSet,
                           const Reference < XTextRange > & rPos,
                           OUString sIDString) :
        XMLHint_Impl( XML_HINT_INDEX_MARK, rPos, rPos ),
        xIndexMarkPropSet( rPropSet ),
        sID(sIDString)
    {
    }

    virtual ~XMLIndexMarkHint_Impl() {}

    const Reference<beans::XPropertySet> & GetMark() const
        { return xIndexMarkPropSet; }
    const OUString& GetID() const { return sID; }
};

class XMLRubyHint_Impl : public XMLHint_Impl
{
    OUString                 sStyleName;
    OUString                 sTextStyleName;
    OUString                 sText;

public:

    XMLRubyHint_Impl( const Reference < XTextRange > & rPos ) :
        XMLHint_Impl( XML_HINT_RUBY, rPos, rPos )
    {
    }

    virtual ~XMLRubyHint_Impl() {}

    void SetStyleName( const OUString& s ) { sStyleName = s; }
    const OUString& GetStyleName() const { return sStyleName; }
    void SetTextStyleName( const OUString& s ) { sTextStyleName = s; }
    const OUString& GetTextStyleName() const { return sTextStyleName; }
    void AppendText( const OUString& s ) { sText += s; }
    const OUString& GetText() const { return sText; }
};

class XMLTextFrameHint_Impl : public XMLHint_Impl
{
    // OD 2004-04-20 #i26791#
    SvXMLImportContextRef xContext;

public:

    XMLTextFrameHint_Impl( SvXMLImportContext* pContext,
                           const Reference < XTextRange > & rPos ) :
        XMLHint_Impl( XML_HINT_TEXT_FRAME, rPos, rPos ),
        xContext( pContext )
    {
    }

    virtual ~XMLTextFrameHint_Impl()
    {
    }

    Reference < XTextContent > GetTextContent() const
    {
        Reference <XTextContent > xTxt;
        SvXMLImportContext *pContext = &xContext;
        if( pContext->ISA( XMLTextFrameContext ) )
            xTxt = PTR_CAST( XMLTextFrameContext, pContext )->GetTextContent();
        else if( pContext->ISA( XMLTextFrameHyperlinkContext ) )
            xTxt = PTR_CAST( XMLTextFrameHyperlinkContext, pContext )
                        ->GetTextContent();

        return xTxt;
    }

    // --> OD 2004-08-24 #i33242#
    Reference < drawing::XShape > GetShape() const
    {
        Reference < drawing::XShape > xShape;
        SvXMLImportContext *pContext = &xContext;
        if( pContext->ISA( XMLTextFrameContext ) )
            xShape = PTR_CAST( XMLTextFrameContext, pContext )->GetShape();
        else if( pContext->ISA( XMLTextFrameHyperlinkContext ) )
            xShape = PTR_CAST( XMLTextFrameHyperlinkContext, pContext )->GetShape();

        return xShape;
    }
    // <--

    sal_Bool IsBoundAtChar() const
    {
        sal_Bool bRet = sal_False;
        SvXMLImportContext *pContext = &xContext;
        if( pContext->ISA( XMLTextFrameContext ) )
            bRet = TextContentAnchorType_AT_CHARACTER ==
                PTR_CAST( XMLTextFrameContext, pContext )
                    ->GetAnchorType();
        else if( pContext->ISA( XMLTextFrameHyperlinkContext ) )
            bRet = TextContentAnchorType_AT_CHARACTER ==
                PTR_CAST( XMLTextFrameHyperlinkContext, pContext )
                    ->GetAnchorType();
        return bRet;
    }
};

// --> DVO, OD 2004-07-14 #i26791#
class XMLDrawHint_Impl : public XMLHint_Impl
{
    SvXMLImportContextRef xContext;

public:

    XMLDrawHint_Impl( SvXMLShapeContext* pContext,
                      const Reference < XTextRange > & rPos ) :
        XMLHint_Impl( XML_HINT_DRAW, rPos, rPos ),
        xContext( pContext )
    {
    }

    virtual ~XMLDrawHint_Impl()
    {
    }

    // --> OD 2004-08-24 #i33242#
    Reference < drawing::XShape > GetShape() const
    {
        return static_cast<SvXMLShapeContext*>(&xContext)->getShape();
    }
    // <--
};
// <--
#endif
<|endoftext|>