<commit_before>/*
 * Copyright (c) 2007 The Hewlett-Packard Development Company
 * All rights reserved.
 *
 * Redistribution and use of this software in source and binary forms,
 * with or without modification, are permitted provided that the
 * following conditions are met:
 *
 * The software must be used only for Non-Commercial Use which means any
 * use which is NOT directed to receiving any direct monetary
 * compensation for, or commercial advantage from such use.  Illustrative
 * examples of non-commercial use are academic research, personal study,
 * teaching, education and corporate research & development.
 * Illustrative examples of commercial use are distributing products for
 * commercial advantage and providing services using the software for
 * commercial advantage.
 *
 * If you wish to use this software or functionality therein that may be
 * covered by patents for commercial use, please contact:
 *     Director of Intellectual Property Licensing
 *     Office of Strategy and Technology
 *     Hewlett-Packard Company
 *     1501 Page Mill Road
 *     Palo Alto, California  94304
 *
 * 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 HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.  No right of
 * sublicense is granted herewith.  Derivatives of the software and
 * output created using the software may be prepared, but only for
 * Non-Commercial Uses.  Derivatives of the software may be shared with
 * others provided: (i) the others agree to abide by the list of
 * conditions herein which includes the Non-Commercial Use restrictions;
 * and (ii) such Derivatives of the software include the above copyright
 * notice to acknowledge the contribution from this software where
 * applicable, this list of conditions and the disclaimer below.
 *
 * 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: Gabe Black
 */

#include "arch/x86/predecoder.hh"
#include "base/misc.hh"
#include "base/trace.hh"
#include "sim/host.hh"

namespace X86ISA
{
    void Predecoder::reset()
    {
        origPC = basePC + offset;
        DPRINTF(Predecoder, "Setting origPC to %#x\n", origPC);
        emi.rex = 0;
        emi.legacy = 0;
        emi.opcode.num = 0;

        immediateCollected = 0;
        emi.immediate = 0;
        displacementCollected = 0;
        emi.displacement = 0;

        emi.modRM = 0;
        emi.sib = 0;
        emi.mode = 0;
    }

    void Predecoder::process()
    {
        //This function drives the predecoder state machine.

        //Some sanity checks. You shouldn't try to process more bytes if
        //there aren't any, and you shouldn't overwrite an already
        //predecoder ExtMachInst.
        assert(!outOfBytes);
        assert(!emiIsReady);

        //While there's still something to do...
        while(!emiIsReady && !outOfBytes)
        {
            uint8_t nextByte = getNextByte();
            switch(state)
            {
              case ResetState:
                reset();
                state = PrefixState;
              case PrefixState:
                state = doPrefixState(nextByte);
                break;
              case OpcodeState:
                state = doOpcodeState(nextByte);
                break;
              case ModRMState:
                state = doModRMState(nextByte);
                break;
              case SIBState:
                state = doSIBState(nextByte);
                break;
              case DisplacementState:
                state = doDisplacementState();
                break;
              case ImmediateState:
                state = doImmediateState();
                break;
              case ErrorState:
                panic("Went to the error state in the predecoder.\n");
              default:
                panic("Unrecognized state! %d\n", state);
            }
        }
    }

    //Either get a prefix and record it in the ExtMachInst, or send the
    //state machine on to get the opcode(s).
    Predecoder::State Predecoder::doPrefixState(uint8_t nextByte)
    {
        uint8_t prefix = Prefixes[nextByte];
        State nextState = PrefixState;
        if(prefix)
            consumeByte();
        switch(prefix)
        {
            //Operand size override prefixes
          case OperandSizeOverride:
            DPRINTF(Predecoder, "Found operand size override prefix.\n");
            emi.legacy.op = true;
            break;
          case AddressSizeOverride:
            DPRINTF(Predecoder, "Found address size override prefix.\n");
            emi.legacy.addr = true;
            break;
            //Segment override prefixes
          case CSOverride:
          case DSOverride:
          case ESOverride:
          case FSOverride:
          case GSOverride:
          case SSOverride:
            DPRINTF(Predecoder, "Found segment override.\n");
            emi.legacy.seg = prefix;
            break;
          case Lock:
            DPRINTF(Predecoder, "Found lock prefix.\n");
            emi.legacy.lock = true;
            break;
          case Rep:
            DPRINTF(Predecoder, "Found rep prefix.\n");
            emi.legacy.rep = true;
            break;
          case Repne:
            DPRINTF(Predecoder, "Found repne prefix.\n");
            emi.legacy.repne = true;
            break;
          case RexPrefix:
            DPRINTF(Predecoder, "Found Rex prefix %#x.\n", nextByte);
            emi.rex = nextByte;
            break;
          case 0:
            nextState = OpcodeState;
            break;
          default:
            panic("Unrecognized prefix %#x\n", nextByte);
        }
        return nextState;
    }

    //Load all the opcodes (currently up to 2) and then figure out
    //what immediate and/or ModRM is needed.
    Predecoder::State Predecoder::doOpcodeState(uint8_t nextByte)
    {
        State nextState = ErrorState;
        emi.opcode.num++;
        //We can't handle 3+ byte opcodes right now
        assert(emi.opcode.num < 3);
        consumeByte();
        if(emi.opcode.num == 1 && nextByte == 0x0f)
        {
            nextState = OpcodeState;
            DPRINTF(Predecoder, "Found two byte opcode.\n");
            emi.opcode.prefixA = nextByte;
        }
        else if(emi.opcode.num == 2 &&
                (nextByte == 0x0f ||
                 (nextByte & 0xf8) == 0x38))
        {
            panic("Three byte opcodes aren't yet supported!\n");
            nextState = OpcodeState;
            DPRINTF(Predecoder, "Found three byte opcode.\n");
            emi.opcode.prefixB = nextByte;
        }
        else
        {
            DPRINTF(Predecoder, "Found opcode %#x.\n", nextByte);
            emi.opcode.op = nextByte;

            //Figure out the effective operand size. This can be overriden to
            //a fixed value at the decoder level.
            int logOpSize;
            if(/*FIXME long mode*/1)
            {
                if(emi.rex.w)
                    logOpSize = 3; // 64 bit operand size
                else if(emi.legacy.op)
                    logOpSize = 1; // 16 bit operand size
                else
                    logOpSize = 2; // 32 bit operand size
            }
            else if(/*FIXME default 32*/1)
            {
                if(emi.legacy.op)
                    logOpSize = 1; // 16 bit operand size
                else
                    logOpSize = 2; // 32 bit operand size
            }
            else // 16 bit default operand size
            {
                if(emi.legacy.op)
                    logOpSize = 2; // 32 bit operand size
                else
                    logOpSize = 1; // 16 bit operand size
            }

            //Figure out how big of an immediate we'll retreive based
            //on the opcode.
            int immType = ImmediateType[emi.opcode.num - 1][nextByte];
            immediateSize = SizeTypeToSize[logOpSize - 1][immType];

            //Set the actual op size
            emi.opSize = 1 << logOpSize;

            //Determine what to expect next
            if (UsesModRM[emi.opcode.num - 1][nextByte]) {
                nextState = ModRMState;
            } else {
                if(immediateSize) {
                    nextState = ImmediateState;
                } else {
                    emiIsReady = true;
                    nextState = ResetState;
                }
            }
        }
        return nextState;
    }

    //Get the ModRM byte and determine what displacement, if any, there is.
    //Also determine whether or not to get the SIB byte, displacement, or
    //immediate next.
    Predecoder::State Predecoder::doModRMState(uint8_t nextByte)
    {
        State nextState = ErrorState;
        ModRM modRM;
        modRM = nextByte;
        DPRINTF(Predecoder, "Found modrm byte %#x.\n", nextByte);
        if (0) {//FIXME in 16 bit mode
            //figure out 16 bit displacement size
            if(modRM.mod == 0 && modRM.rm == 6 || modRM.mod == 2)
                displacementSize = 2;
            else if(modRM.mod == 1)
                displacementSize = 1;
            else
                displacementSize = 0;
        } else {
            //figure out 32/64 bit displacement size
            if(modRM.mod == 0 && modRM.rm == 4 || modRM.mod == 2)
                displacementSize = 4;
            else if(modRM.mod == 1)
                displacementSize = 1;
            else
                displacementSize = 0;
        }
        //If there's an SIB, get that next.
        //There is no SIB in 16 bit mode.
        if(modRM.rm == 4 && modRM.mod != 3) {
                // && in 32/64 bit mode)
            nextState = SIBState;
        } else if(displacementSize) {
            nextState = DisplacementState;
        } else if(immediateSize) {
            nextState = ImmediateState;
        } else {
            emiIsReady = true;
            nextState = ResetState;
        }
        //The ModRM byte is consumed no matter what
        consumeByte();
        emi.modRM = modRM;
        return nextState;
    }

    //Get the SIB byte. We don't do anything with it at this point, other
    //than storing it in the ExtMachInst. Determine if we need to get a
    //displacement or immediate next.
    Predecoder::State Predecoder::doSIBState(uint8_t nextByte)
    {
        State nextState = ErrorState;
        emi.sib = nextByte;
        DPRINTF(Predecoder, "Found SIB byte %#x.\n", nextByte);
        consumeByte();
        if(displacementSize) {
            nextState = DisplacementState;
        } else if(immediateSize) {
            nextState = ImmediateState;
        } else {
            emiIsReady = true;
            nextState = ResetState;
        }
        return nextState;
    }

    //Gather up the displacement, or at least as much of it
    //as we can get.
    Predecoder::State Predecoder::doDisplacementState()
    {
        State nextState = ErrorState;

        getImmediate(displacementCollected,
                emi.displacement,
                displacementSize);

        DPRINTF(Predecoder, "Collecting %d byte displacement, got %d bytes.\n",
                displacementSize, displacementCollected);

        if(displacementSize == displacementCollected) {
            //Sign extend the displacement
            switch(displacementSize)
            {
              case 1:
                emi.displacement = sext<8>(emi.displacement);
                break;
              case 2:
                emi.displacement = sext<16>(emi.displacement);
                break;
              case 4:
                emi.displacement = sext<32>(emi.displacement);
                break;
              default:
                panic("Undefined displacement size!\n");
            }
            DPRINTF(Predecoder, "Collected displacement %#x.\n",
                    emi.displacement);
            if(immediateSize) {
                nextState = ImmediateState;
            } else {
                emiIsReady = true;
                nextState = ResetState;
            }
        }
        else
            nextState = DisplacementState;
        return nextState;
    }

    //Gather up the immediate, or at least as much of it
    //as we can get
    Predecoder::State Predecoder::doImmediateState()
    {
        State nextState = ErrorState;

        getImmediate(immediateCollected,
                emi.immediate,
                immediateSize);

        DPRINTF(Predecoder, "Collecting %d byte immediate, got %d bytes.\n",
                immediateSize, immediateCollected);

        if(immediateSize == immediateCollected)
        {
            //XXX Warning! The following is an observed pattern and might
            //not always be true!

            //Instructions which use 64 bit operands but 32 bit immediates
            //need to have the immediate sign extended to 64 bits.
            //Instructions which use true 64 bit immediates won't be
            //affected, and instructions that use true 32 bit immediates
            //won't notice.
            switch(immediateSize)
            {
              case 4:
                emi.immediate = sext<32>(emi.immediate);
                break;
              case 1:
                emi.immediate = sext<8>(emi.immediate);
            }

            DPRINTF(Predecoder, "Collected immediate %#x.\n",
                    emi.immediate);
            emiIsReady = true;
            nextState = ResetState;
        }
        else
            nextState = ImmediateState;
        return nextState;
    }
}
<commit_msg>Fix a newly introduced bug where the predecoder wasn't picking up all the displacement.<commit_after>/*
 * Copyright (c) 2007 The Hewlett-Packard Development Company
 * All rights reserved.
 *
 * Redistribution and use of this software in source and binary forms,
 * with or without modification, are permitted provided that the
 * following conditions are met:
 *
 * The software must be used only for Non-Commercial Use which means any
 * use which is NOT directed to receiving any direct monetary
 * compensation for, or commercial advantage from such use.  Illustrative
 * examples of non-commercial use are academic research, personal study,
 * teaching, education and corporate research & development.
 * Illustrative examples of commercial use are distributing products for
 * commercial advantage and providing services using the software for
 * commercial advantage.
 *
 * If you wish to use this software or functionality therein that may be
 * covered by patents for commercial use, please contact:
 *     Director of Intellectual Property Licensing
 *     Office of Strategy and Technology
 *     Hewlett-Packard Company
 *     1501 Page Mill Road
 *     Palo Alto, California  94304
 *
 * 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 HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.  No right of
 * sublicense is granted herewith.  Derivatives of the software and
 * output created using the software may be prepared, but only for
 * Non-Commercial Uses.  Derivatives of the software may be shared with
 * others provided: (i) the others agree to abide by the list of
 * conditions herein which includes the Non-Commercial Use restrictions;
 * and (ii) such Derivatives of the software include the above copyright
 * notice to acknowledge the contribution from this software where
 * applicable, this list of conditions and the disclaimer below.
 *
 * 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: Gabe Black
 */

#include "arch/x86/predecoder.hh"
#include "base/misc.hh"
#include "base/trace.hh"
#include "sim/host.hh"

namespace X86ISA
{
    void Predecoder::reset()
    {
        origPC = basePC + offset;
        DPRINTF(Predecoder, "Setting origPC to %#x\n", origPC);
        emi.rex = 0;
        emi.legacy = 0;
        emi.opcode.num = 0;

        immediateCollected = 0;
        emi.immediate = 0;
        displacementCollected = 0;
        emi.displacement = 0;

        emi.modRM = 0;
        emi.sib = 0;
        emi.mode = 0;
    }

    void Predecoder::process()
    {
        //This function drives the predecoder state machine.

        //Some sanity checks. You shouldn't try to process more bytes if
        //there aren't any, and you shouldn't overwrite an already
        //predecoder ExtMachInst.
        assert(!outOfBytes);
        assert(!emiIsReady);

        //While there's still something to do...
        while(!emiIsReady && !outOfBytes)
        {
            uint8_t nextByte = getNextByte();
            switch(state)
            {
              case ResetState:
                reset();
                state = PrefixState;
              case PrefixState:
                state = doPrefixState(nextByte);
                break;
              case OpcodeState:
                state = doOpcodeState(nextByte);
                break;
              case ModRMState:
                state = doModRMState(nextByte);
                break;
              case SIBState:
                state = doSIBState(nextByte);
                break;
              case DisplacementState:
                state = doDisplacementState();
                break;
              case ImmediateState:
                state = doImmediateState();
                break;
              case ErrorState:
                panic("Went to the error state in the predecoder.\n");
              default:
                panic("Unrecognized state! %d\n", state);
            }
        }
    }

    //Either get a prefix and record it in the ExtMachInst, or send the
    //state machine on to get the opcode(s).
    Predecoder::State Predecoder::doPrefixState(uint8_t nextByte)
    {
        uint8_t prefix = Prefixes[nextByte];
        State nextState = PrefixState;
        if(prefix)
            consumeByte();
        switch(prefix)
        {
            //Operand size override prefixes
          case OperandSizeOverride:
            DPRINTF(Predecoder, "Found operand size override prefix.\n");
            emi.legacy.op = true;
            break;
          case AddressSizeOverride:
            DPRINTF(Predecoder, "Found address size override prefix.\n");
            emi.legacy.addr = true;
            break;
            //Segment override prefixes
          case CSOverride:
          case DSOverride:
          case ESOverride:
          case FSOverride:
          case GSOverride:
          case SSOverride:
            DPRINTF(Predecoder, "Found segment override.\n");
            emi.legacy.seg = prefix;
            break;
          case Lock:
            DPRINTF(Predecoder, "Found lock prefix.\n");
            emi.legacy.lock = true;
            break;
          case Rep:
            DPRINTF(Predecoder, "Found rep prefix.\n");
            emi.legacy.rep = true;
            break;
          case Repne:
            DPRINTF(Predecoder, "Found repne prefix.\n");
            emi.legacy.repne = true;
            break;
          case RexPrefix:
            DPRINTF(Predecoder, "Found Rex prefix %#x.\n", nextByte);
            emi.rex = nextByte;
            break;
          case 0:
            nextState = OpcodeState;
            break;
          default:
            panic("Unrecognized prefix %#x\n", nextByte);
        }
        return nextState;
    }

    //Load all the opcodes (currently up to 2) and then figure out
    //what immediate and/or ModRM is needed.
    Predecoder::State Predecoder::doOpcodeState(uint8_t nextByte)
    {
        State nextState = ErrorState;
        emi.opcode.num++;
        //We can't handle 3+ byte opcodes right now
        assert(emi.opcode.num < 3);
        consumeByte();
        if(emi.opcode.num == 1 && nextByte == 0x0f)
        {
            nextState = OpcodeState;
            DPRINTF(Predecoder, "Found two byte opcode.\n");
            emi.opcode.prefixA = nextByte;
        }
        else if(emi.opcode.num == 2 &&
                (nextByte == 0x0f ||
                 (nextByte & 0xf8) == 0x38))
        {
            panic("Three byte opcodes aren't yet supported!\n");
            nextState = OpcodeState;
            DPRINTF(Predecoder, "Found three byte opcode.\n");
            emi.opcode.prefixB = nextByte;
        }
        else
        {
            DPRINTF(Predecoder, "Found opcode %#x.\n", nextByte);
            emi.opcode.op = nextByte;

            //Figure out the effective operand size. This can be overriden to
            //a fixed value at the decoder level.
            int logOpSize;
            if(/*FIXME long mode*/1)
            {
                if(emi.rex.w)
                    logOpSize = 3; // 64 bit operand size
                else if(emi.legacy.op)
                    logOpSize = 1; // 16 bit operand size
                else
                    logOpSize = 2; // 32 bit operand size
            }
            else if(/*FIXME default 32*/1)
            {
                if(emi.legacy.op)
                    logOpSize = 1; // 16 bit operand size
                else
                    logOpSize = 2; // 32 bit operand size
            }
            else // 16 bit default operand size
            {
                if(emi.legacy.op)
                    logOpSize = 2; // 32 bit operand size
                else
                    logOpSize = 1; // 16 bit operand size
            }

            //Figure out how big of an immediate we'll retreive based
            //on the opcode.
            int immType = ImmediateType[emi.opcode.num - 1][nextByte];
            immediateSize = SizeTypeToSize[logOpSize - 1][immType];

            //Set the actual op size
            emi.opSize = 1 << logOpSize;

            //Determine what to expect next
            if (UsesModRM[emi.opcode.num - 1][nextByte]) {
                nextState = ModRMState;
            } else {
                if(immediateSize) {
                    nextState = ImmediateState;
                } else {
                    emiIsReady = true;
                    nextState = ResetState;
                }
            }
        }
        return nextState;
    }

    //Get the ModRM byte and determine what displacement, if any, there is.
    //Also determine whether or not to get the SIB byte, displacement, or
    //immediate next.
    Predecoder::State Predecoder::doModRMState(uint8_t nextByte)
    {
        State nextState = ErrorState;
        ModRM modRM;
        modRM = nextByte;
        DPRINTF(Predecoder, "Found modrm byte %#x.\n", nextByte);
        if (0) {//FIXME in 16 bit mode
            //figure out 16 bit displacement size
            if(modRM.mod == 0 && modRM.rm == 6 || modRM.mod == 2)
                displacementSize = 2;
            else if(modRM.mod == 1)
                displacementSize = 1;
            else
                displacementSize = 0;
        } else {
            //figure out 32/64 bit displacement size
            if(modRM.mod == 0 && (modRM.rm == 4 || modRM.rm == 5)
                    || modRM.mod == 2)
                displacementSize = 4;
            else if(modRM.mod == 1)
                displacementSize = 1;
            else
                displacementSize = 0;
        }
        //If there's an SIB, get that next.
        //There is no SIB in 16 bit mode.
        if(modRM.rm == 4 && modRM.mod != 3) {
                // && in 32/64 bit mode)
            nextState = SIBState;
        } else if(displacementSize) {
            nextState = DisplacementState;
        } else if(immediateSize) {
            nextState = ImmediateState;
        } else {
            emiIsReady = true;
            nextState = ResetState;
        }
        //The ModRM byte is consumed no matter what
        consumeByte();
        emi.modRM = modRM;
        return nextState;
    }

    //Get the SIB byte. We don't do anything with it at this point, other
    //than storing it in the ExtMachInst. Determine if we need to get a
    //displacement or immediate next.
    Predecoder::State Predecoder::doSIBState(uint8_t nextByte)
    {
        State nextState = ErrorState;
        emi.sib = nextByte;
        DPRINTF(Predecoder, "Found SIB byte %#x.\n", nextByte);
        consumeByte();
        if(displacementSize) {
            nextState = DisplacementState;
        } else if(immediateSize) {
            nextState = ImmediateState;
        } else {
            emiIsReady = true;
            nextState = ResetState;
        }
        return nextState;
    }

    //Gather up the displacement, or at least as much of it
    //as we can get.
    Predecoder::State Predecoder::doDisplacementState()
    {
        State nextState = ErrorState;

        getImmediate(displacementCollected,
                emi.displacement,
                displacementSize);

        DPRINTF(Predecoder, "Collecting %d byte displacement, got %d bytes.\n",
                displacementSize, displacementCollected);

        if(displacementSize == displacementCollected) {
            //Sign extend the displacement
            switch(displacementSize)
            {
              case 1:
                emi.displacement = sext<8>(emi.displacement);
                break;
              case 2:
                emi.displacement = sext<16>(emi.displacement);
                break;
              case 4:
                emi.displacement = sext<32>(emi.displacement);
                break;
              default:
                panic("Undefined displacement size!\n");
            }
            DPRINTF(Predecoder, "Collected displacement %#x.\n",
                    emi.displacement);
            if(immediateSize) {
                nextState = ImmediateState;
            } else {
                emiIsReady = true;
                nextState = ResetState;
            }
        }
        else
            nextState = DisplacementState;
        return nextState;
    }

    //Gather up the immediate, or at least as much of it
    //as we can get
    Predecoder::State Predecoder::doImmediateState()
    {
        State nextState = ErrorState;

        getImmediate(immediateCollected,
                emi.immediate,
                immediateSize);

        DPRINTF(Predecoder, "Collecting %d byte immediate, got %d bytes.\n",
                immediateSize, immediateCollected);

        if(immediateSize == immediateCollected)
        {
            //XXX Warning! The following is an observed pattern and might
            //not always be true!

            //Instructions which use 64 bit operands but 32 bit immediates
            //need to have the immediate sign extended to 64 bits.
            //Instructions which use true 64 bit immediates won't be
            //affected, and instructions that use true 32 bit immediates
            //won't notice.
            switch(immediateSize)
            {
              case 4:
                emi.immediate = sext<32>(emi.immediate);
                break;
              case 1:
                emi.immediate = sext<8>(emi.immediate);
            }

            DPRINTF(Predecoder, "Collected immediate %#x.\n",
                    emi.immediate);
            emiIsReady = true;
            nextState = ResetState;
        }
        else
            nextState = ImmediateState;
        return nextState;
    }
}
<|endoftext|>


<commit_before>/*
* (C) 2014,2015 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include "tests.h"

#if defined(BOTAN_HAS_ECDSA)

#include "test_pubkey.h"

#include <botan/pubkey.h>
#include <botan/ecdsa.h>
#include <botan/oids.h>
#include <botan/hex.h>
#include <iostream>
#include <fstream>

using namespace Botan;

namespace {

size_t ecdsa_sig_kat(const std::string& group_id,
                     const std::string& x,
                     const std::string& hash,
                     const std::string& msg,
                     const std::string& signature)
   {
   auto& rng = test_rng();

   EC_Group group(OIDS::lookup(group_id));
   ECDSA_PrivateKey ecdsa(rng, group, BigInt(x));

   const std::string padding = "EMSA1(" + hash + ")";

   PK_Verifier verify(ecdsa, padding);
   PK_Signer sign(ecdsa, padding);

   return validate_signature(verify, sign, "ECDSA/" + group_id + "/" + hash,
                             msg, rng, signature);
   }

}

size_t test_ecdsa()
   {
   size_t fails = 0;

   std::ifstream ecdsa_sig(TEST_DATA_DIR_PK "/ecdsa.vec");

   fails += run_tests_bb(ecdsa_sig, "ECDSA Signature", "Signature", false,
             [](std::map<std::string, std::string> m) -> size_t
             {
             return ecdsa_sig_kat(m["Group"], m["X"], m["Hash"], m["Msg"], m["Signature"]);
             });

   return fails;
   }

#else

SKIP_TEST(ecdsa);

#endif // BOTAN_HAS_ECDSA
<commit_msg>ECDSA KATs only work for base impl<commit_after>/*
* (C) 2014,2015 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include "tests.h"

#if defined(BOTAN_HAS_ECDSA)

#include "test_pubkey.h"

#include <botan/pubkey.h>
#include <botan/ecdsa.h>
#include <botan/oids.h>
#include <botan/hex.h>
#include <iostream>
#include <fstream>

using namespace Botan;

namespace {

size_t ecdsa_sig_kat(const std::string& group_id,
                     const std::string& x,
                     const std::string& hash,
                     const std::string& msg,
                     const std::string& signature)
   {
   auto& rng = test_rng();

   EC_Group group(OIDS::lookup(group_id));
   ECDSA_PrivateKey ecdsa(rng, group, BigInt(x));

   const std::string padding = "EMSA1(" + hash + ")";

   PK_Verifier verify(ecdsa, padding, "base");
   PK_Signer sign(ecdsa, padding, "base");

   return validate_signature(verify, sign, "ECDSA/" + group_id + "/" + hash,
                             msg, rng, signature);
   }

}

size_t test_ecdsa()
   {
   size_t fails = 0;

   std::ifstream ecdsa_sig(TEST_DATA_DIR_PK "/ecdsa.vec");

   fails += run_tests_bb(ecdsa_sig, "ECDSA Signature", "Signature", false,
             [](std::map<std::string, std::string> m) -> size_t
             {
             return ecdsa_sig_kat(m["Group"], m["X"], m["Hash"], m["Msg"], m["Signature"]);
             });

   return fails;
   }

#else

SKIP_TEST(ecdsa);

#endif // BOTAN_HAS_ECDSA
<|endoftext|>


<commit_before>#include "LMHistory.hh"

using namespace std;

LMHistory::Word::Word() :
		m_word_id(-1), m_lm_id(-1), m_cm_log_prob(0)
{
}

void LMHistory::Word::set_ids(int word_id, int lm_id)
{
  m_word_id = word_id;
  m_lm_id = lm_id;
}

void LMHistory::Word::set_cm_log_prob(float cm_log_prob)
{
  m_cm_log_prob = cm_log_prob;
}

#ifdef ENABLE_MULTIWORD_SUPPORT
void LMHistory::Word::add_component(int lm_id)
{
  m_component_lm_ids.push_back(lm_id);
}
#endif

<commit_msg>Stores also ID to lookahead LM.<commit_after>#include "LMHistory.hh"

using namespace std;

LMHistory::Word::Word() :
		m_word_id(-1), m_lm_id(-1), m_cm_log_prob(0)
{
}

void LMHistory::Word::set_ids(int word_id, int lm_id)
{
  m_word_id = word_id;
  m_lm_id = lm_id;
}

void LMHistory::Word::set_lookahead_lm_id(int lookahead_lm_id)
{
  m_lookahead_lm_id = lookahead_lm_id;
}

void LMHistory::Word::set_cm_log_prob(float cm_log_prob)
{
  m_cm_log_prob = cm_log_prob;
}

#ifdef ENABLE_MULTIWORD_SUPPORT
void LMHistory::Word::add_component(int lm_id)
{
  m_component_lm_ids.push_back(lm_id);
}
#endif

<|endoftext|>


<commit_before>
<commit_msg>Update LessThan.cpp<commit_after>#include "LessThan.h"

    LessThan::LessThan(Runcmd* r, Runcmd* l) : Connector("<",r,l)
    {

    }

    bool LessThan::run()
    {
        char file[256];
			strcpy(file, rhs->getCmd().c_str());
            int redir;
			if((redir = open(file, O_RDONLY )) == -1)
			{
				perror("Input Redirection Error: Could not open file");
				return false;
			}

			int saveSTDin = dup(0);
			if(-1 == dup2(redir, 0))
            {
	        	perror("There was an error with dup2");

            }

			lhs->run();

			if(-1 == dup2(saveSTDin, 0))
            {
	        	perror("There was an error with dup2");

            }
            return true;

    }
<|endoftext|>


<commit_before>/*
 * NicoW
 * 27.05.12
 */

#include "Scanner.hpp"
#include "Unpackman.hpp"
#include "LoadSave.hpp"
#include <fstream>

LoadSave::LoadSave(GameManager& game)
  : AMenu("menu/Background2.png", "menu/Background2.png", 3200.0f, -1.0f, 900.0f, game),
    _buildTags(false)
{
}

LoadSave::~LoadSave(void)
{
}

double		LoadSave::getCenterX(void) const
{
  return (4000.0f);
}

double		LoadSave::getCenterY(void) const
{
  return (1350.0f);
}

void		LoadSave::loadSave()
{
  Serializer::Unpackman up(*this->_gameManager._mainProfile, this->_gameManager._match);
  std::string	path("Ressources/saves/" + this->_gameManager._mainProfile->getSave()[this->_cursor]);
  std::ifstream	file(path.c_str());

  if (!file.good())
    this->_curToken = TokenMenu::MAINMENU;
  else
    {
      Serializer::Scanner	scanner(file);
      Serializer::Loader	loader(scanner, up);

      loader.parse();
      /*if (up.ma._gameMode != GameMode::SOLO)
	{
	  up.ma._players[0]
	  }*/
    }
}

void		LoadSave::update(gdl::GameClock const& clock, gdl::Input& input)
{
  if (this->_buildTags)
    {
      for (size_t i = 0; i < this->_keyEvent.size(); ++i)
	if (input.isKeyDown(this->_keyEvent[i].first))
	  (this->*_keyEvent[i].second)(clock);
      if (this->_curToken == TokenMenu::CREATEGAME)
	this->loadSave();
    }
  else
    this->buildTags();
}

void		LoadSave::buildTags(void)
{
  bool		select = true;
  double	yText = 400;
  double	yTag = 1350.0f;

  std::vector<std::string>			tmpSave = this->_gameManager._mainProfile->getSave();
  std::vector<std::string>::const_iterator	it = tmpSave.begin();

  this->_buildTags = true;
  if (this->_gameManager._mainProfile != 0)
    {
      for ( ; it != tmpSave.end() ; ++it)
	{
	  this->_tags.push_back(new Tag("menu/BlackNormal.png", "menu/BlackHighlit.png",
					select, true, TokenMenu::CREATEGAME, 4000.0f, 0.0f, yTag));
	  this->_tags.back()->initialize();
	  this->_tags.back()->createText(*it, 20, 800, yText);

	  yText += 50;
	  yTag += 50.0f;
	  if (select)
	    select = false;
	}
    }
  this->_tags.push_back(new Tag("menu/BackNormal.png", "menu/BackHighlit.png", select, true, TokenMenu::PROFILE, 4000.0f, 0.0f, yTag));
  this->_tags.back()->initialize();
}
<commit_msg>Maj Load save<commit_after>/*
 * NicoW
 * 27.05.12
 */

#include "Scanner.hpp"
#include "Unpackman.hpp"
#include "LoadSave.hpp"
#include <fstream>

LoadSave::LoadSave(GameManager& game)
  : AMenu("menu/Background2.png", "menu/Background2.png", 3200.0f, -1.0f, 900.0f, game),
    _buildTags(false)
{
}

LoadSave::~LoadSave(void)
{
}

double		LoadSave::getCenterX(void) const
{
  return (4000.0f);
}

double		LoadSave::getCenterY(void) const
{
  return (1350.0f);
}

void		LoadSave::loadSave()
{
  Serializer::Unpackman up(*this->_gameManager._mainProfile, this->_gameManager._match);
  std::string	path("Ressources/saves/" + this->_gameManager._mainProfile->getSave()[this->_cursor]);
  std::ifstream	file(path.c_str());

  if (!file.good())
    this->_curToken = TokenMenu::MAINMENU;
  else
    {
      Serializer::Scanner	scanner(file);
      Serializer::Loader	loader(scanner, up);

      loader.parse();
    }
}

void		LoadSave::update(gdl::GameClock const& clock, gdl::Input& input)
{
  if (this->_buildTags)
    {
      for (size_t i = 0; i < this->_keyEvent.size(); ++i)
	if (input.isKeyDown(this->_keyEvent[i].first))
	  (this->*_keyEvent[i].second)(clock);
      if (this->_curToken == TokenMenu::CREATEGAME)
	this->loadSave();
    }
  else
    this->buildTags();
}

void		LoadSave::buildTags(void)
{
  bool		select = true;
  double	yText = 400;
  double	yTag = 1350.0f;

  std::vector<std::string>			tmpSave = this->_gameManager._mainProfile->getSave();
  std::vector<std::string>::const_iterator	it = tmpSave.begin();

  this->_buildTags = true;
  if (this->_gameManager._mainProfile != 0)
    {
      for ( ; it != tmpSave.end() ; ++it)
	{
	  this->_tags.push_back(new Tag("menu/BlackNormal.png", "menu/BlackHighlit.png",
					select, true, TokenMenu::CREATEGAME, 4000.0f, 0.0f, yTag));
	  this->_tags.back()->initialize();
	  this->_tags.back()->createText(*it, 20, 800, yText);

	  yText += 50;
	  yTag += 50.0f;
	  if (select)
	    select = false;
	}
    }
  this->_tags.push_back(new Tag("menu/BackNormal.png", "menu/BackHighlit.png", select, true, TokenMenu::PROFILE, 4000.0f, 0.0f, yTag));
  this->_tags.back()->initialize();
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>

#include "parseJsonStr.h"
#include "xalt_quotestring.h"

void processArray(const char* name, const char* js, int& i, int ntokens, jsmntok_t* tokens, Vstring& vA)
{
  if (tokens[i].type != JSMN_ARRAY)
    {
      fprintf(stderr,"processArray for: %s, token type is not an array\n",name);
      fprintf(stderr, "%d: type: %d, start: %d, end: %d, size: %d, parent: %d\n",
              i, tokens[i].type, tokens[i].start, tokens[i].end, tokens[i].size, tokens[i].parent);
      exit(1);
    }

  int iend = tokens[i].end;

  std::string  value;
  const char * p;

  ++i;
  while (i < ntokens)
    {
      if (tokens[i].start > iend)
        return;

      if (tokens[i].type != JSMN_STRING)
        {
          fprintf(stderr,"processArray for: %s, token type is not a string\n",name);
          exit(1);
        }
      p = xalt_unquotestring(&js[tokens[i].start],tokens[i].end - tokens[i].start); ++i;
      value.assign(p);
      vA.push_back(value);
    }
}

void processSet(const char* name, const char* js, int& i, int ntokens, jsmntok_t* tokens, Set& set)
{
  if (tokens[i].type != JSMN_ARRAY)
    {
      fprintf(stderr,"processSet for: %s, token type is not an array\n",name);
      fprintf(stderr, "%d: type: %d, start: %d, end: %d, size: %d, parent: %d\n",
              i, tokens[i].type, tokens[i].start, tokens[i].end, tokens[i].size, tokens[i].parent);
      exit(1);
    }

  int iend = tokens[i].end;
  std::string value;
  const char  *p;

  ++i;
  while (i < ntokens)
    {
      if (tokens[i].start > iend)
        return;

      if (tokens[i].type != JSMN_STRING)
        {
          fprintf(stderr,"processSet for: %s, token type is not a string\n",name);
          exit(1);
        }
      p = xalt_unquotestring(&js[tokens[i].start],tokens[i].end - tokens[i].start); ++i;
      value.assign(p);
      set.insert(value);
    }
}
void processTable(const char* name, const char* js, int& i, int ntokens, jsmntok_t* tokens, Table& t)
{
  if (tokens[i].type != JSMN_OBJECT)
    {
      fprintf(stderr,"processTable for: %s, token type is not an object\n",name);
      fprintf(stderr, "%d: type: %d, start: %d, end: %d, size: %d, parent: %d\n",
              i, tokens[i].type, tokens[i].start, tokens[i].end, tokens[i].size, tokens[i].parent);
      exit(1);
    }

  int iend = tokens[i].end;
  std::string key;
  std::string value;
  const char  *p;

  ++i;
  while (i < ntokens)
    {
      if (tokens[i].start > iend)
        return;

      if (tokens[i].type != JSMN_STRING && tokens[i+1].type != JSMN_STRING)
        {
          fprintf(stderr,"processTable for: %s, token types are not strings\n",name);
          exit(1);
        }
      p = xalt_unquotestring(&js[tokens[i].start],tokens[i].end - tokens[i].start); ++i;
      key.assign(p);
      p = xalt_unquotestring(&js[tokens[i].start],tokens[i].end - tokens[i].start); ++i;
      value.assign(p);
      t[key] = value;
    }
}
void processA2JsonStr(const char* name, const char* js, int& i, int ntokens, jsmntok_t* tokens, std::string& value)
{
  value = "[";
  if (tokens[i].type != JSMN_ARRAY)
    {
      fprintf(stderr,"processA2JsonStr for: %s, token type is not an array\n",name);
      fprintf(stderr, "%d: type: %d, start: %d, end: %d, size: %d, parent: %d\n",
              i, tokens[i].type, tokens[i].start, tokens[i].end, tokens[i].size, tokens[i].parent);
      exit(1);
    }

  int iend = tokens[i].end;

  ++i;
  while (i < ntokens)
    {
      if (tokens[i].start > iend)
        break;

      if (tokens[i].type != JSMN_STRING)
        {
          fprintf(stderr,"processSet for: %s, token type is not a string\n",name);
          exit(1);
        }
      value.append("\"");
      value.append(&js[tokens[i].start], tokens[i].end - tokens[i].start); ++i;
      value.append("\",");
    }
  if (value.back() == ',')
    value.replace(value.size()-1,1,"]");
  else
    value.append("]");
}

void processLibA(const char* name, const char* js, int& i, int ntokens, jsmntok_t* tokens, std::vector<Libpair>& libA)
{
  if (tokens[i].type != JSMN_ARRAY)
    {
      fprintf(stderr,"processTable for: %s, token type is not an object\n",name);
      fprintf(stderr, "%d: type: %d, start: %d, end: %d, size: %d, parent: %d\n",
              i, tokens[i].type, tokens[i].start, tokens[i].end, tokens[i].size, tokens[i].parent);
      exit(1);
    }

  int iend = tokens[i].end;
  std::string lib;
  std::string sha1;
  const char  *p;

  ++i;
  while (i < ntokens)
    {
      if (tokens[i].start > iend)
        return;

      if (tokens[i].type != JSMN_ARRAY)
        {
          fprintf(stderr,"processLibA for %s: token type is not an array\n",name);
          exit(1);
        }
      i++;
      if (tokens[i].type != JSMN_STRING && tokens[i+1].type != JSMN_STRING)
        {
          fprintf(stderr,"processLibA for: %s, token types are not strings\n",name);
          exit(1);
        }

      p = xalt_unquotestring(&js[tokens[i].start],tokens[i].end - tokens[i].start); ++i;
      lib.assign(p);
      sha1.assign(&js[tokens[i].start],tokens[i].end - tokens[i].start));           ++i;
      Libpair libpair(lib,sha1);
      libA.push_back(libpair);
    }
}

void processValue(const char* name, const char* js, int& i, int ntokens, jsmntok_t* tokens, std::string& value)
{
  if (tokens[i].type != JSMN_STRING)
    {
      fprintf(stderr,"processValue for: %s, token type is not an object\n",name);
      fprintf(stderr, "%d: type: %d, start: %d, end: %d, size: %d, parent: %d\n", i, tokens[i].type, tokens[i].start, tokens[i].end, tokens[i].size, tokens[i].parent);
      exit(1);
    }

  value.assign( js, tokens[i].start, tokens[i].end - tokens[i].start);
  i++;
}

void parseRunJsonStr(const char* name, std::string& jsonStr, std::string& usr_cmdline, std::string& hash_id,
                     Table& envT, Table& userT, Table& recordT, std::vector<Libpair>& libA)
{
  jsmn_parser parser;
  jsmntok_t*  tokens;
  int         maxTokens = 1000;

  tokens = (jsmntok_t *) malloc(sizeof(jsmntok_t)*maxTokens);

  jsmn_init(&parser);

  // js - pointer to JSON string
  // tokens - an array of tokens available
  int ntokens;

  const char * js = jsonStr.c_str();

  while (1)
    {
      ntokens = jsmn_parse(&parser, js, jsonStr.size(), tokens, maxTokens);
      if (ntokens > 0)
        break;
      if (ntokens == JSMN_ERROR_NOMEM)
        {
          maxTokens *= 2;
          tokens = (jsmntok_t *) realloc(tokens,sizeof(jsmntok_t)*maxTokens);
        }
    }

  if (tokens[0].type != JSMN_OBJECT)
    {
      fprintf(stderr,"(5) Bad run.*.json file: %s\n",name);
      exit(1);
    }

  int i = 1;
  while (i < ntokens)
    {
      if (tokens[i].type != JSMN_STRING )
        {
          fprintf(stderr,"(6) Bad file(%s): i: %d, Type: %d\n", name, i, tokens[i].type);
          fprintf(stderr,"%.*s\n",tokens[i].end - tokens[i].start, &js[tokens[i].start]);
          exit(1);
        }
      std::string mapName(js, tokens[i].start, tokens[i].end - tokens[i].start); ++i;
      if (mapName == "cmdlineA")
        processA2JsonStr(name, js, i, ntokens, tokens, usr_cmdline);
      else if (mapName == "envT")
        processTable(name,js, i, ntokens, tokens, envT);
      else if (mapName == "hash_id")
        processValue(name,js, i, ntokens, tokens, hash_id);
      else if (mapName == "libA")
        processLibA(name, js, i, ntokens, tokens, libA);
      else if (mapName == "userT")
        processTable(name,js, i, ntokens, tokens, userT);
      else if (mapName == "xaltLinkT")
        processTable(name,js, i, ntokens, tokens, recordT);
    }
  free(tokens);
}

void parseLinkJsonStr(const char* name, std::string& jsonStr, Vstring& linklineA, Table& resultT, std::vector<Libpair>& libA, Set& funcSet)
{
  jsmn_parser parser;
  jsmntok_t*  tokens;
  int         maxTokens = 1000;

  tokens = (jsmntok_t *) malloc(sizeof(jsmntok_t)*maxTokens);

  jsmn_init(&parser);

  // js - pointer to JSON string
  // tokens - an array of tokens available
  int ntokens;

  const char * js = jsonStr.c_str();

  while (1)
    {
      ntokens = jsmn_parse(&parser, js, jsonStr.size(), tokens, maxTokens);
      if (ntokens > 0)
        break;
      if (ntokens == JSMN_ERROR_NOMEM)
        {
          maxTokens *= 2;
          tokens = (jsmntok_t *) realloc(tokens,sizeof(jsmntok_t)*maxTokens);
        }
    }

  if (tokens[0].type != JSMN_OBJECT)
    {
      fprintf(stderr,"(5) Bad link.*.json file: %s\n",name);
      exit(1);
    }

  int i = 1;
  while (i < ntokens)
    {
      if (tokens[i].type != JSMN_STRING )
        {
          fprintf(stderr,"(6) Bad file(%s): i: %d, Type: %d\n", name, i, tokens[i].type);
          exit(1);
        }
      std::string mapName(js, tokens[i].start, tokens[i].end - tokens[i].start); ++i;
      if (mapName == "function")
         processSet(name, js, i, ntokens, tokens, funcSet);
      else if (mapName == "linkA")
        processLibA(name, js, i, ntokens, tokens, libA);
      else if (mapName == "link_line")
        processArray(name,js, i, ntokens, tokens, linklineA);
      else if (mapName == "resultT")
          processTable(name,js, i, ntokens, tokens, resultT);
    }
  free(tokens);
}

void parseCompTJsonStr(const char* name, std::string& jsonStr, std::string& compiler, std::string& compilerPath,
                       Vstring& linklineA)
{
  jsmn_parser parser;
  jsmntok_t*  tokens;
  int         maxTokens = 1000;

  tokens = (jsmntok_t *) malloc(sizeof(jsmntok_t)*maxTokens);

  jsmn_init(&parser);

  // js - pointer to JSON string
  // tokens - an array of tokens available
  int ntokens;

  const char * js = jsonStr.c_str();

  while (1)
    {
      ntokens = jsmn_parse(&parser, js, jsonStr.size(), tokens, maxTokens);
      if (ntokens > 0)
        break;
      if (ntokens == JSMN_ERROR_NOMEM)
        {
          maxTokens *= 2;
          tokens = (jsmntok_t *) realloc(tokens,sizeof(jsmntok_t)*maxTokens);
        }
    }

  if (tokens[0].type != JSMN_OBJECT)
    {
      fprintf(stderr,"(5) Bad run.*.json file: %s\n",name);
      exit(1);
    }

  int i = 1;
  while (i < ntokens)
    {
      if (tokens[i].type != JSMN_STRING )
        {
          fprintf(stderr,"(6) Bad file(%s): i: %d, Type: %d\n", name, i, tokens[i].type);
          exit(1);
        }
      std::string mapName(js, tokens[i].start, tokens[i].end - tokens[i].start); ++i;
      if (mapName == "compiler")
        processValue(name,js, i, ntokens, tokens, compiler);
      else if (mapName == "compilerPath")
        processValue(name,js, i, ntokens, tokens, compilerPath);
      else if (mapName == "link_line")
        processArray(name,js, i, ntokens, tokens, linklineA);
    }
  free(tokens);
}
<commit_msg>typo in parseJsonStr.C<commit_after>#include <stdio.h>
#include <stdlib.h>

#include "parseJsonStr.h"
#include "xalt_quotestring.h"

void processArray(const char* name, const char* js, int& i, int ntokens, jsmntok_t* tokens, Vstring& vA)
{
  if (tokens[i].type != JSMN_ARRAY)
    {
      fprintf(stderr,"processArray for: %s, token type is not an array\n",name);
      fprintf(stderr, "%d: type: %d, start: %d, end: %d, size: %d, parent: %d\n",
              i, tokens[i].type, tokens[i].start, tokens[i].end, tokens[i].size, tokens[i].parent);
      exit(1);
    }

  int iend = tokens[i].end;

  std::string  value;
  const char * p;

  ++i;
  while (i < ntokens)
    {
      if (tokens[i].start > iend)
        return;

      if (tokens[i].type != JSMN_STRING)
        {
          fprintf(stderr,"processArray for: %s, token type is not a string\n",name);
          exit(1);
        }
      p = xalt_unquotestring(&js[tokens[i].start],tokens[i].end - tokens[i].start); ++i;
      value.assign(p);
      vA.push_back(value);
    }
}

void processSet(const char* name, const char* js, int& i, int ntokens, jsmntok_t* tokens, Set& set)
{
  if (tokens[i].type != JSMN_ARRAY)
    {
      fprintf(stderr,"processSet for: %s, token type is not an array\n",name);
      fprintf(stderr, "%d: type: %d, start: %d, end: %d, size: %d, parent: %d\n",
              i, tokens[i].type, tokens[i].start, tokens[i].end, tokens[i].size, tokens[i].parent);
      exit(1);
    }

  int iend = tokens[i].end;
  std::string value;
  const char  *p;

  ++i;
  while (i < ntokens)
    {
      if (tokens[i].start > iend)
        return;

      if (tokens[i].type != JSMN_STRING)
        {
          fprintf(stderr,"processSet for: %s, token type is not a string\n",name);
          exit(1);
        }
      p = xalt_unquotestring(&js[tokens[i].start],tokens[i].end - tokens[i].start); ++i;
      value.assign(p);
      set.insert(value);
    }
}
void processTable(const char* name, const char* js, int& i, int ntokens, jsmntok_t* tokens, Table& t)
{
  if (tokens[i].type != JSMN_OBJECT)
    {
      fprintf(stderr,"processTable for: %s, token type is not an object\n",name);
      fprintf(stderr, "%d: type: %d, start: %d, end: %d, size: %d, parent: %d\n",
              i, tokens[i].type, tokens[i].start, tokens[i].end, tokens[i].size, tokens[i].parent);
      exit(1);
    }

  int iend = tokens[i].end;
  std::string key;
  std::string value;
  const char  *p;

  ++i;
  while (i < ntokens)
    {
      if (tokens[i].start > iend)
        return;

      if (tokens[i].type != JSMN_STRING && tokens[i+1].type != JSMN_STRING)
        {
          fprintf(stderr,"processTable for: %s, token types are not strings\n",name);
          exit(1);
        }
      p = xalt_unquotestring(&js[tokens[i].start],tokens[i].end - tokens[i].start); ++i;
      key.assign(p);
      p = xalt_unquotestring(&js[tokens[i].start],tokens[i].end - tokens[i].start); ++i;
      value.assign(p);
      t[key] = value;
    }
}
void processA2JsonStr(const char* name, const char* js, int& i, int ntokens, jsmntok_t* tokens, std::string& value)
{
  value = "[";
  if (tokens[i].type != JSMN_ARRAY)
    {
      fprintf(stderr,"processA2JsonStr for: %s, token type is not an array\n",name);
      fprintf(stderr, "%d: type: %d, start: %d, end: %d, size: %d, parent: %d\n",
              i, tokens[i].type, tokens[i].start, tokens[i].end, tokens[i].size, tokens[i].parent);
      exit(1);
    }

  int iend = tokens[i].end;

  ++i;
  while (i < ntokens)
    {
      if (tokens[i].start > iend)
        break;

      if (tokens[i].type != JSMN_STRING)
        {
          fprintf(stderr,"processSet for: %s, token type is not a string\n",name);
          exit(1);
        }
      value.append("\"");
      value.append(&js[tokens[i].start], tokens[i].end - tokens[i].start); ++i;
      value.append("\",");
    }
  if (value.back() == ',')
    value.replace(value.size()-1,1,"]");
  else
    value.append("]");
}

void processLibA(const char* name, const char* js, int& i, int ntokens, jsmntok_t* tokens, std::vector<Libpair>& libA)
{
  if (tokens[i].type != JSMN_ARRAY)
    {
      fprintf(stderr,"processTable for: %s, token type is not an object\n",name);
      fprintf(stderr, "%d: type: %d, start: %d, end: %d, size: %d, parent: %d\n",
              i, tokens[i].type, tokens[i].start, tokens[i].end, tokens[i].size, tokens[i].parent);
      exit(1);
    }

  int iend = tokens[i].end;
  std::string lib;
  std::string sha1;
  const char  *p;

  ++i;
  while (i < ntokens)
    {
      if (tokens[i].start > iend)
        return;

      if (tokens[i].type != JSMN_ARRAY)
        {
          fprintf(stderr,"processLibA for %s: token type is not an array\n",name);
          exit(1);
        }
      i++;
      if (tokens[i].type != JSMN_STRING && tokens[i+1].type != JSMN_STRING)
        {
          fprintf(stderr,"processLibA for: %s, token types are not strings\n",name);
          exit(1);
        }

      p = xalt_unquotestring(&js[tokens[i].start],tokens[i].end - tokens[i].start); ++i;
      lib.assign(p);
      sha1.assign(&js[tokens[i].start],tokens[i].end - tokens[i].start);            ++i;
      Libpair libpair(lib,sha1);
      libA.push_back(libpair);
    }
}

void processValue(const char* name, const char* js, int& i, int ntokens, jsmntok_t* tokens, std::string& value)
{
  if (tokens[i].type != JSMN_STRING)
    {
      fprintf(stderr,"processValue for: %s, token type is not an object\n",name);
      fprintf(stderr, "%d: type: %d, start: %d, end: %d, size: %d, parent: %d\n", i, tokens[i].type, tokens[i].start, tokens[i].end, tokens[i].size, tokens[i].parent);
      exit(1);
    }

  value.assign( js, tokens[i].start, tokens[i].end - tokens[i].start);
  i++;
}

void parseRunJsonStr(const char* name, std::string& jsonStr, std::string& usr_cmdline, std::string& hash_id,
                     Table& envT, Table& userT, Table& recordT, std::vector<Libpair>& libA)
{
  jsmn_parser parser;
  jsmntok_t*  tokens;
  int         maxTokens = 1000;

  tokens = (jsmntok_t *) malloc(sizeof(jsmntok_t)*maxTokens);

  jsmn_init(&parser);

  // js - pointer to JSON string
  // tokens - an array of tokens available
  int ntokens;

  const char * js = jsonStr.c_str();

  while (1)
    {
      ntokens = jsmn_parse(&parser, js, jsonStr.size(), tokens, maxTokens);
      if (ntokens > 0)
        break;
      if (ntokens == JSMN_ERROR_NOMEM)
        {
          maxTokens *= 2;
          tokens = (jsmntok_t *) realloc(tokens,sizeof(jsmntok_t)*maxTokens);
        }
    }

  if (tokens[0].type != JSMN_OBJECT)
    {
      fprintf(stderr,"(5) Bad run.*.json file: %s\n",name);
      exit(1);
    }

  int i = 1;
  while (i < ntokens)
    {
      if (tokens[i].type != JSMN_STRING )
        {
          fprintf(stderr,"(6) Bad file(%s): i: %d, Type: %d\n", name, i, tokens[i].type);
          fprintf(stderr,"%.*s\n",tokens[i].end - tokens[i].start, &js[tokens[i].start]);
          exit(1);
        }
      std::string mapName(js, tokens[i].start, tokens[i].end - tokens[i].start); ++i;
      if (mapName == "cmdlineA")
        processA2JsonStr(name, js, i, ntokens, tokens, usr_cmdline);
      else if (mapName == "envT")
        processTable(name,js, i, ntokens, tokens, envT);
      else if (mapName == "hash_id")
        processValue(name,js, i, ntokens, tokens, hash_id);
      else if (mapName == "libA")
        processLibA(name, js, i, ntokens, tokens, libA);
      else if (mapName == "userT")
        processTable(name,js, i, ntokens, tokens, userT);
      else if (mapName == "xaltLinkT")
        processTable(name,js, i, ntokens, tokens, recordT);
    }
  free(tokens);
}

void parseLinkJsonStr(const char* name, std::string& jsonStr, Vstring& linklineA, Table& resultT, std::vector<Libpair>& libA, Set& funcSet)
{
  jsmn_parser parser;
  jsmntok_t*  tokens;
  int         maxTokens = 1000;

  tokens = (jsmntok_t *) malloc(sizeof(jsmntok_t)*maxTokens);

  jsmn_init(&parser);

  // js - pointer to JSON string
  // tokens - an array of tokens available
  int ntokens;

  const char * js = jsonStr.c_str();

  while (1)
    {
      ntokens = jsmn_parse(&parser, js, jsonStr.size(), tokens, maxTokens);
      if (ntokens > 0)
        break;
      if (ntokens == JSMN_ERROR_NOMEM)
        {
          maxTokens *= 2;
          tokens = (jsmntok_t *) realloc(tokens,sizeof(jsmntok_t)*maxTokens);
        }
    }

  if (tokens[0].type != JSMN_OBJECT)
    {
      fprintf(stderr,"(5) Bad link.*.json file: %s\n",name);
      exit(1);
    }

  int i = 1;
  while (i < ntokens)
    {
      if (tokens[i].type != JSMN_STRING )
        {
          fprintf(stderr,"(6) Bad file(%s): i: %d, Type: %d\n", name, i, tokens[i].type);
          exit(1);
        }
      std::string mapName(js, tokens[i].start, tokens[i].end - tokens[i].start); ++i;
      if (mapName == "function")
         processSet(name, js, i, ntokens, tokens, funcSet);
      else if (mapName == "linkA")
        processLibA(name, js, i, ntokens, tokens, libA);
      else if (mapName == "link_line")
        processArray(name,js, i, ntokens, tokens, linklineA);
      else if (mapName == "resultT")
          processTable(name,js, i, ntokens, tokens, resultT);
    }
  free(tokens);
}

void parseCompTJsonStr(const char* name, std::string& jsonStr, std::string& compiler, std::string& compilerPath,
                       Vstring& linklineA)
{
  jsmn_parser parser;
  jsmntok_t*  tokens;
  int         maxTokens = 1000;

  tokens = (jsmntok_t *) malloc(sizeof(jsmntok_t)*maxTokens);

  jsmn_init(&parser);

  // js - pointer to JSON string
  // tokens - an array of tokens available
  int ntokens;

  const char * js = jsonStr.c_str();

  while (1)
    {
      ntokens = jsmn_parse(&parser, js, jsonStr.size(), tokens, maxTokens);
      if (ntokens > 0)
        break;
      if (ntokens == JSMN_ERROR_NOMEM)
        {
          maxTokens *= 2;
          tokens = (jsmntok_t *) realloc(tokens,sizeof(jsmntok_t)*maxTokens);
        }
    }

  if (tokens[0].type != JSMN_OBJECT)
    {
      fprintf(stderr,"(5) Bad run.*.json file: %s\n",name);
      exit(1);
    }

  int i = 1;
  while (i < ntokens)
    {
      if (tokens[i].type != JSMN_STRING )
        {
          fprintf(stderr,"(6) Bad file(%s): i: %d, Type: %d\n", name, i, tokens[i].type);
          exit(1);
        }
      std::string mapName(js, tokens[i].start, tokens[i].end - tokens[i].start); ++i;
      if (mapName == "compiler")
        processValue(name,js, i, ntokens, tokens, compiler);
      else if (mapName == "compilerPath")
        processValue(name,js, i, ntokens, tokens, compilerPath);
      else if (mapName == "link_line")
        processArray(name,js, i, ntokens, tokens, linklineA);
    }
  free(tokens);
}
<|endoftext|>


<commit_before>#pragma once

#include <cmath>
#include <limits>
#include <type_traits>
#include <algorithm>

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

// http://en.cppreference.com/w/cpp/types/numeric_limits/epsilon
template<typename T> typename std::enable_if<!std::numeric_limits<T>::is_integer, bool>::type
inline float_equal(T x, T y, int ulp=1)
{
    // the machine epsilon has to be scaled to the magnitude of the values used
    // and multiplied by the desired precision in ULPs (units in the last place)
    return std::abs(x-y) < std::numeric_limits<T>::epsilon() * std::abs(x+y) * ulp
    // unless the result is subnormal
                           || std::abs(x-y) < std::numeric_limits<T>::min();
}

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

template<typename T> typename std::enable_if<!std::numeric_limits<T>::is_integer, bool>::type
inline float_zero(T x, int ulp=1)
{
    return float_equal(x, T(0), ulp);
}

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

inline std::string double_to_string(double value)
{
    constexpr const size_t buffer_size = 100;
    char buffer[buffer_size + 1];
    const int written = snprintf(buffer, buffer_size, "%.32g", value);
    if (written < 0 && static_cast<size_t>(written) >= buffer_size)
        throw std::runtime_error("double_to_string internal error");
    return {buffer, static_cast<size_t>(written)};
}

// ----------------------------------------------------------------------
<commit_msg>bug fix<commit_after>#pragma once

#include <string>
#include <cmath>
#include <limits>
#include <type_traits>
#include <algorithm>
#include <stdexcept>

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

// http://en.cppreference.com/w/cpp/types/numeric_limits/epsilon
template<typename T> typename std::enable_if<!std::numeric_limits<T>::is_integer, bool>::type
inline float_equal(T x, T y, int ulp=1)
{
    // the machine epsilon has to be scaled to the magnitude of the values used
    // and multiplied by the desired precision in ULPs (units in the last place)
    return std::abs(x-y) < std::numeric_limits<T>::epsilon() * std::abs(x+y) * ulp
    // unless the result is subnormal
                           || std::abs(x-y) < std::numeric_limits<T>::min();
}

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

template<typename T> typename std::enable_if<!std::numeric_limits<T>::is_integer, bool>::type
inline float_zero(T x, int ulp=1)
{
    return float_equal(x, T(0), ulp);
}

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

inline std::string double_to_string(double value)
{
    constexpr const size_t buffer_size = 100;
    char buffer[buffer_size + 1];
    const int written = snprintf(buffer, buffer_size, "%.32g", value);
    if (written < 0 && static_cast<size_t>(written) >= buffer_size)
        throw std::runtime_error("double_to_string internal error");
    return {buffer, static_cast<size_t>(written)};
}

// ----------------------------------------------------------------------
<|endoftext|>


<commit_before>// UjoImro, 2013

#include <chrono>
#include <opencv2/opencv.hpp>
#include <opencv2/ocl/ocl.hpp>
#include <opencv2/imgproc/imgproc.hpp>

#include "opencl.hpp"
#include "utility.hpp"
#include "filtering_boxFilter.clh"

namespace
{
    inline void normalizeAnchor(int &anchor, int ksize)
    {
        if (anchor < 0)
        {
            anchor = ksize >> 1;
        }

        CV_Assert(0 <= anchor && anchor < ksize);
    }

    inline void normalizeAnchor(cv::Point &anchor, const cv::Size &ksize)
    {
        normalizeAnchor(anchor.x, ksize.width);
        normalizeAnchor(anchor.y, ksize.height);
    }

} // unnamed namespace

template<class T0>
void
time_boxFilter( carp::opencl::device & device, T0 & pool )
{
    std::vector<int> ksizes = { 11,15,21,25,31,35,41 };
    std::vector<std::pair<std::string, int> > border_types =
        { {"BORDER_REPLICATE",   cv::BORDER_REPLICATE },
          {"BORDER_REFLECT",     cv::BORDER_REFLECT },
          {"BORDER_REFLECT_101", cv::BORDER_REFLECT_101 },
//          {"BORDER_WRAP",        cv::BORDER_WRAP },
          {"BORDER_CONSTANT",    cv::BORDER_CONSTANT } };

    double sum_quotient = 0;

    for ( auto & item : pool ) {

        PRINT(item.path());
        for ( auto size : ksizes ) {

            PRINT(size);
            long int elapsed_time_gpu = 0;
            long int elapsed_time_cpu = 0;

            for ( auto & border_type : border_types ) {
                // PRINT(border_type.first);

                cv::Mat host_filtered;
                cv::Mat cpu_gray;
                cv::Mat check;

                // the ksize must be 2k+1 form and anchor must be (2k+1)<<1
                cv::Size  ksize(size,size);
                cv::Point anchor((size>>1),(size>>1));

                cv::cvtColor( item.cpuimg(), cpu_gray, CV_RGB2GRAY );
                auto cpu_start = std::chrono::high_resolution_clock::now();
                cv::boxFilter( cpu_gray, host_filtered, -1, ksize, anchor, true, border_type.second );
                auto cpu_end = std::chrono::high_resolution_clock::now();
                elapsed_time_cpu += carp::microseconds(cpu_end - cpu_start);

                cv::ocl::oclMat gpu_result;
                cv::ocl::oclMat gpu_gray(cpu_gray);
                gpu_result.create( cpu_gray.rows, cpu_gray.cols, CV_8U );
                float alpha = ksize.height * ksize.width;
                size_t blockSizeX = 256, blockSizeY = 1;
                size_t gSize = blockSizeX - (ksize.width - 1);
                size_t threads = (gpu_result.offset % gpu_result.step % 4 + gpu_result.cols + 3) / 4;
                size_t globalSizeX = threads % gSize == 0 ? threads / gSize * blockSizeX : (threads / gSize + 1) * blockSizeX;
                size_t globalSizeY = ((gpu_result.rows + 1) / 2) % blockSizeY == 0 ? ((gpu_result.rows + 1) / 2) : (((gpu_result.rows + 1) / 2) / blockSizeY + 1) * blockSizeY;

                size_t globalThreads[3] = { globalSizeX, globalSizeY, 1 };
                size_t localThreads[3]  = { blockSizeX, blockSizeY, 1 };
                normalizeAnchor(anchor, ksize);

                auto gpu_start = std::chrono::high_resolution_clock::now();
                device.source_compile(
                    filtering_boxFilter_cl,
                    filtering_boxFilter_cl_len,
                    carp::string_vector("boxFilter_C1_D0"),
                    "   -D anX=" + carp::cast<std::string>(anchor.x)
                    + " -D anY=" + carp::cast<std::string>(anchor.y)
                    + " -D ksX=" + carp::cast<std::string>(ksize.width)
                    + " -D ksY=" + carp::cast<std::string>(ksize.height)
                    + " -D " + border_type.first );

                device["boxFilter_C1_D0"] (
                    reinterpret_cast<cl_mem>(gpu_gray.data),
                    reinterpret_cast<cl_mem>(gpu_result.data),
                    static_cast<cl_float>(alpha),
                    gpu_gray.offset,
                    gpu_gray.wholerows,
                    gpu_gray.wholecols,
                    static_cast<int>(gpu_gray.step),
                    gpu_result.offset,
                    gpu_result.rows,
                    gpu_result.cols,
                    static_cast<int>(gpu_result.step)
                    ).groupsize( { blockSizeX, blockSizeY, 1 }, { globalSizeX, globalSizeY, 1 } );
                // //.groupsize( localThreads, globalThreads );
                auto gpu_end = std::chrono::high_resolution_clock::now();
                elapsed_time_gpu += carp::microseconds(gpu_end - gpu_start);
                device.erase("boxFilter_C1_D0");
                check = gpu_result;

                // Verifying the results
                if ( cv::norm(check - host_filtered) > 0.01 ) {
                    PRINT(cv::norm(check - host_filtered));
                    cv::imwrite( "gpu_boxFilter_img.png", check );
                    cv::imwrite( "cpu_boxFilter_img.png", host_filtered );
                    throw std::runtime_error("The GPU results are not equivalent with the CPU results.");
                }

            } // for border_type

            carp::Timing::print( "cvtColor", elapsed_time_cpu, elapsed_time_gpu );

            if (elapsed_time_gpu > 1)
                sum_quotient += static_cast<double>(elapsed_time_cpu) / elapsed_time_gpu;

        } // for size

    } // for item

    std::cout << "Cumulated Speed Improvement: " << (sum_quotient/pool.size()/ksizes.size()) << "x" << std::endl;

    return;
} // text_boxFilter

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

    std::cout << "This executable is iterating over all the files which are present in the directory `./pool'. " << std::endl;

    auto pool = carp::get_pool("pool");

    // Initializing OpenCL
    cv::ocl::Context * context = cv::ocl::Context::getContext();
    carp::Timing::printHeader();
    carp::opencl::device device(context);
    time_boxFilter( device, pool );

    return EXIT_SUCCESS;
} // main

// LuM end of file
<commit_msg>boxFilter name change<commit_after>// UjoImro, 2013

#include <chrono>
#include <opencv2/opencv.hpp>
#include <opencv2/ocl/ocl.hpp>
#include <opencv2/imgproc/imgproc.hpp>

#include "opencl.hpp"
#include "utility.hpp"
#include "filtering_boxFilter.clh"

namespace
{
    inline void normalizeAnchor(int &anchor, int ksize)
    {
        if (anchor < 0)
        {
            anchor = ksize >> 1;
        }

        CV_Assert(0 <= anchor && anchor < ksize);
    }

    inline void normalizeAnchor(cv::Point &anchor, const cv::Size &ksize)
    {
        normalizeAnchor(anchor.x, ksize.width);
        normalizeAnchor(anchor.y, ksize.height);
    }

} // unnamed namespace

template<class T0>
void
time_boxFilter( carp::opencl::device & device, T0 & pool )
{
    std::vector<int> ksizes = { 11,15,21,25,31,35,41 };
    std::vector<std::pair<std::string, int> > border_types =
        { {"BORDER_REPLICATE",   cv::BORDER_REPLICATE },
          {"BORDER_REFLECT",     cv::BORDER_REFLECT },
          {"BORDER_REFLECT_101", cv::BORDER_REFLECT_101 },
//          {"BORDER_WRAP",        cv::BORDER_WRAP },
          {"BORDER_CONSTANT",    cv::BORDER_CONSTANT } };

    double sum_quotient = 0;

    for ( auto & item : pool ) {

        PRINT(item.path());
        for ( auto size : ksizes ) {

            PRINT(size);
            long int elapsed_time_gpu = 0;
            long int elapsed_time_cpu = 0;

            for ( auto & border_type : border_types ) {
                // PRINT(border_type.first);

                cv::Mat host_filtered;
                cv::Mat cpu_gray;
                cv::Mat check;

                // the ksize must be 2k+1 form and anchor must be (2k+1)<<1
                cv::Size  ksize(size,size);
                cv::Point anchor((size>>1),(size>>1));

                cv::cvtColor( item.cpuimg(), cpu_gray, CV_RGB2GRAY );
                auto cpu_start = std::chrono::high_resolution_clock::now();
                cv::boxFilter( cpu_gray, host_filtered, -1, ksize, anchor, true, border_type.second );
                auto cpu_end = std::chrono::high_resolution_clock::now();
                elapsed_time_cpu += carp::microseconds(cpu_end - cpu_start);

                cv::ocl::oclMat gpu_result;
                cv::ocl::oclMat gpu_gray(cpu_gray);
                gpu_result.create( cpu_gray.rows, cpu_gray.cols, CV_8U );
                float alpha = ksize.height * ksize.width;
                size_t blockSizeX = 256, blockSizeY = 1;
                size_t gSize = blockSizeX - (ksize.width - 1);
                size_t threads = (gpu_result.offset % gpu_result.step % 4 + gpu_result.cols + 3) / 4;
                size_t globalSizeX = threads % gSize == 0 ? threads / gSize * blockSizeX : (threads / gSize + 1) * blockSizeX;
                size_t globalSizeY = ((gpu_result.rows + 1) / 2) % blockSizeY == 0 ? ((gpu_result.rows + 1) / 2) : (((gpu_result.rows + 1) / 2) / blockSizeY + 1) * blockSizeY;

                size_t globalThreads[3] = { globalSizeX, globalSizeY, 1 };
                size_t localThreads[3]  = { blockSizeX, blockSizeY, 1 };
                normalizeAnchor(anchor, ksize);

                auto gpu_start = std::chrono::high_resolution_clock::now();
                device.source_compile(
                    filtering_boxFilter_cl,
                    filtering_boxFilter_cl_len,
                    carp::string_vector("boxFilter_C1_D0"),
                    "   -D anX=" + carp::cast<std::string>(anchor.x)
                    + " -D anY=" + carp::cast<std::string>(anchor.y)
                    + " -D ksX=" + carp::cast<std::string>(ksize.width)
                    + " -D ksY=" + carp::cast<std::string>(ksize.height)
                    + " -D " + border_type.first );

                device["boxFilter_C1_D0"] (
                    reinterpret_cast<cl_mem>(gpu_gray.data),
                    reinterpret_cast<cl_mem>(gpu_result.data),
                    static_cast<cl_float>(alpha),
                    gpu_gray.offset,
                    gpu_gray.wholerows,
                    gpu_gray.wholecols,
                    static_cast<int>(gpu_gray.step),
                    gpu_result.offset,
                    gpu_result.rows,
                    gpu_result.cols,
                    static_cast<int>(gpu_result.step)
                    ).groupsize( { blockSizeX, blockSizeY, 1 }, { globalSizeX, globalSizeY, 1 } );
                // //.groupsize( localThreads, globalThreads );
                auto gpu_end = std::chrono::high_resolution_clock::now();
                elapsed_time_gpu += carp::microseconds(gpu_end - gpu_start);
                device.erase("boxFilter_C1_D0");
                check = gpu_result;

                // Verifying the results
                if ( cv::norm(check - host_filtered) > 0.01 ) {
                    PRINT(cv::norm(check - host_filtered));
                    cv::imwrite( "gpu_boxFilter_img.png", check );
                    cv::imwrite( "cpu_boxFilter_img.png", host_filtered );
                    throw std::runtime_error("The GPU results are not equivalent with the CPU results.");
                }

            } // for border_type

            carp::Timing::print( "boxFilter", elapsed_time_cpu, elapsed_time_gpu );

            if (elapsed_time_gpu > 1)
                sum_quotient += static_cast<double>(elapsed_time_cpu) / elapsed_time_gpu;

        } // for size

    } // for item

    std::cout << "Cumulated Speed Improvement: " << (sum_quotient/pool.size()/ksizes.size()) << "x" << std::endl;

    return;
} // text_boxFilter

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

    std::cout << "This executable is iterating over all the files which are present in the directory `./pool'. " << std::endl;

    auto pool = carp::get_pool("pool");

    // Initializing OpenCL
    cv::ocl::Context * context = cv::ocl::Context::getContext();
    carp::Timing::printHeader();
    carp::opencl::device device(context);
    time_boxFilter( device, pool );

    return EXIT_SUCCESS;
} // main

// LuM end of file
<|endoftext|>


<commit_before>#pragma once

#include <SFML/Graphics.hpp>
#include <bitset>
#include <string>
#include "SceneManager.hpp"
#include "SoundManager.hpp"
#include "TextureManager.hpp"

#define PATH "./"
#define INPUT_SIZE 6

namespace global {

	static const unsigned int numLevels = 9;

	// window properties
	static const int pixelSizeX = 16;
	static const int pixelSizeY = 16;
	static const int sizeX = 5;
	static const int sizeY = 4;
	static const int largeTileSizeX = 6;
	static const int largeTileSizeY = 6;
	static const int gridWidth = largeTileSizeX * sizeX * pixelSizeX;
	static const int gridHeight = largeTileSizeY * sizeY * pixelSizeY;
	static const int screenWidth = 800;
	static const int screenHeight = 600;

	// define number of keyboards binding
	typedef std::bitset<INPUT_SIZE> InputType;
	extern sf::Keyboard::Key keyboardBinding[INPUT_SIZE];

	extern sf::RenderWindow window;
	extern SceneManager sceneManager;
	extern SoundManager soundManager;
	extern TextureManager textureManager;

	extern bool inMenu;
	extern bool showOutline;
	extern InputType input;
	extern sf::Clock clock;

}
<commit_msg>Anzahl der Level angepasst<commit_after>#pragma once

#include <SFML/Graphics.hpp>
#include <bitset>
#include <string>
#include "SceneManager.hpp"
#include "SoundManager.hpp"
#include "TextureManager.hpp"

#define PATH "./"
#define INPUT_SIZE 6

namespace global {

	static const unsigned int numLevels = 10;

	// window properties
	static const int pixelSizeX = 16;
	static const int pixelSizeY = 16;
	static const int sizeX = 5;
	static const int sizeY = 4;
	static const int largeTileSizeX = 6;
	static const int largeTileSizeY = 6;
	static const int gridWidth = largeTileSizeX * sizeX * pixelSizeX;
	static const int gridHeight = largeTileSizeY * sizeY * pixelSizeY;
	static const int screenWidth = 800;
	static const int screenHeight = 600;

	// define number of keyboards binding
	typedef std::bitset<INPUT_SIZE> InputType;
	extern sf::Keyboard::Key keyboardBinding[INPUT_SIZE];

	extern sf::RenderWindow window;
	extern SceneManager sceneManager;
	extern SoundManager soundManager;
	extern TextureManager textureManager;

	extern bool inMenu;
	extern bool showOutline;
	extern InputType input;
	extern sf::Clock clock;

}
<|endoftext|>


<commit_before>// This file is part of Playslave-C++.
// Playslave-C++ is licenced under the MIT license: see LICENSE.txt.

/**
 * @file
 * The RingBuffer class template.
 */

#ifndef PS_RINGBUFFER_HPP
#define PS_RINGBUFFER_HPP

extern "C" {
#include "../contrib/pa_ringbuffer.h"
}

/**
 * A ring buffer.
 *
 * This ring buffer is based on the PortAudio ring buffer, provided in the
 * contrib/ directory.
 *
 * This is stable and performs well, but, as it is C code, necessitates some
 * hoop jumping to integrate and could do with being replaced with a native
 * solution.
 */
template <typename RepT, typename SampleCountT>
class RingBuffer {
public:
	/**
	 * Constructs a RingBuffer.
	 * @param power n, where 2^n is the number of elements in the ring
	 *   buffer.
	 * @param size The size of one element in the ring buffer.
	 */
	RingBuffer(int power, int size)
	{
		this->rb = new PaUtilRingBuffer;
		this->buffer = new char[(1 << power) * size];

		int init_result = PaUtil_InitializeRingBuffer(
		                this->rb, size,
		                static_cast<ring_buffer_size_t>(1 << power),
		                this->buffer);
		if (init_result != 0) {
			throw InternalError(MSG_OUTPUT_RINGINIT);
		}
	}

	/// Destructs a PaRingBuffer.
	~RingBuffer()
	{
		assert(this->rb != nullptr);
		delete this->rb;

		assert(this->buffer != nullptr);
		delete[] this->buffer;
	}

	/// Deleted copy constructor.
	RingBuffer(const RingBuffer &) = delete;

	/// Deleted copy-assignment.
	RingBuffer &operator=(const RingBuffer &) = delete;

	/**
	 * The current write capacity.
	 * @return The number of samples this ring buffer has space to store.
	 */
	SampleCountT WriteCapacity() const
	{
		return CountCast(PaUtil_GetRingBufferWriteAvailable(this->rb));
	}

	/**
	 * The current read capacity.
	 * @return The number of samples available in this ring buffer.
	 */
	SampleCountT ReadCapacity() const
	{
		return CountCast(PaUtil_GetRingBufferReadAvailable(this->rb));
	}

	/**
	 * Writes samples from an array into the ring buffer.
	 *
	 * To write one sample, pass a count of 1 and take a pointer to the
	 * sample variable.
	 *
	 * Note that start pointer is not constant.  This is because the
	 * underlying implementation of the ring buffer might not guarantee
	 * that the array is left untouched.
	 *
	 * @param start The start of the array buffer from which we read
	 *   samples.  Must not be nullptr.
	 * @param count The number of samples to write.  This must not exceed
	 *   the minimum of WriteCapacity() and the length of the array.
	 *
	 * @return The number of samples written, which should not exceed count.
	 */
	SampleCountT Write(RepT *start, SampleCountT count)
	{
		return CountCast(PaUtil_WriteRingBuffer(
		                this->rb, start,
		                static_cast<ring_buffer_size_t>(count)));
	}

	/**
	 * Reads samples from the ring buffer into an array.
	 *
	 * To read one sample, pass a count of 1 and take a pointer to the
	 * sample variable.
	 *
	 * @param start The start of the array buffer to which we write samples.
	 *   Must not be nullptr.
	 * @param count The number of samples to read.  This must not exceed the
	 *   minimum of ReadCapacity() and the length of the array.
	 *
	 * @return The number of samples read, which should not exceed count.
	 */
	SampleCountT Read(RepT *start, SampleCountT count)
	{
		return CountCast(PaUtil_ReadRingBuffer(
		                this->rb, start,
		                static_cast<ring_buffer_size_t>(count)));
	}

	/// Empties the ring buffer.
	void Flush() { PaUtil_FlushRingBuffer(this->rb); }

private:
	char *buffer;         ///< The array used by the ringbuffer.
	PaUtilRingBuffer *rb; ///< The internal PortAudio ringbuffer.

	/**
	 * Converts a ring buffer size into an external size.
	 * @param count  The size/count in PortAudio form.
	 * @return       The size/count after casting to SampleCountT.
	 */
	SampleCountT CountCast(ring_buffer_size_t count) const
	{
		return static_cast<SampleCountT>(count);
	}
};

#endif // PS_RINGBUFFER_HPP
<commit_msg>Add missing messages.h include.<commit_after>// This file is part of Playslave-C++.
// Playslave-C++ is licenced under the MIT license: see LICENSE.txt.

/**
 * @file
 * The RingBuffer class template.
 */

#ifndef PS_RINGBUFFER_HPP
#define PS_RINGBUFFER_HPP

extern "C" {
#include "../contrib/pa_ringbuffer.h"
}

#include "../messages.h"

/**
 * A ring buffer.
 *
 * This ring buffer is based on the PortAudio ring buffer, provided in the
 * contrib/ directory.
 *
 * This is stable and performs well, but, as it is C code, necessitates some
 * hoop jumping to integrate and could do with being replaced with a native
 * solution.
 */
template <typename RepT, typename SampleCountT>
class RingBuffer {
public:
	/**
	 * Constructs a RingBuffer.
	 * @param power n, where 2^n is the number of elements in the ring
	 *   buffer.
	 * @param size The size of one element in the ring buffer.
	 */
	RingBuffer(int power, int size)
	{
		this->rb = new PaUtilRingBuffer;
		this->buffer = new char[(1 << power) * size];

		int init_result = PaUtil_InitializeRingBuffer(
		                this->rb, size,
		                static_cast<ring_buffer_size_t>(1 << power),
		                this->buffer);
		if (init_result != 0) {
			throw InternalError(MSG_OUTPUT_RINGINIT);
		}
	}

	/// Destructs a PaRingBuffer.
	~RingBuffer()
	{
		assert(this->rb != nullptr);
		delete this->rb;

		assert(this->buffer != nullptr);
		delete[] this->buffer;
	}

	/// Deleted copy constructor.
	RingBuffer(const RingBuffer &) = delete;

	/// Deleted copy-assignment.
	RingBuffer &operator=(const RingBuffer &) = delete;

	/**
	 * The current write capacity.
	 * @return The number of samples this ring buffer has space to store.
	 */
	SampleCountT WriteCapacity() const
	{
		return CountCast(PaUtil_GetRingBufferWriteAvailable(this->rb));
	}

	/**
	 * The current read capacity.
	 * @return The number of samples available in this ring buffer.
	 */
	SampleCountT ReadCapacity() const
	{
		return CountCast(PaUtil_GetRingBufferReadAvailable(this->rb));
	}

	/**
	 * Writes samples from an array into the ring buffer.
	 *
	 * To write one sample, pass a count of 1 and take a pointer to the
	 * sample variable.
	 *
	 * Note that start pointer is not constant.  This is because the
	 * underlying implementation of the ring buffer might not guarantee
	 * that the array is left untouched.
	 *
	 * @param start The start of the array buffer from which we read
	 *   samples.  Must not be nullptr.
	 * @param count The number of samples to write.  This must not exceed
	 *   the minimum of WriteCapacity() and the length of the array.
	 *
	 * @return The number of samples written, which should not exceed count.
	 */
	SampleCountT Write(RepT *start, SampleCountT count)
	{
		return CountCast(PaUtil_WriteRingBuffer(
		                this->rb, start,
		                static_cast<ring_buffer_size_t>(count)));
	}

	/**
	 * Reads samples from the ring buffer into an array.
	 *
	 * To read one sample, pass a count of 1 and take a pointer to the
	 * sample variable.
	 *
	 * @param start The start of the array buffer to which we write samples.
	 *   Must not be nullptr.
	 * @param count The number of samples to read.  This must not exceed the
	 *   minimum of ReadCapacity() and the length of the array.
	 *
	 * @return The number of samples read, which should not exceed count.
	 */
	SampleCountT Read(RepT *start, SampleCountT count)
	{
		return CountCast(PaUtil_ReadRingBuffer(
		                this->rb, start,
		                static_cast<ring_buffer_size_t>(count)));
	}

	/// Empties the ring buffer.
	void Flush() { PaUtil_FlushRingBuffer(this->rb); }

private:
	char *buffer;         ///< The array used by the ringbuffer.
	PaUtilRingBuffer *rb; ///< The internal PortAudio ringbuffer.

	/**
	 * Converts a ring buffer size into an external size.
	 * @param count  The size/count in PortAudio form.
	 * @return       The size/count after casting to SampleCountT.
	 */
	SampleCountT CountCast(ring_buffer_size_t count) const
	{
		return static_cast<SampleCountT>(count);
	}
};

#endif // PS_RINGBUFFER_HPP
<|endoftext|>


<commit_before>/*  IBM_PROLOG_BEGIN_TAG
 *  This is an automatically generated prolog.
 *
 *  $Source: src/usr/diag/attn/test/attnfakeprd.C $
 *
 *  IBM CONFIDENTIAL
 *
 *  COPYRIGHT International Business Machines Corp. 2012
 *
 *  p1
 *
 *  Object Code Only (OCO) source materials
 *  Licensed Internal Code Source Materials
 *  IBM HostBoot Licensed Internal Code
 *
 *  The source code for this program is not published or other-
 *  wise divested of its trade secrets, irrespective of what has
 *  been deposited with the U.S. Copyright Office.
 *
 *  Origin: 30
 *
 *  IBM_PROLOG_END_TAG
 */
/**
 * @file attnfakeprd.C
 *
 * @brief HBATTN fake PRD class method definitions.
 */

#include "attnfakeprd.H"
#include "attnfakesys.H"
#include "../attnops.H"
#include "../attnlist.H"
#include <sys/time.h>

using namespace PRDF;

namespace ATTN
{

struct Clear
{
    Clear(FakeSystem & i_system) : iv_system(&i_system), err(0) {}

    void operator()(const Attention & i_attention)
    {
        if(!err)
        {
            AttnData d;

            i_attention.getData(d);

            // sleep for a random interval to simulate
            // real prd processing time

            nanosleep(0, randint(TEN_CTX_SWITCHES_NS, TEN_CTX_SWITCHES_NS * 10));

            uint64_t behavior = randint(0, 2);

            switch(behavior)
            {
                case 1:

                    // periodically do nothing to force the main service
                    // to see attentions that were not cleared and call PRD
                    // again

                    break;

                default:

                    err = iv_system->clearAllAttentions(d);

                    break;
            }
        }
    }

    FakeSystem * iv_system;
    errlHndl_t err;
};

errlHndl_t FakePrd::callPrd(const AttentionList & i_attentions)
{
    return i_attentions.forEach(Clear(*iv_system)).err;
}

FakePrd::FakePrd(FakeSystem & i_system) :
    iv_system(&i_system)
{

}
}
<commit_msg>Attention handler workaround broken randint function.<commit_after>/*  IBM_PROLOG_BEGIN_TAG
 *  This is an automatically generated prolog.
 *
 *  $Source: src/usr/diag/attn/test/attnfakeprd.C $
 *
 *  IBM CONFIDENTIAL
 *
 *  COPYRIGHT International Business Machines Corp. 2012
 *
 *  p1
 *
 *  Object Code Only (OCO) source materials
 *  Licensed Internal Code Source Materials
 *  IBM HostBoot Licensed Internal Code
 *
 *  The source code for this program is not published or other-
 *  wise divested of its trade secrets, irrespective of what has
 *  been deposited with the U.S. Copyright Office.
 *
 *  Origin: 30
 *
 *  IBM_PROLOG_END_TAG
 */
/**
 * @file attnfakeprd.C
 *
 * @brief HBATTN fake PRD class method definitions.
 */

#include "attnfakeprd.H"
#include "attnfakesys.H"
#include "../attnops.H"
#include "../attnlist.H"
#include <sys/time.h>

using namespace PRDF;

namespace ATTN
{

struct Clear
{
    Clear(FakeSystem & i_system) : iv_system(&i_system), err(0) {}

    void operator()(const Attention & i_attention)
    {
        if(!err)
        {
            AttnData d;

            i_attention.getData(d);

            // sleep for a random interval to simulate
            // real prd processing time

            nanosleep(0, randint(TEN_CTX_SWITCHES_NS, TEN_CTX_SWITCHES_NS * 10));

            if(randint(0, 10) < 8)
            {
                // periodically do nothing to force the main service
                // to see attentions that were not cleared and call PRD
                // again

                err = iv_system->clearAllAttentions(d);
            }
        }
    }

    FakeSystem * iv_system;
    errlHndl_t err;
};

errlHndl_t FakePrd::callPrd(const AttentionList & i_attentions)
{
    return i_attentions.forEach(Clear(*iv_system)).err;
}

FakePrd::FakePrd(FakeSystem & i_system) :
    iv_system(&i_system)
{

}
}
<|endoftext|>