<commit_before>/*
   Copyright 2011 John Selbie

   Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

#include "commonincludes.hpp"
#include "unittest.h"

#include "polling.h"

#include "testpolling.h"

CTestPolling::CTestPolling()
{
    ;
}

CTestPolling::~CTestPolling()
{
    TestUnInit();
}

HRESULT CTestPolling::Run()
{
    HRESULT hr = S_OK;

#ifdef HAS_EPOLL
    _polltype = IPOLLING_TYPE_EPOLL;
    ChkA(Test1());
    ChkA(Test2());
#endif

    _polltype = IPOLLING_TYPE_POLL;
    ChkA(Test1());
    ChkA(Test2());
    ChkA(Test3());
Cleanup:
    return hr;
}

void CTestPolling::TestUnInit()
{
    size_t size = _pipes.size();
    _spPolling.ReleaseAndClear();

    for (size_t index = 0; index < size; index++)
    {
        close(_pipes[index].readpipe);
        close(_pipes[index].writepipe);
    }

    _pipes.clear();

}

HRESULT CTestPolling::SetNonBlocking(int fd)
{
    HRESULT hr = S_OK;
    int result;
    int flags;

    flags = ::fcntl(fd, F_GETFL, 0);

    ChkIfA(flags == -1, ERRNOHR);

    flags |= O_NONBLOCK;

    result = fcntl(fd , F_SETFL , flags);

    ChkIfA(result == -1, ERRNOHR);

Cleanup:
    return hr;

}

HRESULT CTestPolling::CreateAndAddPipe()
{
    HRESULT hr = S_OK;
    PipePair pp = {};
    int ret = -1;
    int fds[2];
    ret = ::pipe(fds);

    ChkIfA(ret == -1, ERRNOHR);

    pp.readpipe = fds[0];
    pp.writepipe = fds[1];
    pp.fDataPending = false;

    ChkA(SetNonBlocking(pp.readpipe));
    ChkA(SetNonBlocking(pp.writepipe));

    _pipes.push_back(pp);

    ChkA(_spPolling->Add(fds[0], IPOLLING_READ));

Cleanup:
    return hr;
}

HRESULT CTestPolling::TestInit(size_t sizePolling, size_t sizePipeArray)
{
    HRESULT hr = S_OK;

    TestUnInit();

    ChkA(CreatePollingInstance(_polltype, sizePolling, _spPolling.GetPointerPointer()));

    for (size_t index = 0; index < sizePipeArray; index++)
    {
        ChkA(CreateAndAddPipe());
    }

Cleanup:
    return hr;
}

HRESULT CTestPolling::WritePipe(PipePair* pPair)
{
    HRESULT hr = S_OK;
    char ch = 'x';
    int ret = -1;

    ret = write(pPair->writepipe, &ch, 1);
    ChkIfA(ret < 0, ERRNOHR);
    ChkIfA(ret == 0, E_UNEXPECTED);
    pPair->fDataPending = true;

Cleanup:
    return hr;
}

HRESULT CTestPolling::ConsumeEvent(int* pFD, int* pCount)
{
    HRESULT hr = S_OK;
    HRESULT hrResult = S_OK;
    PollEvent event;
    char ch;
    int result;
    int count = 0;
    int fd = -1;
    int pipesindex = -1;

    hrResult = _spPolling->WaitForNextEvent(&event, 0);
    ChkA(hrResult);

    ChkIfA(hrResult == S_FALSE, S_FALSE);

    fd = event.fd;

    while (true)
    {
        result = ::read(fd, &ch, 1);
        if (result <= 0)
        {
            break;
        }
        count++;
    }

    pipesindex = FindPipePairIndex(fd);
    ChkIfA(pipesindex == -1, E_UNEXPECTED);

    ChkIfA(count == 0, E_UNEXPECTED);

    ChkIfA(_pipes[pipesindex].fDataPending == false, E_UNEXPECTED);
    _pipes[pipesindex].fDataPending = false;

Cleanup:
    if (pFD)
    {
        *pFD = fd;
    }
    if (pCount)
    {
        *pCount = count;
    }
    return hr;
}

int CTestPolling::FindPipePairIndex(int fd)
{
    size_t size = _pipes.size();

    for (size_t index = 0; index < size; index++)
    {
        if ((_pipes[index].readpipe == fd) || (_pipes[index].writepipe == fd))
        {
            return index;
        }
    }

    return -1;
}

size_t CTestPolling::GetPendingCount()
{
    size_t size = _pipes.size();
    size_t count = 0;

    for (size_t index = 0; index < size; index++)
    {
        if (_pipes[index].fDataPending)
        {
            count++;
        }
    }

    return count;
}

HRESULT CTestPolling::RemovePipe(int pipeindex)
{
    HRESULT hr = S_OK;

    size_t size = _pipes.size();

    ChkIfA(pipeindex < 0, E_FAIL);
    ChkIfA(pipeindex >= (int)size, E_FAIL);

    ChkA(_spPolling->Remove(_pipes[pipeindex].readpipe));

    close(_pipes[pipeindex].readpipe);
    _pipes[pipeindex].readpipe = -1;

    close(_pipes[pipeindex].writepipe);
    _pipes[pipeindex].writepipe = -1;

    _pipes.erase(_pipes.begin()+pipeindex);

Cleanup:
    return hr;
}

// simplest of all tests. Just set a file descriptor and see that it's available
// repeat many times
HRESULT CTestPolling::Test1()
{
    HRESULT hr = S_OK;
    HRESULT hrResult;
    size_t size;
    PollEvent event;
    int fd;
    int count = 0;

    srand(100);

    ChkA(TestInit(10, 10));

    size = _pipes.size();

    hrResult = _spPolling->WaitForNextEvent(&event, 0);
    ChkIfA(hrResult != S_FALSE, E_UNEXPECTED);

    // one event at a time model
    for (int index = 0; index < 100; index++)
    {

        size_t item = rand() % size;

        ChkA(WritePipe(&_pipes[item]));

        ConsumeEvent(&fd, &count);

        ChkIfA(fd != _pipes[item].readpipe, E_UNEXPECTED);
        ChkIfA(count != 1, E_UNEXPECTED);
    }

    hrResult = _spPolling->WaitForNextEvent(&event, 0);
    ChkIfA(hrResult != S_FALSE, E_UNEXPECTED);

Cleanup:
    return hr;
}

// create a polling set
HRESULT CTestPolling::Test2()
{
    // simulate the following events in random order:
    //    socket added (did it succeed as expected)
    //    incoming data (write to a random pipe)
    //    WaitForNextEvent called (did it return an expected result/socket)
    //        Remove socket last notified about

    HRESULT hr = S_OK;
    HRESULT hrResult;
    PollEvent event;
    const size_t c_maxSockets = 10;

    srand(100);

    ChkA(TestInit(c_maxSockets, 0));

    hrResult = _spPolling->WaitForNextEvent(&event, 0);
    ChkIfA(hrResult != S_FALSE, E_UNEXPECTED);

    for (size_t index = 0; index < 1000; index++)
    {
        int randresult = ::rand() % 4;

        switch (randresult)
        {
            case 0:
            {
                // simulate a new socket being added
                if (_pipes.size() >= c_maxSockets)
                {
                    continue;
                }

                ChkA(CreateAndAddPipe());

                break;
            }

            case 1:
            {
                // simulate incoming data
                size_t size = _pipes.size();
                size_t itemindex;

                if (size == 0)
                {
                    continue;
                }

                itemindex = rand() % size;
                ChkA(WritePipe(&_pipes[itemindex]));

                break;
            }

            case 2:
            case 3:
            {
                int fd;
                size_t pending = GetPendingCount();
                if (pending == 0)
                {
                    continue;
                }

                ChkA(ConsumeEvent(&fd, NULL));

                if (randresult == 3)
                {
                    // simulate removing this pipe from the set
                    ChkA(RemovePipe(FindPipePairIndex(fd)));
                }
                break;
            } // case
        } // switch
    } // for

Cleanup:
    return hr;
}

HRESULT CTestPolling::Test3()
{
    HRESULT hr = S_OK;

    const size_t c_maxSockets = 10;

    ChkA(TestInit(c_maxSockets, 0));

    ChkA(_spPolling->Add(3, IPOLLING_READ));
    ChkA(_spPolling->Remove(3));
    ChkA(_spPolling->Add(5, IPOLLING_READ));
    ChkA(_spPolling->Add(7, IPOLLING_READ));
    ChkA(_spPolling->Add(9, IPOLLING_READ));
    ChkA(_spPolling->Remove(5));
    ChkA(_spPolling->Add(11, IPOLLING_READ));
    ChkA(_spPolling->Add(13, IPOLLING_READ));
    ChkA(_spPolling->Remove(7));
    ChkA(_spPolling->Add(15, IPOLLING_READ));
    ChkA(_spPolling->Add(17, IPOLLING_READ));
    ChkA(_spPolling->Add(19, IPOLLING_READ));
    ChkA(_spPolling->Remove(11));
    ChkA(_spPolling->Add(21, IPOLLING_READ));
    ChkA(_spPolling->Add(23, IPOLLING_READ));
    ChkA(_spPolling->Add(25, IPOLLING_READ));
    ChkA(_spPolling->Add(27, IPOLLING_READ));
    ChkA(_spPolling->Remove(13));

Cleanup:
    return hr;

}<commit_msg>added end of line to testpolling.cpp<commit_after>/*
   Copyright 2011 John Selbie

   Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

#include "commonincludes.hpp"
#include "unittest.h"

#include "polling.h"

#include "testpolling.h"

CTestPolling::CTestPolling()
{
    ;
}

CTestPolling::~CTestPolling()
{
    TestUnInit();
}

HRESULT CTestPolling::Run()
{
    HRESULT hr = S_OK;

#ifdef HAS_EPOLL
    _polltype = IPOLLING_TYPE_EPOLL;
    ChkA(Test1());
    ChkA(Test2());
#endif

    _polltype = IPOLLING_TYPE_POLL;
    ChkA(Test1());
    ChkA(Test2());
    ChkA(Test3());
Cleanup:
    return hr;
}

void CTestPolling::TestUnInit()
{
    size_t size = _pipes.size();
    _spPolling.ReleaseAndClear();

    for (size_t index = 0; index < size; index++)
    {
        close(_pipes[index].readpipe);
        close(_pipes[index].writepipe);
    }

    _pipes.clear();

}

HRESULT CTestPolling::SetNonBlocking(int fd)
{
    HRESULT hr = S_OK;
    int result;
    int flags;

    flags = ::fcntl(fd, F_GETFL, 0);

    ChkIfA(flags == -1, ERRNOHR);

    flags |= O_NONBLOCK;

    result = fcntl(fd , F_SETFL , flags);

    ChkIfA(result == -1, ERRNOHR);

Cleanup:
    return hr;

}

HRESULT CTestPolling::CreateAndAddPipe()
{
    HRESULT hr = S_OK;
    PipePair pp = {};
    int ret = -1;
    int fds[2];
    ret = ::pipe(fds);

    ChkIfA(ret == -1, ERRNOHR);

    pp.readpipe = fds[0];
    pp.writepipe = fds[1];
    pp.fDataPending = false;

    ChkA(SetNonBlocking(pp.readpipe));
    ChkA(SetNonBlocking(pp.writepipe));

    _pipes.push_back(pp);

    ChkA(_spPolling->Add(fds[0], IPOLLING_READ));

Cleanup:
    return hr;
}

HRESULT CTestPolling::TestInit(size_t sizePolling, size_t sizePipeArray)
{
    HRESULT hr = S_OK;

    TestUnInit();

    ChkA(CreatePollingInstance(_polltype, sizePolling, _spPolling.GetPointerPointer()));

    for (size_t index = 0; index < sizePipeArray; index++)
    {
        ChkA(CreateAndAddPipe());
    }

Cleanup:
    return hr;
}

HRESULT CTestPolling::WritePipe(PipePair* pPair)
{
    HRESULT hr = S_OK;
    char ch = 'x';
    int ret = -1;

    ret = write(pPair->writepipe, &ch, 1);
    ChkIfA(ret < 0, ERRNOHR);
    ChkIfA(ret == 0, E_UNEXPECTED);
    pPair->fDataPending = true;

Cleanup:
    return hr;
}

HRESULT CTestPolling::ConsumeEvent(int* pFD, int* pCount)
{
    HRESULT hr = S_OK;
    HRESULT hrResult = S_OK;
    PollEvent event;
    char ch;
    int result;
    int count = 0;
    int fd = -1;
    int pipesindex = -1;

    hrResult = _spPolling->WaitForNextEvent(&event, 0);
    ChkA(hrResult);

    ChkIfA(hrResult == S_FALSE, S_FALSE);

    fd = event.fd;

    while (true)
    {
        result = ::read(fd, &ch, 1);
        if (result <= 0)
        {
            break;
        }
        count++;
    }

    pipesindex = FindPipePairIndex(fd);
    ChkIfA(pipesindex == -1, E_UNEXPECTED);

    ChkIfA(count == 0, E_UNEXPECTED);

    ChkIfA(_pipes[pipesindex].fDataPending == false, E_UNEXPECTED);
    _pipes[pipesindex].fDataPending = false;

Cleanup:
    if (pFD)
    {
        *pFD = fd;
    }
    if (pCount)
    {
        *pCount = count;
    }
    return hr;
}

int CTestPolling::FindPipePairIndex(int fd)
{
    size_t size = _pipes.size();

    for (size_t index = 0; index < size; index++)
    {
        if ((_pipes[index].readpipe == fd) || (_pipes[index].writepipe == fd))
        {
            return index;
        }
    }

    return -1;
}

size_t CTestPolling::GetPendingCount()
{
    size_t size = _pipes.size();
    size_t count = 0;

    for (size_t index = 0; index < size; index++)
    {
        if (_pipes[index].fDataPending)
        {
            count++;
        }
    }

    return count;
}

HRESULT CTestPolling::RemovePipe(int pipeindex)
{
    HRESULT hr = S_OK;

    size_t size = _pipes.size();

    ChkIfA(pipeindex < 0, E_FAIL);
    ChkIfA(pipeindex >= (int)size, E_FAIL);

    ChkA(_spPolling->Remove(_pipes[pipeindex].readpipe));

    close(_pipes[pipeindex].readpipe);
    _pipes[pipeindex].readpipe = -1;

    close(_pipes[pipeindex].writepipe);
    _pipes[pipeindex].writepipe = -1;

    _pipes.erase(_pipes.begin()+pipeindex);

Cleanup:
    return hr;
}

// simplest of all tests. Just set a file descriptor and see that it's available
// repeat many times
HRESULT CTestPolling::Test1()
{
    HRESULT hr = S_OK;
    HRESULT hrResult;
    size_t size;
    PollEvent event;
    int fd;
    int count = 0;

    srand(100);

    ChkA(TestInit(10, 10));

    size = _pipes.size();

    hrResult = _spPolling->WaitForNextEvent(&event, 0);
    ChkIfA(hrResult != S_FALSE, E_UNEXPECTED);

    // one event at a time model
    for (int index = 0; index < 100; index++)
    {

        size_t item = rand() % size;

        ChkA(WritePipe(&_pipes[item]));

        ConsumeEvent(&fd, &count);

        ChkIfA(fd != _pipes[item].readpipe, E_UNEXPECTED);
        ChkIfA(count != 1, E_UNEXPECTED);
    }

    hrResult = _spPolling->WaitForNextEvent(&event, 0);
    ChkIfA(hrResult != S_FALSE, E_UNEXPECTED);

Cleanup:
    return hr;
}

// create a polling set
HRESULT CTestPolling::Test2()
{
    // simulate the following events in random order:
    //    socket added (did it succeed as expected)
    //    incoming data (write to a random pipe)
    //    WaitForNextEvent called (did it return an expected result/socket)
    //        Remove socket last notified about

    HRESULT hr = S_OK;
    HRESULT hrResult;
    PollEvent event;
    const size_t c_maxSockets = 10;

    srand(100);

    ChkA(TestInit(c_maxSockets, 0));

    hrResult = _spPolling->WaitForNextEvent(&event, 0);
    ChkIfA(hrResult != S_FALSE, E_UNEXPECTED);

    for (size_t index = 0; index < 1000; index++)
    {
        int randresult = ::rand() % 4;

        switch (randresult)
        {
            case 0:
            {
                // simulate a new socket being added
                if (_pipes.size() >= c_maxSockets)
                {
                    continue;
                }

                ChkA(CreateAndAddPipe());

                break;
            }

            case 1:
            {
                // simulate incoming data
                size_t size = _pipes.size();
                size_t itemindex;

                if (size == 0)
                {
                    continue;
                }

                itemindex = rand() % size;
                ChkA(WritePipe(&_pipes[itemindex]));

                break;
            }

            case 2:
            case 3:
            {
                int fd;
                size_t pending = GetPendingCount();
                if (pending == 0)
                {
                    continue;
                }

                ChkA(ConsumeEvent(&fd, NULL));

                if (randresult == 3)
                {
                    // simulate removing this pipe from the set
                    ChkA(RemovePipe(FindPipePairIndex(fd)));
                }
                break;
            } // case
        } // switch
    } // for

Cleanup:
    return hr;
}

HRESULT CTestPolling::Test3()
{
    HRESULT hr = S_OK;

    const size_t c_maxSockets = 10;

    ChkA(TestInit(c_maxSockets, 0));

    ChkA(_spPolling->Add(3, IPOLLING_READ));
    ChkA(_spPolling->Remove(3));
    ChkA(_spPolling->Add(5, IPOLLING_READ));
    ChkA(_spPolling->Add(7, IPOLLING_READ));
    ChkA(_spPolling->Add(9, IPOLLING_READ));
    ChkA(_spPolling->Remove(5));
    ChkA(_spPolling->Add(11, IPOLLING_READ));
    ChkA(_spPolling->Add(13, IPOLLING_READ));
    ChkA(_spPolling->Remove(7));
    ChkA(_spPolling->Add(15, IPOLLING_READ));
    ChkA(_spPolling->Add(17, IPOLLING_READ));
    ChkA(_spPolling->Add(19, IPOLLING_READ));
    ChkA(_spPolling->Remove(11));
    ChkA(_spPolling->Add(21, IPOLLING_READ));
    ChkA(_spPolling->Add(23, IPOLLING_READ));
    ChkA(_spPolling->Add(25, IPOLLING_READ));
    ChkA(_spPolling->Add(27, IPOLLING_READ));
    ChkA(_spPolling->Remove(13));

Cleanup:
    return hr;

}

<|endoftext|>


<commit_before>
/** RandomAtomGenerator.cc */

#include <opencog/util/random.h>

#include <opencog/atoms/base/types.h>
#include <opencog/truthvalue/SimpleTruthValue.h>
#include <opencog/truthvalue/TruthValue.h>

#include "RandomAtomGenerator.h"

namespace opencog {

RandomAtomGenerator::RandomAtomGenerator(AtomSpace* atomspace,
                                         unsigned long random_seed,
                                         float link_size_mean,
                                         Type default_node_type,
                                         float chance_of_non_default_node,
                                         Type default_link_type,
                                         float chance_of_non_default_link,
                                         float chance_of_default_tv)
{
    _atomspace = atomspace;

    _default_node_type = default_node_type;
    _chance_of_non_default_node = chance_of_non_default_node;
    _default_link_type = default_link_type;
    _chance_of_non_default_link = chance_of_non_default_link;
    _link_size_mean = link_size_mean;

    _total_types = classserver().getNumberOfClasses();

    _counter = 0;
    _chance_of_default_tv = chance_of_default_tv;

    if (random_seed != USE_TIME_RANDOM_SEED)
        _random_seed = random_seed;
    else
        _random_seed = (unsigned long) time(NULL);

    // Create the random generator with the correct seed value.
    _random_generator = new MT19937RandGen(_random_seed);

    // Create the poisson distribution around the link mean.
    _poisson_distribution = new std::poisson_distribution<unsigned>(_link_size_mean);
}

RandomAtomGenerator::~RandomAtomGenerator()
{
    delete _poisson_distribution;
    delete _random_generator;
}

Type RandomAtomGenerator::random_type(Type parent_type)
{
    OC_ASSERT(parent_type < _total_types);
    Type candidate_type;

    // Loop until we get a type that is a subclass of t, skipping TYPE_NODE
    // since that type can't handle randomly generated names. Also skip other
    // validated types since the validation will fail.
    do {
        candidate_type = ATOM + _random_generator->randint(_total_types - ATOM - 1);
    } while (!classserver().isA(candidate_type, parent_type) or
        classserver().isA(candidate_type, FREE_LINK) or
        classserver().isA(candidate_type, SCOPE_LINK) or
        candidate_type == VARIABLE_LIST or
        candidate_type == DEFINE_LINK or
        candidate_type == NUMBER_NODE or
        candidate_type == TYPE_NODE);

    return candidate_type;
}

void RandomAtomGenerator::set_truth_value(Handle& atom)
{
    // Set the truth value to a non default using the chance threshold.
    if (_random_generator->randfloat() > _chance_of_default_tv) {
        float strength = _random_generator->randfloat();
        float confidence = _random_generator->randfloat();
        TruthValuePtr stv = SimpleTruthValue::createTV(strength, confidence);
        atom->setTruthValue(stv);
    }
}

Type RandomAtomGenerator::get_node_type()
{
    Type node_type;
    if (_random_generator->randfloat() < _chance_of_non_default_node)
        node_type = random_type(NODE);
    else
        node_type = _default_node_type;
    return node_type;
}

void RandomAtomGenerator::make_random_node()
{
    // Get the node type (non-default based on random chance and threshold).
    Type node_type = get_node_type();

    // Generate the node name.
    _counter++;
    std::string node_name("node ");
    node_name += std::to_string(_counter);

    // Add the node to the atomspace.
    Handle node = _atomspace->add_node(node_type, node_name);

    // Set the truth value (non-default based on random chance and threshold).
    set_truth_value(node);
}

Type RandomAtomGenerator::get_link_type()
{
    Type link_type;
    if (_random_generator->randfloat() < _chance_of_non_default_link)
        link_type = random_type(LINK);
    else
        link_type = _default_link_type;
    return link_type;
}

Handle RandomAtomGenerator::get_random_handle()
{
    // _random_generator->randint(range);
    return Handle::UNDEFINED;
}

bool RandomAtomGenerator::sequence_contains(HandleSeq& sequence, Handle& target)
{
    if (std::find(sequence.begin(), sequence.end(), target) != sequence.end())
        return true;
    else
        return false;
}

void RandomAtomGenerator::make_random_link()
{
    Handle link = Handle::UNDEFINED;

    // Loop until we add a link in case we randomly create a duplicate which
    // will not create a new link and throw off our counts.
    int initial_atom_count = _atomspace->get_size();
    do {
        // Get the link type (non-default based on random chance and threshold).
        Type link_type = get_link_type();

        // Get the poisson-distributed outgoing arity.
        size_t arity = (*_poisson_distribution)(*_random_generator);
        if (arity == 0)
            arity = 1;

        // AtomSpace will throw if the context link has bad arity
        if (link_type == CONTEXT_LINK)
            arity = 2;

        // Generate the outgoing sequence.
        HandleSeq outgoing;
        for (size_t outgoing_count = 0; outgoing_count < arity; outgoing_count++) {

            // Get a new random handle.
            Handle candidate = get_random_handle();

            // Test to see if it is new for this outgoing sequence.
            while (sequence_contains(outgoing, candidate))
                candidate = get_random_handle();

            // Add this candidate to our outgoing sequence.
            outgoing.push_back(candidate);
        }

        // Add the link to the atomspace.
        link = _atomspace->add_link(link_type, outgoing);

    // Until we've actually added a link.
    } while (_atomspace->get_size() == initial_atom_count);

    // Set the truth value (non-default based on random chance and threshold).
    set_truth_value(link);
}

void RandomAtomGenerator::make_random_atoms(long total_atoms,
                                            float percent_links)
{
    // Add the nodes.
    int total_nodes = total_atoms * (1.0f - percent_links);
    for (int node_count = 0; node_count < total_nodes; node_count++)
        make_random_node();

    // Add the links until we get to to our total.
    int total_links = total_atoms - total_nodes;
    for (int link_count = 0; link_count < total_links; link_count++)
        make_random_link();
}

} // namespace opencog
<commit_msg>Fix compiler warning<commit_after>
/** RandomAtomGenerator.cc */

#include <opencog/util/random.h>

#include <opencog/atoms/base/types.h>
#include <opencog/truthvalue/SimpleTruthValue.h>
#include <opencog/truthvalue/TruthValue.h>

#include "RandomAtomGenerator.h"

namespace opencog {

RandomAtomGenerator::RandomAtomGenerator(AtomSpace* atomspace,
                                         unsigned long random_seed,
                                         float link_size_mean,
                                         Type default_node_type,
                                         float chance_of_non_default_node,
                                         Type default_link_type,
                                         float chance_of_non_default_link,
                                         float chance_of_default_tv)
{
    _atomspace = atomspace;

    _default_node_type = default_node_type;
    _chance_of_non_default_node = chance_of_non_default_node;
    _default_link_type = default_link_type;
    _chance_of_non_default_link = chance_of_non_default_link;
    _link_size_mean = link_size_mean;

    _total_types = classserver().getNumberOfClasses();

    _counter = 0;
    _chance_of_default_tv = chance_of_default_tv;

    if (random_seed != USE_TIME_RANDOM_SEED)
        _random_seed = random_seed;
    else
        _random_seed = (unsigned long) time(NULL);

    // Create the random generator with the correct seed value.
    _random_generator = new MT19937RandGen(_random_seed);

    // Create the poisson distribution around the link mean.
    _poisson_distribution = new std::poisson_distribution<unsigned>(_link_size_mean);
}

RandomAtomGenerator::~RandomAtomGenerator()
{
    delete _poisson_distribution;
    delete _random_generator;
}

Type RandomAtomGenerator::random_type(Type parent_type)
{
    OC_ASSERT(parent_type < _total_types);
    Type candidate_type;

    // Loop until we get a type that is a subclass of t, skipping TYPE_NODE
    // since that type can't handle randomly generated names. Also skip other
    // validated types since the validation will fail.
    do {
        candidate_type = ATOM + _random_generator->randint(_total_types - ATOM - 1);
    } while (!classserver().isA(candidate_type, parent_type) or
        classserver().isA(candidate_type, FREE_LINK) or
        classserver().isA(candidate_type, SCOPE_LINK) or
        candidate_type == VARIABLE_LIST or
        candidate_type == DEFINE_LINK or
        candidate_type == NUMBER_NODE or
        candidate_type == TYPE_NODE);

    return candidate_type;
}

void RandomAtomGenerator::set_truth_value(Handle& atom)
{
    // Set the truth value to a non default using the chance threshold.
    if (_random_generator->randfloat() > _chance_of_default_tv) {
        float strength = _random_generator->randfloat();
        float confidence = _random_generator->randfloat();
        TruthValuePtr stv = SimpleTruthValue::createTV(strength, confidence);
        atom->setTruthValue(stv);
    }
}

Type RandomAtomGenerator::get_node_type()
{
    Type node_type;
    if (_random_generator->randfloat() < _chance_of_non_default_node)
        node_type = random_type(NODE);
    else
        node_type = _default_node_type;
    return node_type;
}

void RandomAtomGenerator::make_random_node()
{
    // Get the node type (non-default based on random chance and threshold).
    Type node_type = get_node_type();

    // Generate the node name.
    _counter++;
    std::string node_name("node ");
    node_name += std::to_string(_counter);

    // Add the node to the atomspace.
    Handle node = _atomspace->add_node(node_type, node_name);

    // Set the truth value (non-default based on random chance and threshold).
    set_truth_value(node);
}

Type RandomAtomGenerator::get_link_type()
{
    Type link_type;
    if (_random_generator->randfloat() < _chance_of_non_default_link)
        link_type = random_type(LINK);
    else
        link_type = _default_link_type;
    return link_type;
}

Handle RandomAtomGenerator::get_random_handle()
{
    // _random_generator->randint(range);
    return Handle::UNDEFINED;
}

bool RandomAtomGenerator::sequence_contains(HandleSeq& sequence, Handle& target)
{
    if (std::find(sequence.begin(), sequence.end(), target) != sequence.end())
        return true;
    else
        return false;
}

void RandomAtomGenerator::make_random_link()
{
    Handle link = Handle::UNDEFINED;

    // Loop until we add a link in case we randomly create a duplicate which
    // will not create a new link and throw off our counts.
    size_t initial_atom_count = _atomspace->get_size();
    do {
        // Get the link type (non-default based on random chance and threshold).
        Type link_type = get_link_type();

        // Get the poisson-distributed outgoing arity.
        size_t arity = (*_poisson_distribution)(*_random_generator);
        if (arity == 0)
            arity = 1;

        // AtomSpace will throw if the context link has bad arity
        if (link_type == CONTEXT_LINK)
            arity = 2;

        // Generate the outgoing sequence.
        HandleSeq outgoing;
        for (size_t outgoing_count = 0; outgoing_count < arity; outgoing_count++) {

            // Get a new random handle.
            Handle candidate = get_random_handle();

            // Test to see if it is new for this outgoing sequence.
            while (sequence_contains(outgoing, candidate))
                candidate = get_random_handle();

            // Add this candidate to our outgoing sequence.
            outgoing.push_back(candidate);
        }

        // Add the link to the atomspace.
        link = _atomspace->add_link(link_type, outgoing);

    // Until we've actually added a link.
    } while (_atomspace->get_size() == initial_atom_count);

    // Set the truth value (non-default based on random chance and threshold).
    set_truth_value(link);
}

void RandomAtomGenerator::make_random_atoms(long total_atoms,
                                            float percent_links)
{
    // Add the nodes.
    int total_nodes = total_atoms * (1.0f - percent_links);
    for (int node_count = 0; node_count < total_nodes; node_count++)
        make_random_node();

    // Add the links until we get to to our total.
    int total_links = total_atoms - total_nodes;
    for (int link_count = 0; link_count < total_links; link_count++)
        make_random_link();
}

} // namespace opencog
<|endoftext|>


<commit_before>/*
* This file is part of ATLAS. It is subject to the license terms in
* the LICENSE file found in the top-level directory of this distribution.
* (Also avialable at http://www.apache.org/licenses/LICENSE-2.0.txt)
* You may not use this file except in compliance with the License.
*/
#pragma once

#include "ColladaMassager.hpp"
#include "ColladaMassagerRegistry.hpp"
#include "../AssimpImporter.hpp"
#include "../Importer.hpp"
#include <assimp/scene.h>
#include <atlas/model/Folder.hpp>
#include "../AiImporter/AiSceneImporter.hpp"

namespace AssimpWorker {

	class ColladaRecursiveImporter :public Importer
	{
	public:
		ColladaRecursiveImporter(const Poco::URI& colladaFileURI, Log& log, Poco::URI pathToWorkingDirectory, ColladaMassagerRegistry& registry, float parentScale);

		~ColladaRecursiveImporter();

		virtual void addElementsTo(ATLAS::Model::Folder& asset);
		const float getLocalScale();
		const std::string getColladaUpAxis();

	private:
		AssimpImporter* importer;
		std::vector<ColladaRecursiveImporter*> childImporter;
		Poco::URI pathToWorkingDirectory;
		const Poco::URI& colladaFileURI;
		ColladaMassagerRegistry& massagerRegistry;
		ColladaMassager* massager;
		const float parentScale;

		void preprocessCollada();
		const aiScene* runAssimpImport();
		void convertToFolderStructure(const aiScene* scene, ATLAS::Model::Folder& root);
		void importChildColladas(ATLAS::Model::Folder& root);

		std::string fixRelativeReference(std::string relativeURI);
		ATLAS::Model::Folder& findFolderWithName(ATLAS::Model::Folder& root, std::string name);
		aiNode* findaiNodeWithName(aiNode* node, const std::string& name);
		ATLAS::Model::Folder& findFolderWithColladaID(ATLAS::Model::Folder& folder, std::string id);
		void restoreOriginalNames(aiNode* node);
	};

} // End namespace AssimpWorker

<commit_msg>Removes declaration of not implemented function<commit_after>/*
* This file is part of ATLAS. It is subject to the license terms in
* the LICENSE file found in the top-level directory of this distribution.
* (Also avialable at http://www.apache.org/licenses/LICENSE-2.0.txt)
* You may not use this file except in compliance with the License.
*/
#pragma once

#include "ColladaMassager.hpp"
#include "ColladaMassagerRegistry.hpp"
#include "../AssimpImporter.hpp"
#include "../Importer.hpp"
#include <assimp/scene.h>
#include <atlas/model/Folder.hpp>
#include "../AiImporter/AiSceneImporter.hpp"

namespace AssimpWorker {

	class ColladaRecursiveImporter :public Importer
	{
	public:
		ColladaRecursiveImporter(const Poco::URI& colladaFileURI, Log& log, Poco::URI pathToWorkingDirectory, ColladaMassagerRegistry& registry, float parentScale);

		~ColladaRecursiveImporter();

		virtual void addElementsTo(ATLAS::Model::Folder& asset);
		const float getLocalScale();
		const std::string getColladaUpAxis();

	private:
		AssimpImporter* importer;
		std::vector<ColladaRecursiveImporter*> childImporter;
		Poco::URI pathToWorkingDirectory;
		const Poco::URI& colladaFileURI;
		ColladaMassagerRegistry& massagerRegistry;
		ColladaMassager* massager;
		const float parentScale;

		void preprocessCollada();
		const aiScene* runAssimpImport();
		void convertToFolderStructure(const aiScene* scene, ATLAS::Model::Folder& root);
		void importChildColladas(ATLAS::Model::Folder& root);

		std::string fixRelativeReference(std::string relativeURI);
		ATLAS::Model::Folder& findFolderWithName(ATLAS::Model::Folder& root, std::string name);
		aiNode* findaiNodeWithName(aiNode* node, const std::string& name);
		ATLAS::Model::Folder& findFolderWithColladaID(ATLAS::Model::Folder& folder, std::string id);
	};

} // End namespace AssimpWorker

<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014, Ford Motor Company
 * 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 Ford Motor Company 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 HOLDER 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.
 */

#include <string.h>

#include "utils/macro.h"
#include "application_manager/mobile_message_handler.h"
#include "protocol_handler/protocol_payload.h"
#include "protocol_handler/protocol_packet.h"
#include "utils/bitstream.h"
#include "utils/logger.h"

#include <stdint.h>
#include <memory>
#include <string>

namespace {
const uint8_t kRequest = 0x0;
const uint8_t kResponse = 0x1;
const uint8_t kNotification = 0x2;
const uint8_t kUnknown = 0xF;
}

namespace application_manager {
using protocol_handler::Extract;

namespace {
typedef std::map<MessageType, std::string> MessageTypeMap;
MessageTypeMap message_types = {std::make_pair(kRequest, "Request"),
                                std::make_pair(kResponse, "Response"),
                                std::make_pair(kNotification, "Notification")};
}
CREATE_LOGGERPTR_GLOBAL(logger_, "ApplicationManager")

application_manager::Message*
MobileMessageHandler::HandleIncomingMessageProtocol(
    const protocol_handler::RawMessagePtr message) {
  DCHECK_OR_RETURN(message, NULL);
  application_manager::Message* out_message = NULL;
  switch (message->protocol_version()) {
    case protocol_handler::MajorProtocolVersion::PROTOCOL_VERSION_1:
      LOG4CXX_DEBUG(logger_, "Protocol version - V1");
      out_message =
          MobileMessageHandler::HandleIncomingMessageProtocolV1(message);
      break;
    case protocol_handler::MajorProtocolVersion::PROTOCOL_VERSION_2:
      LOG4CXX_DEBUG(logger_, "Protocol version - V2");
      out_message =
          MobileMessageHandler::HandleIncomingMessageProtocolV2(message);
      break;
    case protocol_handler::MajorProtocolVersion::PROTOCOL_VERSION_3:
      LOG4CXX_DEBUG(logger_, "Protocol version - V3");
      out_message =
          MobileMessageHandler::HandleIncomingMessageProtocolV2(message);
      break;
    case protocol_handler::MajorProtocolVersion::PROTOCOL_VERSION_4:
      LOG4CXX_DEBUG(logger_, "Protocol version - V4");
      out_message =
          MobileMessageHandler::HandleIncomingMessageProtocolV2(message);
      break;
    case protocol_handler::MajorProtocolVersion::PROTOCOL_VERSION_5:
      LOG4CXX_DEBUG(logger_, "Protocol version - V5");
      out_message =
          MobileMessageHandler::HandleIncomingMessageProtocolV2(message);
      break;
    default:
      LOG4CXX_WARN(logger_, "Can't recognise protocol version");
      out_message = NULL;
      break;
  }
  if (out_message == NULL) {
    LOG4CXX_WARN(logger_, "Message is NULL");
    return NULL;
  }
  LOG4CXX_DEBUG(logger_,
                "Incoming RPC_INFO: " << (out_message->connection_key() >> 16)
                                      << ", "
                                      << message_types[out_message->type()]
                                      << ", " << out_message->function_id()
                                      << ", " << out_message->correlation_id()
                                      << ", " << out_message->json_message());
  return out_message;
}

protocol_handler::RawMessage*
MobileMessageHandler::HandleOutgoingMessageProtocol(
    const MobileMessage& message) {
  LOG4CXX_DEBUG(logger_,
                "Outgoing RPC_INFO: " << (message->connection_key() >> 16)
                                      << ", " << message_types[message->type()]
                                      << ", " << message->function_id() << ", "
                                      << message->correlation_id() << ", "
                                      << message->json_message());

  if (message->protocol_version() ==
      protocol_handler::MajorProtocolVersion::PROTOCOL_VERSION_1) {
    return MobileMessageHandler::HandleOutgoingMessageProtocolV1(message);
  }
  if (Message::is_sufficient_version(
          protocol_handler::MajorProtocolVersion::PROTOCOL_VERSION_2,
          message->protocol_version())) {
    return MobileMessageHandler::HandleOutgoingMessageProtocolV2(message);
  }
  return NULL;
}

application_manager::Message*
MobileMessageHandler::HandleIncomingMessageProtocolV1(
    const ::protocol_handler::RawMessagePtr message) {
  LOG4CXX_AUTO_TRACE(logger_);
  application_manager::Message* outgoing_message =
      new application_manager::Message(
          protocol_handler::MessagePriority::FromServiceType(
              message->service_type()));
  if (!message) {
    NOTREACHED();
    return NULL;
  }

  outgoing_message->set_connection_key(message->connection_key());
  outgoing_message->set_protocol_version(
      static_cast<protocol_handler::MajorProtocolVersion>(
          message->protocol_version()));
  outgoing_message->set_json_message(std::string(
      reinterpret_cast<const char*>(message->data()), message->data_size()));

  if (outgoing_message->json_message().empty()) {
    delete outgoing_message;
    return NULL;
  }

  return outgoing_message;
}

application_manager::Message*
MobileMessageHandler::HandleIncomingMessageProtocolV2(
    const ::protocol_handler::RawMessagePtr message) {
  LOG4CXX_AUTO_TRACE(logger_);
  utils::BitStream message_bytestream(message->data(), message->data_size());
  protocol_handler::ProtocolPayloadV2 payload;
  protocol_handler::Extract(
      &message_bytestream, &payload, message->data_size());

  // Silently drop message if it wasn't parsed correctly
  if (message_bytestream.IsBad()) {
    LOG4CXX_WARN(
        logger_,
        "Drop ill-formed message from mobile, partially parsed: " << payload);
    return NULL;
  }

  std::auto_ptr<application_manager::Message> outgoing_message(
      new application_manager::Message(
          protocol_handler::MessagePriority::FromServiceType(
              message->service_type())));

  outgoing_message->set_json_message(payload.json);
  outgoing_message->set_function_id(payload.header.rpc_function_id);
  outgoing_message->set_message_type(
      MessageTypeFromRpcType(payload.header.rpc_type));
  outgoing_message->set_correlation_id(int32_t(payload.header.correlation_id));
  outgoing_message->set_connection_key(message->connection_key());
  outgoing_message->set_protocol_version(
      static_cast<protocol_handler::MajorProtocolVersion>(
          message->protocol_version()));
  outgoing_message->set_data_size(message->data_size());
  outgoing_message->set_payload_size(message->payload_size());

  if (!payload.data.empty()) {
    const BinaryData binary_payload_data(payload.data);
    outgoing_message->set_binary_data(&binary_payload_data);
  }
  return outgoing_message.release();
}

protocol_handler::RawMessage*
MobileMessageHandler::HandleOutgoingMessageProtocolV1(
    const MobileMessage& message) {
  LOG4CXX_AUTO_TRACE(logger_);
  std::string message_string = message->json_message();
  if (message_string.length() == 0) {
    LOG4CXX_WARN(logger_, "Drop ill-formed message from mobile");
    return NULL;
  }

  BinaryData raw_message(message_string.length() + 1);
  memcpy(&raw_message[0], message_string.c_str(), message_string.length() + 1);

  protocol_handler::RawMessage* result =
      new protocol_handler::RawMessage(message->connection_key(),
                                       1,
                                       &raw_message[0],
                                       message_string.length() + 1);

  return result;
}

protocol_handler::RawMessage*
MobileMessageHandler::HandleOutgoingMessageProtocolV2(
    const MobileMessage& message) {
  LOG4CXX_AUTO_TRACE(logger_);
  if (message->json_message().length() == 0) {
    LOG4CXX_ERROR(logger_, "json string is empty.");
  }
  uint32_t json_size = message->json_message().length();
  uint32_t binary_size = 0;
  if (message->has_binary_data()) {
    binary_size = message->binary_data()->size();
  }

  const size_t data_for_sending_size =
      protocol_handler::PROTOCOL_HEADER_V2_SIZE + json_size + binary_size;
  BinaryData data_for_sending(data_for_sending_size);
  uint8_t offset = 0;

  uint8_t rpc_type_flag = 0;
  switch (message->type()) {
    case application_manager::kRequest:
      rpc_type_flag = kRequest;
      break;
    case application_manager::kResponse:
      rpc_type_flag = kResponse;
      break;
    case application_manager::kNotification:
      rpc_type_flag = kNotification;
      break;
    default:
      NOTREACHED();
      break;
  }

  uint32_t function_id = message->function_id();
  data_for_sending[offset++] =
      ((rpc_type_flag << 4) & 0xF0) | (function_id >> 24);
  data_for_sending[offset++] = function_id >> 16;
  data_for_sending[offset++] = function_id >> 8;
  data_for_sending[offset++] = function_id;

  uint32_t correlation_id = message->correlation_id();
  data_for_sending[offset++] = correlation_id >> 24;
  data_for_sending[offset++] = correlation_id >> 16;
  data_for_sending[offset++] = correlation_id >> 8;
  data_for_sending[offset++] = correlation_id;

  data_for_sending[offset++] = json_size >> 24;
  data_for_sending[offset++] = json_size >> 16;
  data_for_sending[offset++] = json_size >> 8;
  data_for_sending[offset++] = json_size;

  memcpy(&data_for_sending[offset], message->json_message().c_str(), json_size);

  // Default the service type to RPC Service
  uint8_t type = 0x07;

  if (message->has_binary_data()) {
    // Change the service type to Hybrid Service
    type = 0x0F;
    const BinaryData& binary_data = *(message->binary_data());
    BinaryData::value_type* current_pointer =
        &data_for_sending[offset + json_size];
    for (uint32_t i = 0; i < binary_size; ++i) {
      current_pointer[i] = binary_data[i];
    }
  }

  protocol_handler::RawMessage* msg_to_protocol_handler =
      new protocol_handler::RawMessage(message->connection_key(),
                                       message->protocol_version(),
                                       &data_for_sending[0],
                                       data_for_sending_size,
                                       type);

  return msg_to_protocol_handler;
}
}  // namespace application_manager
<commit_msg>fix: remove memory leak warning from cppcheck<commit_after>/*
 * Copyright (c) 2014, Ford Motor Company
 * 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 Ford Motor Company 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 HOLDER 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.
 */

#include <string.h>

#include "utils/macro.h"
#include "application_manager/mobile_message_handler.h"
#include "protocol_handler/protocol_payload.h"
#include "protocol_handler/protocol_packet.h"
#include "utils/bitstream.h"
#include "utils/logger.h"

#include <stdint.h>
#include <memory>
#include <string>

namespace {
const uint8_t kRequest = 0x0;
const uint8_t kResponse = 0x1;
const uint8_t kNotification = 0x2;
const uint8_t kUnknown = 0xF;
}

namespace application_manager {
using protocol_handler::Extract;

namespace {
typedef std::map<MessageType, std::string> MessageTypeMap;
MessageTypeMap message_types = {std::make_pair(kRequest, "Request"),
                                std::make_pair(kResponse, "Response"),
                                std::make_pair(kNotification, "Notification")};
}
CREATE_LOGGERPTR_GLOBAL(logger_, "ApplicationManager")

application_manager::Message*
MobileMessageHandler::HandleIncomingMessageProtocol(
    const protocol_handler::RawMessagePtr message) {
  DCHECK_OR_RETURN(message, NULL);
  application_manager::Message* out_message = NULL;
  switch (message->protocol_version()) {
    case protocol_handler::MajorProtocolVersion::PROTOCOL_VERSION_1:
      LOG4CXX_DEBUG(logger_, "Protocol version - V1");
      out_message =
          MobileMessageHandler::HandleIncomingMessageProtocolV1(message);
      break;
    case protocol_handler::MajorProtocolVersion::PROTOCOL_VERSION_2:
      LOG4CXX_DEBUG(logger_, "Protocol version - V2");
      out_message =
          MobileMessageHandler::HandleIncomingMessageProtocolV2(message);
      break;
    case protocol_handler::MajorProtocolVersion::PROTOCOL_VERSION_3:
      LOG4CXX_DEBUG(logger_, "Protocol version - V3");
      out_message =
          MobileMessageHandler::HandleIncomingMessageProtocolV2(message);
      break;
    case protocol_handler::MajorProtocolVersion::PROTOCOL_VERSION_4:
      LOG4CXX_DEBUG(logger_, "Protocol version - V4");
      out_message =
          MobileMessageHandler::HandleIncomingMessageProtocolV2(message);
      break;
    case protocol_handler::MajorProtocolVersion::PROTOCOL_VERSION_5:
      LOG4CXX_DEBUG(logger_, "Protocol version - V5");
      out_message =
          MobileMessageHandler::HandleIncomingMessageProtocolV2(message);
      break;
    default:
      LOG4CXX_WARN(logger_, "Can't recognise protocol version");
      out_message = NULL;
      break;
  }
  if (out_message == NULL) {
    LOG4CXX_WARN(logger_, "Message is NULL");
    return NULL;
  }
  LOG4CXX_DEBUG(logger_,
                "Incoming RPC_INFO: " << (out_message->connection_key() >> 16)
                                      << ", "
                                      << message_types[out_message->type()]
                                      << ", " << out_message->function_id()
                                      << ", " << out_message->correlation_id()
                                      << ", " << out_message->json_message());
  return out_message;
}

protocol_handler::RawMessage*
MobileMessageHandler::HandleOutgoingMessageProtocol(
    const MobileMessage& message) {
  LOG4CXX_DEBUG(logger_,
                "Outgoing RPC_INFO: " << (message->connection_key() >> 16)
                                      << ", " << message_types[message->type()]
                                      << ", " << message->function_id() << ", "
                                      << message->correlation_id() << ", "
                                      << message->json_message());

  if (message->protocol_version() ==
      protocol_handler::MajorProtocolVersion::PROTOCOL_VERSION_1) {
    return MobileMessageHandler::HandleOutgoingMessageProtocolV1(message);
  }
  if (Message::is_sufficient_version(
          protocol_handler::MajorProtocolVersion::PROTOCOL_VERSION_2,
          message->protocol_version())) {
    return MobileMessageHandler::HandleOutgoingMessageProtocolV2(message);
  }
  return NULL;
}

application_manager::Message*
MobileMessageHandler::HandleIncomingMessageProtocolV1(
    const ::protocol_handler::RawMessagePtr message) {
  LOG4CXX_AUTO_TRACE(logger_);
  application_manager::Message* outgoing_message =
      new application_manager::Message(
          protocol_handler::MessagePriority::FromServiceType(
              message->service_type()));
  if (!message) {
    NOTREACHED();
    delete outgoing_message;
    return NULL;
  }

  outgoing_message->set_connection_key(message->connection_key());
  outgoing_message->set_protocol_version(
      static_cast<protocol_handler::MajorProtocolVersion>(
          message->protocol_version()));
  outgoing_message->set_json_message(std::string(
      reinterpret_cast<const char*>(message->data()), message->data_size()));

  if (outgoing_message->json_message().empty()) {
    delete outgoing_message;
    return NULL;
  }

  return outgoing_message;
}

application_manager::Message*
MobileMessageHandler::HandleIncomingMessageProtocolV2(
    const ::protocol_handler::RawMessagePtr message) {
  LOG4CXX_AUTO_TRACE(logger_);
  utils::BitStream message_bytestream(message->data(), message->data_size());
  protocol_handler::ProtocolPayloadV2 payload;
  protocol_handler::Extract(
      &message_bytestream, &payload, message->data_size());

  // Silently drop message if it wasn't parsed correctly
  if (message_bytestream.IsBad()) {
    LOG4CXX_WARN(
        logger_,
        "Drop ill-formed message from mobile, partially parsed: " << payload);
    return NULL;
  }

  std::auto_ptr<application_manager::Message> outgoing_message(
      new application_manager::Message(
          protocol_handler::MessagePriority::FromServiceType(
              message->service_type())));

  outgoing_message->set_json_message(payload.json);
  outgoing_message->set_function_id(payload.header.rpc_function_id);
  outgoing_message->set_message_type(
      MessageTypeFromRpcType(payload.header.rpc_type));
  outgoing_message->set_correlation_id(int32_t(payload.header.correlation_id));
  outgoing_message->set_connection_key(message->connection_key());
  outgoing_message->set_protocol_version(
      static_cast<protocol_handler::MajorProtocolVersion>(
          message->protocol_version()));
  outgoing_message->set_data_size(message->data_size());
  outgoing_message->set_payload_size(message->payload_size());

  if (!payload.data.empty()) {
    const BinaryData binary_payload_data(payload.data);
    outgoing_message->set_binary_data(&binary_payload_data);
  }
  return outgoing_message.release();
}

protocol_handler::RawMessage*
MobileMessageHandler::HandleOutgoingMessageProtocolV1(
    const MobileMessage& message) {
  LOG4CXX_AUTO_TRACE(logger_);
  std::string message_string = message->json_message();
  if (message_string.length() == 0) {
    LOG4CXX_WARN(logger_, "Drop ill-formed message from mobile");
    return NULL;
  }

  BinaryData raw_message(message_string.length() + 1);
  memcpy(&raw_message[0], message_string.c_str(), message_string.length() + 1);

  protocol_handler::RawMessage* result =
      new protocol_handler::RawMessage(message->connection_key(),
                                       1,
                                       &raw_message[0],
                                       message_string.length() + 1);

  return result;
}

protocol_handler::RawMessage*
MobileMessageHandler::HandleOutgoingMessageProtocolV2(
    const MobileMessage& message) {
  LOG4CXX_AUTO_TRACE(logger_);
  if (message->json_message().length() == 0) {
    LOG4CXX_ERROR(logger_, "json string is empty.");
  }
  uint32_t json_size = message->json_message().length();
  uint32_t binary_size = 0;
  if (message->has_binary_data()) {
    binary_size = message->binary_data()->size();
  }

  const size_t data_for_sending_size =
      protocol_handler::PROTOCOL_HEADER_V2_SIZE + json_size + binary_size;
  BinaryData data_for_sending(data_for_sending_size);
  uint8_t offset = 0;

  uint8_t rpc_type_flag = 0;
  switch (message->type()) {
    case application_manager::kRequest:
      rpc_type_flag = kRequest;
      break;
    case application_manager::kResponse:
      rpc_type_flag = kResponse;
      break;
    case application_manager::kNotification:
      rpc_type_flag = kNotification;
      break;
    default:
      NOTREACHED();
      break;
  }

  uint32_t function_id = message->function_id();
  data_for_sending[offset++] =
      ((rpc_type_flag << 4) & 0xF0) | (function_id >> 24);
  data_for_sending[offset++] = function_id >> 16;
  data_for_sending[offset++] = function_id >> 8;
  data_for_sending[offset++] = function_id;

  uint32_t correlation_id = message->correlation_id();
  data_for_sending[offset++] = correlation_id >> 24;
  data_for_sending[offset++] = correlation_id >> 16;
  data_for_sending[offset++] = correlation_id >> 8;
  data_for_sending[offset++] = correlation_id;

  data_for_sending[offset++] = json_size >> 24;
  data_for_sending[offset++] = json_size >> 16;
  data_for_sending[offset++] = json_size >> 8;
  data_for_sending[offset++] = json_size;

  memcpy(&data_for_sending[offset], message->json_message().c_str(), json_size);

  // Default the service type to RPC Service
  uint8_t type = 0x07;

  if (message->has_binary_data()) {
    // Change the service type to Hybrid Service
    type = 0x0F;
    const BinaryData& binary_data = *(message->binary_data());
    BinaryData::value_type* current_pointer =
        &data_for_sending[offset + json_size];
    for (uint32_t i = 0; i < binary_size; ++i) {
      current_pointer[i] = binary_data[i];
    }
  }

  protocol_handler::RawMessage* msg_to_protocol_handler =
      new protocol_handler::RawMessage(message->connection_key(),
                                       message->protocol_version(),
                                       &data_for_sending[0],
                                       data_for_sending_size,
                                       type);

  return msg_to_protocol_handler;
}
}  // namespace application_manager
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_recovery_ffdc_sgpe.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
// *INDENT-OFF*

///
/// @file   p9_pm_recovery_ffdc_sgpe.C
/// @brief  Models SGPE platform for the FFDC collection of PM complex
///
/// *HWP HWP Owner:      Greg Still <stillgs@us.ibm.com>
/// *HWP FW Owner:       Prem S Jha <premjha2@in.ibm.com>
/// *HWP Team:           PM
/// *HWP Level:          2
/// *HWP Consumed by:    Hostboot
//
// *INDENT-OFF*
//--------------------------------------------------------------------------
// Includes
//--------------------------------------------------------------------------

#include <p9_pm_recovery_ffdc_sgpe.H>
#include <p9_hcd_memmap_occ_sram.H>
#include <p9_ppe_defs.H>
#include <stddef.h>
#include <endian.h>

 namespace p9_stop_recov_ffdc
 {
    PlatSgpe::PlatSgpe( const fapi2::Target< fapi2::TARGET_TYPE_PROC_CHIP > i_procChipTgt )
      : PlatPmComplex( i_procChipTgt,
                       PLAT_SGPE,
                       OCC_SRAM_SGPE_HEADER_ADDR,
                       OCC_SRAM_SGPE_TRACE_START,
                       OCC_SRAM_SGPE_DASHBOARD_START )
    { }

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

    fapi2::ReturnCode PlatSgpe::init ( void* i_pHomerBuf )
    {
        FAPI_DBG (">> PlatSgpe::init" );
        FAPI_TRY ( collectFfdc( i_pHomerBuf, INIT),
                   "Failed To init SGPE FFDC" );

    fapi_try_exit:
        FAPI_DBG ("<< PlatSgpe::init" );
        return fapi2::current_err;
    }

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

    fapi2::ReturnCode PlatSgpe::collectFfdc( void *  i_pHomerBuf,
                                             uint8_t i_ffdcType )
    {
        FAPI_DBG(">> PlatSgpe::collectFfdc");

        fapi2::ReturnCode l_retCode = fapi2::FAPI2_RC_SUCCESS;

        HomerFfdcRegion * l_pHomerFfdc =
                ( HomerFfdcRegion *)( (uint8_t *)i_pHomerBuf + FFDC_REGION_HOMER_BASE_OFFSET );

        uint8_t* l_pFfdcLoc = (uint8_t *)(&l_pHomerFfdc->iv_sgpeFfdcRegion);
        PpeFfdcHeader* l_pSgpeFfdcHdr = (PpeFfdcHeader*) l_pFfdcLoc;

        uint16_t l_ffdcValdityVect = l_pSgpeFfdcHdr->iv_sectionsValid;

        if ( i_ffdcType & INIT )
        {   // overwrite on init
            l_ffdcValdityVect = PPE_FFDC_INVALID;
        }

        //In case of error , invalidate FFDC in header.
        if ( i_ffdcType & PPE_HALT_STATE )
        {
            l_ffdcValdityVect |= PPE_HALT_STATE_VALID;
            l_retCode = readPpeHaltState ( SGPE_BASE_ADDRESS, l_pFfdcLoc );
            if ( l_retCode != fapi2::FAPI2_RC_SUCCESS )
            {
                FAPI_ERR ( "Error collecting SGPE Halt State" );
                l_ffdcValdityVect &= ~PPE_HALT_STATE_VALID;
            }
        }

        if ( i_ffdcType & PPE_STATE )
        {
            l_ffdcValdityVect |= PPE_STATE_VALID;
            l_retCode = collectPpeState ( SGPE_BASE_ADDRESS, l_pFfdcLoc );
            if ( l_retCode != fapi2::FAPI2_RC_SUCCESS )
            {
                FAPI_ERR ( "Error collecting SGPE State" );
                // PPE State Data is bad & continue SRAM FFDC collection
                l_ffdcValdityVect &= ~PPE_STATE_VALID;
            }
        }

        if ( i_ffdcType & TRACES )
        {
            l_ffdcValdityVect |= PPE_TRACE_VALID;
            l_retCode = collectTrace( l_pFfdcLoc );
            if( l_retCode )
            {
                FAPI_ERR("Error in collecting SGPE Trace " );
                l_ffdcValdityVect &= ~PPE_TRACE_VALID;
            }
        }

        if ( i_ffdcType & DASH_BOARD_VAR )
        {
            l_ffdcValdityVect |= PPE_DASHBOARD_VALID;
            l_retCode = collectGlobals( l_pFfdcLoc );

            if( l_retCode )
            {
                FAPI_ERR("Error in collecting SGPE Globals" );
                l_ffdcValdityVect &= ~PPE_DASHBOARD_VALID;
            }
        }

        if ( i_ffdcType & IMAGE_HEADER )
        {
            l_ffdcValdityVect |= PPE_IMAGE_HEADER_VALID;
            l_retCode = collectImageHeader( l_pFfdcLoc );

            if( l_retCode )
            {
                FAPI_ERR("Error in collecting SGPE Image header" );
                l_ffdcValdityVect &= ~PPE_IMAGE_HEADER_VALID;
            }
        }

        FAPI_TRY( updateSgpeFfdcHeader( l_pFfdcLoc, l_ffdcValdityVect),
                          "Failed To Update SGPE FFDC Header for SGPE " );

        if (l_ffdcValdityVect == PPE_FFDC_INVALID)
            setPmFfdcSectionValid ( i_pHomerBuf, PM_FFDC_SGPE_VALID, false );
        else
            setPmFfdcSectionValid ( i_pHomerBuf, PM_FFDC_SGPE_VALID );

    fapi_try_exit:
        FAPI_DBG("<< PlatSgpe::collectFfdc: 0x%02X", l_ffdcValdityVect);
        return fapi2::current_err;
    }

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

    fapi2::ReturnCode PlatSgpe::collectTrace( uint8_t * i_pTraceBuf )
    {
        FAPI_DBG(">> PlatSgpe::collectTrace" );
        PpeFfdcLayout * l_pSgpeFfdc = ( PpeFfdcLayout *) ( i_pTraceBuf );

        uint8_t * l_pTraceLoc = &l_pSgpeFfdc->iv_ppeTraces[0];

        FAPI_TRY( PlatPmComplex::collectSramInfo
                    ( PlatPmComplex::getProcChip(),
                      l_pTraceLoc,
                      TRACES,
                      FFDC_PPE_TRACES_SIZE ),
                  "Trace Collection Failed" );

        fapi_try_exit:
        FAPI_DBG("<< PlatSgpe::collectTrace" );
        return fapi2::current_err;
    }

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

    fapi2::ReturnCode  PlatSgpe::collectGlobals( uint8_t * i_pSgpeGlobals )
    {
        FAPI_DBG(">> PlatSgpe::collectGlobals" );
        PpeFfdcLayout * l_pSgpeFfdc = ( PpeFfdcLayout *) ( i_pSgpeGlobals );
        uint8_t * l_pTraceLoc = &l_pSgpeFfdc->iv_ppeGlobals[0];

        FAPI_TRY( PlatPmComplex::collectSramInfo
                    ( PlatPmComplex::getProcChip(),
                      l_pTraceLoc,
                      DASH_BOARD_VAR,
                      OCC_SRAM_SGPE_DASHBOARD_SIZE ),
                  "Failed To Collect SGPE Global Variables" );

        fapi_try_exit:
        FAPI_DBG("<< PlatSgpe::collectGlobals" );
        return fapi2::current_err;
    }

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

    fapi2::ReturnCode PlatSgpe::collectInternalReg( uint8_t * i_pSgpeIntReg )
    {
        return fapi2::FAPI2_RC_SUCCESS;
    }

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

    fapi2::ReturnCode PlatSgpe::collectImageHeader( uint8_t * i_pSgpeImgHdr )
    {
        FAPI_DBG(">> PlatSgpe::collectImageHeader" );
        PpeFfdcLayout *l_pSgpeFfdc = ( PpeFfdcLayout *) ( i_pSgpeImgHdr );

        uint8_t * l_pTraceLoc = &l_pSgpeFfdc->iv_ppeImageHeader[0];
        FAPI_TRY( PlatPmComplex::collectSramInfo
                  ( PlatPmComplex::getProcChip(),
                    l_pTraceLoc,
                    IMAGE_HEADER,
                    FFDC_PPE_IMG_HDR_SIZE ),
                  "Failed To Collect SGPE Image Header" );

        fapi_try_exit:
        FAPI_DBG("<< PlatSgpe::collectImageHeader" );
        return fapi2::current_err;
    }

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

    fapi2::ReturnCode PlatSgpe::updateSgpeFfdcHeader( uint8_t* i_pHomerBuf,
                                                      uint16_t i_sectionsValid )
    {
        FAPI_DBG(">> updateSgpeFfdcHeader" );

        PpeFfdcHeader * l_pSgpeFfdcHdr       =  ( (PpeFfdcHeader *)(( PpeFfdcHdrRegion * ) i_pHomerBuf ));
        l_pSgpeFfdcHdr->iv_ppeMagicNumber    =  htobe32( FFDC_SGPE_MAGIC_NUM );
        l_pSgpeFfdcHdr->iv_ppeNumber         =  0;
        PlatPmComplex::updatePpeFfdcHeader( l_pSgpeFfdcHdr, i_sectionsValid );

        FAPI_DBG("<< updateSgpeFfdcHeader" );
        return fapi2::FAPI2_RC_SUCCESS;
    }
    //-----------------------------------------------------------------------

extern "C"
{
    fapi2::ReturnCode p9_pm_recovery_ffdc_sgpe( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP >& i_procChip,
                                                void * i_pFfdcBuf )
    {
        FAPI_IMP(">> p9_pm_recovery_sgpe" );

        PlatSgpe l_sgpeFfdc( i_procChip );
        FAPI_TRY( l_sgpeFfdc.collectFfdc( i_pFfdcBuf, (ALL & ~PPE_HALT_STATE) ),
                  "Failed To Collect SGPE FFDC" );

        fapi_try_exit:
        FAPI_IMP("<< p9_pm_recovery_sgpe" );
        return fapi2::current_err;
    }

}

}//namespace p9_stop_recov_ffdc ends
<commit_msg>Idle Stop State: Adds CME and SGPE global variables to FFDC.<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_recovery_ffdc_sgpe.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
// *INDENT-OFF*

///
/// @file   p9_pm_recovery_ffdc_sgpe.C
/// @brief  Models SGPE platform for the FFDC collection of PM complex
///
/// *HWP HWP Owner:      Greg Still <stillgs@us.ibm.com>
/// *HWP FW Owner:       Prem S Jha <premjha2@in.ibm.com>
/// *HWP Team:           PM
/// *HWP Level:          2
/// *HWP Consumed by:    Hostboot
//
// *INDENT-OFF*
//--------------------------------------------------------------------------
// Includes
//--------------------------------------------------------------------------

#include <p9_pm_recovery_ffdc_sgpe.H>
#include <p9_hcd_memmap_occ_sram.H>
#include <p9_ppe_defs.H>
#include <stddef.h>
#include <endian.h>

 namespace p9_stop_recov_ffdc
 {
    PlatSgpe::PlatSgpe( const fapi2::Target< fapi2::TARGET_TYPE_PROC_CHIP > i_procChipTgt )
      : PlatPmComplex( i_procChipTgt,
                       PLAT_SGPE,
                       OCC_SRAM_SGPE_HEADER_ADDR,
                       OCC_SRAM_SGPE_TRACE_START,
                       OCC_SRAM_SGPE_DASHBOARD_START )
    { }

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

    fapi2::ReturnCode PlatSgpe::init ( void* i_pHomerBuf )
    {
        FAPI_DBG (">> PlatSgpe::init" );
        FAPI_TRY ( collectFfdc( i_pHomerBuf, INIT),
                   "Failed To init SGPE FFDC" );

    fapi_try_exit:
        FAPI_DBG ("<< PlatSgpe::init" );
        return fapi2::current_err;
    }

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

    fapi2::ReturnCode PlatSgpe::collectFfdc( void *  i_pHomerBuf,
                                             uint8_t i_ffdcType )
    {
        FAPI_DBG(">> PlatSgpe::collectFfdc");

        fapi2::ReturnCode l_retCode = fapi2::FAPI2_RC_SUCCESS;

        HomerFfdcRegion * l_pHomerFfdc =
                ( HomerFfdcRegion *)( (uint8_t *)i_pHomerBuf + FFDC_REGION_HOMER_BASE_OFFSET );

        uint8_t* l_pFfdcLoc = (uint8_t *)(&l_pHomerFfdc->iv_sgpeFfdcRegion);
        PpeFfdcHeader* l_pSgpeFfdcHdr = (PpeFfdcHeader*) l_pFfdcLoc;

        uint16_t l_ffdcValdityVect = l_pSgpeFfdcHdr->iv_sectionsValid;

        if ( i_ffdcType & INIT )
        {   // overwrite on init
            l_ffdcValdityVect = PPE_FFDC_INVALID;
        }

        //In case of error , invalidate FFDC in header.
        if ( i_ffdcType & PPE_HALT_STATE )
        {
            l_ffdcValdityVect |= PPE_HALT_STATE_VALID;
            l_retCode = readPpeHaltState ( SGPE_BASE_ADDRESS, l_pFfdcLoc );
            if ( l_retCode != fapi2::FAPI2_RC_SUCCESS )
            {
                FAPI_ERR ( "Error collecting SGPE Halt State" );
                l_ffdcValdityVect &= ~PPE_HALT_STATE_VALID;
            }
        }

        if ( i_ffdcType & PPE_STATE )
        {
            l_ffdcValdityVect |= PPE_STATE_VALID;
            l_retCode = collectPpeState ( SGPE_BASE_ADDRESS, l_pFfdcLoc );
            if ( l_retCode != fapi2::FAPI2_RC_SUCCESS )
            {
                FAPI_ERR ( "Error collecting SGPE State" );
                // PPE State Data is bad & continue SRAM FFDC collection
                l_ffdcValdityVect &= ~PPE_STATE_VALID;
            }
        }

        if ( i_ffdcType & TRACES )
        {
            l_ffdcValdityVect |= PPE_TRACE_VALID;
            l_retCode = collectTrace( l_pFfdcLoc );
            if( l_retCode )
            {
                FAPI_ERR("Error in collecting SGPE Trace " );
                l_ffdcValdityVect &= ~PPE_TRACE_VALID;
            }
        }

        if ( i_ffdcType & DASH_BOARD_VAR )
        {
            l_ffdcValdityVect |= PPE_DASHBOARD_VALID;
            l_retCode = collectGlobals( l_pFfdcLoc );

            if( l_retCode )
            {
                FAPI_ERR("Error in collecting SGPE Globals" );
                l_ffdcValdityVect &= ~PPE_DASHBOARD_VALID;
            }
        }

        if ( i_ffdcType & IMAGE_HEADER )
        {
            l_ffdcValdityVect |= PPE_IMAGE_HEADER_VALID;
            l_retCode = collectImageHeader( l_pFfdcLoc );

            if( l_retCode )
            {
                FAPI_ERR("Error in collecting SGPE Image header" );
                l_ffdcValdityVect &= ~PPE_IMAGE_HEADER_VALID;
            }
        }

        FAPI_TRY( updateSgpeFfdcHeader( l_pFfdcLoc, l_ffdcValdityVect),
                          "Failed To Update SGPE FFDC Header for SGPE " );

        if (l_ffdcValdityVect == PPE_FFDC_INVALID)
            setPmFfdcSectionValid ( i_pHomerBuf, PM_FFDC_SGPE_VALID, false );
        else
            setPmFfdcSectionValid ( i_pHomerBuf, PM_FFDC_SGPE_VALID );

    fapi_try_exit:
        FAPI_DBG("<< PlatSgpe::collectFfdc: 0x%02X", l_ffdcValdityVect);
        return fapi2::current_err;
    }

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

    fapi2::ReturnCode PlatSgpe::collectPartialFfdc( void * i_pBuf, FfdcDataType i_dataType,
                                                    uint32_t & o_ffdcLength )
    {
        FAPI_DBG(">> PlatSgpe::collectPartialFfdc");
        fapi2::ReturnCode l_retCode = fapi2::FAPI2_RC_SUCCESS;
        uint32_t l_maxSize = o_ffdcLength;
        FAPI_DBG("Max buf size %d", o_ffdcLength );

        switch( i_dataType )
        {
            case IMAGE_HEADER:
                o_ffdcLength = FFDC_PPE_IMG_HDR_SIZE;
                break;
            case DASH_BOARD_VAR:
                o_ffdcLength = OCC_SRAM_SGPE_DASHBOARD_SIZE;
                break;
            case TRACES:
                o_ffdcLength = FFDC_PPE_TRACES_SIZE;
                break;
            default:
                FAPI_ERR("Bad FFDC Data type. Skipping 0x%d", (uint32_t)i_dataType );
                goto fapi_try_exit;
                break;
        }

        if( !i_pBuf )
        {
            FAPI_ERR("Bad Buffer Ptr" );
            goto fapi_try_exit;
        }

        if( o_ffdcLength > l_maxSize )
        {
            o_ffdcLength = l_maxSize;
        }

        FAPI_TRY( PlatPmComplex::collectSramInfo( PlatPmComplex::getProcChip(),
                                                  (uint8_t*)i_pBuf,
                                                  i_dataType,
                                                  o_ffdcLength ),
                  "Failed To Collect SGPE SRAM FFDC" );

        fapi_try_exit:
        FAPI_DBG("<< PlatSgpe::collectPartialFfdc");
        return fapi2::current_err;
    }

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

    fapi2::ReturnCode PlatSgpe::collectTrace( uint8_t * i_pTraceBuf )
    {
        FAPI_DBG(">> PlatSgpe::collectTrace" );
        PpeFfdcLayout * l_pSgpeFfdc = ( PpeFfdcLayout *) ( i_pTraceBuf );

        uint8_t * l_pTraceLoc = &l_pSgpeFfdc->iv_ppeTraces[0];

        FAPI_TRY( PlatPmComplex::collectSramInfo
                    ( PlatPmComplex::getProcChip(),
                      l_pTraceLoc,
                      TRACES,
                      FFDC_PPE_TRACES_SIZE ),
                  "Trace Collection Failed" );

        fapi_try_exit:
        FAPI_DBG("<< PlatSgpe::collectTrace" );
        return fapi2::current_err;
    }

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

    fapi2::ReturnCode  PlatSgpe::collectGlobals( uint8_t * i_pSgpeGlobals )
    {
        FAPI_DBG(">> PlatSgpe::collectGlobals" );

        PpeFfdcLayout * l_pSgpeFfdc = ( PpeFfdcLayout *) ( i_pSgpeGlobals );
        uint8_t * l_pTraceLoc = &l_pSgpeFfdc->iv_ppeGlobals[0];

        FAPI_TRY( PlatPmComplex::collectSramInfo
                    ( PlatPmComplex::getProcChip(),
                      l_pTraceLoc,
                      DASH_BOARD_VAR,
                      OCC_SRAM_SGPE_DASHBOARD_SIZE ),
                  "Failed To Collect SGPE Global Variables" );

        fapi_try_exit:

        FAPI_DBG("<< PlatSgpe::collectGlobals" );
        return fapi2::current_err;
    }

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

    fapi2::ReturnCode PlatSgpe::collectInternalReg( uint8_t * i_pSgpeIntReg )
    {
        return fapi2::FAPI2_RC_SUCCESS;
    }

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

    fapi2::ReturnCode PlatSgpe::collectImageHeader( uint8_t * i_pSgpeImgHdr )
    {
        FAPI_DBG(">> PlatSgpe::collectImageHeader" );
        PpeFfdcLayout *l_pSgpeFfdc = ( PpeFfdcLayout *) ( i_pSgpeImgHdr );

        uint8_t * l_pTraceLoc = &l_pSgpeFfdc->iv_ppeImageHeader[0];
        FAPI_TRY( PlatPmComplex::collectSramInfo
                  ( PlatPmComplex::getProcChip(),
                    l_pTraceLoc,
                    IMAGE_HEADER,
                    FFDC_PPE_IMG_HDR_SIZE ),
                  "Failed To Collect SGPE Image Header" );

        fapi_try_exit:
        FAPI_DBG("<< PlatSgpe::collectImageHeader" );
        return fapi2::current_err;
    }

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

    fapi2::ReturnCode PlatSgpe::updateSgpeFfdcHeader( uint8_t* i_pHomerBuf,
                                                      uint16_t i_sectionsValid )
    {
        FAPI_DBG(">> updateSgpeFfdcHeader" );

        PpeFfdcHeader * l_pSgpeFfdcHdr       =  ( (PpeFfdcHeader *)(( PpeFfdcHdrRegion * ) i_pHomerBuf ));
        l_pSgpeFfdcHdr->iv_ppeMagicNumber    =  htobe32( FFDC_SGPE_MAGIC_NUM );
        l_pSgpeFfdcHdr->iv_ppeNumber         =  0;
        PlatPmComplex::updatePpeFfdcHeader( l_pSgpeFfdcHdr, i_sectionsValid );

        FAPI_DBG("<< updateSgpeFfdcHeader" );
        return fapi2::FAPI2_RC_SUCCESS;
    }
    //-----------------------------------------------------------------------

extern "C"
{
    fapi2::ReturnCode p9_pm_recovery_ffdc_sgpe( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP >& i_procChip,
                                                void * i_pFfdcBuf )
    {
        FAPI_IMP(">> p9_pm_recovery_sgpe" );

        PlatSgpe l_sgpeFfdc( i_procChip );
        FAPI_TRY( l_sgpeFfdc.collectFfdc( i_pFfdcBuf, (ALL & ~PPE_HALT_STATE) ),
                  "Failed To Collect SGPE FFDC" );

        fapi_try_exit:
        FAPI_IMP("<< p9_pm_recovery_sgpe" );
        return fapi2::current_err;
    }

}

}//namespace p9_stop_recov_ffdc ends
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: ZipPackageEntry.cxx,v $
 *
 *  $Revision: 1.24 $
 *
 *  last change: $Author: kz $ $Date: 2003-09-11 10:17:42 $
 *
 *  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): Martin Gallwey (gallwey@sun.com)
 *
 *
 ************************************************************************/
#ifndef _ZIP_PACKAGE_ENTRY_HXX
#include <ZipPackageEntry.hxx>
#endif
#ifndef _COM_SUN_STAR_PACKAGE_ZIP_ZIPCONSTANTS_HPP_
#include <com/sun/star/packages/zip/ZipConstants.hpp>
#endif
#ifndef _VOS_DIAGNOSE_H_
#include <vos/diagnose.hxx>
#endif
#ifndef _IMPL_VALID_CHARACTERS_HXX_
#include <ImplValidCharacters.hxx>
#endif
#ifndef _ZIP_PACKAGE_FOLDER_HXX
#include <ZipPackageFolder.hxx>
#endif
#ifndef _ZIP_PACKAGE_STREAM_HXX
#include <ZipPackageStream.hxx>
#endif
#ifndef _CONTENT_INFO_HXX_
#include <ContentInfo.hxx>
#endif

using namespace rtl;
using namespace com::sun::star;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::container;
using namespace com::sun::star::packages::zip;
using namespace com::sun::star::packages::zip::ZipConstants;

ZipPackageEntry::ZipPackageEntry ( bool bNewFolder )
: pParent ( NULL )
, mbIsFolder ( bNewFolder )
{
}

ZipPackageEntry::~ZipPackageEntry()
{
}
// XChild
OUString SAL_CALL ZipPackageEntry::getName(  )
    throw(RuntimeException)
{
    return aEntry.sName;
}
void SAL_CALL ZipPackageEntry::setName( const OUString& aName )
    throw(RuntimeException)
{
    if ( pParent && pParent->hasByName ( aEntry.sName ) )
        pParent->removeByName ( aEntry.sName );

    const sal_Unicode *pChar = aName.getStr();
    VOS_ENSURE ( Impl_IsValidChar (pChar, static_cast < sal_Int16 > ( aName.getLength() ), sal_False), "Invalid character in new zip package entry name!");

    aEntry.sName = aName;

    if ( pParent )
        pParent->doInsertByName ( this, sal_False );
}
Reference< XInterface > SAL_CALL ZipPackageEntry::getParent(  )
        throw(RuntimeException)
{
    return Reference< XInterface >( xParent, UNO_QUERY );
}

void ZipPackageEntry::doSetParent ( ZipPackageFolder * pNewParent, sal_Bool bInsert )
{
    xParent = pParent = pNewParent;
    if ( bInsert && !pNewParent->hasByName ( aEntry.sName ) )
        pNewParent->doInsertByName ( this, sal_False );
}

void SAL_CALL ZipPackageEntry::setParent( const Reference< XInterface >& xNewParent )
        throw(NoSupportException, RuntimeException)
{
    sal_Int64 nTest;
    Reference < XUnoTunnel > xTunnel ( xNewParent, UNO_QUERY );
    if ( !xNewParent.is() || ( nTest = xTunnel->getSomething ( ZipPackageFolder::static_getImplementationId () ) ) == 0 )
        throw NoSupportException();

    ZipPackageFolder *pNewParent = reinterpret_cast < ZipPackageFolder * > ( nTest );

    if ( pNewParent != pParent )
    {
        if ( pParent && pParent->hasByName ( aEntry.sName ) )
            pParent->removeByName( aEntry.sName );
        doSetParent ( pNewParent, sal_True );
    }
}
    //XPropertySet
Reference< beans::XPropertySetInfo > SAL_CALL ZipPackageEntry::getPropertySetInfo(  )
        throw(RuntimeException)
{
    return Reference < beans::XPropertySetInfo > ();
}
void SAL_CALL ZipPackageEntry::addPropertyChangeListener( const OUString& aPropertyName, const Reference< beans::XPropertyChangeListener >& xListener )
        throw(beans::UnknownPropertyException, WrappedTargetException, RuntimeException)
{
}
void SAL_CALL ZipPackageEntry::removePropertyChangeListener( const OUString& aPropertyName, const Reference< beans::XPropertyChangeListener >& aListener )
        throw(beans::UnknownPropertyException, WrappedTargetException, RuntimeException)
{
}
void SAL_CALL ZipPackageEntry::addVetoableChangeListener( const OUString& PropertyName, const Reference< beans::XVetoableChangeListener >& aListener )
        throw(beans::UnknownPropertyException, WrappedTargetException, RuntimeException)
{
}
void SAL_CALL ZipPackageEntry::removeVetoableChangeListener( const OUString& PropertyName, const Reference< beans::XVetoableChangeListener >& aListener )
        throw(beans::UnknownPropertyException, WrappedTargetException, RuntimeException)
{
}
<commit_msg>INTEGRATION: CWS mav09 (1.24.50); FILE MERGED 2004/08/06 09:56:51 mav 1.24.50.1: #i29833# reimplement folders and streams life dependencies<commit_after>/*************************************************************************
 *
 *  $RCSfile: ZipPackageEntry.cxx,v $
 *
 *  $Revision: 1.25 $
 *
 *  last change: $Author: kz $ $Date: 2004-10-04 21:09:49 $
 *
 *  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): Martin Gallwey (gallwey@sun.com)
 *
 *
 ************************************************************************/
#ifndef _ZIP_PACKAGE_ENTRY_HXX
#include <ZipPackageEntry.hxx>
#endif
#ifndef _COM_SUN_STAR_PACKAGE_ZIP_ZIPCONSTANTS_HPP_
#include <com/sun/star/packages/zip/ZipConstants.hpp>
#endif
#ifndef _VOS_DIAGNOSE_H_
#include <vos/diagnose.hxx>
#endif
#ifndef _IMPL_VALID_CHARACTERS_HXX_
#include <ImplValidCharacters.hxx>
#endif
#ifndef _ZIP_PACKAGE_FOLDER_HXX
#include <ZipPackageFolder.hxx>
#endif
#ifndef _ZIP_PACKAGE_STREAM_HXX
#include <ZipPackageStream.hxx>
#endif
#ifndef _CONTENT_INFO_HXX_
#include <ContentInfo.hxx>
#endif

using namespace rtl;
using namespace com::sun::star;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::container;
using namespace com::sun::star::packages::zip;
using namespace com::sun::star::packages::zip::ZipConstants;

ZipPackageEntry::ZipPackageEntry ( bool bNewFolder )
: pParent ( NULL )
, mbIsFolder ( bNewFolder )
{
}

ZipPackageEntry::~ZipPackageEntry()
{
    // When the entry is destroyed it must be already disconnected from the parent
    OSL_ENSURE( !pParent, "The parent must be disconnected already! Memory corruption is possible!\n" );
}

// XChild
OUString SAL_CALL ZipPackageEntry::getName(  )
    throw(RuntimeException)
{
    return aEntry.sName;
}
void SAL_CALL ZipPackageEntry::setName( const OUString& aName )
    throw(RuntimeException)
{
    if ( pParent && pParent->hasByName ( aEntry.sName ) )
        pParent->removeByName ( aEntry.sName );

    const sal_Unicode *pChar = aName.getStr();
    VOS_ENSURE ( Impl_IsValidChar (pChar, static_cast < sal_Int16 > ( aName.getLength() ), sal_False), "Invalid character in new zip package entry name!");

    aEntry.sName = aName;

    if ( pParent )
        pParent->doInsertByName ( this, sal_False );
}
Reference< XInterface > SAL_CALL ZipPackageEntry::getParent(  )
        throw(RuntimeException)
{
    // return Reference< XInterface >( xParent, UNO_QUERY );
    return Reference< XInterface >( static_cast< ::cppu::OWeakObject* >( pParent ), UNO_QUERY );
}

void ZipPackageEntry::doSetParent ( ZipPackageFolder * pNewParent, sal_Bool bInsert )
{
    // xParent = pParent = pNewParent;
    pParent = pNewParent;
    if ( bInsert && !pNewParent->hasByName ( aEntry.sName ) )
        pNewParent->doInsertByName ( this, sal_False );
}

void SAL_CALL ZipPackageEntry::setParent( const Reference< XInterface >& xNewParent )
        throw(NoSupportException, RuntimeException)
{
    sal_Int64 nTest;
    Reference < XUnoTunnel > xTunnel ( xNewParent, UNO_QUERY );
    if ( !xNewParent.is() || ( nTest = xTunnel->getSomething ( ZipPackageFolder::static_getImplementationId () ) ) == 0 )
        throw NoSupportException();

    ZipPackageFolder *pNewParent = reinterpret_cast < ZipPackageFolder * > ( nTest );

    if ( pNewParent != pParent )
    {
        if ( pParent && pParent->hasByName ( aEntry.sName ) )
            pParent->removeByName( aEntry.sName );
        doSetParent ( pNewParent, sal_True );
    }
}
    //XPropertySet
Reference< beans::XPropertySetInfo > SAL_CALL ZipPackageEntry::getPropertySetInfo(  )
        throw(RuntimeException)
{
    return Reference < beans::XPropertySetInfo > ();
}
void SAL_CALL ZipPackageEntry::addPropertyChangeListener( const OUString& aPropertyName, const Reference< beans::XPropertyChangeListener >& xListener )
        throw(beans::UnknownPropertyException, WrappedTargetException, RuntimeException)
{
}
void SAL_CALL ZipPackageEntry::removePropertyChangeListener( const OUString& aPropertyName, const Reference< beans::XPropertyChangeListener >& aListener )
        throw(beans::UnknownPropertyException, WrappedTargetException, RuntimeException)
{
}
void SAL_CALL ZipPackageEntry::addVetoableChangeListener( const OUString& PropertyName, const Reference< beans::XVetoableChangeListener >& aListener )
        throw(beans::UnknownPropertyException, WrappedTargetException, RuntimeException)
{
}
void SAL_CALL ZipPackageEntry::removeVetoableChangeListener( const OUString& PropertyName, const Reference< beans::XVetoableChangeListener >& aListener )
        throw(beans::UnknownPropertyException, WrappedTargetException, RuntimeException)
{
}
<|endoftext|>