diff --git a/pool/shard008/C++/0096461_testtime_wstream.cpp b/pool/shard008/C++/0096461_testtime_wstream.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c5a386a10c2a40aa990aaad31572161fe6922648 --- /dev/null +++ b/pool/shard008/C++/0096461_testtime_wstream.cpp @@ -0,0 +1,89 @@ +/* Copyright (c) 2003-2004 CrystalClear Software, Inc. + * Use, modification and distribution is subject to the + * Boost Software License, Version 1.0. (See accompanying + * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) + * Author: Bart Garst + * $Date: 2008-11-26 22:07:14 +0100 (Wed, 26 Nov 2008) $ + */ +#include +#include +#include +#include +#include "../testfrmwk.hpp" +#include + +using namespace boost::gregorian; +using namespace boost::posix_time; +using boost::lexical_cast; + +int main(){ +#if defined(BOOST_NO_STD_WSTRING) || \ + defined(BOOST_DATE_TIME_INCLUDE_LIMITED_HEADERS) + check("No wstring/wstream support for this compiler", false); +#else + + std::wstring res, ws; + std::wstringstream wss; + /* time_period was used because all the time-type objects + * that have operator<< can be easily accessed from it. + * Tose are: ptime, time_duration, time_period */ + date d1(2003,Jan,20), d2(2003,May,10); + time_period tp(ptime(d1,hours(1)), ptime(d2,hours(15))); + + // ptime + wss << tp.begin(); + res = L"2003-Jan-20 01:00:00"; + check("ptime op<<", res == wss.str()); + wss.str(L""); + ws = to_simple_wstring(tp.begin()); + check("ptime to_simple_wstring", res == ws); + res = L"20030120T010000"; + ws = to_iso_wstring(tp.begin()); + check("ptime to_iso_wstring", res == ws); + res = L"2003-01-20T01:00:00"; + ws = to_iso_extended_wstring(tp.begin()); + check("ptime to_iso_extended_wstring", res == ws); + + // time_duration + wss << tp.length(); + res = L"2654:00:00"; + check("time_duration", res == wss.str()); + wss.str(L""); + ws = to_simple_wstring(tp.length()); + check("time_duration to_simple_wstring", res == ws); + res = L"26540000"; + ws = to_iso_wstring(tp.length()); + check("time_duration to_iso_wstring", res == ws); + + // time_period + wss << tp; +#ifdef BOOST_DATE_TIME_POSIX_TIME_STD_CONFIG + res = L"[2003-Jan-20 01:00:00/2003-May-10 14:59:59.999999999]"; +#else + res = L"[2003-Jan-20 01:00:00/2003-May-10 14:59:59.999999]"; +#endif + check("time_period", res == wss.str()); + wss.str(L""); + ws = to_simple_wstring(tp); + check("time_period to_simple_wstring", res == ws); + + // special values + time_duration sv_td(neg_infin); + date sv_d(pos_infin); + ptime sv_tp(sv_d,hours(1)); + res = L"+infinity"; + wss << sv_tp; + check("ptime op<< special value", res == wss.str()); + wss.str(L""); + ws = to_simple_wstring(sv_tp); + check("ptime to_simple_wstring special value", res == ws); + res = L"-infinity"; + wss << sv_td; + check("time_duration op<< special value", res == wss.str()); + wss.str(L""); + ws = to_simple_wstring(sv_td); + check("time_duration to_simple_wstring special value", res == ws); + +#endif + return printTestStats(); +} diff --git a/pool/shard008/C++/0096465_ObsEdge.cc b/pool/shard008/C++/0096465_ObsEdge.cc new file mode 100644 index 0000000000000000000000000000000000000000..a23f7bbf01ca5380e9662a7e29af050274bae711 --- /dev/null +++ b/pool/shard008/C++/0096465_ObsEdge.cc @@ -0,0 +1,181 @@ +#include +#include "ObsEdge.h" +#include "Belief.h" +#include "BeliefNode.h" +#include "Bounds.h" +#include "RandSource.h" +#include "Simulator.h" +using namespace std; + +Simulator* ObsEdge::simulator; + +void ObsEdge::initStatic(Simulator* simulator) +{ + ObsEdge::simulator = simulator; +} + +void ObsEdge::clearParticles() +{ + cachedParticles->particles.clear(); +} + +inline void ObsEdge::addNode(PolicyGraph::Node* node) { + nodes.push_back(node); +} + +void ObsEdge::backup() +{ + if (bounds->model.getObsType(obs) == TermObs){ + bestPolicyNode = bounds->policyGraph.getInitPolicy(0); + lower = upper = cachedParticles->currSum; + // update lastUpdated to prevent count from being increased in + // addParticle() and fails the assert() + lastUpdated = 0; + } else { + if (lastUpdated == Never) { + findBestInitPolicy(); + findInitUpper(); + lastUpdated = 0; + } + + if (bounds->model.getObsType(obs) != LoopObs) { + // LoopObs can only have init policies as child + if (nextBelief != NULL) + backupFromNextBelief(); + + addPolicyNodes(); + backupFromPolicyGraph(); + } else { + // LoopObs + lower = upper = bestPolicyVal; + } + } +} + +void ObsEdge::findBestInitPolicy() +{ + bestPolicyVal = NegInf; + + for (long i = 0; i < bounds->model.getNumInitPolicies(); i++) { + double currPolicyVal = cachedParticles->currSum; + for (long k = 0; k < count; ++k) { + double sumDiscounted; + Particle& particle = cachedParticles->particles[k]; + RandStream randStream; + randStream.initseed(bounds->randSource.getStream(k).get()); + simulator->runSingle(bounds->maxSimulLength, &sumDiscounted, particle.state, *bounds->policyGraph.getInitPolicy(i), &randStream); + double currValue = power(bounds->model.getDiscount(), particle.pathLength) * sumDiscounted; + currPolicyVal += currValue; + } + + if (currPolicyVal > bestPolicyVal) { + bestPolicyVal = currPolicyVal; + bestPolicyNode = bounds->policyGraph.getInitPolicy(i); + } + } + lower = bestPolicyVal; +} + +void ObsEdge::backupFromPolicyGraph() +{ + assert(count == int(cachedParticles->particles.size())); + for (vector::iterator it = nodes.begin(); + it != nodes.end(); ++it) { + double sumPolicyValue = cachedParticles->currSum; + + #pragma omp parallel for reduction(+:sumPolicyValue) + for (long k = 0; k < count; k++) { + double sumDiscounted; + Particle& particle = cachedParticles->particles[k]; + RandStream randStream; + randStream.initseed(bounds->randSource.getStream(k).get()); + + simulator->runSingle(bounds->maxSimulLength, &sumDiscounted, particle.state, *(*it), &randStream); + double currValue = power(bounds->model.getDiscount(), particle.pathLength) * sumDiscounted; + + sumPolicyValue += currValue; + } + + if (sumPolicyValue > bestPolicyVal) { + bestPolicyVal = sumPolicyValue; + bestPolicyNode = *it; + lower = sumPolicyValue; + } + } + + nodes.clear(); +} + +void ObsEdge::backupFromNextBelief() +{ + assert(nextBelief != NULL); + + double nextLower = nextBelief->beliefNode->lBound * count + + cachedParticles->currSum; + double nextUpper = nextBelief->beliefNode->uBound * count + + cachedParticles->currSum; + + if (nextLower > lower) { + lower = nextLower; + bestPolicyVal = nextLower; + bestPolicyNode = nextBelief->beliefNode->bestPolicyNode; + } + //lastUpdated = (nextBelief->beliefNode->lastUpdated > lastUpdated) ? nextBelief->beliefNode->lastUpdated : lastUpdated; + + if (nextUpper < upper) + upper = nextUpper; +} + +void ObsEdge::addPolicyNodes() +{ + if (lastUpdated == Never) { + PolicyGraph& policyGraph = bounds->policyGraph; + for (long j=0; j < bounds->model.getNumInitPolicies(); j++){ + PolicyGraph::Node* node = policyGraph.getInitPolicy(j); + addNode(node); + } + lastUpdated = 0; + } else { + PolicyGraph& policyGraph = bounds->policyGraph; + Model& model = bounds->model; + long obsGrp = model.getObsGrpFromObs(obs); + long end = policyGraph.getSize(obsGrp); + long start = lastUpdated; + + for (long j=start; j < end; j++) { + PolicyGraph::Node* node = policyGraph.getPolicy(obsGrp, j); + addNode(node); + } + lastUpdated = end; + } +} + +void ObsEdge::addParticle(const State& state, long pathLength, double immediateReward) +{ + if (cachedParticles == NULL) { + cachedParticles = new ParticleStore(); + } + // weight = 1 + cachedParticles->particles.push_back(Particle(state, pathLength, 1)); + + if (lastUpdated == Never) { + ++count; + assert(count == int(cachedParticles->particles.size())); + cachedParticles->currSum += immediateReward; + } +} + +double ObsEdge::findInitUpper() +{ + double sumDiscounted = 0; + Model& model = bounds->model; + + for (long k=0; k < count; k++) { + Particle& particle = cachedParticles->particles[k]; + double currValue = power(model.getDiscount(), particle.pathLength) * model.upperBound(particle.state); + sumDiscounted += currValue; + } + upper = cachedParticles->currSum + sumDiscounted; + + return upper; +} diff --git a/pool/shard008/C++/0096469_protocol_packet_test.cc b/pool/shard008/C++/0096469_protocol_packet_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..71c772624347a240bb3622d50a9dc9ffd18bbc54 --- /dev/null +++ b/pool/shard008/C++/0096469_protocol_packet_test.cc @@ -0,0 +1,268 @@ +/* + * Copyright (c) 2016, 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 "gtest/gtest.h" +#include + +#include "utils/macro.h" +#include "protocol_handler/protocol_packet.h" +#include "protocol/common.h" + +namespace test { +namespace components { +namespace protocol_handler_test { + +using protocol_handler::RawMessagePtr; +using protocol_handler::ProtocolPacket; +using protocol_handler::ConnectionID; +using protocol_handler::FRAME_TYPE_MAX_VALUE; +using protocol_handler::FRAME_DATA_FIRST; +using protocol_handler::FRAME_TYPE_FIRST; +using protocol_handler::PROTOCOL_VERSION_1; +using protocol_handler::PROTOCOL_VERSION_3; +using protocol_handler::PROTECTION_OFF; +using protocol_handler::RESULT_CODE; +using protocol_handler::RESULT_OK; +using protocol_handler::RESULT_FAIL; +using protocol_handler::FRAME_TYPE_CONTROL; +using protocol_handler::kControl; +using protocol_handler::kRpc; +using protocol_handler::kAudio; +using protocol_handler::kMobileNav; +using protocol_handler::kBulk; +using protocol_handler::kInvalidServiceType; +using protocol_handler::FRAME_DATA_HEART_BEAT; +using protocol_handler::FRAME_DATA_START_SERVICE_ACK; +using protocol_handler::FRAME_DATA_LAST_CONSECUTIVE; +using protocol_handler::PROTOCOL_HEADER_V1_SIZE; +using protocol_handler::PROTOCOL_HEADER_V2_SIZE; +using protocol_handler::PROTOCOL_VERSION_MAX; + +class ProtocolPacketTest : public ::testing::Test { + protected: + void SetUp() OVERRIDE { + some_message_id_ = 0xABCDEF0; + some_session_id_ = 0xFEDCBA0; + some_connection_id_ = 10; + } + + RawMessagePtr GetRawMessage(uint8_t version, + uint8_t frame_type, + uint8_t service_type) { + ProtocolPacket prot_packet(some_connection_id_, + version, + PROTECTION_OFF, + frame_type, + service_type, + FRAME_DATA_HEART_BEAT, + some_session_id_, + 0u, + some_message_id_); + EXPECT_EQ(frame_type, prot_packet.frame_type()); + return prot_packet.serializePacket(); + } + + const uint8_t zero_test_data_element_ = 0x0u; + uint32_t some_message_id_; + uint32_t some_session_id_; + ConnectionID some_connection_id_; +}; + +TEST_F(ProtocolPacketTest, SerializePacketWithDiffVersions) { + uint8_t version = PROTOCOL_VERSION_1; + for (; version <= PROTOCOL_VERSION_MAX; ++version) { + RawMessagePtr res = GetRawMessage(version, FRAME_TYPE_CONTROL, kControl); + EXPECT_EQ(version, res->protocol_version()); + EXPECT_EQ(kControl, res->service_type()); + EXPECT_EQ(some_connection_id_, res->connection_key()); + if (res->protocol_version() == PROTOCOL_VERSION_1) { + EXPECT_EQ(PROTOCOL_HEADER_V1_SIZE, res->data_size()); + } else { + EXPECT_EQ(PROTOCOL_HEADER_V2_SIZE, res->data_size()); + } + } +} + +// ServiceType should be equal 0x0 (Control), 0x07 (RPC), 0x0A (PCM), 0x0B +// (Video), 0x0F (Bulk) +TEST_F(ProtocolPacketTest, SerializePacketWithDiffServiceType) { + std::vector serv_types; + serv_types.push_back(kControl); + serv_types.push_back(kRpc); + serv_types.push_back(kAudio); + serv_types.push_back(kMobileNav); + serv_types.push_back(kBulk); + + for (size_t i = 0; i < serv_types.size(); ++i) { + RawMessagePtr res = + GetRawMessage(PROTOCOL_VERSION_3, FRAME_TYPE_CONTROL, serv_types[i]); + EXPECT_EQ(PROTOCOL_VERSION_3, + static_cast< ::protocol_handler::MajorProtocolVersion>( + res->protocol_version())); + EXPECT_EQ(serv_types[i], res->service_type()); + EXPECT_EQ(PROTOCOL_HEADER_V2_SIZE, res->data_size()); + } +} + +TEST_F(ProtocolPacketTest, SerializePacketWithWrongServiceType) { + std::vector serv_types; + for (uint8_t service_type = kControl + 1; service_type < kRpc; + ++service_type) { + serv_types.push_back(service_type); + } + serv_types.push_back(0x08); + serv_types.push_back(0x09); + serv_types.push_back(0x0C); + serv_types.push_back(0x0D); + serv_types.push_back(0x0E); + + for (size_t i = 0; i < serv_types.size(); ++i) { + RawMessagePtr res = + GetRawMessage(PROTOCOL_VERSION_3, FRAME_TYPE_CONTROL, serv_types[i]); + EXPECT_EQ(PROTOCOL_VERSION_3, + static_cast< ::protocol_handler::MajorProtocolVersion>( + res->protocol_version())); + EXPECT_EQ(kInvalidServiceType, res->service_type()); + } +} + +TEST_F(ProtocolPacketTest, SetPacketWithDiffFrameType) { + uint8_t frame_type; + for (frame_type = FRAME_TYPE_CONTROL + 1; frame_type <= FRAME_TYPE_MAX_VALUE; + ++frame_type) { + RawMessagePtr res = GetRawMessage(PROTOCOL_VERSION_3, frame_type, kControl); + EXPECT_EQ(PROTOCOL_VERSION_3, + static_cast< ::protocol_handler::MajorProtocolVersion>( + res->protocol_version())); + EXPECT_EQ(kControl, res->service_type()); + } +} + +TEST_F(ProtocolPacketTest, AppendDataToEmptyPacket) { + // Set version, serviceType, frameData, sessionId + const uint8_t session_id = 1u; + uint8_t some_data[] = { + zero_test_data_element_, kRpc, FRAME_DATA_START_SERVICE_ACK, session_id}; + ProtocolPacket protocol_packet; + RESULT_CODE res = protocol_packet.appendData(some_data, sizeof(some_data)); + EXPECT_EQ(RESULT_FAIL, res); +} + +TEST_F(ProtocolPacketTest, SetTotalDataBytes) { + const uint8_t new_data_size = 10u; + ProtocolPacket protocol_packet; + protocol_packet.set_total_data_bytes(new_data_size); + EXPECT_EQ(new_data_size, protocol_packet.total_data_bytes()); +} + +TEST_F(ProtocolPacketTest, AppendDataToPacketWithNonZeroSize) { + // Set version, serviceType, frameData, sessionId + const uint8_t session_id = 1u; + uint8_t some_data[] = { + zero_test_data_element_, kRpc, FRAME_DATA_LAST_CONSECUTIVE, session_id}; + ProtocolPacket protocol_packet; + protocol_packet.set_total_data_bytes(sizeof(some_data) + 1); + RESULT_CODE res = protocol_packet.appendData(some_data, sizeof(some_data)); + EXPECT_EQ(RESULT_OK, res); + EXPECT_EQ(zero_test_data_element_, protocol_packet.data()[0]); + EXPECT_EQ(kRpc, protocol_packet.data()[1]); + EXPECT_EQ(FRAME_DATA_LAST_CONSECUTIVE, protocol_packet.data()[2]); + EXPECT_EQ(session_id, protocol_packet.data()[3]); +} + +TEST_F(ProtocolPacketTest, SetData) { + const uint8_t session_id = 1u; + uint8_t some_data[] = { + zero_test_data_element_, kRpc, FRAME_DATA_HEART_BEAT, session_id}; + ProtocolPacket protocol_packet; + protocol_packet.set_data(some_data, sizeof(some_data)); + EXPECT_EQ(zero_test_data_element_, protocol_packet.data()[0]); + EXPECT_EQ(kRpc, protocol_packet.data()[1]); + EXPECT_EQ(FRAME_DATA_HEART_BEAT, protocol_packet.data()[2]); + EXPECT_EQ(session_id, protocol_packet.data()[3]); +} + +TEST_F(ProtocolPacketTest, DeserializeZeroPacket) { + uint8_t message[] = {}; + ProtocolPacket protocol_packet; + RESULT_CODE res = protocol_packet.deserializePacket(message, 0); + EXPECT_EQ(RESULT_OK, res); +} + +TEST_F(ProtocolPacketTest, DeserializeNonZeroPacket) { + // Set header, serviceType, frameData, sessionId + const uint8_t session_id = 1u; + const uint8_t version_frame_type = 0x21; + uint8_t some_message[] = { + version_frame_type, kRpc, FRAME_DATA_START_SERVICE_ACK, session_id}; + ProtocolPacket protocol_packet; + RESULT_CODE res = + protocol_packet.deserializePacket(some_message, PROTOCOL_HEADER_V2_SIZE); + EXPECT_EQ(RESULT_OK, res); +} + +TEST_F(ProtocolPacketTest, DeserializePacket_FrameTypeFirst_ResultOK) { + // Arrange + const uint8_t session_id = 1u; + const uint8_t data_size = 1u; + const uint8_t version_frame_type = 0x22; + // Set protol version - 2 and frame type - first + uint8_t message[] = {version_frame_type, + kRpc, + FRAME_DATA_FIRST, + session_id, + zero_test_data_element_, + zero_test_data_element_, + zero_test_data_element_, + zero_test_data_element_, + zero_test_data_element_, + zero_test_data_element_, + zero_test_data_element_, + zero_test_data_element_, + zero_test_data_element_, + zero_test_data_element_, + zero_test_data_element_, + data_size, + zero_test_data_element_}; + ProtocolPacket protocol_packet; + // Act + RESULT_CODE res = + protocol_packet.deserializePacket(message, PROTOCOL_HEADER_V2_SIZE); + uint8_t frame_type = protocol_packet.frame_type(); + // Assert + EXPECT_EQ(FRAME_TYPE_FIRST, frame_type); + EXPECT_EQ(RESULT_OK, res); +} + +} // namespace protocol_handler_test +} // namespace components +} // namespace test diff --git a/pool/shard008/C++/0096471_arrays-maxsum.cpp b/pool/shard008/C++/0096471_arrays-maxsum.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6940380e4777ff4bd9d11fcc3b19dbde097d5807 --- /dev/null +++ b/pool/shard008/C++/0096471_arrays-maxsum.cpp @@ -0,0 +1,58 @@ +// http://www.interviewbit.com/courses/programming/topics/arrays/problems/maxsum/ + +// Kadane's Algorithm: https://en.wikipedia.org/wiki/Maximum_subarray_problem + +// Q: how big are expected values? Ok to use int? + +#include +#include +#include + +using std::cin; +using std::cout; + +int maxSubArray(const std::vector &A) { + + if (A.size() <= 0) { + return 0; + } + int max_ending_here = 0; + int max_so_far = 0; + int max_value = std::numeric_limits::min(); //store max value in case all elements in array are negative + + for (int i = 0; i < A.size(); ++i) { + max_ending_here = max_ending_here + A[i]; + + if (max_ending_here < 0) { + max_ending_here = 0; + } else if (max_so_far < max_ending_here) { + max_so_far = max_ending_here; + } + + if (A[i] > max_value) { + max_value = A[i]; + } + } + if (max_value < 0) { //all values in array were negative - return the least negative value + return max_value; + } else { + return max_so_far; + } +} + + +int main() { + std::vector a; + int input; + + while (1) { + cout << "Enter values 1 at a time into vector. Enter 0 when you are finished.\n"; + cin >> input; + + while (input != 0) { + a.push_back(input); + cin >> input; + } + cout << "\nMax subarray sum: " << maxSubArray(a) << "\n"; + } +} \ No newline at end of file diff --git a/pool/shard008/C++/0096472_command.cpp b/pool/shard008/C++/0096472_command.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a1a40861ab81e656d896fd89a968ff2115c37139 --- /dev/null +++ b/pool/shard008/C++/0096472_command.cpp @@ -0,0 +1,174 @@ +// Own header +#include "command.h" + +// Project headers +#include "mutex.h" +#include "string_utils.h" +#include "gui/gui_base.h" +// #include "widgets/command_view.h" + +// Standard headers +#include +#include + + +CommandSender g_commandSender; +char COMMAND_RETURN_NOTHING[] = "nothing"; + + +char *CreateIntToSend(int val) +{ + // Max num chars needed to represent an int is: + // 10 digits + 1 sign + 1 null terminator = 12 + char *rv = new char[12]; + itoa(val, rv, 10); + return rv; +} + + +// **************************************************************************** +// Class CommandReceiver +// **************************************************************************** + +CommandReceiver::CommandReceiver(char const *name) +{ + m_receiverName = StringDuplicate(name); +} + + +CommandReceiver::~CommandReceiver() +{ + delete[] m_receiverName; +} + + +bool CommandReceiver::GetArgumentBool(char const *arguments, char const *argName, bool defaultVal) +{ + bool val = defaultVal; + if (arguments) + { + char const *match = strstr(arguments, argName); + if (match) + { + match += strlen(argName); + if (*match == '=') + { + match++; + if (stricmp(match, "true") == 0) + { + val = true; + } + else + { + val = false; + } + } + } + } + + return val; +} + + +int CommandReceiver::GetArgumentInt(char const *arguments, char const *argName, int defaultVal) +{ + int val = defaultVal; + if (arguments) + { + char const *match = strstr(arguments, argName); + if (match) + { + match += strlen(argName); + if (*match == '=') + { + match++; + val = atoi(match); + } + } + } + + return val; +} + + + +// **************************************************************************** +// Class CommandSender +// **************************************************************************** + +CommandSender::CommandSender() +{ + m_deferredCommandsMutex = new Mutex; +} + + +void CommandSender::RegisterReceiver(CommandReceiver *receiver) +{ + DebugAssert(receiver->m_receiverName); + DebugAssert(strlen(receiver->m_receiverName) > 2); + + // Make sure the specified CommandReceiver isn't already registered + for (int i = 0; i < m_receivers.Size(); ++i) + { + CommandReceiver *r = m_receivers[i]; + if (stricmp(receiver->m_receiverName, r->m_receiverName) == 0) + { + DebugAssert(0); + } + } + + m_receivers.PutData(receiver); +} + + +char *CommandSender::SendCommand(char const *from, char const *target, char const *command, char const *arguments) +{ + CommandReceiver *receiver = g_gui->GetWidgetByName(target); + + if (!receiver) + { + for (int i = 0; i < m_receivers.Size(); ++i) + { + CommandReceiver *thisReceiver = m_receivers[i]; + if (stricmp(thisReceiver->m_receiverName, target) == 0) + { + receiver = thisReceiver; + break; + } + } + } + + if (receiver) + { +// TODO - re-add CommandHistory +// CommandHistory *cv = (CommandHistory*)g_guiManager->GetWidgetByName(COMMAND_VIEW_WINDOW_NAME); +// ReleaseAssert(cv, "CommandSender::SendCommand: command view window not found"); +// cv->AddCommand(from, target, command, arguments); + + return receiver->ExecuteCommand(from, command, arguments); + } + + return NULL; +} + + +void CommandSender::SendCommandDeferred(char const *from, char const *target, + char const *command, char const *arguments) +{ + MutexLocker lock(m_deferredCommandsMutex); + DeferredCommand *dc = new DeferredCommand(from, target, command, arguments); + m_deferredCommands.PutDataAtEnd(dc); +} + + +void CommandSender::ProcessDeferredCommands() +{ + MutexLocker lock(m_deferredCommandsMutex); + while (m_deferredCommands.Size()) + { + DeferredCommand *dc = m_deferredCommands[0]; + m_deferredCommands.RemoveData(0); + SendCommandNoRV(dc->m_from, dc->m_target, dc->m_command, dc->m_arguments); + delete dc; + } +} diff --git a/pool/shard008/C++/0096473_FontHostStreamTest.cpp b/pool/shard008/C++/0096473_FontHostStreamTest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7ac3da363ab4cd253afba6a3680dbef1e90f392f --- /dev/null +++ b/pool/shard008/C++/0096473_FontHostStreamTest.cpp @@ -0,0 +1,116 @@ +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + +#include "SkBitmap.h" +#include "SkCanvas.h" +#include "SkColor.h" +#include "SkFontDescriptor.h" +#include "SkGraphics.h" +#include "SkPaint.h" +#include "SkPoint.h" +#include "SkRect.h" +#include "SkStream.h" +#include "SkTypeface.h" +#include "SkTypes.h" +#include "Test.h" + +static const SkColor bgColor = SK_ColorWHITE; + +static void create(SkBitmap* bm, SkIRect bound) { + bm->allocN32Pixels(bound.width(), bound.height()); +} + +static void drawBG(SkCanvas* canvas) { + canvas->drawColor(bgColor); +} + +/** Assumes that the ref draw was completely inside ref canvas -- + implies that everything outside is "bgColor". + Checks that all overlap is the same and that all non-overlap on the + ref is "bgColor". + */ +static bool compare(const SkBitmap& ref, const SkIRect& iref, + const SkBitmap& test, const SkIRect& itest) +{ + const int xOff = itest.fLeft - iref.fLeft; + const int yOff = itest.fTop - iref.fTop; + + SkAutoLockPixels alpRef(ref); + SkAutoLockPixels alpTest(test); + + for (int y = 0; y < test.height(); ++y) { + for (int x = 0; x < test.width(); ++x) { + SkColor testColor = test.getColor(x, y); + int refX = x + xOff; + int refY = y + yOff; + SkColor refColor; + if (refX >= 0 && refX < ref.width() && + refY >= 0 && refY < ref.height()) + { + refColor = ref.getColor(refX, refY); + } else { + refColor = bgColor; + } + if (refColor != testColor) { + return false; + } + } + } + return true; +} + +DEF_TEST(FontHostStream, reporter) { + { + SkPaint paint; + paint.setColor(SK_ColorGRAY); + paint.setTextSize(SkIntToScalar(30)); + + SkTypeface* fTypeface = SkTypeface::CreateFromName("Georgia", + SkTypeface::kNormal); + SkSafeUnref(paint.setTypeface(fTypeface)); + + SkIRect origRect = SkIRect::MakeWH(64, 64); + SkBitmap origBitmap; + create(&origBitmap, origRect); + SkCanvas origCanvas(origBitmap); + + SkIRect streamRect = SkIRect::MakeWH(64, 64); + SkBitmap streamBitmap; + create(&streamBitmap, streamRect); + SkCanvas streamCanvas(streamBitmap); + + SkPoint point = SkPoint::Make(24, 32); + + // Test: origTypeface and streamTypeface from orig data draw the same + drawBG(&origCanvas); + origCanvas.drawText("A", 1, point.fX, point.fY, paint); + + SkTypeface* origTypeface = paint.getTypeface(); + SkAutoTUnref aur; + if (NULL == origTypeface) { + origTypeface = aur.reset(SkTypeface::RefDefault()); + } + + int ttcIndex; + SkAutoTDelete fontData(origTypeface->openStream(&ttcIndex)); + SkTypeface* streamTypeface = SkTypeface::CreateFromStream(fontData.detach()); + + SkFontDescriptor desc; + bool isLocalStream = false; + streamTypeface->getFontDescriptor(&desc, &isLocalStream); + REPORTER_ASSERT(reporter, isLocalStream); + + SkSafeUnref(paint.setTypeface(streamTypeface)); + drawBG(&streamCanvas); + streamCanvas.drawPosText("A", 1, &point, paint); + + REPORTER_ASSERT(reporter, + compare(origBitmap, origRect, streamBitmap, streamRect)); + } + //Make sure the typeface is deleted and removed. + SkGraphics::PurgeFontCache(); +} diff --git a/pool/shard008/C++/0096474_QuotaVirtualMachine.cc b/pool/shard008/C++/0096474_QuotaVirtualMachine.cc new file mode 100644 index 0000000000000000000000000000000000000000..1df620dba7330ef9916ccb224d140b1fae14d33b --- /dev/null +++ b/pool/shard008/C++/0096474_QuotaVirtualMachine.cc @@ -0,0 +1,141 @@ +/* -------------------------------------------------------------------------- */ +/* Copyright 2002-2013, OpenNebula Project (OpenNebula.org), C12G Labs */ +/* */ +/* 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 "QuotaVirtualMachine.h" +#include "Quotas.h" + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +const char * QuotaVirtualMachine::VM_METRICS[] = {"VMS", "CPU", "MEMORY"}; + +const int QuotaVirtualMachine::NUM_VM_METRICS = 3; + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +int QuotaVirtualMachine::get_quota(const string& id, VectorAttribute **va) +{ + vector values; + int num; + + *va = 0; + + num = get(template_name, values); + + if ( num == 0 ) + { + return 0; + } + + *va = dynamic_cast(values[0]); + + return 0; +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +bool QuotaVirtualMachine::check(Template * tmpl, + Quotas& default_quotas, + string& error) +{ + map vm_request; + + int memory; + float cpu; + + if ( tmpl->get("MEMORY", memory) == false || memory <= 0 ) + { + error = "MEMORY attribute must be a positive integer value"; + return false; + } + + if ( tmpl->get("CPU", cpu) == false || cpu <= 0 ) + { + error = "CPU attribute must be a positive float or integer value"; + return false; + } + + vm_request.insert(make_pair("VMS",1)); + vm_request.insert(make_pair("MEMORY", memory)); + vm_request.insert(make_pair("CPU", cpu)); + + return check_quota("", vm_request, default_quotas, error); +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +void QuotaVirtualMachine::del(Template * tmpl) +{ + map vm_request; + + int memory; + float cpu; + + if ( tmpl->get("MEMORY", memory) == false ) + { + memory = 0; + } + + if ( tmpl->get("CPU", cpu) == false ) + { + cpu = 0; + } + + vm_request.insert(make_pair("VMS",1)); + vm_request.insert(make_pair("MEMORY", memory)); + vm_request.insert(make_pair("CPU", cpu)); + + del_quota("", vm_request); +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +int QuotaVirtualMachine::get_default_quota( + const string& id, + Quotas& default_quotas, + VectorAttribute **va) +{ + return default_quotas.vm_get(id, va); +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +bool QuotaVirtualMachine::update(Template * tmpl, + Quotas& default_quotas, + string& error) +{ + map vm_request; + + int delta_memory; + float delta_cpu; + + if ( tmpl->get("MEMORY", delta_memory) == true ) + { + vm_request.insert(make_pair("MEMORY", delta_memory)); + } + + if ( tmpl->get("CPU", delta_cpu) == true ) + { + vm_request.insert(make_pair("CPU", delta_cpu)); + } + + return check_quota("", vm_request, default_quotas, error); +} diff --git a/pool/shard008/C++/0096475_qgscurvev2.cpp b/pool/shard008/C++/0096475_qgscurvev2.cpp new file mode 100644 index 0000000000000000000000000000000000000000..045c7bacc575092e56ab9ceab51c02c3ccb15320 --- /dev/null +++ b/pool/shard008/C++/0096475_qgscurvev2.cpp @@ -0,0 +1,103 @@ +/*************************************************************************** + qgscurvev2.cpp + -------------- + begin : November 2014 + copyright : (C) 2014 by Marco Hugentobler + email : marco at sourcepole dot ch + ***************************************************************************/ + +/*************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ + +#include "qgscurvev2.h" +#include "qgslinestringv2.h" + +QgsCurveV2::QgsCurveV2(): QgsAbstractGeometryV2() +{} + +QgsCurveV2::~QgsCurveV2() +{} + +bool QgsCurveV2::isClosed() const +{ + if ( numPoints() == 0 ) + return false; + + //don't consider M-coordinates when testing closedness + QgsPointV2 start = startPoint(); + QgsPointV2 end = endPoint(); + return ( qgsDoubleNear( start.x(), end.x(), 1E-8 ) && + qgsDoubleNear( start.y(), end.y(), 1E-8 ) && + qgsDoubleNear( start.z(), end.z(), 1E-8 ) ); +} + +bool QgsCurveV2::isRing() const +{ + return ( isClosed() && numPoints() >= 4 ); +} + +QgsCoordinateSequenceV2 QgsCurveV2::coordinateSequence() const +{ + if ( !mCoordinateSequence.isEmpty() ) + return mCoordinateSequence; + + mCoordinateSequence.append( QgsRingSequenceV2() ); + mCoordinateSequence.back().append( QgsPointSequenceV2() ); + points( mCoordinateSequence.back().back() ); + + return mCoordinateSequence; +} + +bool QgsCurveV2::nextVertex( QgsVertexId& id, QgsPointV2& vertex ) const +{ + if ( id.vertex < 0 ) + { + id.vertex = 0; + if ( id.part < 0 ) + { + id.part = 0; + } + if ( id.ring < 0 ) + { + id.ring = 0; + } + } + else + { + if ( id.vertex + 1 >= numPoints() ) + { + return false; + } + ++id.vertex; + } + return pointAt( id.vertex, vertex, id.type ); +} + +QgsCurveV2* QgsCurveV2::segmentize() const +{ + return curveToLine(); +} + +QgsPointV2 QgsCurveV2::vertexAt( QgsVertexId id ) const +{ + QgsPointV2 v; + QgsVertexId::VertexType type; + pointAt( id.vertex, v, type ); + return v; +} + +QgsRectangle QgsCurveV2::boundingBox() const +{ + if ( mBoundingBox.isNull() ) + { + mBoundingBox = calculateBoundingBox(); + } + return mBoundingBox; +} + diff --git a/pool/shard008/C++/0096476_generate.cpp b/pool/shard008/C++/0096476_generate.cpp new file mode 100644 index 0000000000000000000000000000000000000000..890bab986c1b859fd7409370694909c4446ecef5 --- /dev/null +++ b/pool/shard008/C++/0096476_generate.cpp @@ -0,0 +1,96 @@ +// Boost.Range library +// +// Copyright Neil Groves 2009. Use, modification and +// distribution is subject to the Boost Software License, Version +// 1.0. (See accompanying file LICENSE_1_0.txt or copy at +// http://www.boost.org/LICENSE_1_0.txt) +// +// +// For more information, see http://www.boost.org/libs/range/ +// +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace boost +{ + namespace + { + class generator_fn + { + public: + typedef int result_type; + + generator_fn() : m_count(0) {} + int operator()() { return ++m_count; } + + private: + int m_count; + }; + + template< class Container > + void test_generate_impl(Container& cont) + { + Container reference(cont); + std::generate(reference.begin(), reference.end(), generator_fn()); + + Container test(cont); + boost::generate(test, generator_fn()); + + BOOST_CHECK_EQUAL_COLLECTIONS( reference.begin(), reference.end(), + test.begin(), test.end() ); + + Container test2(cont); + boost::generate(boost::make_iterator_range(test2), generator_fn()); + + BOOST_CHECK_EQUAL_COLLECTIONS( reference.begin(), reference.end(), + test2.begin(), test2.end() ); + } + + template< class Container > + void test_generate_impl() + { + using namespace boost::assign; + + Container cont; + test_generate_impl(cont); + + cont.clear(); + cont += 9; + test_generate_impl(cont); + + cont.clear(); + cont += 9,8,7,6,5,4,3,2,1; + test_generate_impl(cont); + } + + void test_generate() + { + test_generate_impl< std::vector >(); + test_generate_impl< std::list >(); + test_generate_impl< std::deque >(); + } + } +} + + +boost::unit_test::test_suite* +init_unit_test_suite(int argc, char* argv[]) +{ + boost::unit_test::test_suite* test + = BOOST_TEST_SUITE( "RangeTestSuite.algorithm.generate" ); + + test->add( BOOST_TEST_CASE( &boost::test_generate ) ); + + return test; +} diff --git a/pool/shard008/C++/0096477_matcher.cc b/pool/shard008/C++/0096477_matcher.cc new file mode 100644 index 0000000000000000000000000000000000000000..469c06b385764753127110238d2f0717985b0362 --- /dev/null +++ b/pool/shard008/C++/0096477_matcher.cc @@ -0,0 +1,41 @@ +// +// Copyright RIME Developers +// Distributed under the BSD License +// +// 2012-01-01 GONG Chen +// +#include +#include +#include +#include +#include + +namespace rime { + +Matcher::Matcher(const Ticket& ticket) : Segmentor(ticket) { + // read schema settings + if (!ticket.schema) + return; + Config* config = ticket.schema->config(); + patterns_.LoadConfig(config); +} + +bool Matcher::Proceed(Segmentation* segmentation) { + if (patterns_.empty()) + return true; + auto match = patterns_.GetMatch(segmentation->input(), *segmentation); + if (match.found()) { + DLOG(INFO) << "match: " << match.tag + << " [" << match.start << ", " << match.end << ")"; + while (segmentation->GetCurrentStartPosition() > match.start) + segmentation->pop_back(); + Segment segment(match.start, match.end); + segment.tags.insert(match.tag); + segmentation->AddSegment(segment); + // terminate this round? + //return false; + } + return true; +} + +} // namespace rime diff --git a/pool/shard008/C++/0096480_match_test.cc b/pool/shard008/C++/0096480_match_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..2f44e304e5b78e1b4650eb1d42e73ed461c5de46 --- /dev/null +++ b/pool/shard008/C++/0096480_match_test.cc @@ -0,0 +1,66 @@ +/* Copyright 2015 Google Inc. All Rights Reserved. + +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 +#include +#include "tensorflow/core/lib/core/status_test_util.h" +#include "tensorflow/core/lib/io/match.h" +#include "tensorflow/core/lib/io/path.h" +#include "tensorflow/core/lib/strings/strcat.h" +#include "tensorflow/core/platform/test.h" +#include "tensorflow/core/public/env.h" + +namespace tensorflow { +namespace io { + +static string Match(Env* env, const string& suffix_pattern) { + std::vector results; + Status s = GetMatchingFiles(env, JoinPath(testing::TmpDir(), suffix_pattern), + &results); + if (!s.ok()) { + return s.ToString(); + } else { + string r; + std::sort(results.begin(), results.end()); + for (size_t i = 0; i < results.size(); i++) { + strings::StrAppend(&r, (i > 0) ? "," : "", Basename(results[i])); + } + return r; + } +} +TEST(GetMatchingFiles, Simple) { + Env* env = Env::Default(); + EXPECT_EQ(Match(env, "thereisnosuchfile"), ""); + EXPECT_EQ(Match(env, "thereisnosuchfile*"), ""); + + // Populate a few files + EXPECT_OK(WriteStringToFile(Env::Default(), + JoinPath(testing::TmpDir(), "match-00"), "")); + EXPECT_OK(WriteStringToFile(Env::Default(), + JoinPath(testing::TmpDir(), "match-0a"), "")); + EXPECT_OK(WriteStringToFile(Env::Default(), + JoinPath(testing::TmpDir(), "match-01"), "")); + EXPECT_OK(WriteStringToFile(Env::Default(), + JoinPath(testing::TmpDir(), "match-aaa"), "")); + + EXPECT_EQ(Match(env, "match-*"), "match-00,match-01,match-0a,match-aaa"); + EXPECT_EQ(Match(env, "match-0[0-9]"), "match-00,match-01"); + EXPECT_EQ(Match(env, "match-?[0-9]"), "match-00,match-01"); + EXPECT_EQ(Match(env, "match-?a*"), "match-0a,match-aaa"); + EXPECT_EQ(Match(env, "match-??"), "match-00,match-01,match-0a"); +} + +} // namespace io +} // namespace tensorflow diff --git a/pool/shard008/C++/0096483_HardwareCAN.cpp b/pool/shard008/C++/0096483_HardwareCAN.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fb2c65088c00bee177e68aa5e52cd5ca2459c2ae --- /dev/null +++ b/pool/shard008/C++/0096483_HardwareCAN.cpp @@ -0,0 +1,122 @@ +/** + * @brief HardwareCAN "wiring-like" api for CAN + */ + +#include "wirish.h" +#include "utility/can.h" +#include "HardwareCAN.h" + +/** + * @brief Initialize a CAN peripheral + * @param freq frequency to run at, must one of the following values: + * - CAN_SPEED_1000 + * - CAN_SPEED_500 + * - CAN_SPEED_250 + * - CAN_SPEED_125 + * - CAN_SPEED_95 + * - CAN_SPEED_33 + */ +CAN_STATUS HardwareCAN::begin(CAN_SPEED speed, uint32 mode) +{ +/* Begin Fix JMD + if (can_init(Port, CAN_MCR_NART, CAN_SPEED_250) == CAN_OK) + // NART empêche la réémission en cas de perte d'arbitrage d'où trames perdues + */ + Serial.end(); // disable USB interface -- JMD + if (can_init(Port, 0, speed) == CAN_OK) + // End Fix JMD + return can_set_mode(Port, mode); + return can_status(); +} + +void HardwareCAN::set_pool_mode(void) +{ + return can_set_pool_mode(Port); +} + +void HardwareCAN::set_irq_mode(void) +{ + return can_set_irq_mode(Port); +} + +CAN_STATUS HardwareCAN::filter(uint8 idx, uint32 id, uint32 mask) +{ + return can_filter(Port, idx, CAN_FIFO0, CAN_FILTER_32BIT, CAN_FILTER_MASK, id, mask); +} + +CAN_STATUS HardwareCAN::status(void) +{ + return can_status(); +} + +CAN_TX_MBX HardwareCAN::send(CanMsg* message) +{ + return can_transmit(Port, message); +} + +uint8 HardwareCAN::available(void) +{ + return can_rx_available(); +} + +CanMsg* HardwareCAN::recv(void) +{ + return can_rx_queue_get(); +} + +void HardwareCAN::clear(void) +{ + can_rx_queue_clear(); +} + +void HardwareCAN::free(void) +{ + can_rx_queue_free(); +} + +void HardwareCAN::cancel(CAN_TX_MBX mbx) +{ + can_cancel(Port, mbx); +} + +/** + * @brief Initialize a CAN peripheral + */ +CAN_STATUS HardwareCAN::begin(void) +{ + return begin(CAN_SPEED_250, CAN_MODE_NORMAL); +} + +void HardwareCAN::end(void) +{ + can_deinit(Port); +} + +CanMsg* HardwareCAN::read(CAN_FIFO fifo, CanMsg* msg) +{ + return can_read(Port, fifo, msg); +} + +void HardwareCAN::release(CAN_FIFO fifo) +{ + can_rx_release(Port, fifo); +} + +/** + * @brief Initialize a CAN peripheral + */ +CAN_STATUS HardwareCAN::map(CAN_GPIO_MAP remap) +{ + return can_gpio_map(Port, remap); +} + +uint8 HardwareCAN::fifo_ready(CAN_FIFO fifo) +{ + return can_fifo_ready(Port, fifo); +} + +HardwareCAN::HardwareCAN(CAN_Port* CANx) +{ + Port = CANx; +} + diff --git a/pool/shard008/C++/0096489_BenchGfxCommmands.cpp b/pool/shard008/C++/0096489_BenchGfxCommmands.cpp new file mode 100644 index 0000000000000000000000000000000000000000..343a715c21cd55c40cb45d0baf1c470e3f1db027 --- /dev/null +++ b/pool/shard008/C++/0096489_BenchGfxCommmands.cpp @@ -0,0 +1,30 @@ +/***************************************************************************** + * Copyright (c) 2014-2019 OpenRCT2 developers + * + * For a complete list of all authors, please refer to contributors.md + * Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2 + * + * OpenRCT2 is licensed under the GNU General Public License version 3. + *****************************************************************************/ + +#include "../interface/Screenshot.h" +#include "CommandLine.hpp" + +static exitcode_t HandleBenchGfx(CommandLineArgEnumerator* argEnumerator); + +const CommandLineCommand CommandLine::BenchGfxCommands[]{ + // Main commands + DefineCommand("", " [iterations count]", nullptr, HandleBenchGfx), CommandTableEnd +}; + +static exitcode_t HandleBenchGfx(CommandLineArgEnumerator* argEnumerator) +{ + const char** argv = (const char**)argEnumerator->GetArguments() + argEnumerator->GetIndex(); + int32_t argc = argEnumerator->GetCount() - argEnumerator->GetIndex(); + int32_t result = cmdline_for_gfxbench(argv, argc); + if (result < 0) + { + return EXITCODE_FAIL; + } + return EXITCODE_OK; +} diff --git a/pool/shard008/C++/0096504_math_test.cc b/pool/shard008/C++/0096504_math_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..6d55fa33e4587e43bf1e4bab4ea43e7099f4b2e4 --- /dev/null +++ b/pool/shard008/C++/0096504_math_test.cc @@ -0,0 +1,210 @@ +/* -*- mode: C++ c-basic-offset: 4 -*- + * + * Copyright (c) 1999 Joe Yandle + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + */ + +#include +#include +#include + +#include +#include +#include + +using jlib::math::matrix; +using jlib::math::cuboid; +using jlib::math::vertex; +using jlib::math::Polynomial; +using jlib::util::tokenize; +using jlib::util::int_value; +using jlib::util::double_value; + +int main(int argc, char** argv) { + std::string ss[] = { + "2 3\n" + "4 0", + + "10 15\n" + "20 0", + + "1 2 0\n" + "5 -1 0", + + "17 1 0\n" + "4 8 0", + + "1 1 1\n" + "1 1 3\n" + "2 5 8", + + "0 0 1\n" + "1 1 3\n" + "0 5 8", + + "0 1\n" + "1 2" }; + + uint n = sizeof(ss) / sizeof(std::string); + std::vector< matrix > m; + + for (uint i = 0; i < n; i++) { + std::vector tok = tokenize(ss[i], "\n", false); + + uint x = tok.size(); + uint y = tokenize(tok[0], " ", false).size(); + + std::istringstream is(ss[i]); + matrix ma(x, y); + + is >> ma; + + m.push_back(ma); + } + + matrix mi = matrix::identity(2); + matrix md = matrix::diagonal(2, 5); + + try { + matrix m4 = (m[0] * m[2]); + if(m4 != m[3]) { + std::cerr << m[0] << std::endl << "*" << std::endl + << m[2] << std::endl << "=" << std::endl + << m4 << std::endl << "rather than" << std::endl + << m[3] << std::endl << std::endl; + } + + matrix m5 = (m[0] * mi); + if(m5 != m[0]) { + std::cerr << m[0] << std::endl << "*" << std::endl + << mi << std::endl << "=" << std::endl + << m5 << std::endl << "rather than" << std::endl + << m[0] << std::endl << std::endl; + } + + matrix m6 = (m[0] * md); + if(m6 != m[1]) { + std::cerr << m[0] << std::endl << "*" << std::endl + << md << std::endl << "=" << std::endl + << m6 << std::endl << "rather than" << std::endl + << m[1] << std::endl << std::endl; + } + + std::map > factors = + m[5].factor(matrix::LU); + + std::cout << factors.find("P")->second << "*" << std::endl + << m[5] << "=" << std::endl + << (m[5] * factors.find("P")->second) << std::endl << std::endl; + + std::vector< std::pair > clip; + clip.push_back(std::make_pair(-1.0, 1.0)); + clip.push_back(std::make_pair(-1.0, 1.0)); + clip.push_back(std::make_pair(-1.0, 1.0)); + clip.push_back(std::make_pair(1.0, 4.0)); + matrix tp4 = matrix::project(4, clip); + std::cout << tp4 << std::endl << std::endl; + + cuboid square(2); + + matrix reg(3, 1); + + reg(0, 0) = 0; + reg(1, 0) = 1; + reg(2, 0) = 2; + + matrix trans = reg.transpose(); + + std::cout << reg << std::endl; + std::cout << trans << std::endl; + + Polynomial x = std::vector{ 1, 1 }; + Polynomial y = std::vector{ 1, 1 }; + Polynomial z = x * y; + Polynomial zz = z * x; + Polynomial zzz = zz * x; + + std::cout << "(" << x << ") * (" << y << ") = " << z << std::endl; + std::cout << "(" << z << ") * (" << x << ") = " << zz << std::endl; + std::cout << "(" << zz << ") * (" << x << ") = " << zzz << std::endl; + + if(z != Polynomial(std::vector{1, 2, 1})) { + std::cerr << "first binomial expansion failed" << std::endl; + return 1; + } + + if(zz != Polynomial(std::vector{1, 3, 3, 1})) { + std::cerr << "second binomial expansion failed" << std::endl; + return 1; + } + + // now try something more complicated + Polynomial a = std::vector{ -1, 0, 2 }; + Polynomial b = std::vector{ -6, 0, -1 }; + Polynomial c = a * b; + + std::cout << "(" << a << ") * (" << b << ") = " << c << std::endl; + if(c != Polynomial(std::vector{6, 0, -11, 0, -2})) { + std::cerr << "weird expansion failed" << std::endl; + return 1; + } + + Polynomial a1 = std::vector{ -1, 2, 1 }; + Polynomial b1 = std::vector{ 6, -3, 2 }; + Polynomial c1 = a1 * b1; + + std::cout << "(" << a1 << ") * (" << b1 << ") = " << c1 << std::endl; + if(c1 != Polynomial(std::vector{-6, 15, -2, 1, 2})) { + std::cerr << "super weird expansion failed" << std::endl; + return 1; + } + + int eval0 = a1(0); + if(eval0 != -1) { + std::cerr << "(" << a1 << ")(0) = " << eval0 << " not -1" << std::endl; + return 1; + } + + int eval1 = a1(1); + if(eval1 != 2) { + std::cerr << "(" << a1 << ")(1) = " << eval1 << " not -1" << std::endl; + return 1; + } + + int eval2 = a1(2); + if(eval2 != 7) { + std::cerr << "(" << a1 << ")(2) = " << eval2 << " not -1" << std::endl; + return 1; + } + + int eval3 = a1(3); + if(eval3 != 14) { + std::cerr << "(" << a1 << ")(3) = " << eval3 << " not -1" << std::endl; + return 1; + } + + + } catch (matrix::mismatch) { + std::cerr << "matrices are mismatched" << std::endl; + return 1; + } catch (...) { + std::cerr << "caught error" << std::endl; + return 1; + } + return 0; +} + diff --git a/pool/shard008/C++/0096507_dicomimagelabel.cpp b/pool/shard008/C++/0096507_dicomimagelabel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..49c510d2e074c21d136d1265a142edc2c7e89456 --- /dev/null +++ b/pool/shard008/C++/0096507_dicomimagelabel.cpp @@ -0,0 +1,69 @@ +#include "dicomimagelabel.h" +#include "imageinstance.h" + +#include +#include +#include +#include +#include + +DicomImageLabel::DicomImageLabel(ImageInstance *image, QWidget *parent) : + imageInst(image), + QLabel(parent) +{ + setStyleSheet(QString::fromLatin1("background-color: rgb(0, 0, 0);")); + setFrameShape(QFrame::Box); + setFrameShadow(QFrame::Plain); + setLineWidth(2); + setAlignment(Qt::AlignCenter); + init(); +} + +DicomImageLabel::~DicomImageLabel() +{ + delete imageInst; +} + +void DicomImageLabel::init() +{ + if (imageInst) { + QPixmap pixmap; + imageInst->setImageType(false); + imageInst->getPixmap(pixmap); + setPixmap(pixmap.scaled(IMAGE_LABEL_SIZE-2, IMAGE_LABEL_SIZE-2, Qt::KeepAspectRatio)); + } +} + +void DicomImageLabel::setHighlight(bool yes) +{ + QPalette p = palette(); + if (yes) p.setColor(QPalette::WindowText, Qt::green); + else p.setColor(QPalette::WindowText, Qt::black); + setPalette(p); +} + +void DicomImageLabel::mousePressEvent(QMouseEvent *e) +{ + emit imageClicked(this); + dragOrg = e->pos(); + QLabel::mousePressEvent(e); +} + +void DicomImageLabel::mouseMoveEvent(QMouseEvent *e) +{ + if ((e->buttons() & Qt::LeftButton) && + ((e->pos()-dragOrg).manhattanLength() > QApplication::startDragDistance())) { + QDrag *drag = new QDrag(this); + QMimeData *data = new QMimeData; + data->setImageData((qulonglong)imageInst); + drag->setMimeData(data); + drag->exec(Qt::CopyAction); + } + QLabel::mouseMoveEvent(e); +} + +void DicomImageLabel::mouseDoubleClickEvent(QMouseEvent *e) +{ + emit imageDoubleClicked(this); + QLabel::mouseDoubleClickEvent(e); +} diff --git a/pool/shard008/C++/0096510_GLTextureRectangle.cpp b/pool/shard008/C++/0096510_GLTextureRectangle.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bdf611759aa471b8d9726a0b1bb400742994519c --- /dev/null +++ b/pool/shard008/C++/0096510_GLTextureRectangle.cpp @@ -0,0 +1,112 @@ +// Copyright (c) 2009 Stef Busking +// Distributed under the terms of the MIT License. + +#include "GLTextureRectangle.h" + +#include "GLUtility.h" + +#ifndef NDEBUG +#include +#endif + +using namespace std; + +// ---------------------------------------------------------------------------- +GLTextureRectangle *GLTextureRectangle::New( + int width, int height, int internalformat, + int format, int type, void *data) +{ + // Check if rectangular textures are supported + if (GLEW_ARB_texture_rectangle) + { + GLTextureRectangle *tex = new GLTextureRectangle( + width, height, internalformat); + if (!tex->Allocate(format, type, data)) + { + delete tex; + return 0; + } + return tex; + } + else + { +#ifndef NDEBUG + cerr << "GLTextureRectangle: rectangular textures not supported" + << endl; +#endif + return 0; + } +} + +// ---------------------------------------------------------------------------- +GLTextureRectangle::GLTextureRectangle( + int width, int height, int internalformat) +: GLTexture(width, height, internalformat) +{ +} + +// ---------------------------------------------------------------------------- +GLTextureRectangle::~GLTextureRectangle() +{ +} + +// ---------------------------------------------------------------------------- +bool GLTextureRectangle::Allocate(int format, int type, void *data) +{ + // Store old binding to avoid messing up the state + glPushAttrib(GL_TEXTURE_BIT); + + // Store new params + this->dataformat = format; + this->datatype = type; + + BindToCurrent(); + + // Set texture object parameters + glTexParameterf(GetTextureTarget(), GL_TEXTURE_MAG_FILTER, GL_LINEAR ); + glTexParameterf(GetTextureTarget(), GL_TEXTURE_MIN_FILTER, GL_LINEAR ); + glTexParameterf(GetTextureTarget(), GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE ); + glTexParameterf(GetTextureTarget(), GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE ); + + // Try a proxy allocation to check available memory and parameters + glTexImage2D(GL_PROXY_TEXTURE_RECTANGLE_ARB, 0, internalformat, + width, height, 0, format, type, data); + GLint w; + glGetTexLevelParameteriv(GL_PROXY_TEXTURE_RECTANGLE_ARB, 0, + GL_TEXTURE_WIDTH, &w); + + GLUtility::CheckOpenGLError( + "GLTextureRectangle: Allocate() - proxy allocation"); + + bool eflag = GLUtility::GetErrorFlag(); + if (w == 0 || eflag) + { +#ifndef NDEBUG + cerr << "GLTextureRectangle: " + << "Proxy allocation failed, out of video memory?" << endl; +#endif + UnbindCurrent(); + glPopAttrib(); + return false; + } + + // Allocate the texture + glTexImage2D(GetTextureTarget(), 0, internalformat, + width, height, 0, format, type, data); + GLUtility::CheckOpenGLError("GLTextureRectangle: Allocate - glTexImage2D"); + + UnbindCurrent(); + glPopAttrib(); + + if (GLUtility::GetErrorFlag()) + { +#ifndef NDEBUG + cerr << "GLTextureRectangle: " + << "An error occurred while allocating the texture" << endl; +#endif + GLUtility::ClearOpenGLError(); + return false; + } + + return true; +} diff --git a/pool/shard008/C++/0096511_mesh2d.cpp b/pool/shard008/C++/0096511_mesh2d.cpp new file mode 100644 index 0000000000000000000000000000000000000000..552d93b8eee3c3928ab1305bc4a7c281378a0e4f --- /dev/null +++ b/pool/shard008/C++/0096511_mesh2d.cpp @@ -0,0 +1,189 @@ +/* + * Copyright (c) 2017 Rafael Pagés + * + * This file is part of SSMVtex + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + * of the Software, and to permit persons to whom the Software is furnished to do + * so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +#include "mesh2d.h" + +Mesh2D::Mesh2D(){ + nVtx_ = nTri_ = 0; + triarea_ = 0.0; + bBoxMax_ = bBoxMin_ = Vector2f(0.0,0.0); +} + +Mesh2D::~Mesh2D(){ + +} + +void Mesh2D::addVector(const Vector2f& _vector){ + vtx_.push_back(_vector); + origVtx_.push_back(-1); + nVtx_++; + + // Update the bounding box + bBoxMin_(0) = bBoxMin_(0) < _vector(0) ? bBoxMin_(0) : _vector(0); + bBoxMin_(1) = bBoxMin_(1) < _vector(1) ? bBoxMin_(1) : _vector(1); + bBoxMax_(0) = bBoxMax_(0) > _vector(0) ? bBoxMax_(0) : _vector(0); + bBoxMax_(1) = bBoxMax_(1) > _vector(1) ? bBoxMax_(1) : _vector(1); +} + +void Mesh2D::addVector(const Vector2f& _vector, unsigned int _3dindex){ + vtx_.push_back(_vector); + origVtx_.push_back((int)_3dindex); + nVtx_++; + + // Update the bounding box + bBoxMin_(0) = bBoxMin_(0) < _vector(0) ? bBoxMin_(0) : _vector(0); + bBoxMin_(1) = bBoxMin_(1) < _vector(1) ? bBoxMin_(1) : _vector(1); + bBoxMax_(0) = bBoxMax_(0) > _vector(0) ? bBoxMax_(0) : _vector(0); + bBoxMax_(1) = bBoxMax_(1) > _vector(1) ? bBoxMax_(1) : _vector(1); +} + +void Mesh2D::addTriangle(const Triangle& _triangle){ + tri_.push_back(_triangle); + origTri_.push_back(-1); + nTri_++; + + const float area = triangleArea(tri_.size()-1); + triarea_ += area; +} + +void Mesh2D::addTriangle(const Triangle& _triangle, unsigned int _3dindex){ + tri_.push_back(_triangle); + origTri_.push_back(_3dindex); + nTri_++; + + const float area = triangleArea(tri_.size()-1); + triarea_ += area; +} + +void Mesh2D::replaceTriangles(const std::vector& _newTriangles){ + + tri_.clear(); + tri_ = _newTriangles; + +} + +float Mesh2D::getHypotheticalBBoxArea (const Vector2f& _nv) const { + const float minx = bBoxMin_(0) < _nv(0) ? bBoxMin_(0) : _nv(0); + const float maxx = bBoxMax_(0) > _nv(0) ? bBoxMax_(0) : _nv(0); + const float miny = bBoxMin_(1) < _nv(1) ? bBoxMin_(1) : _nv(1); + const float maxy = bBoxMax_(1) > _nv(1) ? bBoxMax_(1) : _nv(1); + return (maxx - minx) * (maxy - miny); +} + + +void Mesh2D::setOrigVtx(unsigned int _2dindex, unsigned int _3dindex){ + origVtx_[_2dindex] = (int)_3dindex; +} + +void Mesh2D::setOrigTri(unsigned int _2dindex, unsigned int _3dindex){ + origTri_[_2dindex] = (int)_3dindex; +} + +int Mesh2D::getOrigVtx(unsigned int _index) const { + return origVtx_[_index]; +} + +int Mesh2D::getOrigTri(unsigned int _index) const { + return origTri_[_index]; +} + +void Mesh2D::replaceOrigTri(const std::vector& _newOrigTri){ + origTri_.clear(); + origTri_ = _newOrigTri; + nTri_ = tri_.size(); + +} + +float Mesh2D::triangleArea(unsigned int _v0, unsigned int _v1, unsigned int _v2) const{ + + const Vector2f v1v0 = vtx_[_v1] - vtx_[_v0]; + const Vector2f v2v0 = vtx_[_v2] - vtx_[_v0]; + + return (v1v0(0) * v2v0(1) - v1v0(1) * v2v0(0)) * 0.5; + +} + +float Mesh2D::triangleArea(unsigned int _index) const { + + return triangleArea(tri_[_index].getIndex(0), tri_[_index].getIndex(1), tri_[_index].getIndex(2)); + +} + +float Mesh2D::triangleArea(const Vector2f &_v0, const Vector2f &_v1, const Vector2f &_v2){ + + const Vector2f v1v0 = _v1 - _v0; + const Vector2f v2v0 = _v2 - _v0; + + return (v1v0(0) * v2v0(1) - v1v0(1) * v2v0(0)) * 0.5; +} + + +void Mesh2D::displaceMesh(const Vector2f& _v){ + + std::vector::iterator it; + for (it = vtx_.begin(); it != vtx_.end(); ++it){ + (*it) = (*it) + _v; + } + bBoxMax_ = bBoxMax_ + _v; + bBoxMin_ = bBoxMin_ + _v; +} + +void Mesh2D::rotateMesh(){ + std::vector::iterator it; + for (it = vtx_.begin(); it != vtx_.end(); ++it){ + const Vector2f thisv = (*it); + Vector2f rot; + // x' = -y ; y' = x + rot(0) = (-1) * thisv(1); + rot(1) = thisv(0); + (*it) = rot; + } + + // The new min and max values are the opposite + // corners of the bounding box + const Vector2f b1 (bBoxMin_(0), bBoxMax_(1)); + const Vector2f b2 (bBoxMax_(0), bBoxMin_(1)); + // And now we rotate them + bBoxMin_(0) = (-1) * b1(1); + bBoxMin_(1) = b1(0); + bBoxMax_(0) = (-1) * b2(1); + bBoxMax_(1) = b2(0); + + // Vertices are displaced so the mesh is aligned with the origin + const Vector2f origin(0.0,0.0); + displaceMesh(origin - bBoxMin_); +} + +void Mesh2D::addOffset2BoundingBox(float _offset){ + + const Vector2f off(_offset, _offset); + const Vector2f aux = bBoxMax_ + off; + bBoxMax_ = aux; + + std::vector::iterator it; + for (it = vtx_.begin(); it != vtx_.end(); ++it){ + (*it) = (*it) + off * 0.5; + } +} + diff --git a/pool/shard008/C++/0096512_CWE590_Free_Memory_Not_on_Heap__delete_array_int_static_67b.cpp b/pool/shard008/C++/0096512_CWE590_Free_Memory_Not_on_Heap__delete_array_int_static_67b.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cea7451eb8cf523ef214b7da216f53d04cf6dd21 --- /dev/null +++ b/pool/shard008/C++/0096512_CWE590_Free_Memory_Not_on_Heap__delete_array_int_static_67b.cpp @@ -0,0 +1,54 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE590_Free_Memory_Not_on_Heap__delete_array_int_static_67b.cpp +Label Definition File: CWE590_Free_Memory_Not_on_Heap__delete_array.label.xml +Template File: sources-sink-67b.tmpl.cpp +*/ +/* + * @description + * CWE: 590 Free Memory Not on Heap + * BadSource: static Data buffer is declared static on the stack + * GoodSource: Allocate memory on the heap + * Sinks: + * BadSink : Print then free data + * Flow Variant: 67 Data flow: data passed in a struct from one function to another in different source files + * + * */ + +#include "std_testcase.h" + +#include + +namespace CWE590_Free_Memory_Not_on_Heap__delete_array_int_static_67 +{ + +typedef struct _structType +{ + int * structFirst; +} structType; + +#ifndef OMITBAD + +void badSink(structType myStruct) +{ + int * data = myStruct.structFirst; + printIntLine(data[0]); + /* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */ + delete [] data; +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void goodG2BSink(structType myStruct) +{ + int * data = myStruct.structFirst; + printIntLine(data[0]); + /* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */ + delete [] data; +} + +#endif /* OMITGOOD */ + +} /* close namespace */ diff --git a/pool/shard008/C++/0096515_TestReverse.cpp b/pool/shard008/C++/0096515_TestReverse.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b6e9a789759be6e98d6e1a92c617b9e7a35b282c --- /dev/null +++ b/pool/shard008/C++/0096515_TestReverse.cpp @@ -0,0 +1,37 @@ +#include +#include + +testing::AssertionResult AreEqual(int* a, int* b, int count) +{ + for (int i = 0; i < count; ++i) { + if (a[i] != b[i]) { + return testing::AssertionFailure() << " mismatch at index " << i; + } + } + + return testing::AssertionSuccess(); +} + +TEST(Reverse, Basic) +{ + int a[] = { 1, 2, 3 }; + int b[] = { 3, 2, 1 }; + int count = sizeof(a) / sizeof(a[0]); + + stx::Reverse(a, a + count); + + EXPECT_TRUE(AreEqual(a, b, count)); +} + +TEST(Reverse, DoubleReverse) +{ + int a[] = { 1, 2, 3 }; + int b[] = { 1, 2, 3 }; + int count = sizeof(a) / sizeof(a[0]); + + stx::Reverse(a, a + count); + stx::Reverse(a, a + count); + + EXPECT_TRUE(AreEqual(a , b, count)); +} + diff --git a/pool/shard008/C++/0096517_ST_NUCLEO-F042K6-spis.cpp b/pool/shard008/C++/0096517_ST_NUCLEO-F042K6-spis.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8f8b4dda7d06f0c44f5414b766e557c0478e2611 --- /dev/null +++ b/pool/shard008/C++/0096517_ST_NUCLEO-F042K6-spis.cpp @@ -0,0 +1,105 @@ +/** + * \file + * \brief Definitions of low-level SPI master drivers for SPIv2 in ST,NUCLEO-F042K6 (ST,STM32F042K6 chip) + * + * \author Copyright (C) 2016-2020 Kamil Szczygiel https://distortec.com https://freddiechopin.info + * + * \par License + * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not + * distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/. + * + * \warning + * Automatically generated file - do not edit! + */ + +#include "distortos/chip/spis.hpp" + +#include "distortos/chip/dmas.hpp" +#include "distortos/chip/PinInitializer.hpp" +#include "distortos/chip/SpiMasterLowLevelDmaBased.hpp" +#include "distortos/chip/SpiMasterLowLevelInterruptBased.hpp" +#include "distortos/chip/STM32-SPIv2-SpiPeripheral.hpp" + +#include "distortos/BIND_LOW_LEVEL_INITIALIZER.h" + +/** + * \brief Generates name of DMA channel object in the form `dmaChannel`. + * + * \param [in] dmaId is a DMA identifier + * \param [in] channelId is a DMA channel identifier + */ + +#define DMA_CHANNEL(dmaId, channelId) CONCATENATE4(dma, dmaId, Channel, channelId) + +namespace distortos +{ + +namespace chip +{ + +#ifdef DISTORTOS_CHIP_SPI1_ENABLE + +/*---------------------------------------------------------------------------------------------------------------------+ +| SPI1 ++---------------------------------------------------------------------------------------------------------------------*/ + +namespace +{ + +/** + * \brief Low-level chip initializer for SPI1 + * + * This function is called before constructors for global and static objects via BIND_LOW_LEVEL_INITIALIZER(). + */ + +void spi1LowLevelInitializer() +{ +#if defined(RCC_APB1ENR_SPI1EN) + RCC->APB1ENR |= RCC_APB1ENR_SPI1EN; +#elif defined(RCC_APB1ENR1_SPI1EN) + RCC->APB1ENR1 |= RCC_APB1ENR1_SPI1EN; +#elif defined(RCC_APB2ENR_SPI1EN) + RCC->APB2ENR |= RCC_APB2ENR_SPI1EN; +#else + #error "Unsupported bus for SPI1!" +#endif +} + +BIND_LOW_LEVEL_INITIALIZER(50, spi1LowLevelInitializer); + +/// raw SPI1 peripheral +const SpiPeripheral spi1Peripheral {SPI1_BASE}; + +} // namespace + +#ifdef DISTORTOS_CHIP_SPI1_DMA_BASED + +SpiMasterLowLevelDmaBased spi1 +{ + spi1Peripheral, + DMA_CHANNEL(DISTORTOS_CHIP_SPI1_RX_DMA, DISTORTOS_CHIP_SPI1_RX_DMA_CHANNEL), + DISTORTOS_CHIP_SPI1_RX_DMA_REQUEST, + DMA_CHANNEL(DISTORTOS_CHIP_SPI1_TX_DMA, DISTORTOS_CHIP_SPI1_TX_DMA_CHANNEL), + DISTORTOS_CHIP_SPI1_TX_DMA_REQUEST +}; + +#else // !def DISTORTOS_CHIP_SPI1_DMA_BASED + +SpiMasterLowLevelInterruptBased spi1 {spi1Peripheral}; + +/** + * \brief SPI1 interrupt handler + */ + +extern "C" void SPI1_IRQHandler() +{ + spi1.interruptHandler(); +} + +#endif // !def DISTORTOS_CHIP_SPI1_DMA_BASED + +#endif // def DISTORTOS_CHIP_SPI1_ENABLE + +} // namespace chip + +} // namespace distortos diff --git a/pool/shard008/C++/0096519_tcpMessageClient.cpp b/pool/shard008/C++/0096519_tcpMessageClient.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e2c805e934178af4ff306c5ff6d7d2bf7ee14807 --- /dev/null +++ b/pool/shard008/C++/0096519_tcpMessageClient.cpp @@ -0,0 +1,181 @@ +/*** +* Inferno Engine v4 2015-2017 +* Written by Tomasz "Rex Dex" Jonarski +* +* [#filter: messages\tcp #] +***/ + +#include "build.h" +#include "tcpMessageClient.h" +#include "tcpMessageInternal.h" + +#include "messageReassembler.h" +#include "messagePool.h" +#include "messageObjectRepository.h" +#include "messageObjectExecutor.h" +#include "messageReplicator.h" + +#include "base/replication/include/replicationDataModelRepository.h" + +namespace base +{ + namespace net + { + + //-- + + RTTI_BEGIN_TYPE_NOCOPY_CLASS(TcpMessageClient); + RTTI_END_TYPE(); + + TcpMessageClient::TcpMessageClient() + : m_connectionId(1) + , m_client(this) + , m_fatalError(false) + { + m_objects = CreateSharedPtr(); + m_models = CreateSharedPtr(); + + m_pool.create(); + m_replicator.create(m_models, m_objects); + m_executor.create(MessageConnection::GetStaticClass()); + m_reassembler.create(&TcpMessageReassemblerHandler::GetInstance()); + } + + TcpMessageClient::~TcpMessageClient() + {} + + ///--- + + Bool TcpMessageClient::connect(const socket::Address& address) + { + if (!m_client.connect(address)) + return false; + + m_connectionId += 1; + m_fatalError = false; + return true; + } + + Bool TcpMessageClient::isConnected() const + { + return m_client.isConnected() && !m_fatalError; + } + + Uint32 TcpMessageClient::getConnectionId() const + { + return m_connectionId; + } + + StringBuf TcpMessageClient::getLocalAddress() const + { + TempString str; + m_client.getLocalAddress().print(str); + return str; + } + + StringBuf TcpMessageClient::getRemoteAddress() const + { + TempString str; + m_client.getRemoteAddress().print(str); + return str; + } + + ///--- + + Uint32 TcpMessageClient::allocObjectId() + { + return m_objects->allocateObjectId(); + } + + void TcpMessageClient::attachObject(const Uint32 id, const obj::ObjectPtr& ptr) + { + m_objects->attachObject(id, ptr); + } + + void TcpMessageClient::dettachObject(const Uint32 id) + { + m_objects->detachObject(id); + } + + obj::ObjectPtr TcpMessageClient::resolveObject(const Uint32 id) const + { + return m_objects->resolveObject(id); + } + + //--- + + void TcpMessageClient::executePendingMessages() + { + m_executor->executeQueuedMessges(getSharedFromThis()); + } + + //--- + + void TcpMessageClient::sendPtr(Uint32 targetObjectId, const void* messageData, const rtti::IType* messageClass) + { + // if we are in error state don't do anything more + if (m_fatalError) + return; + + TcpMessageClientReplicatorDataSink dataSink(m_client); + m_replicator->send(targetObjectId, messageData, messageClass, &dataSink); + } + + void TcpMessageClient::handleConnectionClosed(socket::tcp::Client* client, const socket::Address& address) + { + + } + + void TcpMessageClient::handleConnectionData(socket::tcp::Client* client, const socket::Address& address, const void* data, const Uint32 dataSize) + { + // if we are in error state don't do anything more + if (m_fatalError) + return; + + // push data to reassembler, we will buffer it until we can assemble a packet + if (!m_reassembler->pushData(data, dataSize)) + { + TRACE_ERROR("TcpMessageClient: Fatal error on message reassembly from '{}'", m_client.getRemoteAddress()); + m_fatalError = true; + return; + } + + // process messages + Bool needsMore = true; + while (needsMore) + { + const Uint8* messageData = nullptr; + Uint32 messageSize = 0; + switch (m_reassembler->reassemble(messageData, messageSize)) + { + case ReassemblerResult::NeedsMore: + { + needsMore = false; + break; + } + + case ReassemblerResult::Valid: + { + const auto* header = (const TcpMessageTransportHeader*) messageData; + + TRACE_INFO("TcpMessageClient: reassembled message, size {} from '{}'", header->m_length, m_client.getRemoteAddress()); + + TcpMessageExecutorForwarder executor(*m_executor, *m_pool, *m_objects); + m_replicator->processMessageData(messageData + sizeof(TcpMessageTransportHeader), header->m_length - sizeof(TcpMessageTransportHeader), &executor); + break; + } + + case ReassemblerResult::Corruption: + { + TRACE_ERROR("TcpMessageClient: Fatal error on message reassembly from '{}'", m_client.getRemoteAddress()); + m_fatalError = true; + break; + } + } + } + } + + //--- + + } // net +} // base \ No newline at end of file diff --git a/pool/shard008/C++/0096521_basic_sspi_auth.cc b/pool/shard008/C++/0096521_basic_sspi_auth.cc new file mode 100644 index 0000000000000000000000000000000000000000..c33f411a5bcdff04814793774389e032261342d0 --- /dev/null +++ b/pool/shard008/C++/0096521_basic_sspi_auth.cc @@ -0,0 +1,182 @@ +/* + * Copyright (C) 1996-2015 The Squid Software Foundation and contributors + * + * Squid software is distributed under GPLv2+ license and includes + * contributions from numerous individuals and organizations. + * Please see the COPYING and CONTRIBUTORS files for details. + */ + +/* + NT_auth - Version 2.0 + + Returns OK for a successful authentication, or ERR upon error. + + Guido Serassio, Torino - Italy + + Uses code from - + Antonino Iannella 2000 + Andrew Tridgell 1997 + Richard Sharpe 1996 + Bill Welliver 1999 + + * Distributed freely under the terms of the GNU General Public License, + * version 2 or later. See the file COPYING for licensing details + * + * This program 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 General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. +*/ + +#include "squid.h" +#include "helpers/defines.h" +#include "rfc1738.h" +#include "util.h" +#include "valid.h" + +#if GETOPT_H +#include +#endif + +/* Check if we try to compile on a Windows Platform */ +#if !_SQUID_WINDOWS_ +/* NON Windows Platform !!! */ +#error NON WINDOWS PLATFORM +#endif + +static char NTGroup[256]; +char * NTAllowedGroup; +char * NTDisAllowedGroup; +int UseDisallowedGroup = 0; +int UseAllowedGroup = 0; +int debug_enabled = 0; + +/* + * options: + * -A can specify a Windows Local Group name allowed to authenticate. + * -D can specify a Windows Local Group name not allowed to authenticate. + * -O can specify the default Domain against to authenticate. + */ +static void +usage(const char *name) +{ + fprintf(stderr, "Usage:\n%s [-A|D UserGroup][-O DefaultDomain][-d]\n" + "-A can specify a Windows Local Group name allowed to authenticate\n" + "-D can specify a Windows Local Group name not allowed to authenticate\n" + "-O can specify the default Domain against to authenticate\n" + "-d enable debugging.\n" + "-h this message\n\n", + name); +} + +void +process_options(int argc, char *argv[]) +{ + int opt; + while (-1 != (opt = getopt(argc, argv, "dhA:D:O:"))) { + switch (opt) { + case 'A': + safe_free(NTAllowedGroup); + NTAllowedGroup=xstrdup(optarg); + UseAllowedGroup = 1; + break; + case 'D': + safe_free(NTDisAllowedGroup); + NTDisAllowedGroup=xstrdup(optarg); + UseDisallowedGroup = 1; + break; + case 'O': + strncpy(Default_NTDomain, optarg, DNLEN); + break; + case 'd': + debug_enabled = 1; + break; + case 'h': + usage(argv[0]); + exit(0); + case '?': + opt = optopt; + /* fall thru to default */ + default: + fprintf(stderr, "FATAL: Unknown option: -%c\n", opt); + usage(argv[0]); + exit(1); + } + } +} + +/* Main program for simple authentication. + Scans and checks for Squid input, and attempts to validate the user. +*/ +int +main(int argc, char **argv) +{ + char wstr[HELPER_INPUT_BUFFER]; + char username[256]; + char password[256]; + char *p; + int err = 0; + + process_options(argc, argv); + + if (LoadSecurityDll(SSP_BASIC, NTLM_PACKAGE_NAME) == NULL) { + fprintf(stderr, "FATAL: can't initialize SSPI, exiting.\n"); + exit(1); + } + debug("SSPI initialized OK\n"); + + atexit(UnloadSecurityDll); + + /* initialize FDescs */ + setbuf(stdout, NULL); + setbuf(stderr, NULL); + + while (fgets(wstr, HELPER_INPUT_BUFFER, stdin) != NULL) { + + if (NULL == strchr(wstr, '\n')) { + err = 1; + continue; + } + if (err) { + SEND_ERR("Oversized message"); + err = 0; + fflush(stdout); + continue; + } + + if ((p = strchr(wstr, '\n')) != NULL) + *p = '\0'; /* strip \n */ + if ((p = strchr(wstr, '\r')) != NULL) + *p = '\0'; /* strip \r */ + /* Clear any current settings */ + username[0] = '\0'; + password[0] = '\0'; + sscanf(wstr, "%s %s", username, password); /* Extract parameters */ + + debug("Got %s from Squid\n", wstr); + + /* Check for invalid or blank entries */ + if ((username[0] == '\0') || (password[0] == '\0')) { + SEND_ERR("Invalid Request"); + fflush(stdout); + continue; + } + rfc1738_unescape(username); + rfc1738_unescape(password); + + debug("Trying to validate; %s %s\n", username, password); + + if (Valid_User(username, password, NTGroup) == NTV_NO_ERROR) + SEND_OK(""); + else + SEND_ERR(errormsg); + err = 0; + fflush(stdout); + } + return 0; +} + diff --git a/pool/shard008/C++/0096533_kate.cpp b/pool/shard008/C++/0096533_kate.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6dbb711da4f342fabbae8973b078dd4913752195 --- /dev/null +++ b/pool/shard008/C++/0096533_kate.cpp @@ -0,0 +1,81 @@ +/* + mkvmerge -- utility for splicing together matroska files + from component media subtypes + + Distributed under the GPL + see the file COPYING for details + or visit http://www.gnu.org/copyleft/gpl.html + + Kate helper functions + + Written by ogg.k.ogg.k . + Adapted from code by Moritz Bunkus . +*/ + +#include "common/common_pch.h" + +#include "common/bit_cursor.h" +#include "common/kate.h" + +kate_identification_header_t::kate_identification_header_t() { + memset(this, 0, sizeof(kate_identification_header_t)); +} + +static int32_t +get_bits32_le(bit_reader_c &bc) { + int32_t v = 0; + + for (int n = 0; n < 4; ++n) { + v |= bc.get_bits(8) << (n * 8); + } + + return v; +} + +void +kate_parse_identification_header(const unsigned char *buffer, + int size, + kate_identification_header_t &header) { + bit_reader_c bc(buffer, size); + int i; + + header.headertype = bc.get_bits(8); + if (KATE_HEADERTYPE_IDENTIFICATION != header.headertype) + throw mtx::kate::header_parsing_x(boost::format(Y("Wrong header type: 0x%|1$02x| != 0x%|2$02x|")) % header.headertype % KATE_HEADERTYPE_IDENTIFICATION); + + for (i = 0; 7 > i; ++i) + header.kate_string[i] = bc.get_bits(8); + if (memcmp(header.kate_string, "kate\0\0\0", 7)) + throw mtx::kate::header_parsing_x(boost::format(Y("Wrong identification string: '%|1$7s|' != 'kate\\0\\0\\0'")) % header.kate_string); /* won't print NULs well, but hey */ + + bc.get_bits(8); // we don't need those - they are reserved + + header.vmaj = bc.get_bits(8); + header.vmin = bc.get_bits(8); + + // do not test vmin, as the header is stable for minor version changes + static const int supported_version = 0; + if (header.vmaj > supported_version) + throw mtx::kate::header_parsing_x(boost::format(Y("Wrong Kate version: %1%.%2% > %3%.x")) % header.vmaj % header.vmin % supported_version); + + header.nheaders = bc.get_bits(8); + header.tenc = bc.get_bits(8); + header.tdir = bc.get_bits(8); + bc.get_bits(8); // we don't need those - they are reserved + header.kfgshift = bc.get_bits(8); + + bc.skip_bits(32); // from bitstream 0.3, these 32 bits are allocated + bc.skip_bits(32); // we don't need those - they are reserved + + header.gnum = get_bits32_le(bc); + header.gden = get_bits32_le(bc); + + for (i = 0; 16 > i; ++i) + header.language[i] = bc.get_bits(8); + if (header.language[15]) + throw mtx::kate::header_parsing_x(Y("Language is not NUL terminated")); + for (i = 0; 16 > i; ++i) + header.category[i] = bc.get_bits(8); + if (header.category[15]) + throw mtx::kate::header_parsing_x(Y("Category is not NUL terminated")); +} diff --git a/pool/shard008/C++/0096536_pepper_broker.cc b/pool/shard008/C++/0096536_pepper_broker.cc new file mode 100644 index 0000000000000000000000000000000000000000..0869e80d78dfe76c7828a76c3e72fb3f96e9dc7f --- /dev/null +++ b/pool/shard008/C++/0096536_pepper_broker.cc @@ -0,0 +1,259 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "content/renderer/pepper/pepper_broker.h" + +#include "build/build_config.h" +#include "content/renderer/pepper/pepper_proxy_channel_delegate_impl.h" +#include "content/renderer/pepper/plugin_module.h" +#include "content/renderer/pepper/ppb_broker_impl.h" +#include "content/renderer/pepper/renderer_restrict_dispatch_group.h" +#include "ipc/ipc_channel_handle.h" +#include "ppapi/proxy/broker_dispatcher.h" +#include "ppapi/proxy/ppapi_messages.h" +#include "ppapi/shared_impl/platform_file.h" + +#if defined(OS_WIN) +#include +#endif + +namespace content { + +namespace { + +base::SyncSocket::Handle DuplicateHandle(base::SyncSocket::Handle handle) { + base::SyncSocket::Handle out_handle = base::SyncSocket::kInvalidHandle; +#if defined(OS_WIN) + DWORD options = DUPLICATE_SAME_ACCESS; + if (!::DuplicateHandle(::GetCurrentProcess(), + handle, + ::GetCurrentProcess(), + &out_handle, + 0, + FALSE, + options)) { + out_handle = base::SyncSocket::kInvalidHandle; + } +#elif defined(OS_POSIX) + // If asked to close the source, we can simply re-use the source fd instead of + // dup()ing and close()ing. + out_handle = ::dup(handle); +#else +#error Not implemented. +#endif + return out_handle; +} + +} // namespace + +PepperBrokerDispatcherWrapper::PepperBrokerDispatcherWrapper() {} + +PepperBrokerDispatcherWrapper::~PepperBrokerDispatcherWrapper() {} + +bool PepperBrokerDispatcherWrapper::Init( + base::ProcessId broker_pid, + const IPC::ChannelHandle& channel_handle) { + if (channel_handle.name.empty()) + return false; + +#if defined(OS_POSIX) + DCHECK_NE(-1, channel_handle.socket.fd); + if (channel_handle.socket.fd == -1) + return false; +#endif + + dispatcher_delegate_.reset(new PepperProxyChannelDelegateImpl); + dispatcher_.reset(new ppapi::proxy::BrokerHostDispatcher()); + + if (!dispatcher_->InitBrokerWithChannel(dispatcher_delegate_.get(), + broker_pid, + channel_handle, + true)) { // Client. + dispatcher_.reset(); + dispatcher_delegate_.reset(); + return false; + } + dispatcher_->channel()->SetRestrictDispatchChannelGroup( + kRendererRestrictDispatchGroup_Pepper); + return true; +} + +// Does not take ownership of the local pipe. +int32_t PepperBrokerDispatcherWrapper::SendHandleToBroker( + PP_Instance instance, + base::SyncSocket::Handle handle) { + IPC::PlatformFileForTransit foreign_socket_handle = + dispatcher_->ShareHandleWithRemote(handle, false); + if (foreign_socket_handle == IPC::InvalidPlatformFileForTransit()) + return PP_ERROR_FAILED; + + int32_t result = PP_ERROR_FAILED; + if (!dispatcher_->Send(new PpapiMsg_ConnectToPlugin( + instance, foreign_socket_handle, &result))) { + // The plugin did not receive the handle, so it must be closed. + // The easiest way to clean it up is to just put it in an object + // and then close it. This failure case is not performance critical. + // The handle could still leak if Send succeeded but the IPC later failed. + base::SyncSocket temp_socket( + IPC::PlatformFileForTransitToPlatformFile(foreign_socket_handle)); + return PP_ERROR_FAILED; + } + + return result; +} + +PepperBroker::PepperBroker(PluginModule* plugin_module) + : plugin_module_(plugin_module) { + DCHECK(plugin_module_); + + plugin_module_->SetBroker(this); +} + +PepperBroker::~PepperBroker() { + ReportFailureToClients(PP_ERROR_ABORTED); + plugin_module_->SetBroker(NULL); + plugin_module_ = NULL; +} + +// If the channel is not ready, queue the connection. +void PepperBroker::AddPendingConnect(PPB_Broker_Impl* client) { + DCHECK(pending_connects_.find(client) == pending_connects_.end()) + << "Connect was already called for this client"; + + // Ensure this object and the associated broker exist as long as the + // client exists. There is a corresponding Release() call in Disconnect(), + // which is called when the PPB_Broker_Impl is destroyed. The only other + // possible reference is in pending_connect_broker_, which only holds a + // transient reference. This ensures the broker is available as long as the + // plugin needs it and allows the plugin to release the broker when it is no + // longer using it. + AddRef(); + + pending_connects_[client].client = client->AsWeakPtr(); +} + +void PepperBroker::Disconnect(PPB_Broker_Impl* client) { + // Remove the pending connect if one exists. This class will not call client's + // callback. + pending_connects_.erase(client); + + // TODO(ddorwin): Send message disconnect message using dispatcher_. + + // Release the reference added in Connect(). + // This must be the last statement because it may delete this object. + Release(); +} + +void PepperBroker::OnBrokerChannelConnected( + base::ProcessId broker_pid, + const IPC::ChannelHandle& channel_handle) { + scoped_ptr dispatcher( + new PepperBrokerDispatcherWrapper); + if (!dispatcher->Init(broker_pid, channel_handle)) { + ReportFailureToClients(PP_ERROR_FAILED); + return; + } + + dispatcher_.reset(dispatcher.release()); + + // Process all pending channel requests from the plugins. + for (ClientMap::iterator i = pending_connects_.begin(); + i != pending_connects_.end();) { + base::WeakPtr& weak_ptr = i->second.client; + if (!i->second.is_authorized) { + ++i; + continue; + } + + if (weak_ptr.get()) + ConnectPluginToBroker(weak_ptr.get()); + + pending_connects_.erase(i++); + } +} + +void PepperBroker::OnBrokerPermissionResult(PPB_Broker_Impl* client, + bool result) { + ClientMap::iterator entry = pending_connects_.find(client); + if (entry == pending_connects_.end()) + return; + + if (!entry->second.client.get()) { + // Client has gone away. + pending_connects_.erase(entry); + return; + } + + if (!result) { + // Report failure. + client->BrokerConnected( + ppapi::PlatformFileToInt(base::SyncSocket::kInvalidHandle), + PP_ERROR_NOACCESS); + pending_connects_.erase(entry); + return; + } + + if (dispatcher_) { + ConnectPluginToBroker(client); + pending_connects_.erase(entry); + return; + } + + // Mark the request as authorized, continue waiting for the broker + // connection. + DCHECK(!entry->second.is_authorized); + entry->second.is_authorized = true; +} + +PepperBroker::PendingConnection::PendingConnection() : is_authorized(false) {} + +PepperBroker::PendingConnection::PendingConnection( + const PendingConnection& other) = default; + +PepperBroker::PendingConnection::~PendingConnection() {} + +void PepperBroker::ReportFailureToClients(int error_code) { + DCHECK_NE(PP_OK, error_code); + for (ClientMap::iterator i = pending_connects_.begin(); + i != pending_connects_.end(); + ++i) { + base::WeakPtr& weak_ptr = i->second.client; + if (weak_ptr.get()) { + weak_ptr->BrokerConnected( + ppapi::PlatformFileToInt(base::SyncSocket::kInvalidHandle), + error_code); + } + } + pending_connects_.clear(); +} + +void PepperBroker::ConnectPluginToBroker(PPB_Broker_Impl* client) { + base::SyncSocket::Handle plugin_handle = base::SyncSocket::kInvalidHandle; + int32_t result = PP_OK; + + // The socket objects will be deleted when this function exits, closing the + // handles. Any uses of the socket must duplicate them. + scoped_ptr broker_socket(new base::SyncSocket()); + scoped_ptr plugin_socket(new base::SyncSocket()); + if (base::SyncSocket::CreatePair(broker_socket.get(), plugin_socket.get())) { + result = dispatcher_->SendHandleToBroker(client->pp_instance(), + broker_socket->handle()); + + // If the broker has its pipe handle, duplicate the plugin's handle. + // Otherwise, the plugin's handle will be automatically closed. + if (result == PP_OK) + plugin_handle = DuplicateHandle(plugin_socket->handle()); + } else { + result = PP_ERROR_FAILED; + } + + // TOOD(ddorwin): Change the IPC to asynchronous: Queue an object containing + // client and plugin_socket.release(), then return. + // That message handler will then call client->BrokerConnected() with the + // saved pipe handle. + // Temporarily, just call back. + client->BrokerConnected(ppapi::PlatformFileToInt(plugin_handle), result); +} + +} // namespace content diff --git a/pool/shard008/C++/0096537_tictactoe.cpp b/pool/shard008/C++/0096537_tictactoe.cpp new file mode 100644 index 0000000000000000000000000000000000000000..727cdd3cdaf1663bc2750ca4ec51ca1132371f66 --- /dev/null +++ b/pool/shard008/C++/0096537_tictactoe.cpp @@ -0,0 +1,176 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial Usage +** Licensees holding valid Qt Commercial licenses may use this file in +** accordance with the Qt Commercial License Agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and Nokia. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** If you have questions regarding the use of this file, please contact +** Nokia at qt-info@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +#include "tictactoe.h" + +TicTacToe::TicTacToe(QWidget *parent) + : QWidget(parent) +{ +} + +QSize TicTacToe::minimumSizeHint() const +{ + return QSize(200, 200); +} + +QSize TicTacToe::sizeHint() const +{ + return QSize(200, 200); +} + +void TicTacToe::setState(const QString &newState) +{ + turnNumber = 0; + myState = "---------"; + int position = 0; + while (position < 9 && position < newState.length()) { + QChar mark = newState.at(position); + if (mark == Cross || mark == Nought) { + ++turnNumber; + myState.replace(position, 1, mark); + } + position++; + } + update(); +} + +QString TicTacToe::state() const +{ + return myState; +} + +void TicTacToe::clearBoard() +{ + myState = "---------"; + turnNumber = 0; + update(); +} + +void TicTacToe::mousePressEvent(QMouseEvent *event) +{ + if (turnNumber == 9) { + clearBoard(); + update(); + } else { + for (int position = 0; position < 9; ++position) { + QRect cell = cellRect(position / 3, position % 3); + if (cell.contains(event->pos())) { + if (myState.at(position) == Empty) { + if (turnNumber % 2 == 0) + myState.replace(position, 1, Cross); + else + myState.replace(position, 1, Nought); + ++turnNumber; + update(); + } + } + } + } +} + +void TicTacToe::paintEvent(QPaintEvent * /* event */) +{ + QPainter painter(this); + painter.setRenderHint(QPainter::Antialiasing); + + painter.setPen(QPen(Qt::darkGreen, 1)); + painter.drawLine(cellWidth(), 0, cellWidth(), height()); + painter.drawLine(2 * cellWidth(), 0, 2 * cellWidth(), height()); + painter.drawLine(0, cellHeight(), width(), cellHeight()); + painter.drawLine(0, 2 * cellHeight(), width(), 2 * cellHeight()); + + painter.setPen(QPen(Qt::darkBlue, 2)); + + for (int position = 0; position < 9; ++position) { + QRect cell = cellRect(position / 3, position % 3); + + if (myState.at(position) == Cross) { + painter.drawLine(cell.topLeft(), cell.bottomRight()); + painter.drawLine(cell.topRight(), cell.bottomLeft()); + } else if (myState.at(position) == Nought) { + painter.drawEllipse(cell); + } + } + + painter.setPen(QPen(Qt::yellow, 3)); + + for (int position = 0; position < 9; position = position + 3) { + if (myState.at(position) != Empty + && myState.at(position + 1) == myState.at(position) + && myState.at(position + 2) == myState.at(position)) { + int y = cellRect((position / 3), 0).center().y(); + painter.drawLine(0, y, width(), y); + turnNumber = 9; + } + } + + for (int position = 0; position < 3; ++position) { + if (myState.at(position) != Empty + && myState.at(position + 3) == myState.at(position) + && myState.at(position + 6) == myState.at(position)) { + int x = cellRect(0, position).center().x(); + painter.drawLine(x, 0, x, height()); + turnNumber = 9; + } + } + if (myState.at(0) != Empty && myState.at(4) == myState.at(0) + && myState.at(8) == myState.at(0)) { + painter.drawLine(0, 0, width(), height()); + turnNumber = 9; + } + if (myState.at(2) != Empty && myState.at(4) == myState.at(2) + && myState.at(6) == myState.at(2)) { + painter.drawLine(0, height(), width(), 0); + turnNumber = 9; + } +} + +QRect TicTacToe::cellRect(int row, int column) const +{ + const int HMargin = width() / 30; + const int VMargin = height() / 30; + return QRect(column * cellWidth() + HMargin, + row * cellHeight() + VMargin, + cellWidth() - 2 * HMargin, + cellHeight() - 2 * VMargin); +} diff --git a/pool/shard008/C++/0096542_Sch.cpp b/pool/shard008/C++/0096542_Sch.cpp new file mode 100644 index 0000000000000000000000000000000000000000..853897b2ee996f185f5ed3b8de912233d0bf98f0 --- /dev/null +++ b/pool/shard008/C++/0096542_Sch.cpp @@ -0,0 +1,115 @@ +#include "Browser.h" + +String ReadId(CParser& p, String& rr) +{ + p.Char('('); + String id = p.ReadId(); + p.Char(','); + if(p.IsNumber()) + p.ReadNumber(); + p.Char(','); + if(p.IsNumber()) + p.ReadNumber(); + p.Char(')'); + rr << "SqlId " << id << "(\"" << id << "\");"; + return id; +} + +void ScanSchFile(const char *fn) +{ + String s = LoadFile(fn); + CParser p(s); + String r, rr; + String S_name; + int line; + while(!p.IsEof()) + try { + line = p.GetLine(); + if(p.Id("TABLE") || p.Id("TABLE_") || p.Id("TYPE") || p.Id("TYPE_")) { + S_name = "S_" + ReadId(p, rr); + r << "struct " << S_name << " {"; + } + else + if(p.Id("END_TABLE") || p.Id("END_TYPE")) + r << + "static const char TableName[];" + "static const SqlSet& ColumnSet();" + "static SqlSet ColumnSet(const String& prefix);" + "static SqlSet Of(SqlId table);" + "static const Vector& GetColumnIds();" + "" + "void Clear();" + "" + "void FieldLayoutRaw(FieldOperator& f, const String& prefix = String());" + "void FieldLayout(FieldOperator& f);" + "operator Fields();" + "" + "bool operator==(const " << S_name << "& x) const;" + "bool operator!=(const " << S_name << "& x) const;" + "String ToString() const;" + "" + "int GetCount() const;" + "SqlId GetId(int i) const;" + "Ref GetRef(int i);" + "Ref GetRef(const SqlId& id);" + "Value Get(const SqlId& id) const;" + "Value Get(int i) const;" + "ValueMap Get() const;" + "void Set(int i, const Value& v);" + "void Set(const SqlId& id, const Value& v);" + "void Set(const ValueMap& m);" + << S_name << "();" + << S_name << "(const ValueMap& m);" + "};"; + else + if(p.Id("LONGRAW") || p.Id("LONGRAW_") || p.Id("BLOB") || p.Id("BLOB_") || + p.Id("STRING_") || p.Id("STRING") || p.Id("CLOB") || p.Id("CLOB_")) + r << "\tString " << ReadId(p, rr) << ";"; + else + if(p.Id("INT") || p.Id("INT_") || p.Id("SERIAL") || p.Id("ISERIAL")) + r << "\tint " << ReadId(p, rr) << ";"; + else + if(p.Id("DOUBLE") || p.Id("DOUBLE_")) + r << "\tdouble " << ReadId(p, rr) << ";"; + else + if(p.Id("TIME") || p.Id("TIME_")) + r << "\tTime " << ReadId(p, rr) << ";"; + else + if(p.Id("DATE") || p.Id("DATE_")) + r << "\tDate " << ReadId(p, rr) << ";"; + else + if(p.Id("BIT") || p.Id("BIT_") || p.Id("BOOL") || p.Id("BOOL_")) + r << "\tbool " << ReadId(p, rr) << ";"; + else + if(p.Id("INT_ARRAY") || p.Id("INT_ARRAY_")) + r << "\tint " << ReadId(p, rr) << "[1];"; + else + if(p.Id("DOUBLE_ARRAY") || p.Id("DOUBLE_ARRAY_")) + r << "\tdouble " << ReadId(p, rr) << "[1];"; + else + if(p.Id("TIME_ARRAY") || p.Id("TIME_ARRAY_")) + r << "\tTime " << ReadId(p, rr) << "[1];"; + else + if(p.Id("DATE_ARRAY") || p.Id("DATE_ARRAY_")) + r << "\tDate " << ReadId(p, rr) << "[1];"; + else + if(p.Id("BOOL_ARRAY") || p.Id("BOOL_ARRAY_") || p.Id("BIT_ARRAY") || p.Id("BIT_ARRAY_")) + r << "\tbool " << ReadId(p, rr) << "[1];"; + else + if(p.Id("SEQUENCE") || p.Id("SEQUENCE_")) + ReadId(p, rr); + else + p.SkipTerm(); + line = p.GetLine() - line; + for(int i = 0; i < line; ++i) { + r << '\n'; + rr << '\n'; + } + } + catch(CParser::Error) + {} + StringStream ss(r), sr(rr); + CppBase& base = CodeBase(); + Parse(sr, IgnoreList(), base, fn, CNULL); + Parse(ss, IgnoreList(), base, fn, CNULL); +} diff --git a/pool/shard008/C++/0096543_ContainerTraitsTest.cpp b/pool/shard008/C++/0096543_ContainerTraitsTest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f1f4090f61f648ef348096abda5e31bad639dbaa --- /dev/null +++ b/pool/shard008/C++/0096543_ContainerTraitsTest.cpp @@ -0,0 +1,51 @@ +/* + * Copyright 2017 Facebook, Inc. + * + * 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 + +#include + +using namespace std; +using namespace folly; + +struct Node { + size_t copies = 0; + Node() noexcept {} + Node(const Node& n) noexcept { copies = n.copies; ++copies; } + Node(Node&& n) noexcept { swap(copies, n.copies); ++copies; } +}; + +template +class VectorWrapper { +public: + using value_type = T; + vector& underlying; + explicit VectorWrapper(vector& v) : underlying(v) {} + void push_back(const T& t) { underlying.push_back(t); } +}; + +TEST(ContainerTraits, WithoutEmplaceBack) { + vector v; + VectorWrapper vw(v); + container_emplace_back_or_push_back(vw); + EXPECT_EQ(1, v.at(0).copies); +} + +TEST(ContainerTraits, WithEmplaceBack) { + vector v; + container_emplace_back_or_push_back(v); + EXPECT_EQ(0, v.at(0).copies); +} diff --git a/pool/shard008/C++/0096547_obstacle-shadowing-propagation-loss-model.cc b/pool/shard008/C++/0096547_obstacle-shadowing-propagation-loss-model.cc new file mode 100644 index 0000000000000000000000000000000000000000..20854b57e42b22903dcb25de447ed284e7b2a607 --- /dev/null +++ b/pool/shard008/C++/0096547_obstacle-shadowing-propagation-loss-model.cc @@ -0,0 +1,124 @@ +/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */ +/* + * Copyright (c) 2014 North Carolina State University + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation; + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * Author: Scott E. Carpenter + * + */ + +#include "ns3/log.h" +#include "ns3/double.h" +#include "ns3/enum.h" +#include "ns3/mobility-model.h" +#include +#include "ns3/topology.h" + +#include "obstacle-shadowing-propagation-loss-model.h" + +NS_LOG_COMPONENT_DEFINE ("ObstacleShadowingPropagationLossModel"); + +namespace ns3 { + +NS_OBJECT_ENSURE_REGISTERED (ObstacleShadowingPropagationLossModel); + +TypeId +ObstacleShadowingPropagationLossModel::GetTypeId (void) +{ + static TypeId tid = TypeId ("ns3::ObstacleShadowingPropagationLossModel") + + .SetParent () + .AddConstructor () + .AddAttribute ("ForBeacon", "beacons", + UintegerValue (0), + MakeUintegerAccessor (&ObstacleShadowingPropagationLossModel::m_forbeacon), + MakeUintegerChecker (0)) +// .AddAttribute ("IsSub1G", "sub 1Ghz beacon", +// UintegerValue (0), +// MakeUintegerAccessor (&ObstacleShadowingPropagationLossModel::m_isSub1G), +// MakeUintegerChecker (0)) + .AddAttribute ("MaxDistance", "Maximum allowed transmission distance (m)", + UintegerValue (500), + MakeUintegerAccessor (&ObstacleShadowingPropagationLossModel::m_maxDistance), + MakeUintegerChecker (0)) + + ; + return tid; +} + +ObstacleShadowingPropagationLossModel::ObstacleShadowingPropagationLossModel () + : PropagationLossModel (), + m_forbeacon(0), + m_isSub1G(0), + m_maxDistance(500) +{ +} + +ObstacleShadowingPropagationLossModel::~ObstacleShadowingPropagationLossModel () +{ +} + +double +ObstacleShadowingPropagationLossModel::GetLoss (Ptr a, Ptr b) const +{ + NS_LOG_FUNCTION (this); + + // initialize = no loss + + double L_obs = 0.0; + + // get the topology instance, to search for obstacles + Topology * topology = Topology::GetTopology(); + NS_ASSERT(topology != 0); + + if (topology->HasObstacles() == true) + { + // additional loss for obstacles + double p1_x = a->GetPosition ().x; + double p1_y = a->GetPosition ().y; + double p2_x = b->GetPosition ().x; + double p2_y = b->GetPosition ().y; + // for two points, p1 and p2 + Point p1(p1_x, p1_y); + Point p2(p2_x, p2_y); + + double r = m_maxDistance; + + // get the obstructed loss, from the topology class + L_obs = topology->GetObstructedLossBetween(p1, p2, r, m_forbeacon, m_isSub1G); + NS_LOG_DEBUG("LOSS:"< a, + Ptr b) const +{ + double retVal = 0.0; + double loss = GetLoss (a, b); + retVal = txPowerDbm - loss; + return (retVal); +} + +int64_t +ObstacleShadowingPropagationLossModel::DoAssignStreams (int64_t stream) +{ + return 0; +} + +} // namespace ns3 diff --git a/pool/shard008/C++/0096548_animgoals_stackentry.cpp b/pool/shard008/C++/0096548_animgoals_stackentry.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b912e18e4c53a45a3977c50095f62ae7792b5b1e --- /dev/null +++ b/pool/shard008/C++/0096548_animgoals_stackentry.cpp @@ -0,0 +1,122 @@ + +#include "stdafx.h" + +#include + +#include "gamesystems/gamesystems.h" +#include "gamesystems/objects/objsystem.h" +#include "gamesystems/mapsystem.h" +#include "animgoals_stackentry.h" + +static_assert(temple::validate_size::value); +static_assert(temple::validate_size::value); + +// Originally @ 0x100556C0 +bool AnimSlotGoalStackEntry::InitWithInterrupt(objHndl handle, AnimGoalType goalType) { + return Init(handle, goalType, true); +} + +bool AnimSlotGoalStackEntry::Push(AnimSlotId* idNew) { + return gameSystems->GetAnim().PushGoal(*this, idNew); +} + +// Originally @ 0x10055570 +bool AnimSlotGoalStackEntry::Init(objHndl handle, AnimGoalType goalType, bool withInterrupt) { + auto gdata = this; + + if (!gdata) { + logger->error("Null goalData ptr"); + gameSystems->GetAnim().Debug(); + } + + if ((goalType & 0x80000000) || goalType >= ag_count) { + logger->error("Illegal goalType"); + gameSystems->GetAnim().Debug(); + } + gdata->animId.number = -1; + gdata->animIdPrevious.number = -1; + gdata->animData.number = -1; + gdata->spellData.number = -1; + gdata->flagsData.number = -1; + gdata->soundStreamId = -1; + gdata->goalType = goalType; + gdata->self.obj = handle; + gdata->target.obj = objHndl::null; + gdata->block.obj = objHndl::null; + gdata->scratch.obj = objHndl::null; + gdata->parent.obj = objHndl::null; + gdata->targetTile.location = LocAndOffsets::null; + gdata->range.location = LocAndOffsets::null; + gdata->skillData.number = 0; + gdata->scratchVal1.number = 0; + gdata->scratchVal2.number = 0; + gdata->scratchVal3.number = 0; + gdata->scratchVal4.number = 0; + gdata->scratchVal5.number = 0; + gdata->scratchVal6.number = 0; + gdata->soundHandle.number = 0; + if (withInterrupt) + { + auto ag = gameSystems->GetAnim().GetGoal(goalType); + if (!ag) { + logger->error("pGoalNode != NULL assertion failed"); + gameSystems->GetAnim().Debug(); + } + return gameSystems->GetAnim().Interrupt(handle, ag->priority, ag->interruptAll); + } + return TRUE; +} + +void AnimSlotGoalStackEntry::FreezeObjectRefs() +{ + selfTracking = FrozenObjRef::Freeze(self.obj); + targetTracking = FrozenObjRef::Freeze(target.obj); + blockTracking = FrozenObjRef::Freeze(block.obj); + scratchTracking = FrozenObjRef::Freeze(scratch.obj); + parentTracking = FrozenObjRef::Freeze(parent.obj); +} + +static bool ValidateObjectRef(objHndl &handle, const FrozenObjRef &frozenRef) { + if (!objSystem->IsValidHandle(handle)) { + if (FrozenObjRef::Unfreeze(frozenRef, &handle)) { + logger->error("Failed to recover object reference in anim goal"); + handle = objHndl::null; + return false; + } + } + return true; +} + +bool AnimSlotGoalStackEntry::ValidateObjectRefs() +{ + if (gameSystems->GetMap().IsClearingMap()) { + self.obj = objHndl::null; + target.obj = objHndl::null; + block.obj = objHndl::null; + scratch.obj = objHndl::null; + parent.obj = objHndl::null; + return false; + } + + if (!ValidateObjectRef(self.obj, selfTracking)) { + return false; + } + if (!ValidateObjectRef(target.obj, targetTracking)) { + return false; + } + if (!ValidateObjectRef(block.obj, blockTracking)) { + return false; + } + if (!ValidateObjectRef(scratch.obj, scratchTracking)) { + return false; + } + if (!ValidateObjectRef(parent.obj, parentTracking)) { + return false; + } + + return true; +} + +AnimSlotGoalStackEntry::AnimSlotGoalStackEntry(objHndl handle, AnimGoalType GoalType, bool withInterrupt) { + Init(handle, GoalType, withInterrupt); +} diff --git a/pool/shard008/C++/0096549_qgsfieldformatter.cpp b/pool/shard008/C++/0096549_qgsfieldformatter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d799df199dce32b9db1efc446233e9d1fdfc94c7 --- /dev/null +++ b/pool/shard008/C++/0096549_qgsfieldformatter.cpp @@ -0,0 +1,91 @@ +/*************************************************************************** + qgsfieldformatter.cpp - QgsFieldFormatter + + --------------------- + begin : 2.12.2016 + copyright : (C) 2016 by Matthias Kuhn + email : matthias@opengis.ch + *************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ +#include "qgsfieldformatter.h" + +#include "qgsfield.h" +#include "qgsfields.h" +#include "qgsvectorlayer.h" +#include "qgsvectordataprovider.h" + + +QString QgsFieldFormatter::representValue( QgsVectorLayer *layer, int fieldIndex, const QVariantMap &config, const QVariant &cache, const QVariant &value ) const +{ + Q_UNUSED( config ) + Q_UNUSED( cache ) + + QString defVal; + if ( layer->fields().fieldOrigin( fieldIndex ) == QgsFields::OriginProvider && layer->dataProvider() ) + defVal = layer->dataProvider()->defaultValueClause( layer->fields().fieldOriginIndex( fieldIndex ) ); + + if ( ! layer->fields().exists( fieldIndex ) ) + { + return defVal; + } + else + { + return layer->fields().at( fieldIndex ).displayString( value.isNull() ? defVal : value ); + } +} + +QVariant QgsFieldFormatter::sortValue( QgsVectorLayer *layer, int fieldIndex, const QVariantMap &config, const QVariant &cache, const QVariant &value ) const +{ + Q_UNUSED( layer ) + Q_UNUSED( fieldIndex ) + Q_UNUSED( config ) + Q_UNUSED( cache ) + + return value; +} + +Qt::AlignmentFlag QgsFieldFormatter::alignmentFlag( QgsVectorLayer *layer, int fieldIndex, const QVariantMap &config ) const +{ + Q_UNUSED( config ) + + QgsField field = layer->fields().at( fieldIndex ); + if ( field.isNumeric() || field.isDateOrTime() ) + return Qt::AlignRight; + else + return Qt::AlignLeft; +} + +QVariant QgsFieldFormatter::createCache( QgsVectorLayer *layer, int fieldIndex, const QVariantMap &config ) const +{ + Q_UNUSED( layer ) + Q_UNUSED( fieldIndex ) + Q_UNUSED( config ) + + return QVariant(); +} + +QList QgsFieldFormatter::layerDependencies( const QVariantMap &config ) const +{ + Q_UNUSED( config ) + return QList(); +} + +QVariantList QgsFieldFormatter::availableValues( const QVariantMap &config, int countLimit, const QgsFieldFormatterContext &context ) const +{ + Q_UNUSED( config ) + Q_UNUSED( countLimit ) + Q_UNUSED( context ) + + return QVariantList(); +} + +void QgsFieldFormatter::setFlags( const Flags &flags ) +{ + mFlags = flags; +} diff --git a/pool/shard008/C++/0096551_nofCarpenter.cpp b/pool/shard008/C++/0096551_nofCarpenter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d613756a4b2085cb394609f54c96f3dede007de2 --- /dev/null +++ b/pool/shard008/C++/0096551_nofCarpenter.cpp @@ -0,0 +1,69 @@ +// Copyright (c) 2005 - 2015 Settlers Freaks (sf-team at siedler25.org) +// +// This file is part of Return To The Roots. +// +// Return To The Roots is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 2 of the License, or +// (at your option) any later version. +// +// Return To The Roots 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 General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with Return To The Roots. If not, see . + +/////////////////////////////////////////////////////////////////////////////// +// Header + + +#include "defines.h" +#include "nofCarpenter.h" +#include "Loader.h" +#include "macros.h" +#include "GameClient.h" +#include "buildings/nobUsual.h" +#include "SoundManager.h" + +/////////////////////////////////////////////////////////////////////////////// +// Makros / Defines +#if defined _WIN32 && defined _DEBUG && defined _MSC_VER +#define new new(_NORMAL_BLOCK, THIS_FILE, __LINE__) +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +nofCarpenter::nofCarpenter(const MapPoint pos, const unsigned char player, nobUsual* workplace) + : nofWorkman(JOB_CARPENTER, pos, player, workplace) +{ +} + +nofCarpenter::nofCarpenter(SerializedGameData* sgd, const unsigned obj_id) : nofWorkman(sgd, obj_id) +{ +} + +void nofCarpenter::DrawWorking(int x, int y) +{ + signed char offsets[NAT_COUNT][2] = { {30, 3}, {38, 3}, {30, 8}, {17, -2}, {38, 3} }; + + unsigned now_id; + + LOADER.GetImageN("rom_bobs", 32 + ((now_id = GAMECLIENT.Interpolate(136, current_ev)) % 8)) + ->Draw(x + offsets[workplace->GetNation()][0], y + offsets[workplace->GetNation()][1], 0, 0, 0, 0, 0, 0, COLOR_WHITE, COLORS[gwg->GetPlayer(workplace->GetPlayer()).color]); + + // Evtl Sound abspielen + if(now_id % 8 == 3 || now_id % 8 == 7) + { + SOUNDMANAGER.PlayNOSound(54 + ((now_id) % 8) / 4, this, now_id / 4); + was_sounding = true; + } + + last_id = now_id; +} + +GoodType nofCarpenter::ProduceWare() +{ + return GD_BOARDS; +} diff --git a/pool/shard008/C++/0096563_fingerprint_calculator.cpp b/pool/shard008/C++/0096563_fingerprint_calculator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..081ca50e4d5a58a667b4cc66b5b8f21d72ce9c55 --- /dev/null +++ b/pool/shard008/C++/0096563_fingerprint_calculator.cpp @@ -0,0 +1,67 @@ +/* + * Chromaprint -- Audio fingerprinting toolkit + * Copyright (C) 2010 Lukas Lalinsky + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 + * USA + */ + +#include "fingerprint_calculator.h" +#include "classifier.h" +#include "debug.h" +#include "utils.h" + +using namespace std; +using namespace Chromaprint; + +FingerprintCalculator::FingerprintCalculator(const Classifier *classifiers, int num_classifiers) + : m_classifiers(classifiers), m_num_classifiers(num_classifiers) +{ + m_max_filter_width = 0; + for (int i = 0; i < num_classifiers; i++) { + m_max_filter_width = max(m_max_filter_width, classifiers[i].filter().width()); + } + assert(m_max_filter_width > 0); +} + + +vector FingerprintCalculator::Calculate(Image *image) +{ + int length = image->NumRows() - m_max_filter_width + 1; + if (length <= 0) { + DEBUG() << "Chromaprint::FingerprintCalculator::Calculate() -- Not " + << "enough data. Image has " << image->NumRows() << " rows, " + << "needs at least " << m_max_filter_width << " rows.\n"; + return vector(); + } + IntegralImage integral_image(image); + vector fingerprint(length); + for (int i = 0; i < length; i++) { + fingerprint[i] = CalculateSubfingerprint(&integral_image, i); + } + return fingerprint; +} + +int32_t FingerprintCalculator::CalculateSubfingerprint(IntegralImage *image, int offset) +{ + uint32_t bits = 0; + for (int i = 0; i < m_num_classifiers; i++) { + //for (int i = m_num_classifiers - 1; i >= 0; i--) { + bits = (bits << 2) | GrayCode(m_classifiers[i].Classify(image, offset)); + //bits = (bits << 2) | m_classifiers[i].Classify(image, offset); + } + return UnsignedToSigned(bits); +} + diff --git a/pool/shard008/C++/0096564_desktop_native_cursor_manager.cc b/pool/shard008/C++/0096564_desktop_native_cursor_manager.cc new file mode 100644 index 0000000000000000000000000000000000000000..eed97f32af54167d7e59bd1919331523bd15e62f --- /dev/null +++ b/pool/shard008/C++/0096564_desktop_native_cursor_manager.cc @@ -0,0 +1,96 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ui/views/widget/desktop_aura/desktop_native_cursor_manager.h" + +#include "ui/aura/root_window.h" +#include "ui/base/cursor/cursor_loader.h" +#include "ui/views/widget/desktop_aura/desktop_cursor_loader_updater.h" + +namespace views { + +DesktopNativeCursorManager::DesktopNativeCursorManager( + aura::RootWindow* window, + scoped_ptr cursor_loader_updater) + : root_window_(window), + cursor_loader_updater_(cursor_loader_updater.Pass()), + cursor_loader_(ui::CursorLoader::Create()) { + if (cursor_loader_updater_.get()) + cursor_loader_updater_->OnCreate(root_window_, cursor_loader_.get()); +} + +DesktopNativeCursorManager::~DesktopNativeCursorManager() { +} + +gfx::NativeCursor DesktopNativeCursorManager::GetInitializedCursor(int type) { + gfx::NativeCursor cursor(type); + cursor_loader_->SetPlatformCursor(&cursor); + return cursor; +} + +void DesktopNativeCursorManager::SetDisplay( + const gfx::Display& display, + views::corewm::NativeCursorManagerDelegate* delegate) { + cursor_loader_->UnloadAll(); + cursor_loader_->set_display(display); + + if (cursor_loader_updater_.get()) + cursor_loader_updater_->OnDisplayUpdated(display, cursor_loader_.get()); + + SetCursor(delegate->GetCurrentCursor(), delegate); +} + +void DesktopNativeCursorManager::SetCursor( + gfx::NativeCursor cursor, + views::corewm::NativeCursorManagerDelegate* delegate) { + gfx::NativeCursor new_cursor = cursor; + cursor_loader_->SetPlatformCursor(&new_cursor); + delegate->CommitCursor(new_cursor); + + if (delegate->GetCurrentVisibility()) + root_window_->SetCursor(new_cursor); +} + +void DesktopNativeCursorManager::SetVisibility( + bool visible, + views::corewm::NativeCursorManagerDelegate* delegate) { + delegate->CommitVisibility(visible); + + if (visible) { + SetCursor(delegate->GetCurrentCursor(), delegate); + } else { + gfx::NativeCursor invisible_cursor(ui::kCursorNone); + cursor_loader_->SetPlatformCursor(&invisible_cursor); + root_window_->SetCursor(invisible_cursor); + } + + root_window_->OnCursorVisibilityChanged(visible); +} + +void DesktopNativeCursorManager::SetCursorSet( + ui::CursorSetType cursor_set, + views::corewm::NativeCursorManagerDelegate* delegate) { + NOTIMPLEMENTED(); +} + +void DesktopNativeCursorManager::SetScale( + float scale, + views::corewm::NativeCursorManagerDelegate* delegate) { + NOTIMPLEMENTED(); +} + +void DesktopNativeCursorManager::SetMouseEventsEnabled( + bool enabled, + views::corewm::NativeCursorManagerDelegate* delegate) { + delegate->CommitMouseEventsEnabled(enabled); + + // TODO(erg): In the ash version, we set the last mouse location on Env. I'm + // not sure this concept makes sense on the desktop. + + SetVisibility(delegate->GetCurrentVisibility(), delegate); + + root_window_->OnMouseEventsEnableStateChanged(enabled); +} + +} // namespace views diff --git a/pool/shard008/C++/0096566_HashMap_Test.cpp b/pool/shard008/C++/0096566_HashMap_Test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..45f3904258ae810fdc1bd66444e06af1c8a36cf5 --- /dev/null +++ b/pool/shard008/C++/0096566_HashMap_Test.cpp @@ -0,0 +1,94 @@ +/* + * Copyright 2016-2018 Jerome Pasquier + * + * This file is part of librlgl. + * + * librlgl is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * librlgl 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with librlgl. If not, see . + * + */ + +#include "HashMap.hpp" + +#include +#include +#include + +using namespace std; +using namespace RLGL; + +class SerializableObject +{ +public: + int a; + string b; + + friend ostream& operator<< (ostream &out, SerializableObject const& c) + { + return out << c.a << c.b; + } + + friend istream& operator>> (istream &in, SerializableObject& c) + { + return in >> c.a >> c.b ; + } + +}; + +// Test a string value +TEST( HashMap, str ) +{ + HashMap hm; + hm.set("key", "aze"); + string str = hm.get("key"); + ASSERT_EQ( str, "aze" ); +} + +TEST( HashMap, grouped_str ) +{ + HashMap hm; + hm.addGroup("gr1"); + hm.set("key", "aze"); + string str = hm.get("gr1::key"); + ASSERT_EQ( str, "aze" ); +} + +TEST( HashMap, cant_find ) +{ + HashMap hm; + hm.addGroup("gr1"); + hm.set("key", "aze"); + ASSERT_THROW(hm.get("gr1::key2"), KeyException ); +} + +TEST( HashMap, unserializable ) +{ + HashMap hm; + SerializableObject so; + so.a = 8; + so.b = "aze"; + hm.addGroup("gr1"); + hm.set("key", so); + + SerializableObject so2 = hm.get("gr1::key"); + ASSERT_EQ( so2.a, 8 ); + ASSERT_EQ( so2.b, "aze" ); +} + +TEST( HashMap, already_exist ) +{ + HashMap hm; + hm.addGroup("gr1"); + hm.set("key", "aze"); + ASSERT_THROW(hm.set("key", "zer"), KeyException ); +} diff --git a/pool/shard008/C++/0096567_media_stream_device_permission_context_unittest.cc b/pool/shard008/C++/0096567_media_stream_device_permission_context_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..35caf13a3709a2d7220117613c2086617072c2e1 --- /dev/null +++ b/pool/shard008/C++/0096567_media_stream_device_permission_context_unittest.cc @@ -0,0 +1,138 @@ +// Copyright 2015 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/media/webrtc/media_stream_device_permission_context.h" + +#include "base/bind.h" +#include "base/macros.h" +#include "build/build_config.h" +#include "chrome/browser/content_settings/host_content_settings_map_factory.h" +#include "chrome/test/base/chrome_render_view_host_test_harness.h" +#include "chrome/test/base/testing_profile.h" +#include "components/content_settings/core/browser/host_content_settings_map.h" +#include "components/content_settings/core/common/content_settings.h" +#include "components/content_settings/core/common/content_settings_types.h" +#include "components/infobars/content/content_infobar_manager.h" +#include "components/permissions/permission_request_id.h" +#include "content/public/browser/web_contents.h" +#include "content/public/common/content_features.h" +#include "content/public/test/mock_render_process_host.h" +#include "content/public/test/web_contents_tester.h" +#include "testing/gtest/include/gtest/gtest.h" + +#if !defined(OS_ANDROID) +#include "components/permissions/permission_request_manager.h" +#endif + +namespace { +class TestPermissionContext : public MediaStreamDevicePermissionContext { + public: + TestPermissionContext(Profile* profile, + const ContentSettingsType content_settings_type) + : MediaStreamDevicePermissionContext(profile, content_settings_type) {} + + ~TestPermissionContext() override {} +}; + +} // anonymous namespace + +// TODO(raymes): many tests in MediaStreamDevicesControllerTest should be +// converted to tests in this file. +class MediaStreamDevicePermissionContextTests + : public ChromeRenderViewHostTestHarness { + public: + MediaStreamDevicePermissionContextTests( + const MediaStreamDevicePermissionContextTests&) = delete; + MediaStreamDevicePermissionContextTests& operator=( + const MediaStreamDevicePermissionContextTests&) = delete; + + protected: + MediaStreamDevicePermissionContextTests() = default; + + void TestInsecureQueryingUrl(ContentSettingsType content_settings_type) { + TestPermissionContext permission_context(profile(), content_settings_type); + GURL insecure_url("http://www.example.com"); + GURL secure_url("https://www.example.com"); + + // Check that there is no saved content settings. + EXPECT_EQ(CONTENT_SETTING_ASK, + HostContentSettingsMapFactory::GetForProfile(profile()) + ->GetContentSetting(insecure_url.DeprecatedGetOriginAsURL(), + insecure_url.DeprecatedGetOriginAsURL(), + content_settings_type)); + EXPECT_EQ(CONTENT_SETTING_ASK, + HostContentSettingsMapFactory::GetForProfile(profile()) + ->GetContentSetting(secure_url.DeprecatedGetOriginAsURL(), + insecure_url.DeprecatedGetOriginAsURL(), + content_settings_type)); + EXPECT_EQ(CONTENT_SETTING_ASK, + HostContentSettingsMapFactory::GetForProfile(profile()) + ->GetContentSetting(insecure_url.DeprecatedGetOriginAsURL(), + secure_url.DeprecatedGetOriginAsURL(), + content_settings_type)); + + EXPECT_EQ(CONTENT_SETTING_BLOCK, + permission_context + .GetPermissionStatus(nullptr /* render_frame_host */, + insecure_url, insecure_url) + .content_setting); + + EXPECT_EQ(CONTENT_SETTING_BLOCK, + permission_context + .GetPermissionStatus(nullptr /* render_frame_host */, + insecure_url, secure_url) + .content_setting); + } + + void TestSecureQueryingUrl(ContentSettingsType content_settings_type) { + TestPermissionContext permission_context(profile(), content_settings_type); + GURL secure_url("https://www.example.com"); + + // Check that there is no saved content settings. + EXPECT_EQ(CONTENT_SETTING_ASK, + HostContentSettingsMapFactory::GetForProfile(profile()) + ->GetContentSetting(secure_url.DeprecatedGetOriginAsURL(), + secure_url.DeprecatedGetOriginAsURL(), + content_settings_type)); + + EXPECT_EQ(CONTENT_SETTING_ASK, + permission_context + .GetPermissionStatus(nullptr /* render_frame_host */, + secure_url, secure_url) + .content_setting); + } + + private: + // ChromeRenderViewHostTestHarness: + void SetUp() override { + ChromeRenderViewHostTestHarness::SetUp(); +#if defined(OS_ANDROID) + infobars::ContentInfoBarManager::CreateForWebContents(web_contents()); +#else + permissions::PermissionRequestManager::CreateForWebContents(web_contents()); +#endif + } +}; + +// MEDIASTREAM_MIC permission status should be ask for insecure origin to +// accommodate the usage case of Flash. +TEST_F(MediaStreamDevicePermissionContextTests, TestMicInsecureQueryingUrl) { + TestInsecureQueryingUrl(ContentSettingsType::MEDIASTREAM_MIC); +} + +// MEDIASTREAM_CAMERA permission status should be ask for insecure origin to +// accommodate the usage case of Flash. +TEST_F(MediaStreamDevicePermissionContextTests, TestCameraInsecureQueryingUrl) { + TestInsecureQueryingUrl(ContentSettingsType::MEDIASTREAM_CAMERA); +} + +// MEDIASTREAM_MIC permission status should be ask for Secure origin. +TEST_F(MediaStreamDevicePermissionContextTests, TestMicSecureQueryingUrl) { + TestSecureQueryingUrl(ContentSettingsType::MEDIASTREAM_MIC); +} + +// MEDIASTREAM_CAMERA permission status should be ask for Secure origin. +TEST_F(MediaStreamDevicePermissionContextTests, TestCameraSecureQueryingUrl) { + TestSecureQueryingUrl(ContentSettingsType::MEDIASTREAM_CAMERA); +} diff --git a/pool/shard008/C++/0096568_UrlFilter.cpp b/pool/shard008/C++/0096568_UrlFilter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..addf79ad4824869e79b6530d45a5ccea01ce8128 --- /dev/null +++ b/pool/shard008/C++/0096568_UrlFilter.cpp @@ -0,0 +1,72 @@ +/* Simple Chat + * Copyright (c) 2008-2014 Alexander Sedov + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include + +#include "ChatUrls.h" +#include "net/SimpleID.h" +#include "QtEscape.h" +#include "sglobal.h" +#include "text/UrlFilter.h" + +bool UrlFilter::filter(QList &tokens, const ChatId &id) const +{ + Q_UNUSED(id) + + QString name; + bool modified; + + for (int i = 0; i < tokens.size(); ++i) { + const HtmlToken &token = tokens.at(i); + if (token.type == HtmlToken::StartTag && token.tag == LS("a")) { + HtmlATag tag(tokens.at(i)); + modified = false; + + if (tag.url.startsWith(LS("chat://channel/"))) { + tag.classes = LS("nick"); + ClientChannel user = ChatUrls::channel(QUrl(tag.url)); + if (user) { + tag.classes += LC(' ') + SimpleID::encode(user->id()); + name = user->name(); + + tag.classes += LS(" color-") + Gender::colorToString(user->gender().color()); + } + + modified = true; + } + + if (QUrl(tag.url).scheme() == LS("javascript")) { + tag.url = QString(); + modified = true; + } + + if (tag.title.isEmpty()) { + tag.title = tag.url; + modified = true; + } + + if (modified) + tokens[i].text = tag.toText(); + } + else if (token.type == HtmlToken::Text && !name.isEmpty()) { + tokens[i].text = Qt::escape(name); + name.clear(); + } + } + + return true; +} diff --git a/pool/shard008/C++/0096569_ImportDeviceDialog.cpp b/pool/shard008/C++/0096569_ImportDeviceDialog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5e2a2c7a5d3d5dd4467acade9f779f9db89077fb --- /dev/null +++ b/pool/shard008/C++/0096569_ImportDeviceDialog.cpp @@ -0,0 +1,82 @@ +#include "ImportDeviceDialog.h" + +#include + +#include +#include + +#include + +#include +#include + +ImportDeviceDialog::ImportDeviceDialog(QWidget* parent) + : QDialog(parent) +{ + setupUi(this); + + this->treeWidgetDevice->headerItem()->setText(0, ""); + this->treeWidgetDevice->setColumnWidth(0, 25); +} + +void ImportDeviceDialog::setImportFile(const QString& path) +{ + QFile file(path); + if (file.open(QFile::ReadOnly | QIODevice::Text)) + { + QTextStream stream(&file); + stream.setCodec(QTextCodec::codecForName("UTF-8")); + + std::wstringstream wstringstream; + wstringstream << stream.readAll().toStdWString(); + + boost::property_tree::wptree pt; + boost::property_tree::xml_parser::read_xml(wstringstream, pt); + + BOOST_FOREACH(boost::property_tree::wptree::value_type& parentValue, pt.get_child(L"servers")) + { + this->models.push_back(parseData(parentValue.second)); + } + + foreach (DeviceModel model, this->models) + { + QTreeWidgetItem* treeItem = new QTreeWidgetItem(this->treeWidgetDevice); + treeItem->setIcon(0, QIcon(":/Graphics/Images/ServerSmall.png")); + treeItem->setText(1, model.getName()); + treeItem->setText(2, model.getDescription()); + } + } +} + +DeviceModel ImportDeviceDialog::parseData(boost::property_tree::wptree& pt) +{ + QString name = QString::fromStdWString(pt.get(L"name", L"")); + QString address = QString::fromStdWString(pt.get(L"address", L"")); + QString port = QString::fromStdWString(pt.get(L"port", L"5250")); + QString username = QString::fromStdWString(pt.get(L"username", L"")); + QString password = QString::fromStdWString(pt.get(L"password", L"")); + QString description = QString::fromStdWString(pt.get(L"description", L"")); + QString shadow = QString::fromStdWString(pt.get(L"shadow", L"No")); + QString previewChannel = QString::fromStdWString(pt.get(L"previewchannel", L"0")); + QString lockedChannel = QString::fromStdWString(pt.get(L"lockedchannel", L"0")); + + return DeviceModel(0, name, address, port.toInt(), username, password, description, "", shadow, 0, "", previewChannel.toInt(), lockedChannel.toInt()); +} + +const QList ImportDeviceDialog::getDevice() const +{ + QList models; + for (int i = 0; i < this->treeWidgetDevice->invisibleRootItem()->childCount(); i++) + { + QTreeWidgetItem* item = this->treeWidgetDevice->invisibleRootItem()->child(i); + if (item->isSelected()) + models.push_back(this->models.at(i)); + } + + return models; +} + +void ImportDeviceDialog::accept() +{ + QDialog::accept(); +} diff --git a/pool/shard008/C++/0096571_chown.cpp b/pool/shard008/C++/0096571_chown.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e9c5a4e755c07efa83fc48b94ba7a1a1f51bf343 --- /dev/null +++ b/pool/shard008/C++/0096571_chown.cpp @@ -0,0 +1,219 @@ +/* + * Copyright (c) 1992, Brian Berliner and Jeff Polk + * Copyright (c) 1989-1992, Brian Berliner + * + * You may distribute under the terms of the GNU General Public License as + * specified in the README file that comes with the CVS 1.4 kit. + * + * chown + * + * Changes the owner of a directory to the given name. + */ + +#include "cvs.h" +#include "fileattr.h" + +static const char *chown_user; + +static const char *const chown_usage[] = +{ + "Usage: %s %s [-R] user directory...\n", + "\t-R\tChange owner recursively\n", + NULL +}; + +static const char *const rchown_usage[] = +{ + "Usage: %s %s [-R] user module...\n", + "\t-R\tChange owner recursively\n", + NULL +}; + +static Dtype chown_dirproc (void *callerdat, char *dir, char *repos, char *update_dir, List *entries, const char *virtual_repository, Dtype hint); +static int rchown_proc(int argc, char **argv, const char *xwhere, + const char *mwhere, const char *mfile, int shorten, + int local_specified, const char *mname, const char *msg); + +int chowner (int argc, char **argv) +{ + int c; + int err = 0; + int local = 1; + int is_rchown = !strcmp(command_name,"rchown"); + + if (argc == 1 || argc == -1) + usage (is_rchown?rchown_usage:chown_usage); + + optind = 0; + while ((c = getopt (argc, argv, "+R")) != -1) + { + switch (c) + { + case 'R': + local = 0; + break; + case '?': + default: + usage (chown_usage); + break; + } + } + argc -= optind; + argv += optind; + + if (argc <= 0) + usage (chown_usage); + + if (current_parsed_root->isremote) + { + if(is_rchown) + { + if (!supported_request ("rchown")) + error (1, 0, "server does not support rchown"); + } + else + { + if (!supported_request ("chown")) + error (1, 0, "server does not support chown"); + } + if(!local) + { + send_arg("-R"); + } + + send_arg("--"); + send_arg(argv[0]); + argv++; + argc--; + if (is_rchown) + { + for (int i = 0; i < argc; i++) + send_arg (argv[i]); + send_to_server ("rchown\n", 0); + } + else + { + send_file_names (argc, argv, SEND_EXPAND_WILD); + send_files (argc, argv, local, 0, SEND_NO_CONTENTS); + send_to_server ("chown\n", 0); + } + return get_responses_and_close (); + } + + chown_user = argv[0]; + argv++; + argc--; + + if(!acl_mode) + error(1,0,"Access control is disabled on this repository."); + + if (is_rchown) + { + DBM *db; + int i; + db = open_module (); + for (i = 0; i < argc; i++) + { + err += do_module (db, argv[i], MISC, "Changing", rchown_proc, + (char *) NULL, 0, local, 0, 0, (char *) NULL); + } + close_module (db); + } + else + { + /* start the recursion processor */ + err = start_recursion ((FILEPROC) NULL, (FILESDONEPROC) NULL, + (PREDIRENTPROC) NULL, chown_dirproc, (DIRLEAVEPROC) NULL, NULL, + argc, argv, local, + W_LOCAL, 0, 1, (char *) NULL, NULL, 1, verify_control); + } + return (err); +} + +static Dtype chown_dirproc (void *callerdat, char *dir, char *repos, char *update_dir, List *entries, const char *virtual_repository, Dtype hint) +{ + if(hint!=R_PROCESS) + return hint; + + if(!quiet) + printf("Changing owner for directory %s\n",update_dir); + change_owner(chown_user); + return R_PROCESS; +} + +static int rchown_proc(int argc, char **argv, const char *xwhere, + const char *mwhere, const char *mfile, int shorten, + int local_specified, const char *mname, const char *msg) +{ + /* Begin section which is identical to patch_proc--should this + be abstracted out somehow? */ + char *myargv[2]; + int err = 0; + char *repository, *mapped_repository; + char *where; + + repository = (char*)xmalloc (strlen (current_parsed_root->directory) + strlen (argv[0]) + + (mfile == NULL ? 0 : strlen (mfile) + 1) + 2); + (void) sprintf (repository, "%s/%s", current_parsed_root->directory, argv[0]); + where = (char*)xmalloc (strlen (argv[0]) + (mfile == NULL ? 0 : strlen (mfile) + 1) + + 1); + (void) strcpy (where, argv[0]); + + /* if mfile isn't null, we need to set up to do only part of the module */ + if (mfile != NULL) + { + char *cp; + char *path; + + /* if the portion of the module is a path, put the dir part on repos */ + if ((cp = (char*)strrchr (mfile, '/')) != NULL) + { + *cp = '\0'; + (void) strcat (repository, "/"); + (void) strcat (repository, mfile); + (void) strcat (where, "/"); + (void) strcat (where, mfile); + mfile = cp + 1; + } + + /* take care of the rest */ + path = (char*)xmalloc (strlen (repository) + strlen (mfile) + 5); + (void) sprintf (path, "%s/%s", repository, mfile); + if (isdir (path)) + { + /* directory means repository gets the dir tacked on */ + (void) strcpy (repository, path); + (void) strcat (where, "/"); + (void) strcat (where, mfile); + } + else + { + myargv[0] = argv[0]; + myargv[1] = (char*)mfile; + argc = 2; + argv = myargv; + } + xfree (path); + } + + mapped_repository = map_repository(repository); + + /* cd to the starting repository */ + if ( CVS_CHDIR (mapped_repository) < 0) + { + error (0, errno, "cannot chdir to %s", fn_root(repository)); + xfree (repository); + xfree (mapped_repository); + return (1); + } + xfree (repository); + /* End section which is identical to patch_proc. */ + + err = start_recursion (NULL, (FILESDONEPROC) NULL, (PREDIRENTPROC) NULL, chown_dirproc, + (DIRLEAVEPROC) NULL, NULL, + argc - 1, argv + 1, local_specified, W_REPOS, 0, 1, + where, mapped_repository, 1, verify_control); + + xfree (mapped_repository); + return err; +} diff --git a/pool/shard008/C++/0096575_firstrun.cpp b/pool/shard008/C++/0096575_firstrun.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d440710cd8cc76d68cb4f68aa94f2b00c240b9bc --- /dev/null +++ b/pool/shard008/C++/0096575_firstrun.cpp @@ -0,0 +1,115 @@ +/***************************************************************************** + * firstrun.cpp : First Run dialogs + **************************************************************************** + * Copyright © 2009 VideoLAN + * $Id$ + * + * Authors: Jean-Baptiste Kempf + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. + *****************************************************************************/ + +#include "dialogs/firstrun.hpp" + +#include +#include +#include +#include +#include + +FirstRun::FirstRun( QWidget *_p, intf_thread_t *_p_intf ) + : QWidget( _p ), p_intf( _p_intf ) +{ + msg_Dbg( p_intf, "Boring first Run Wizard" ); + buildPrivDialog(); + setVisible( true ); +} + +#define ALBUM_ART_WHEN_ASKED 0 +#define ALBUM_ART_ALL 2 + +void FirstRun::save() +{ + config_PutInt( p_intf, "album-art", checkbox->isChecked() ? ALBUM_ART_ALL: ALBUM_ART_WHEN_ASKED ); +#ifdef UPDATE_CHECK + config_PutInt( p_intf, "qt-updates-notif", checkbox2->isChecked() ); +#endif + config_PutInt( p_intf, "qt-privacy-ask", 0 ); + + /* FIXME Should not save here. This will not work as expected if another + * plugin overwrote items of its own. */ +#warning FIXME + /* We have to save here because the user may not launch Prefs */ + config_SaveConfigFile( p_intf ); + close(); +} + +void FirstRun::buildPrivDialog() +{ + setWindowTitle( qtr( "Privacy and Network Access Policy" ) ); + setWindowRole( "vlc-privacy" ); + setWindowModality( Qt::ApplicationModal ); + setWindowFlags( Qt::Dialog ); + setAttribute( Qt::WA_DeleteOnClose ); + + QGridLayout *gLayout = new QGridLayout( this ); + + QGroupBox *blabla = new QGroupBox( qtr( "Privacy and Network Access Policy" ) ); + QGridLayout *blablaLayout = new QGridLayout( blabla ); + QLabel *text = new QLabel( qtr( + "

In order to protect your privacy, VLC media player " + "does not collect personal data or transmit them, " + "not even in anonymized form, to anyone." + "

\n" + "

Nevertheless, VLC is able to automatically retrieve " + "information about the media in your playlist from third party " + "Internet-based services. This includes cover art, track names, " + "artist names and other meta-data." + "

\n" + "

Consequently, this may entail identifying some of your media files to third party " + "entities. Therefore the VLC developers require your express " + "consent for the media player to access the Internet automatically." + "

\n" + ) ); + text->setWordWrap( true ); + text->setTextFormat( Qt::RichText ); + + blablaLayout->addWidget( text, 0, 0 ) ; + + QGroupBox *options = new QGroupBox( qtr( "Network Access Policy" ) ); + QGridLayout *optionsLayout = new QGridLayout( options ); + + gLayout->addWidget( blabla, 0, 0, 1, 3 ); + gLayout->addWidget( options, 1, 0, 1, 3 ); + int line = 0; + + checkbox = new QCheckBox( qtr( "Automatically retrieve media info" ) ); + checkbox->setChecked( true ); + optionsLayout->addWidget( checkbox, line++, 0 ); + +#ifdef UPDATE_CHECK + checkbox2 = new QCheckBox( qtr( "Regularly check for VLC updates" ) ); + checkbox2->setChecked( true ); + optionsLayout->addWidget( checkbox2, line++, 0 ); +#endif + + QDialogButtonBox *buttonsBox = new QDialogButtonBox( this ); + buttonsBox->addButton( qtr( "Continue" ), QDialogButtonBox::AcceptRole ); + + gLayout->addWidget( buttonsBox, 2, 0, 2, 3 ); + + CONNECT( buttonsBox, accepted(), this, save() ); + buttonsBox->setFocus(); +} diff --git a/pool/shard008/C++/0096577_catv_randomizer_bb_impl.cc b/pool/shard008/C++/0096577_catv_randomizer_bb_impl.cc new file mode 100644 index 0000000000000000000000000000000000000000..3d22bfe284afdd5353aedc2e458413d10c1850b5 --- /dev/null +++ b/pool/shard008/C++/0096577_catv_randomizer_bb_impl.cc @@ -0,0 +1,96 @@ +/* -*- c++ -*- */ +/* + * Copyright 2016,2017 Free Software Foundation, Inc. + * + * This is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3, or (at your option) + * any later version. + * + * This software 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this software; see the file COPYING. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, + * Boston, MA 02110-1301, USA. + */ + +#include "catv_randomizer_bb_impl.h" +#include + +namespace gr { +namespace dtv { + +catv_randomizer_bb::sptr catv_randomizer_bb::make(catv_constellation_t constellation) +{ + return gnuradio::get_initial_sptr(new catv_randomizer_bb_impl(constellation)); +} + +/* + * The private constructor + */ +catv_randomizer_bb_impl::catv_randomizer_bb_impl(catv_constellation_t constellation) + : gr::sync_block("catv_randomizer_bb", + gr::io_signature::make(1, 1, sizeof(unsigned char)), + gr::io_signature::make(1, 1, sizeof(unsigned char))) +{ + offset = 0; + if (constellation == CATV_MOD_64QAM) { + max_offset = 60 * 128; + } else { + max_offset = 88 * 128; + } + init_rand(); +} + +/* + * Our virtual destructor. + */ +catv_randomizer_bb_impl::~catv_randomizer_bb_impl() {} + +void catv_randomizer_bb_impl::init_rand() +{ + unsigned char c2 = 0x7F, c1 = 0x7F, c0 = 0x7F; + unsigned char c2_new, c1_new, c0_new; + int n, i; + + for (n = 0; n < max_offset; n++) { + rseq[n] = c2; + c2_new = c1; + c1_new = c0 ^ c2; + c0_new = c2; + for (i = 0; i < 3; i++) { + c0_new <<= 1; + if (c0_new & 0x80) { + c0_new = (c0_new & 0x7F) ^ 0x09; + } + } + c2 = c2_new; + c1 = c1_new; + c0 = c0_new; + } +} + +int catv_randomizer_bb_impl::work(int noutput_items, + gr_vector_const_void_star& input_items, + gr_vector_void_star& output_items) +{ + const unsigned char* in = (const unsigned char*)input_items[0]; + unsigned char* out = (unsigned char*)output_items[0]; + + for (int i = 0; i < noutput_items; i++) { + out[i] = in[i] ^ rseq[offset++]; + if (offset == max_offset) { + offset = 0; + } + } + + // Tell runtime system how many output items we produced. + return noutput_items; +} + +} /* namespace dtv */ +} /* namespace gr */ diff --git a/pool/shard008/C++/0096578_AP_Follow.cpp b/pool/shard008/C++/0096578_AP_Follow.cpp new file mode 100644 index 0000000000000000000000000000000000000000..56e945c240bb997cfd76ae3d490529fde6015127 --- /dev/null +++ b/pool/shard008/C++/0096578_AP_Follow.cpp @@ -0,0 +1,392 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + */ + +#include +#include +#include "AP_Follow.h" +#include +#include + +extern const AP_HAL::HAL& hal; + +#define AP_FOLLOW_TIMEOUT_MS 3000 // position estimate timeout after 1 second +#define AP_FOLLOW_SYSID_TIMEOUT_MS 10000 // forget sysid we are following if we haave not heard from them in 10 seconds + +#define AP_FOLLOW_OFFSET_TYPE_NED 0 // offsets are in north-east-down frame +#define AP_FOLLOW_OFFSET_TYPE_RELATIVE 1 // offsets are relative to lead vehicle's heading + +#define AP_FOLLOW_ALTITUDE_TYPE_RELATIVE 1 // relative altitude is used by default + +#define AP_FOLLOW_POS_P_DEFAULT 0.1f // position error gain default + +// table of user settable parameters +const AP_Param::GroupInfo AP_Follow::var_info[] = { + + // @Param: _ENABLE + // @DisplayName: Follow enable/disable + // @Description: Enabled/disable following a target + // @Values: 0:Disabled,1:Enabled + // @User: Standard + AP_GROUPINFO_FLAGS("_ENABLE", 1, AP_Follow, _enabled, 0, AP_PARAM_FLAG_ENABLE), + + // 2 is reserved for TYPE parameter + + // @Param: _SYSID + // @DisplayName: Follow target's mavlink system id + // @Description: Follow target's mavlink system id + // @Range: 0 255 + // @User: Standard + AP_GROUPINFO("_SYSID", 3, AP_Follow, _sysid, 0), + + // 4 is reserved for MARGIN parameter + + // @Param: _DIST_MAX + // @DisplayName: Follow distance maximum + // @Description: Follow distance maximum. targets further than this will be ignored + // @Units: m + // @Range: 1 1000 + // @User: Standard + AP_GROUPINFO("_DIST_MAX", 5, AP_Follow, _dist_max, 100), + + // @Param: _OFS_TYPE + // @DisplayName: Follow offset type + // @Description: Follow offset type + // @Values: 0:North-East-Down, 1:Relative to lead vehicle heading + // @User: Standard + AP_GROUPINFO("_OFS_TYPE", 6, AP_Follow, _offset_type, AP_FOLLOW_OFFSET_TYPE_NED), + + // @Param: _OFS_X + // @DisplayName: Follow offsets in meters north/forward + // @Description: Follow offsets in meters north/forward. If positive, this vehicle fly ahead or north of lead vehicle. Depends on FOLL_OFS_TYPE + // @Range: -100 100 + // @Units: m + // @Increment: 1 + // @User: Standard + + // @Param: _OFS_Y + // @DisplayName: Follow offsets in meters east/right + // @Description: Follow offsets in meters east/right. If positive, this vehicle fly to the right or east of lead vehicle. Depends on FOLL_OFS_TYPE + // @Range: -100 100 + // @Units: m + // @Increment: 1 + // @User: Standard + + // @Param: _OFS_Z + // @DisplayName: Follow offsets in meters down + // @Description: Follow offsets in meters down. If positive, this vehicle fly below the lead vehicle + // @Range: -100 100 + // @Units: m + // @Increment: 1 + // @User: Standard + AP_GROUPINFO("_OFS", 7, AP_Follow, _offset, 0), + + // @Param: _YAW_BEHAVE + // @DisplayName: Follow yaw behaviour + // @Description: Follow yaw behaviour + // @Values: 0:None,1:Face Lead Vehicle,2:Same as Lead vehicle,3:Direction of Flight + // @User: Standard + AP_GROUPINFO("_YAW_BEHAVE", 8, AP_Follow, _yaw_behave, 1), + + // @Param: _POS_P + // @DisplayName: Follow position error P gain + // @Description: Follow position error P gain. Converts the difference between desired vertical speed and actual speed into a desired acceleration that is passed to the throttle acceleration controller + // @Range: 0.01 1.00 + // @Increment: 0.01 + // @User: Standard + AP_SUBGROUPINFO(_p_pos, "_POS_", 9, AP_Follow, AC_P), + + // @Param: _ALT_TYPE + // @DisplayName: Follow altitude type + // @Description: Follow altitude type + // @Values: 0:absolute, 1: relative + // @User: Standard + AP_GROUPINFO("_ALT_TYPE", 10, AP_Follow, _alt_type, AP_FOLLOW_ALTITUDE_TYPE_RELATIVE), + + AP_GROUPEND +}; + +/* + The constructor also initialises the proximity sensor. Note that this + constructor is not called until detect() returns true, so we + already know that we should setup the proximity sensor +*/ +AP_Follow::AP_Follow() : + _p_pos(AP_FOLLOW_POS_P_DEFAULT) +{ + AP_Param::setup_object_defaults(this, var_info); +} + +// get target's estimated location +bool AP_Follow::get_target_location_and_velocity(Location &loc, Vector3f &vel_ned) const +{ + // exit immediately if not enabled + if (!_enabled) { + return false; + } + + // check for timeout + if ((_last_location_update_ms == 0) || (AP_HAL::millis() - _last_location_update_ms > AP_FOLLOW_TIMEOUT_MS)) { + return false; + } + + // calculate time since last actual position update + const float dt = (AP_HAL::millis() - _last_location_update_ms) * 0.001f; + + // get velocity estimate + if (!get_velocity_ned(vel_ned, dt)) { + return false; + } + + // project the vehicle position + Location last_loc = _target_location; + location_offset(last_loc, vel_ned.x * dt, vel_ned.y * dt); + last_loc.alt -= vel_ned.z * 100.0f * dt; // convert m/s to cm/s, multiply by dt. minus because NED + + // return latest position estimate + loc = last_loc; + return true; +} + +// get distance vector to target (in meters) and target's velocity all in NED frame +bool AP_Follow::get_target_dist_and_vel_ned(Vector3f &dist_ned, Vector3f &dist_with_offs, Vector3f &vel_ned) +{ + // get our location + Location current_loc; + if (!AP::ahrs().get_position(current_loc)) { + clear_dist_and_bearing_to_target(); + return false; + } + + // get target location and velocity + Location target_loc; + Vector3f veh_vel; + if (!get_target_location_and_velocity(target_loc, veh_vel)) { + clear_dist_and_bearing_to_target(); + return false; + } + + // change to altitude above home if relative altitude is being used + if (target_loc.flags.relative_alt == 1) { + current_loc.alt -= AP::ahrs().get_home().alt; + } + + // calculate difference + const Vector3f dist_vec = location_3d_diff_NED(current_loc, target_loc); + + // fail if too far + if (is_positive(_dist_max.get()) && (dist_vec.length() > _dist_max)) { + clear_dist_and_bearing_to_target(); + return false; + } + + // initialise offsets from distance vector if required + init_offsets_if_required(dist_vec); + + // get offsets + Vector3f offsets; + if (!get_offsets_ned(offsets)) { + clear_dist_and_bearing_to_target(); + return false; + } + + // calculate results + dist_ned = dist_vec; + dist_with_offs = dist_vec + offsets; + vel_ned = veh_vel; + + // record distance and heading for reporting purposes + if (is_zero(dist_with_offs.x) && is_zero(dist_with_offs.y)) { + clear_dist_and_bearing_to_target(); + } else { + _dist_to_target = safe_sqrt(sq(dist_with_offs.x) + sq(dist_with_offs.y)); + _bearing_to_target = degrees(atan2f(dist_with_offs.y, dist_with_offs.x)); + } + + return true; +} + +// get target's heading in degrees (0 = north, 90 = east) +bool AP_Follow::get_target_heading(float &heading) const +{ + // exit immediately if not enabled + if (!_enabled) { + return false; + } + + // check for timeout + if ((_last_heading_update_ms == 0) || (AP_HAL::millis() - _last_heading_update_ms > AP_FOLLOW_TIMEOUT_MS)) { + return false; + } + + // return latest heading estimate + heading = _target_heading; + return true; +} + +// handle mavlink DISTANCE_SENSOR messages +void AP_Follow::handle_msg(const mavlink_message_t &msg) +{ + // exit immediately if not enabled + if (!_enabled) { + return; + } + + // skip our own messages + if (msg.sysid == mavlink_system.sysid) { + return; + } + + // skip message if not from our target + if (_sysid != 0 && msg.sysid != _sysid) { + if (_automatic_sysid) { + // maybe timeout who we were following... + if ((_last_location_update_ms == 0) || (AP_HAL::millis() - _last_location_update_ms > AP_FOLLOW_SYSID_TIMEOUT_MS)) { + _sysid.set(0); + } + } + return; + } + + // decode global-position-int message + if (msg.msgid == MAVLINK_MSG_ID_GLOBAL_POSITION_INT) { + + // get estimated location and velocity (for logging) + Location loc_estimate{}; + Vector3f vel_estimate; + UNUSED_RESULT(get_target_location_and_velocity(loc_estimate, vel_estimate)); + + // decode message + mavlink_global_position_int_t packet; + mavlink_msg_global_position_int_decode(&msg, &packet); + + // ignore message if lat and lon are (exactly) zero + if ((packet.lat == 0 && packet.lon == 0)) { + return; + } + + _target_location.lat = packet.lat; + _target_location.lng = packet.lon; + + // select altitude source based on FOLL_ALT_TYPE param + if (_alt_type == AP_FOLLOW_ALTITUDE_TYPE_RELATIVE) { + // relative altitude + _target_location.alt = packet.relative_alt / 10; // convert millimeters to cm + _target_location.flags.relative_alt = 1; // set relative_alt flag + } else { + // absolute altitude + _target_location.alt = packet.alt / 10; // convert millimeters to cm + _target_location.flags.relative_alt = 0; // reset relative_alt flag + } + + _target_velocity_ned.x = packet.vx * 0.01f; // velocity north + _target_velocity_ned.y = packet.vy * 0.01f; // velocity east + _target_velocity_ned.z = packet.vz * 0.01f; // velocity down + + // get a local timestamp with correction for transport jitter + _last_location_update_ms = _jitter.correct_offboard_timestamp_msec(packet.time_boot_ms, AP_HAL::millis()); + if (packet.hdg <= 36000) { // heading (UINT16_MAX if unknown) + _target_heading = packet.hdg * 0.01f; // convert centi-degrees to degrees + _last_heading_update_ms = _last_location_update_ms; + } + // initialise _sysid if zero to sender's id + if (_sysid == 0) { + _sysid.set(msg.sysid); + _automatic_sysid = true; + } + + // log lead's estimated vs reported position + DataFlash_Class::instance()->Log_Write("FOLL", + "TimeUS,Lat,Lon,Alt,VelN,VelE,VelD,LatE,LonE,AltE", // labels + "sDUmnnnDUm", // units + "F--B000--B", // mults + "QLLifffLLi", // fmt + AP_HAL::micros64(), + _target_location.lat, + _target_location.lng, + _target_location.alt, + (double)_target_velocity_ned.x, + (double)_target_velocity_ned.y, + (double)_target_velocity_ned.z, + loc_estimate.lat, + loc_estimate.lng, + loc_estimate.alt + ); + } +} + +// get velocity estimate in m/s in NED frame using dt since last update +bool AP_Follow::get_velocity_ned(Vector3f &vel_ned, float dt) const +{ + vel_ned = _target_velocity_ned + (_target_accel_ned * dt); + return true; +} + +// initialise offsets to provided distance vector to other vehicle (in meters in NED frame) if required +void AP_Follow::init_offsets_if_required(const Vector3f &dist_vec_ned) +{ + // return immediately if offsets have already been set + if (!_offset.get().is_zero()) { + return; + } + + float target_heading_deg; + if ((_offset_type == AP_FOLLOW_OFFSET_TYPE_RELATIVE) && get_target_heading(target_heading_deg)) { + // rotate offsets from north facing to vehicle's perspective + _offset = rotate_vector(-dist_vec_ned, -target_heading_deg); + } else { + // initialise offset in NED frame + _offset = -dist_vec_ned; + // ensure offset_type used matches frame of offsets saved + _offset_type = AP_FOLLOW_OFFSET_TYPE_NED; + } +} + +// get offsets in meters in NED frame +bool AP_Follow::get_offsets_ned(Vector3f &offset) const +{ + const Vector3f &off = _offset.get(); + + // if offsets are zero or type is NED, simply return offset vector + if (off.is_zero() || (_offset_type == AP_FOLLOW_OFFSET_TYPE_NED)) { + offset = off; + return true; + } + + // offset type is relative, exit if we cannot get vehicle's heading + float target_heading_deg; + if (!get_target_heading(target_heading_deg)) { + return false; + } + + // rotate offsets from vehicle's perspective to NED + offset = rotate_vector(off, target_heading_deg); + return true; +} + +// rotate 3D vector clockwise by specified angle (in degrees) +Vector3f AP_Follow::rotate_vector(const Vector3f &vec, float angle_deg) const +{ + // rotate roll, pitch input from north facing to vehicle's perspective + const float cos_yaw = cosf(radians(angle_deg)); + const float sin_yaw = sinf(radians(angle_deg)); + return Vector3f((vec.x * cos_yaw) - (vec.y * sin_yaw), (vec.y * cos_yaw) + (vec.x * sin_yaw), vec.z); +} + +// set recorded distance and bearing to target to zero +void AP_Follow::clear_dist_and_bearing_to_target() +{ + _dist_to_target = 0.0f; + _bearing_to_target = 0.0f; +} diff --git a/pool/shard008/C++/0096579_GameFieldText.cpp b/pool/shard008/C++/0096579_GameFieldText.cpp new file mode 100644 index 0000000000000000000000000000000000000000..30c16d079ddfaa8af1c4370a420ba7ed888e2b02 --- /dev/null +++ b/pool/shard008/C++/0096579_GameFieldText.cpp @@ -0,0 +1,190 @@ +#include "GameFieldText.h" +#include "Resources.h" +#include "textures.h" +#include +using std::to_string; + +GameFieldText::GameFieldText(Resources& _resources) : resources(_resources) { + nameTag.setFont(resources.gfx->typewriter); + nameTag.setCharacterSize(32); + readyText.setFont(resources.gfx->typewriter); + readyText.setCharacterSize(32); + readyText.setPosition(100, 75); readyText.setString("Ready"); + awayText.setFont(resources.gfx->typewriter); + awayText.setCharacterSize(48); + awayText.setPosition(110, 150); awayText.setString("Away"); + positionText.setFont(resources.gfx->typewriter); + positionText.setCharacterSize(48); + positionText.setPosition(130, 200); + countdownText.setFont(resources.gfx->typewriter); + countdownText.setCharacterSize(96); + countdownText.setPosition(130,210); + + comboText.setFont(resources.gfx->typewriter); comboText.setString("0"); + pendingText.setFont(resources.gfx->typewriter); pendingText.setString("0"); + bpmText.setFont(resources.gfx->typewriter); bpmText.setString("0"); + comboText.setCharacterSize(48); + comboText.setPosition(360,320); + pendingText.setCharacterSize(48); + pendingText.setPosition(360,500); + bpmText.setCharacterSize(48); + bpmText.setPosition(360, 420); + gameOverText.setFont(resources.gfx->typewriter); + gameOverText.setPosition(50,250); + gameOverText.setCharacterSize(48); + + comboTimer.setPosition(315, 290); + comboTimer.setFillColor(sf::Color(255,0,0)); + setComboTimer(0); + + combo = 0; pending = 0; bpm = 0; position = 0; countdown = 0; gameover = 0; + away = false; ready = false; + + setColor(resources.gfx->gameFieldTextColor); +} + +GameFieldText::GameFieldText(const GameFieldText& text) : resources(text.resources) { + nameTag=text.nameTag; readyText=text.readyText; awayText=text.awayText; positionText = text.positionText; + countdownText = text.countdownText; comboText = text.comboText; pendingText = text.pendingText; + bpmText = text.bpmText; gameOverText = text.gameOverText; + + comboTimer.setPosition(315, 240); + comboTimer.setFillColor(sf::Color(255,0,0)); + setComboTimer(0); + + combo = 0; pending = 0; bpm = 0; position = 0; countdown = 0; gameover = 0; + away = false; ready = false; +} + +void GameFieldText::setName(const std::string& n) { + std::lock_guard mute(fieldTextMutex); + name = n; + nameTag.setString(n); + short x = (310-nameTag.getLocalBounds().width)/2; + if (x<0) + x=0; + nameTag.setPosition(x, 555); +} + +void GameFieldText::setPosition(const int8_t _position) { + std::lock_guard mute(fieldTextMutex); + position = _position; + if (position == 1) + positionText.setString("1st"); + else if (position == 2) + positionText.setString("2nd"); + else if (position == 3) + positionText.setString("3rd"); + else if (position) + positionText.setString(to_string((int)position) + "th"); +} + +void GameFieldText::setCountdown(const int8_t _countdown) { + std::lock_guard mute(fieldTextMutex); + countdown = _countdown; + if (countdown) + countdownText.setString(to_string(countdown)); +} + +void GameFieldText::setGameover(const int8_t _gameover) { + std::lock_guard mute(fieldTextMutex); + gameover = _gameover; + if (gameover == 1) + gameOverText.setString("Game Over"); + else if (gameover == 2) + gameOverText.setString("Winner"); +} + +const float PI = 3.14159265; +bool GameFieldText::setComboTimer(uint8_t count) { + std::lock_guard mute(fieldTextMutex); + if (count>100) + count=100; + if (comboTimer.getPointCount() == static_cast(count+2)) + return false; + comboTimer.setPointCount(count+2); + + comboTimer.setPoint(0, sf::Vector2f(60, 60)); + for (int x=1; x<(count+2); x++) + comboTimer.setPoint(x, sf::Vector2f(60 + 60*cos((PI*2)/100 * (x-26)), 60 + 60*sin((PI*2)/100 * (x-26) ))); + + return true; +} + +void GameFieldText::setBpm(const uint16_t _bpm) { + std::lock_guard mute(fieldTextMutex); + if (bpm != _bpm) { + bpm = _bpm; + bpmText.setString(to_string(bpm)); + } +} + +void GameFieldText::setCombo(const uint8_t _combo) { + std::lock_guard mute(fieldTextMutex); + if (combo != _combo) { + combo = _combo; + comboText.setString(to_string(combo)); + } +} + +void GameFieldText::setPending(const uint8_t _pending) { + std::lock_guard mute(fieldTextMutex); + if (pending != _pending) { + pending = _pending; + pendingText.setString(to_string(pending)); + } +} + +void GameFieldText::setColor(sf::Color color) { + std::lock_guard mute(fieldTextMutex); + nameTag.setFillColor(color); + awayText.setFillColor(color); + positionText.setFillColor(color); + readyText.setFillColor(color); + comboText.setFillColor(color); + pendingText.setFillColor(color); + countdownText.setFillColor(color); + bpmText.setFillColor(color); + gameOverText.setFillColor(color); + + nameTag.setOutlineColor(color); + awayText.setOutlineColor(color); + positionText.setOutlineColor(color); + readyText.setOutlineColor(color); + comboText.setOutlineColor(color); + pendingText.setOutlineColor(color); + countdownText.setOutlineColor(color); + bpmText.setOutlineColor(color); + gameOverText.setOutlineColor(color); +} + +void GameFieldText::clear() { + setComboTimer(0); + setCombo(0); + setPending(0); + setBpm(0); + setPosition(0); + setCountdown(0); + setGameover(0); + ready=false; +} + +void GameFieldText::drawText() { + std::lock_guard mute(fieldTextMutex); + if (away) + texture->draw(awayText); + if (position) + texture->draw(positionText); + if (ready) + texture->draw(readyText); + if (countdown) + texture->draw(countdownText); + if (gameover) + texture->draw(gameOverText); + + texture->draw(nameTag); + texture->draw(comboTimer); + texture->draw(comboText); + texture->draw(pendingText); + texture->draw(bpmText); +} \ No newline at end of file diff --git a/pool/shard008/C++/0096580_opimport.cpp b/pool/shard008/C++/0096580_opimport.cpp new file mode 100644 index 0000000000000000000000000000000000000000..44084ae8a17d13b544344f940837cf461d62d40b --- /dev/null +++ b/pool/shard008/C++/0096580_opimport.cpp @@ -0,0 +1,239 @@ +/** + * @file opimport.cpp + * Import sample files from other ABI + * + * @remark Copyright 2002 OProfile authors + * @remark Read the file COPYING + * + * @author Graydon Hoare + */ + +#include "abi.h" +#include "odb.h" +#include "popt_options.h" +#include "op_sample_file.h" + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +using namespace std; + +namespace { + string output_filename; + string abi_filename; + bool verbose; + bool force; +}; + + +popt::option options_array[] = { + popt::option(verbose, "verbose", 'V', "verbose output"), + popt::option(output_filename, "output", 'o', "output to file", "filename"), + popt::option(abi_filename, "abi", 'a', "abi description", "filename"), + popt::option(force, "force", 'f', "force conversion, even if identical") +}; + + +struct extractor { + + abi const & theabi; + + unsigned char const * begin; + unsigned char const * end; + bool little_endian; + + explicit + extractor(abi const & a, unsigned char const * src, size_t len) + : theabi(a), begin(src), end(src + len) { + little_endian = theabi.need(string("little_endian")) == 1; + if (verbose) { + cerr << "source byte order is: " + << string(little_endian ? "little" : "big") + << " endian" << endl; + } + } + + template + void extract(T & targ, void const * src_, + char const * sz, char const * off); +}; + + +template +void extractor::extract(T & targ, void const * src_, + char const * sz, char const * off) +{ + unsigned char const * src = static_cast(src_) + + theabi.need(string(off)); + size_t nbytes = theabi.need(string(sz)); + + targ = 0; + if (nbytes == 0) + return; + + assert(nbytes <= sizeof(T)); + assert(src >= begin); + assert(src + nbytes <= end); + + if (verbose) { + ostringstream message; + message << hex << "get " << sz << " = " << nbytes + << " bytes @ " << off << " = " << (src - begin) + << " : "; + cerr << message.str(); + } + + if (little_endian) + while(nbytes--) + targ = (targ << 8) | src[nbytes]; + else + for(size_t i = 0; i < nbytes; ++i) + targ = (targ << 8) | src[i]; + + if (verbose) + cerr << " = " << targ << endl; +} + + +void import_from_abi(abi const & abi, void const * srcv, + size_t len, odb_t * dest) +{ + struct opd_header * head = + static_cast(odb_get_data(dest)); + unsigned char const * src = static_cast(srcv); + unsigned char const * const begin = src; + extractor ext(abi, src, len); + + memcpy(head->magic, src + abi.need("offsetof_header_magic"), 4); + + // begin extracting opd header + ext.extract(head->version, src, "sizeof_u32", "offsetof_header_version"); + ext.extract(head->cpu_type, src, "sizeof_u32", "offsetof_header_cpu_type"); + ext.extract(head->ctr_event, src, "sizeof_u32", "offsetof_header_ctr_event"); + ext.extract(head->ctr_um, src, "sizeof_u32", "offsetof_header_ctr_um"); + ext.extract(head->ctr_count, src, "sizeof_u32", "offsetof_header_ctr_count"); + ext.extract(head->is_kernel, src, "sizeof_u32", "offsetof_header_is_kernel"); + // "double" extraction is unlikely to work + head->cpu_speed = 0.0; + ext.extract(head->mtime, src, "sizeof_u64", "offsetof_header_mtime"); + ext.extract(head->cg_to_is_kernel, src, "sizeof_u32", + "offsetof_header_cg_to_is_kernel"); + ext.extract(head->anon_start, src, "sizeof_u32", + "offsetof_header_anon_start"); + ext.extract(head->cg_to_anon_start, src, "sizeof_u32", + "offsetof_header_cg_to_anon_start"); + src += abi.need("sizeof_struct_opd_header"); + // done extracting opd header + + // begin extracting necessary parts of descr + odb_node_nr_t node_nr; + ext.extract(node_nr, src, "sizeof_odb_node_nr_t", "offsetof_descr_current_size"); + src += abi.need("sizeof_odb_descr_t"); + // done extracting descr + + // skip node zero, it is reserved and contains nothing usefull + src += abi.need("sizeof_odb_node_t"); + + // begin extracting nodes + unsigned int step = abi.need("sizeof_odb_node_t"); + if (verbose) + cerr << "extracting " << node_nr << " nodes of " << step << " bytes each " << endl; + + assert(src + (node_nr * step) <= begin + len); + + for (odb_node_nr_t i = 1 ; i < node_nr ; ++i, src += step) { + odb_key_t key; + odb_value_t val; + ext.extract(key, src, "sizeof_odb_key_t", "offsetof_node_key"); + ext.extract(val, src, "sizeof_odb_value_t", "offsetof_node_value"); + int rc = odb_add_node(dest, key, val); + if (rc != EXIT_SUCCESS) { + cerr << strerror(rc) << endl; + exit(EXIT_FAILURE); + } + } + // done extracting nodes +} + + +int main(int argc, char const ** argv) +{ + + vector inputs; + popt::parse_options(argc, argv, inputs); + + if (inputs.size() != 1) { + cerr << "error: must specify exactly 1 input file" << endl; + exit(1); + } + + if (inputs[0].rfind(".jo") == inputs[0].size() - 3) { + if (verbose) { + cerr << "Found a .jo file. Import is not allowed or necessary. Done." << endl; + cerr << inputs[0] << endl; + } + // Silently exit with success. + exit(EXIT_SUCCESS); + } + + abi current_abi, input_abi; + + { + ifstream abi_file(abi_filename.c_str()); + if (!abi_file) { + cerr << "error: cannot open abi file " + << abi_filename << endl; + exit(1); + } + abi_file >> input_abi; + } + + if (!force && current_abi == input_abi) { + cerr << "input abi is identical to native. " + << "no conversion necessary." << endl; + exit(1); + } + + int in_fd; + struct stat statb; + void * in; + odb_t dest; + int rc; + + in_fd = open(inputs[0].c_str(), O_RDONLY); + assert(in_fd > 0); + assert(fstat(in_fd, &statb) == 0); + in = mmap(0, statb.st_size, PROT_READ, MAP_PRIVATE, in_fd, 0); + assert(in != (void *)-1); + + rc = odb_open(&dest, output_filename.c_str(), ODB_RDWR, + sizeof(struct opd_header)); + if (rc) { + cerr << "odb_open() fail:\n" + << strerror(rc) << endl; + exit(EXIT_FAILURE); + } + + try { + import_from_abi(input_abi, in, statb.st_size, &dest); + } catch (abi_exception & e) { + cerr << "caught abi exception: " << e.desc << endl; + } + + odb_close(&dest); + + assert(munmap(in, statb.st_size) == 0); +} diff --git a/pool/shard008/C++/0096581_OrderAmount.cpp b/pool/shard008/C++/0096581_OrderAmount.cpp new file mode 100644 index 0000000000000000000000000000000000000000..30bfd86dc1bcffe1fb4cba8bb435d71956fff04b --- /dev/null +++ b/pool/shard008/C++/0096581_OrderAmount.cpp @@ -0,0 +1,116 @@ +#include +QString OrderAmount::getAdjustFee() const { + return adjustFee; +} +void OrderAmount::setAdjustFee (QString adjustFee) { + this->adjustFee = adjustFee; +} + +QString OrderAmount::getDiscountFee() const { + return discountFee; +} +void OrderAmount::setDiscountFee (QString discountFee) { + this->discountFee = discountFee; +} + +qlonglong OrderAmount::getNum() const { + return num; +} +void OrderAmount::setNum (qlonglong num) { + this->num = num; +} + +qlonglong OrderAmount::getNumIid() const { + return numIid; +} +void OrderAmount::setNumIid (qlonglong numIid) { + this->numIid = numIid; +} + +qlonglong OrderAmount::getOid() const { + return oid; +} +void OrderAmount::setOid (qlonglong oid) { + this->oid = oid; +} + +QString OrderAmount::getPayment() const { + return payment; +} +void OrderAmount::setPayment (QString payment) { + this->payment = payment; +} + +QString OrderAmount::getPrice() const { + return price; +} +void OrderAmount::setPrice (QString price) { + this->price = price; +} + +QString OrderAmount::getPromotionName() const { + return promotionName; +} +void OrderAmount::setPromotionName (QString promotionName) { + this->promotionName = promotionName; +} + +qlonglong OrderAmount::getSkuId() const { + return skuId; +} +void OrderAmount::setSkuId (qlonglong skuId) { + this->skuId = skuId; +} + +QString OrderAmount::getSkuPropertiesName() const { + return skuPropertiesName; +} +void OrderAmount::setSkuPropertiesName (QString skuPropertiesName) { + this->skuPropertiesName = skuPropertiesName; +} + +QString OrderAmount::getTitle() const { + return title; +} +void OrderAmount::setTitle (QString title) { + this->title = title; +} + + +void OrderAmount::parseResponse() { + if (responseParser->hasName("adjust_fee")) { + adjustFee = responseParser->getStrByName("adjust_fee"); + } + if (responseParser->hasName("discount_fee")) { + discountFee = responseParser->getStrByName("discount_fee"); + } + if (responseParser->hasName("num")) { + num = responseParser->getNumByName("num"); + } + if (responseParser->hasName("num_iid")) { + numIid = responseParser->getNumByName("num_iid"); + } + if (responseParser->hasName("oid")) { + oid = responseParser->getNumByName("oid"); + } + if (responseParser->hasName("payment")) { + payment = responseParser->getStrByName("payment"); + } + if (responseParser->hasName("price")) { + price = responseParser->getStrByName("price"); + } + if (responseParser->hasName("promotion_name")) { + promotionName = responseParser->getStrByName("promotion_name"); + } + if (responseParser->hasName("sku_id")) { + skuId = responseParser->getNumByName("sku_id"); + } + if (responseParser->hasName("sku_properties_name")) { + skuPropertiesName = responseParser->getStrByName("sku_properties_name"); + } + if (responseParser->hasName("title")) { + title = responseParser->getStrByName("title"); + } + +} + diff --git a/pool/shard008/C++/0096582_test.cpp b/pool/shard008/C++/0096582_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fd517ad7441543161b2037b4e7f55d706a2b9231 --- /dev/null +++ b/pool/shard008/C++/0096582_test.cpp @@ -0,0 +1,133 @@ +/* +---------------------------------------------------------------------------+ + | The Mobile Robot Programming Toolkit (MRPT) | + | | + | http://www.mrpt.org/ | + | | + | Copyright (c) 2005-2013, Individual contributors, see AUTHORS file | + | Copyright (c) 2005-2013, MAPIR group, University of Malaga | + | Copyright (c) 2012-2013, University of Almeria | + | All rights reserved. | + | | + | Redistribution and use in source and binary forms, with or without | + | modification, are permitted provided that the following conditions are | + | met: | + | * Redistributions of source code must retain the above copyright | + | notice, this list of conditions and the following disclaimer. | + | * Redistributions in binary form must reproduce the above copyright | + | notice, this list of conditions and the following disclaimer in the | + | documentation and/or other materials provided with the distribution. | + | * Neither the name of the copyright holders nor the | + | names of its contributors may be used to endorse or promote products | + | derived from this software without specific prior written permission.| + | | + | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | + | 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED | + | TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR| + | PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS 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 +#include +#include + +using namespace mrpt; +using namespace mrpt::gui; +using namespace mrpt::opengl; +using namespace mrpt::math; + + +// ------------------------------------------------------ +// TestOpenGLVideo +// ------------------------------------------------------ +void TestOpenGLVideo() +{ + // Show to the user a list of possible camera drivers and creates and open the selected camera. + cout << "Please, select the input video file or camera...\n"; + + mrpt::hwdrivers::CCameraSensorPtr cam = mrpt::hwdrivers::prepareVideoSourceFromUserSelection(); + if (!cam) return; + + cout << "Video stream open OK\n"; + + // Create 3D window: + CDisplayWindow3D win("Demo of video textures with MRPT's OpenGL objects",640,480); + + // XY Grid + opengl::CGridPlaneXYPtr gl_ground = opengl::CGridPlaneXY::Create(-7,7,-7,7,0,1); + gl_ground->setColor(0.7,0.7,0.7); + + // An opengl plane with the video texture + opengl::CTexturedPlanePtr gl_plane1 = opengl::CTexturedPlane::Create(0,1,0,0.75); // 4/3 aspect ratio + opengl::CTexturedPlanePtr gl_plane2 = opengl::CTexturedPlane::Create(0,1,0,0.75); + opengl::CTexturedPlanePtr gl_plane3 = opengl::CTexturedPlane::Create(0,1,0,0.75); + + gl_plane1->setPose(mrpt::poses::CPose3D(0,0,1, DEG2RAD(0), DEG2RAD(0), DEG2RAD(-90))); + gl_plane2->setPose(mrpt::poses::CPose3D(1,0,1, DEG2RAD(120), DEG2RAD(0), DEG2RAD(-90))); + gl_plane3->setPose(mrpt::poses::CPose3D(0,0,1, DEG2RAD(60), DEG2RAD(0), DEG2RAD(-90))); + + win.setCameraZoom(5); + + // Insert objects in scene: + { + COpenGLScenePtr &theScene = win.get3DSceneAndLock(); + theScene->insert( gl_ground ); + theScene->insert( gl_plane1 ); + theScene->insert( gl_plane2 ); + theScene->insert( gl_plane3 ); + // IMPORTANT!!! IF NOT UNLOCKED, THE WINDOW WILL NOT BE UPDATED! + win.unlockAccess3DScene(); + } + win.repaint(); + + cout << "Close the window to end.\n"; + while (win.isOpen()) + { + win.addTextMessage(5,5, format("%.02fFPS", win.getRenderingFPS())); + mrpt::system::sleep(1); + + // Grab new video frame: + CObservationPtr obs = cam->getNextFrame(); + if (obs) + { + if (IS_CLASS(obs,CObservationImage)) + { + CObservationImagePtr o = CObservationImagePtr(obs); + win.get3DSceneAndLock(); + gl_plane1->assignImage( o->image ); + gl_plane2->assignImage( o->image ); + gl_plane3->assignImage( o->image ); + win.unlockAccess3DScene(); + win.repaint(); + } + } + } +} + +// ------------------------------------------------------ +// MAIN +// ------------------------------------------------------ +int main() +{ + try + { + TestOpenGLVideo(); + + return 0; + } catch (std::exception &e) + { + std::cout << "MRPT exception caught: " << e.what() << std::endl; + return -1; + } + catch (...) + { + printf("Untyped exception!!"); + return -1; + } +} diff --git a/pool/shard008/C++/0096584_csvr.cpp b/pool/shard008/C++/0096584_csvr.cpp new file mode 100644 index 0000000000000000000000000000000000000000..116d1c8534bf1a7ae2c33a28a962ad0e9a37e837 --- /dev/null +++ b/pool/shard008/C++/0096584_csvr.cpp @@ -0,0 +1,100 @@ +#include "csvr.hpp" +#include "utility/style.hpp" +#include "utility/common_utils.hpp" + +using style::Color; + +#include // For FLT_MAX as an internal error code +#include +#include +#include + + +csvr::csvr(std::string const& file_name, bool suppress_file_not_found) : + iFile{}, iLine(1) { + + auto file { std14::make_unique(file_name) }; + // Check if open successful + if (!file->is_open() && !suppress_file_not_found) { + std::cout << style::apply(Color::red) << "CSV file input failed. CSV file \'" << + file_name << "\' not found or open." << style::reset() << '\n'; + return; + } + + iFile = std::move(file); +} + +bool csvr::has_stream() const { + return iFile.get(); +} + +bool csvr::skip_next() { + return csvr::get_next(static_cast(nullptr)); +} + +bool csvr::get_next(int* rate) { + Real result; + bool success = get_next(&result); + if (success && rate) *rate = std::round(result); + return success; +} + +bool csvr::get_next(Real* pnRate) { + return csvr::get_real(*iFile, pnRate); +} + +bool csvr::get_real(std::istream& iFile, Real* pnRate) { + // tParam data from file to be "pushed" to pfRate + std::string tParam; int iLine = 0; + + char c; + while (iFile >> c) { + // Skip line comments + if (c == '#') { + iFile.ignore(std::numeric_limits::max(), '\n'); + tParam.clear(); + ++iLine; + } + // Parse only if not whitespace except for \n + else if (c != ' ' && c != '\t') + { + // Ignore non-numeric, non data seperator, non e, -, and + characters + if (!( (c >= '0' && c <= '9') || c == '.' || c == ',' || c == '\n' || + c == 'e' || c == '-' || c == '+') ) + { + iFile.ignore(std::numeric_limits::max(), ','); + tParam.clear(); + } + // If hit data seperator, add data to respective array + // '\n' is there in case there is no comma after last item + else if (c != ',' && c != '\n') { + tParam += c; + } + else if (!tParam.empty()) { + char* tInvalidAt; + Real tRate = strtold(tParam.c_str(), &tInvalidAt); + + // If found invalid while parsing + if (*tInvalidAt) + { + std::cout << style::apply(Color::red) << + "CSV parsing failed. Invalid data contained " + "at line " << "(unknown)" << "." << + style::reset() << '\n'; + return false; + } + // Else was success + if (pnRate) { *pnRate = tRate; } + return true; + } + } + + // Increment line counter + if (c == '\n') { + ++iLine; + } + } + + // End of file + return false; +} diff --git a/pool/shard008/C++/0096586_storage_monitor.cc b/pool/shard008/C++/0096586_storage_monitor.cc new file mode 100644 index 0000000000000000000000000000000000000000..6d27d3bdfc41534b2230ecf419f39675faa089cc --- /dev/null +++ b/pool/shard008/C++/0096586_storage_monitor.cc @@ -0,0 +1,185 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/storage_monitor/storage_monitor.h" + +#include "base/stl_util.h" +#include "base/strings/utf_string_conversions.h" +#include "chrome/browser/storage_monitor/removable_storage_observer.h" +#include "chrome/browser/storage_monitor/transient_device_ids.h" + +namespace chrome { + +static StorageMonitor* g_storage_monitor = NULL; + +StorageMonitor::Receiver::~Receiver() { +} + +class StorageMonitor::ReceiverImpl : public StorageMonitor::Receiver { + public: + explicit ReceiverImpl(StorageMonitor* notifications) + : notifications_(notifications) {} + + virtual ~ReceiverImpl() {} + + virtual void ProcessAttach(const StorageInfo& info) OVERRIDE; + + virtual void ProcessDetach(const std::string& id) OVERRIDE; + + virtual void MarkInitialized() OVERRIDE; + + private: + StorageMonitor* notifications_; +}; + +void StorageMonitor::ReceiverImpl::ProcessAttach(const StorageInfo& info) { + notifications_->ProcessAttach(info); +} + +void StorageMonitor::ReceiverImpl::ProcessDetach(const std::string& id) { + notifications_->ProcessDetach(id); +} + +void StorageMonitor::ReceiverImpl::MarkInitialized() { + notifications_->MarkInitialized(); +} + +StorageMonitor* StorageMonitor::GetInstance() { + return g_storage_monitor; +} + +std::vector StorageMonitor::GetAllAvailableStorages() const { + std::vector results; + + base::AutoLock lock(storage_lock_); + for (StorageMap::const_iterator it = storage_map_.begin(); + it != storage_map_.end(); + ++it) { + results.push_back(it->second); + } + return results; +} + +void StorageMonitor::EnsureInitialized(base::Closure callback) { + DCHECK(thread_checker_.CalledOnValidThread()); + if (initialized_) { + if (!callback.is_null()) + callback.Run(); + return; + } + + if (!callback.is_null()) { + on_initialize_callbacks_.push_back(callback); + } + + if (initializing_) + return; + + initializing_ = true; + Init(); +} + +bool StorageMonitor::IsInitialized() { + return initialized_; +} + +void StorageMonitor::AddObserver(RemovableStorageObserver* obs) { + observer_list_->AddObserver(obs); +} + +void StorageMonitor::RemoveObserver( + RemovableStorageObserver* obs) { + observer_list_->RemoveObserver(obs); +} + +std::string StorageMonitor::GetTransientIdForDeviceId( + const std::string& device_id) { + return transient_device_ids_->GetTransientIdForDeviceId(device_id); +} + +std::string StorageMonitor::GetDeviceIdForTransientId( + const std::string& transient_id) const { + return transient_device_ids_->DeviceIdFromTransientId(transient_id); +} + +void StorageMonitor::EjectDevice( + const std::string& device_id, + base::Callback callback) { + // Platform-specific implementations will override this method to + // perform actual device ejection. + callback.Run(EJECT_FAILURE); +} + +StorageMonitor::StorageMonitor() + : observer_list_(new ObserverListThreadSafe()), + initializing_(false), + initialized_(false), + transient_device_ids_(new TransientDeviceIds) { + receiver_.reset(new ReceiverImpl(this)); + + DCHECK(!g_storage_monitor); + g_storage_monitor = this; +} + +StorageMonitor::~StorageMonitor() { + g_storage_monitor = NULL; +} + +// static +void StorageMonitor::RemoveSingletonForTesting() { + g_storage_monitor = NULL; +} + +StorageMonitor::Receiver* StorageMonitor::receiver() const { + return receiver_.get(); +} + +void StorageMonitor::MarkInitialized() { + initialized_ = true; + for (std::vector::iterator iter = + on_initialize_callbacks_.begin(); + iter != on_initialize_callbacks_.end(); ++iter) { + iter->Run(); + } + on_initialize_callbacks_.clear(); +} + +void StorageMonitor::ProcessAttach(const StorageInfo& info) { + { + base::AutoLock lock(storage_lock_); + if (ContainsKey(storage_map_, info.device_id())) { + // This can happen if our unique id scheme fails. Ignore the incoming + // non-unique attachment. + return; + } + storage_map_.insert(std::make_pair(info.device_id(), info)); + } + + DVLOG(1) << "RemovableStorageAttached with name " << UTF16ToUTF8(info.name()) + << " and id " << info.device_id(); + if (StorageInfo::IsRemovableDevice(info.device_id())) { + observer_list_->Notify( + &RemovableStorageObserver::OnRemovableStorageAttached, info); + } +} + +void StorageMonitor::ProcessDetach(const std::string& id) { + StorageInfo info; + { + base::AutoLock lock(storage_lock_); + StorageMap::iterator it = storage_map_.find(id); + if (it == storage_map_.end()) + return; + info = it->second; + storage_map_.erase(it); + } + + DVLOG(1) << "RemovableStorageDetached for id " << id; + if (StorageInfo::IsRemovableDevice(info.device_id())) { + observer_list_->Notify( + &RemovableStorageObserver::OnRemovableStorageDetached, info); + } +} + +} // namespace chrome diff --git a/pool/shard008/C++/0096587_point_set_read_xyz.cpp b/pool/shard008/C++/0096587_point_set_read_xyz.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d206bfc88c94d4b294a8c7ad3ce85873e0501c88 --- /dev/null +++ b/pool/shard008/C++/0096587_point_set_read_xyz.cpp @@ -0,0 +1,47 @@ +#include +#include +#include + +#include +#include + +typedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel; +typedef Kernel::FT FT; +typedef Kernel::Point_3 Point; +typedef Kernel::Vector_3 Vector; + +typedef CGAL::Point_set_3 Point_set; + +int main (int argc, char** argv) +{ + std::ifstream f (argc > 1 ? argv[1] : "data/oni.xyz"); + + Point_set point_set; + + // Reading input in XYZ format + if (!f || !CGAL::read_xyz_point_set (f, point_set)) + { + std::cerr << "Can't read input file " << std::endl; + return EXIT_FAILURE; + } + + if (point_set.has_normal_map()) + { + // Normalization + inversion of normal vectors + for (Point_set::iterator it = point_set.begin(); it != point_set.end(); ++ it) + { + Vector n = point_set.normal(*it); + n = - n / std::sqrt (n * n); + point_set.normal(*it) = n; + } + } + + // Writing result in OFF format + std::ofstream out("normalized_normals.off"); + if (!out || !CGAL::write_off_point_set (out, point_set)) + { + return EXIT_FAILURE; + } + + return EXIT_SUCCESS; +} diff --git a/pool/shard008/C++/0096589_utils.cpp b/pool/shard008/C++/0096589_utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8d9673df170d17556d42bea3ef420fb41402d1a1 --- /dev/null +++ b/pool/shard008/C++/0096589_utils.cpp @@ -0,0 +1,31 @@ +#include "utils.hpp" + +std::string replace(std::string source, std::string target, std::string replacement) { + size_t start = source.find(target); + + if (start != std::string::npos) { + size_t end = start + target.size(); + std::string left = source.substr(0, start); + std::string right = source.substr(end, source.size() - end); + return left + replacement + right; + } + + return source; +} + +std::string params(std::vector params_) { + if (params_.size() == 0) + return ""; + + std::string source = params_[0]; + + for (size_t i = 1; i < params_.size(); ++i) { + source += ", " + params_[i]; + } + + return source; +} + +std::string braces(std::string inner) { + return "{" + inner + "}"; +} diff --git a/pool/shard008/C++/0096590_configsettingslog.cpp b/pool/shard008/C++/0096590_configsettingslog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..47dcfc141c1aada2ed04be29dae6e16cc9b798b9 --- /dev/null +++ b/pool/shard008/C++/0096590_configsettingslog.cpp @@ -0,0 +1,153 @@ +#include "configsettingslog.h" +#include "util.h" +#include "configsettings.h" +#include "logfile.h" +#include +#include +#include +#include + +using namespace std; + +void ConfigSettingsLog::addConfigSettings(double t, const ConfigSettings &config) +{ + string timeString = strprintf("%10.10f", t); + + if (m_configLog.size() == 0) // first entry + { + vector keys; + config.getKeys(keys); + + for (size_t k = 0 ; k < keys.size() ; k++) + { + string key = keys[k]; + string value; + bool used = false; + + if (!config.getStringKeyValue(key, value, used)) + abortWithMessage("Unexpected error: couldn't retrieve config value for key '" + key + "' even though it was reported to exist"); + + vector initialValue { value }; + m_configLog[key] = initialValue; + } + + vector initialTime { timeString }; + m_configLog["t"] = initialTime; + } + else + { + const size_t numEntries = m_configLog.begin()->second.size(); + + vector keys; + config.getKeys(keys); + + for (size_t k = 0 ; k < keys.size() ; k++) + { + string key = keys[k]; + string value; + bool used = false; + + if (!config.getStringKeyValue(key, value, used)) + abortWithMessage("Unexpected error: couldn't retrieve config value for key '" + key + "' even though it was reported to exist"); + + auto it = m_configLog.find(key); + + if (it == m_configLog.end()) // not found yet, add empty entry + { + vector empty; + + m_configLog[key] = empty; + it = m_configLog.find(key); + } + + vector &knownValues = it->second; + if (knownValues.size() < numEntries) + { + const size_t s = knownValues.size(); + + for (size_t i = s ; i < numEntries ; i++) + knownValues.push_back("NA"); + } + + // Finally, add the current value + knownValues.push_back(value); + } + + // And log the time + m_configLog["t"].push_back(timeString); + + /* + for (auto it = m_configLog.begin() ; it != m_configLog.end() ; ++it) + { + cout << it->first; + for (auto it2 = it->second.begin() ; it2 != it->second.end() ; ++it2) + cout << "\t" << *it2; + cout << endl; + } + + abortWithMessage("TODO"); + */ + } + +} + +map > ConfigSettingsLog::m_configLog; + +void ConfigSettingsLog::writeConfigSettings(LogFile &s) +{ + if (!s.isOpen()) // no logging requested + return; + + list keys; + + // Order the keys, but skip 't' for now + for (auto it = m_configLog.begin() ; it != m_configLog.end() ; ++it) + { + string key = it->first; + + if (key != "t") + keys.push_back(key); + } + + // Order the keys + keys.sort(); + + // Make sure 't' is first + keys.push_front("t"); + + bool first = true; + for (auto it = keys.begin() ; it != keys.end() ; ++it) + { + if (!first) + s.printNoNewLine(","); + s.printNoNewLine("\"%s\"", it->c_str()); + first = false; + } + s.print(""); + + const size_t numEntries = m_configLog["t"].size(); + for (size_t i = 0 ; i < numEntries ; i++) + { + bool first = true; + for (auto it = keys.begin() ; it != keys.end() ; ++it) + { + if (!first) + s.printNoNewLine(","); + + vector &vals = m_configLog[*it]; + if (vals.size() != numEntries) + abortWithMessage(strprintf("key %s, numEntries: %d vals.size(): %d", it->c_str(), (int)numEntries, (int)vals.size())); + + assert(vals.size() == numEntries); + + string value = vals[i]; + if (value.find(",") != string::npos) + value = "\"" + value + "\""; + + s.printNoNewLine("%s", value.c_str()); + first = false; + } + s.print(""); + } +} + diff --git a/pool/shard008/C++/0096597_config_test.cc b/pool/shard008/C++/0096597_config_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..4e6dd6a7683a85fc077e6bcadb8c5f5128f67601 --- /dev/null +++ b/pool/shard008/C++/0096597_config_test.cc @@ -0,0 +1,43 @@ +// Copyright 2017 The Abseil Authors. +// +// 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 "absl/base/config.h" + +#include + +#include "gtest/gtest.h" + +namespace { + +TEST(ConfigTest, Endianness) { + union { + uint32_t value; + uint8_t data[sizeof(uint32_t)]; + } number; + number.data[0] = 0x00; + number.data[1] = 0x01; + number.data[2] = 0x02; + number.data[3] = 0x03; +#if defined(ABSL_IS_LITTLE_ENDIAN) && defined(ABSL_IS_BIG_ENDIAN) +#error Both ABSL_IS_LITTLE_ENDIAN and ABSL_IS_BIG_ENDIAN are defined +#elif defined(ABSL_IS_LITTLE_ENDIAN) + EXPECT_EQ(UINT32_C(0x03020100), number.value); +#elif defined(ABSL_IS_BIG_ENDIAN) + EXPECT_EQ(UINT32_C(0x00010203), number.value); +#else +#error Unknown endianness +#endif +} + +} // namespace diff --git a/pool/shard008/C++/0096598_iwEconomicProgress.cpp b/pool/shard008/C++/0096598_iwEconomicProgress.cpp new file mode 100644 index 0000000000000000000000000000000000000000..52bb1c199b1d8f596ebc14235a42b01c14a04db6 --- /dev/null +++ b/pool/shard008/C++/0096598_iwEconomicProgress.cpp @@ -0,0 +1,219 @@ +// Copyright (c) 2005 - 2020 Settlers Freaks (sf-team at siedler25.org) +// +// This file is part of Return To The Roots. +// +// Return To The Roots is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 2 of the License, or +// (at your option) any later version. +// +// Return To The Roots 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 General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with Return To The Roots. If not, see . + +#include "iwEconomicProgress.h" +#include "EconomyModeHandler.h" +#include "EventManager.h" +#include "GamePlayer.h" +#include "GlobalGameSettings.h" +#include "Loader.h" +#include "Settings.h" +#include "WindowManager.h" +#include "addons/const_addons.h" +#include "controls/ctrlButton.h" +#include "controls/ctrlOptionGroup.h" +#include "controls/ctrlText.h" +#include "controls/ctrlTextDeepening.h" +#include "iwHelp.h" +#include "network/GameClient.h" +#include "world/GameWorldBase.h" +#include "world/GameWorldViewer.h" +#include "gameData/const_gui_ids.h" + +constexpr Extent wareIconSize(26, 26); +constexpr unsigned txtBoxWidth = 63; +constexpr Extent padding1(11, 21); // Left, Top +constexpr Extent padding2(11, 18); // Right, Bottom +constexpr unsigned teamRectHeight = 24; +constexpr unsigned extraSpacing = 2; + +iwEconomicProgress::iwEconomicProgress(const GameWorldViewer& gwv) + : IngameWindow(CGI_ECONOMICPROGRESS, IngameWindow::posLastOrCenter, + Extent(0, 0) /*will be resized inside the constructor*/, _("Economic progress"), + LOADER.GetImageN("resource", 41)), + gwv(gwv) +{ + const unsigned textcolor[] = {COLOR_GREEN, COLOR_YELLOW, COLOR_RED}; + const GameWorldBase& world = gwv.GetWorld(); + EconomyModeHandler* eH = world.econHandler.get(); + + // resize window + Extent size(padding1.x + wareIconSize.x + (std::max((int)eH->GetTeams().size(), 2) + 1) * txtBoxWidth + padding2.x, + padding1.y + teamRectHeight + ((int)eH->GetGoodTypesToCollect().size() + 1) * wareIconSize.y + + extraSpacing * 2 + padding2.y); + this->Resize(size); + + AddText(1, DrawPoint(padding1.x + wareIconSize.x, padding1.y + teamRectHeight), _("Player"), COLOR_GREEN, + FontStyle::LEFT | FontStyle::BOTTOM, NormalFont); + + // determine team display order (main player team first) + for(const auto& curTeam : eH->GetTeams()) + { + if(curTeam.containsPlayer(gwv.GetPlayer().GetPlayerId())) + { + teamOrder.push_back(&curTeam); + break; + } + } + for(const auto& curTeam : eH->GetTeams()) + { + if(&curTeam != teamOrder[0]) + { + teamOrder.push_back(&curTeam); + } + } + + // the goods table + const std::vector& goodsToCollect = eH->GetGoodTypesToCollect(); + DrawPoint curBoxPos(padding1.x, padding1.y + teamRectHeight + extraSpacing); + for(unsigned i = 0; i < goodsToCollect.size(); i++) + { + GoodType good = goodsToCollect[i]; + + AddImage(100 + i, curBoxPos + wareIconSize / 2, LOADER.GetMapImageN(2298), _(WARE_NAMES[good])); + const DrawPoint warePos = curBoxPos + wareIconSize / 2; + AddImage(200 + i, warePos, LOADER.GetMapImageN(WARES_TEX_MAP_OFFSET + good)); + + DrawPoint curTxtPos = curBoxPos + DrawPoint(wareIconSize.x, 0); + for(unsigned j = 0; j < 1 + eH->GetTeams().size(); j++) + { + AddTextDeepening(300 + (MAX_PLAYERS + 2) * j + i, curTxtPos, Extent(txtBoxWidth, wareIconSize.y), TC_GREY, + "?", NormalFont, textcolor[j < 2 ? j : 2]); + curTxtPos.x += txtBoxWidth; + } + curBoxPos.y += wareIconSize.y; + } + + if(!eH->isInfinite()) + { + // game progress display + AddText(2, DrawPoint(wareIconSize.x + extraSpacing + padding1.x, this->GetSize().y - padding2.y), + _("Time remaining:"), COLOR_ORANGE, FontStyle::LEFT | FontStyle::BOTTOM, NormalFont); + txtRemainingTime = + AddText(3, DrawPoint(wareIconSize.x + extraSpacing + txtBoxWidth * 3, this->GetSize().y - padding2.y), "%", + COLOR_ORANGE, FontStyle::RIGHT | FontStyle::BOTTOM, NormalFont); + } + + // help button + AddImageButton(25, DrawPoint(padding1.x, this->GetSize().y - wareIconSize.y - padding2.y), wareIconSize, TC_GREY, + LOADER.GetImageN("io", 225), _("Help")); +} + +iwEconomicProgress::~iwEconomicProgress() = default; + +void iwEconomicProgress::Draw_() +{ + IngameWindow::Draw_(); + + if(IsMinimized()) + return; + + // draw team colors + DrawPoint curTeamRectPos = GetDrawPos() + DrawPoint(padding1.x + wareIconSize.x + txtBoxWidth, padding1.y); + for(auto& team : teamOrder) + { + unsigned ystep = teamRectHeight / team->playersInTeam.count(); + unsigned ypos = 0; + for(unsigned i = 0; i < gwv.GetWorld().GetNumPlayers(); ++i) + { + if(team->containsPlayer(i)) + { + if(teamRectHeight - ypos < 2 * ystep) + ystep = teamRectHeight - ypos; + DrawRectangle(Rect(curTeamRectPos + DrawPoint(0, ypos), Extent(txtBoxWidth - 1, ystep)), + gwv.GetWorld().GetPlayer(i).color); + ypos += ystep; + } + } + curTeamRectPos.x += txtBoxWidth; + } +} + +void iwEconomicProgress::Msg_ButtonClick(const unsigned ctrl_id) +{ + switch(ctrl_id) + { + break; + case 25: // help + { + WINDOWMANAGER.ReplaceWindow( + std::make_unique(_("This window shows the wares that should be collected for " + "the economy mode. Displayed is the current inventory of " + "the player, his team and after game end of the opponent " + "teams."))); + } + break; + } +} + +void iwEconomicProgress::Msg_PaintBefore() +{ + IngameWindow::Msg_PaintBefore(); + + const GameWorldBase& world = gwv.GetWorld(); + EconomyModeHandler* eH = world.econHandler.get(); + const std::vector& economyModeTeams = eH->GetTeams(); + const GamePlayer& mainPlayer = gwv.GetPlayer(); + + RTTR_Assert(economyModeTeams.size() == teamOrder.size()); + + // make sure the amounts are current + eH->UpdateAmounts(); + + // update table elements + for(unsigned i = 0; i < eH->GetGoodTypesToCollect().size(); i++) + { + for(unsigned j = 0; j < 1 + economyModeTeams.size(); j++) + { + auto* text = GetCtrl(300 + (MAX_PLAYERS + 2) * j + i); + if(j == 0) + { + text->SetText(std::to_string(eH->GetAmount(i, mainPlayer.GetPlayerId()))); + } else if(j == 1 || eH->showAllTeamAmounts()) + { + text->SetText(std::to_string(teamOrder[j - 1]->amountsTheTeamCollected[i])); + + // White color when all teams are shown to mark good types that the team has won or is leading in + if(eH->showAllTeamAmounts() && teamOrder[j - 1]->amountsTheTeamCollected[i] >= eH->GetMaxTeamAmount(i)) + { + text->SetTextColor(COLOR_WHITE); + } else + { + if(j == 1) + text->SetTextColor(COLOR_YELLOW); + else + text->SetTextColor(COLOR_RED); + } + } else + { + text->SetText("???"); + } + } + } + + if(!eH->isInfinite()) + { + // Refresh game progress tracker + if(!eH->isOver()) + { + txtRemainingTime->SetText(GAMECLIENT.FormatGFTime(eH->GetEndFrame() - world.GetEvMgr().GetCurrentGF())); + } else + { + txtRemainingTime->SetText(GAMECLIENT.FormatGFTime(0)); + } + } +} diff --git a/pool/shard008/C++/0096599_web_animation_impl.cc b/pool/shard008/C++/0096599_web_animation_impl.cc new file mode 100644 index 0000000000000000000000000000000000000000..1c15bc3170db8e0c3ab56bc5eedf31e53a5b7666 --- /dev/null +++ b/pool/shard008/C++/0096599_web_animation_impl.cc @@ -0,0 +1,96 @@ +// Copyright 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "webkit/renderer/compositor_bindings/web_animation_impl.h" + +#include "cc/animation/animation.h" +#include "cc/animation/animation_curve.h" +#include "cc/animation/animation_id_provider.h" +#include "third_party/WebKit/public/platform/WebAnimation.h" +#include "third_party/WebKit/public/platform/WebAnimationCurve.h" +#include "webkit/renderer/compositor_bindings/web_float_animation_curve_impl.h" +#include "webkit/renderer/compositor_bindings/web_transform_animation_curve_impl.h" + +using cc::Animation; +using cc::AnimationIdProvider; + +using WebKit::WebAnimationCurve; + +namespace webkit { + +WebAnimationImpl::WebAnimationImpl(const WebAnimationCurve& web_curve, + TargetProperty target_property, + int animation_id, + int group_id) { + if (!animation_id) + animation_id = AnimationIdProvider::NextAnimationId(); + if (!group_id) + group_id = AnimationIdProvider::NextGroupId(); + + WebAnimationCurve::AnimationCurveType curve_type = web_curve.type(); + scoped_ptr curve; + switch (curve_type) { + case WebAnimationCurve::AnimationCurveTypeFloat: { + const WebFloatAnimationCurveImpl* float_curve_impl = + static_cast(&web_curve); + curve = float_curve_impl->CloneToAnimationCurve(); + break; + } + case WebAnimationCurve::AnimationCurveTypeTransform: { + const WebTransformAnimationCurveImpl* transform_curve_impl = + static_cast(&web_curve); + curve = transform_curve_impl->CloneToAnimationCurve(); + break; + } + } + animation_ = Animation::Create( + curve.Pass(), + animation_id, + group_id, + static_cast(target_property)); +} + +WebAnimationImpl::~WebAnimationImpl() {} + +int WebAnimationImpl::id() { return animation_->id(); } + +WebKit::WebAnimation::TargetProperty WebAnimationImpl::targetProperty() const { + return static_cast( + animation_->target_property()); +} + +int WebAnimationImpl::iterations() const { return animation_->iterations(); } + +void WebAnimationImpl::setIterations(int n) { animation_->set_iterations(n); } + +double WebAnimationImpl::startTime() const { return animation_->start_time(); } + +void WebAnimationImpl::setStartTime(double monotonic_time) { + animation_->set_start_time(monotonic_time); +} + +double WebAnimationImpl::timeOffset() const { + return animation_->time_offset(); +} + +void WebAnimationImpl::setTimeOffset(double monotonic_time) { + animation_->set_time_offset(monotonic_time); +} + +bool WebAnimationImpl::alternatesDirection() const { + return animation_->alternates_direction(); +} + +void WebAnimationImpl::setAlternatesDirection(bool alternates) { + animation_->set_alternates_direction(alternates); +} + +scoped_ptr WebAnimationImpl::CloneToAnimation() { + scoped_ptr to_return( + animation_->Clone(cc::Animation::NonControllingInstance)); + to_return->set_needs_synchronized_start_time(true); + return to_return.Pass(); +} + +} // namespace webkit diff --git a/pool/shard008/C++/0096601_Ccel.cpp b/pool/shard008/C++/0096601_Ccel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..304311bcc86f6c362bc85cd57e07e67c69e4373a --- /dev/null +++ b/pool/shard008/C++/0096601_Ccel.cpp @@ -0,0 +1,43 @@ +#include "Ccel.h" +#include "Genome.h" +#include "Chemspace.h" +#include "Protein.h" +#include +#include +using namespace std; + + +Ccel::~Ccel() +{ + if(_genome) delete _genome; +} + +void Ccel::update() +{ + _genome->clear(); + + for(int i=0; i<_chemspace->size();i++) + { + _genome->bind(_chemspace->get(i)); + } + _chemspace=_genome->refresh_content(_chemspace); +} + +Ccel::Ccel(Genome* genome) +{ +_genome= genome; +_chemspace= new Chemspace(0); +} + +void Ccel::print() const +{ + // + baby->update(); + + cout << endl << "======updated==========" << endl << endl; + + baby->print(); + _genome -> print(); + // cout << "============= Chemspace ==============" << endl; + _chemspace->print(); +} diff --git a/pool/shard008/C++/0096603_ShortCardSprite.cpp b/pool/shard008/C++/0096603_ShortCardSprite.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5d818d4326d43a32e14b77e01d7ec357bab9f9c6 --- /dev/null +++ b/pool/shard008/C++/0096603_ShortCardSprite.cpp @@ -0,0 +1,75 @@ +#include "ShortCardSprite.h" + +ShortCardSprite::ShortCardSprite() +{ + +} + +ShortCardSprite::~ShortCardSprite() +{ + +} +ShortCardSprite* ShortCardSprite::create(int type, int value) +{ + ShortCardSprite *pRet = new(std::nothrow) ShortCardSprite(); + if (pRet && pRet->init(type, value)) + { + pRet->autorelease(); + return pRet; + } + else + { + delete pRet; + pRet = nullptr; + return nullptr; + } + return nullptr; +} + +bool ShortCardSprite::init(int type, int value) +{ + if (!Node::init()) + { + return false; + } + _cardData.m_Type = type; + _cardData.m_Value = value; + + initUI(type, value); + + this->setState(ShortCardSprite::CardState::ONTouch); //都能触摸 + this->setsortState(ShortCardSprite::SortState::ONE_CARD);//默认单张牌 + + return true; +} + +void ShortCardSprite::initUI(int type, int value) +{ + Sprite *card; + if (type == 0) + { + card = Sprite::create(StringUtils::format("duanpai_x%d.png", value)); + card->setScale(0.8f); + } + else if (type == 1) + { + card = Sprite::create(StringUtils::format("duanpai_d%d.png", value)); + card->setScale(0.8f); + } + addChild(card); + + this->setContentSize(card->getContentSize() *0.8f); +} + +CardData* ShortCardSprite::getCardData() +{ + return &_cardData; +} + +void ShortCardSprite::setCardOpacity(GLubyte opacity) +{ + for (auto &_child : getChildren()) + { + _child->setOpacity(opacity); + } +} \ No newline at end of file diff --git a/pool/shard008/C++/0096604_boss_zuramat.cpp b/pool/shard008/C++/0096604_boss_zuramat.cpp new file mode 100644 index 0000000000000000000000000000000000000000..408a7083383cb6e9899c2dbc795d684e32af7d23 --- /dev/null +++ b/pool/shard008/C++/0096604_boss_zuramat.cpp @@ -0,0 +1,230 @@ +/* + * Copyright (C) 2008-2012 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program 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 General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#include "ScriptMgr.h" +#include "ScriptedCreature.h" +#include "violet_hold.h" + +enum Spells +{ + SPELL_SHROUD_OF_DARKNESS = 54524, + H_SPELL_SHROUD_OF_DARKNESS = 59745, + SPELL_SUMMON_VOID_SENTRY = 54369, + SPELL_VOID_SHIFT = 54361, + H_SPELL_VOID_SHIFT = 59743, + + SPELL_ZURAMAT_ADD_2 = 54342, + H_SPELL_ZURAMAT_ADD_2 = 59747 +}; + +enum ZuramatCreatures +{ + CREATURE_VOID_SENTRY = 29364 +}; + +enum Yells +{ + SAY_AGGRO = -1608037, + SAY_SLAY_1 = -1608038, + SAY_SLAY_2 = -1608039, + SAY_SLAY_3 = -1608040, + SAY_DEATH = -1608041, + SAY_SPAWN = -1608042, + SAY_SHIELD = -1608043, + SAY_WHISPER = -1608044 +}; + +#define DATA_VOID_DANCE 2153 + +class boss_zuramat : public CreatureScript +{ +public: + boss_zuramat() : CreatureScript("boss_zuramat") { } + + CreatureAI* GetAI(Creature* creature) const + { + return new boss_zuramatAI (creature); + } + + struct boss_zuramatAI : public ScriptedAI + { + boss_zuramatAI(Creature* creature) : ScriptedAI(creature) + { + instance = creature->GetInstanceScript(); + } + + InstanceScript* instance; + + uint32 SpellVoidShiftTimer; + uint32 SpellSummonVoidTimer; + uint32 SpellShroudOfDarknessTimer; + bool voidDance; + + void Reset() + { + if (instance) + { + if (instance->GetData(DATA_WAVE_COUNT) == 6) + instance->SetData(DATA_1ST_BOSS_EVENT, NOT_STARTED); + else if (instance->GetData(DATA_WAVE_COUNT) == 12) + instance->SetData(DATA_2ND_BOSS_EVENT, NOT_STARTED); + } + + SpellShroudOfDarknessTimer = 22000; + SpellVoidShiftTimer = 15000; + SpellSummonVoidTimer = 12000; + voidDance = true; + } + + void AttackStart(Unit* who) + { + if (me->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC) || me->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE)) + return; + + if (me->Attack(who, true)) + { + me->AddThreat(who, 0.0f); + me->SetInCombatWith(who); + who->SetInCombatWith(me); + DoStartMovement(who); + } + } + + void EnterCombat(Unit* /*who*/) + { + DoScriptText(SAY_AGGRO, me); + if (instance) + { + if (GameObject* pDoor = instance->instance->GetGameObject(instance->GetData64(DATA_ZURAMAT_CELL))) + if (pDoor->GetGoState() == GO_STATE_READY) + { + EnterEvadeMode(); + return; + } + if (instance->GetData(DATA_WAVE_COUNT) == 6) + instance->SetData(DATA_1ST_BOSS_EVENT, IN_PROGRESS); + else if (instance->GetData(DATA_WAVE_COUNT) == 12) + instance->SetData(DATA_2ND_BOSS_EVENT, IN_PROGRESS); + } + } + + void MoveInLineOfSight(Unit* /*who*/) {} + + void UpdateAI(const uint32 diff) + { + //Return since we have no target + if (!UpdateVictim()) + return; + + if (SpellSummonVoidTimer <= diff) + { + DoCast(me->getVictim(), SPELL_SUMMON_VOID_SENTRY, false); + SpellSummonVoidTimer = 20000; + } else SpellSummonVoidTimer -=diff; + + if (SpellVoidShiftTimer <= diff) + { + if (Unit* unit = SelectTarget(SELECT_TARGET_RANDOM, 0)) + DoCast(unit, SPELL_VOID_SHIFT); + SpellVoidShiftTimer = 20000; + } else SpellVoidShiftTimer -=diff; + + if (SpellShroudOfDarknessTimer <= diff) + { + DoCast(me->getVictim(), SPELL_SHROUD_OF_DARKNESS); + SpellShroudOfDarknessTimer = 20000; + } else SpellShroudOfDarknessTimer -=diff; + + DoMeleeAttackIfReady(); + } + + void SummonedCreatureDies(Creature* summoned, Unit* /*who*/) + { + if (summoned->GetEntry() == CREATURE_VOID_SENTRY) + voidDance = false; + } + + uint32 GetData(uint32 type) const + { + if (type == DATA_VOID_DANCE) + return voidDance ? 1 : 0; + + return 0; + } + + void JustDied(Unit* /*killer*/) + { + DoScriptText(SAY_DEATH, me); + + if (instance) + { + if (instance->GetData(DATA_WAVE_COUNT) == 6) + { + instance->SetData(DATA_1ST_BOSS_EVENT, DONE); + instance->SetData(DATA_WAVE_COUNT, 7); + } + else if (instance->GetData(DATA_WAVE_COUNT) == 12) + { + instance->SetData(DATA_2ND_BOSS_EVENT, DONE); + instance->SetData(DATA_WAVE_COUNT, 13); + } + } + } + + void KilledUnit(Unit* victim) + { + if (victim == me) + return; + + DoScriptText(RAND(SAY_SLAY_1, SAY_SLAY_2, SAY_SLAY_3), me); + } + + void JustSummoned(Creature* summon) + { + summon->AI()->AttackStart(me->getVictim()); + summon->AI()->DoCastAOE(SPELL_ZURAMAT_ADD_2); + summon->SetPhaseMask(17, true); + } + }; + +}; + +class achievement_void_dance : public AchievementCriteriaScript +{ + public: + achievement_void_dance() : AchievementCriteriaScript("achievement_void_dance") + { + } + + bool OnCheck(Player* /*player*/, Unit* target) + { + if (!target) + return false; + + if (Creature* Zuramat = target->ToCreature()) + if (Zuramat->AI()->GetData(DATA_VOID_DANCE)) + return true; + + return false; + } +}; + +void AddSC_boss_zuramat() +{ + new boss_zuramat(); + new achievement_void_dance(); +} diff --git a/pool/shard008/C++/0096605_tactionmanager.cpp b/pool/shard008/C++/0096605_tactionmanager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e90eb03c9703800d2b5dc805a0360a44ed8d31be --- /dev/null +++ b/pool/shard008/C++/0096605_tactionmanager.cpp @@ -0,0 +1,240 @@ +/*************************************************************************** + * Project TUPITUBE DESK * + * Project Contact: info@maefloresta.com * + * Project Website: http://www.maefloresta.com * + * Project Leader: Gustav Gonzalez * + * * + * Developers: * + * 2010: * + * Gustavo Gonzalez / xtingray * + * * + * KTooN's versions: * + * * + * 2006: * + * David Cuadrado * + * Jorge Cuadrado * + * 2003: * + * Fernado Roldan * + * Simena Dinas * + * * + * Copyright (C) 2010 Gustav Gonzalez - http://www.maefloresta.com * + * License: * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program 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 General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program. If not, see . * + ***************************************************************************/ + +#include "tactionmanager.h" + +/** + * Create an actions manager + */ +TActionManager::TActionManager(QObject *parent) : QObject(parent) +{ + setObjectName("TActionManager" + parent->objectName()); +} + +/** + * Destructor + */ +TActionManager::~TActionManager() +{ +} + +/** + * Inserts an action within the manager + */ +bool TActionManager::insert(QAction *action, const QString &_id, const QString &container) +{ + /* + #ifdef TUP_DEBUG + qDebug() << "TActionManager::insert() - _id -> " << _id; + qDebug() << "TActionManager::insert() - container -> " << container; + #endif + */ + + QString id = _id.toLower(); + if (id.isEmpty() || container.isEmpty()) + return false; + + QAction *a = (m_actionContainer[container])[id]; + if (a == action) { + #ifdef TUP_DEBUG + qDebug() << "TActionManager::insert() - Fatal Error: Cannot insert action with id -> " + id; + #endif + + return false; + } + + action->setParent(this); + m_actionContainer[container].insert(id, action); + + return true; +} + +/** + * Removes an action from the manager + */ +void TActionManager::remove(QAction* action, const QString &container) +{ + delete take(action, container); +} + +/** + * Remueve una accion del manejador retornando dicha accion. + * @param action para remover + * @return la accion removida o cero si esta no estaba en el manejador + */ +QAction *TActionManager::take(QAction* action, const QString &container) +{ + QAction *actionItem = nullptr; + QString id = m_actionContainer[container].key(action); + + if (! container.isEmpty()) { + if (m_actionContainer[container].contains(id)) + actionItem = m_actionContainer[container].take(id); + } else { + foreach (QString key, m_actionContainer.keys()) { + if (m_actionContainer[key].contains(id)) { + actionItem = m_actionContainer[key].take(id); + break; + } + } + } + + if (!actionItem || actionItem != action) + return nullptr; + + return actionItem; +} + +/** + * Busca una accion en el manejardor. + * @param id asociado a la accion + * @return la accion requeriada + */ +QAction *TActionManager::find(const QString &_id, const QString &container) const +{ + /* + #ifdef TUP_DEBUG + qDebug() << "TActionManager::find() - _id -> " << _id; + #endif + */ + + QAction *action = nullptr; + QString id = _id.toLower(); + + if (!container.isEmpty()) { + if (m_actionContainer[container].contains(id)) + action = m_actionContainer[container][id]; + } else { + foreach (QString key, m_actionContainer.keys()) { + if (m_actionContainer[key].contains(id)) { + action =m_actionContainer[key][id]; + break; + } + } + } + + if (action == nullptr) { + #ifdef TUP_DEBUG + qDebug() << "TActionManager::find() - Fatal Error: Returning NULL action: " << id << " in " << container; + #endif + } + + return action; +} + +/** + * Retorna la accion asociada a id + * @param id + */ +QAction *TActionManager::operator[](const QString &id) const +{ + return find(id); +} + +/** + * Retorna la accion asociada a id + * @param id + */ +void TActionManager::enable(const QString &id, bool flag) +{ + QAction *action = find(id); + if (action != 0) + action->setEnabled(flag); +} + +/** + * Exec the action defined by id + * @param id + */ +void TActionManager::exec(const QString &id) +{ + QAction *action = find(id); + if (action != 0) { + action->toggle(); + action->setChecked(true); + } +} + +QMenuBar *TActionManager::setupMenuBar(QMenuBar *menuBar, const QStringList &containers, bool clear) +{ + if (menuBar) { + if (clear) + menuBar->clear(); + } else { + menuBar = new QMenuBar(0); + } + + foreach (QString container, containers) + menuBar->addMenu(setupMenu(0, container, clear)); + + return menuBar; +} + +QMenu *TActionManager::setupMenu(QMenu *menu, const QString &container, bool clear) +{ + if (!menu) + menu = new QMenu(container); + + if (clear) + menu->clear(); + + foreach (QAction *action, m_actionContainer[container]) { + if (action) + menu->addAction(action); + } + + return menu; +} + +QToolBar *TActionManager::setupToolBar(QToolBar *toolBar, const QString &container, bool clear) +{ + if (!toolBar) + toolBar = new QToolBar(); + + if (clear) + toolBar->clear(); + + foreach (QAction *a, m_actionContainer[container]) { + if (a) + toolBar->addAction(a); + } + + if (m_actionContainer.count() == 0) + toolBar->hide(); + else + toolBar->show(); + + return toolBar; +} diff --git a/pool/shard008/C++/0096606_qprinterinfo_mac.cpp b/pool/shard008/C++/0096606_qprinterinfo_mac.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bbf790424cbe0716d64036b3abe223be4225886a --- /dev/null +++ b/pool/shard008/C++/0096606_qprinterinfo_mac.cpp @@ -0,0 +1,237 @@ +/**************************************************************************** +** +** Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtGui module of the Qt Toolkit. +** +** Commercial Usage +** Licensees holding valid Qt Commercial licenses may use this file in +** accordance with the Qt Commercial License Agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and Nokia. +** +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License versions 2.0 or 3.0 as published by the Free +** Software Foundation and appearing in the file LICENSE.GPL included in +** the packaging of this file. Please review the following information +** to ensure GNU General Public Licensing requirements will be met: +** http://www.fsf.org/licensing/licenses/info/GPLv2.html and +** http://www.gnu.org/copyleft/gpl.html. In addition, as a special +** exception, Nokia gives you certain additional rights. These rights +** are described in the Nokia Qt GPL Exception version 1.3, included in +** the file GPL_EXCEPTION.txt in this package. +** +** Qt for Windows(R) Licensees +** As a special exception, Nokia, as the sole copyright holder for Qt +** Designer, grants users of the Qt/Eclipse Integration plug-in the +** right for the Qt/Eclipse Integration to link to functionality +** provided by Qt Designer and its related libraries. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** +****************************************************************************/ + +#include "qprinterinfo.h" + +#include "private/qt_mac_p.h" + +QT_BEGIN_NAMESPACE + +#ifndef QT_NO_PRINTER + +class QPrinterInfoPrivate +{ +Q_DECLARE_PUBLIC(QPrinterInfo) +public: + ~QPrinterInfoPrivate(); + QPrinterInfoPrivate(); + QPrinterInfoPrivate(const QString& name); + +private: + QPrinterInfo* q_ptr; + + QString m_name; + bool m_default; + bool m_isNull; +}; + +static QPrinterInfoPrivate nullQPrinterInfoPrivate; + +extern QPrinter::PaperSize qSizeFTopaperSize(const QSizeF& size); + +///////////////////////////////////////////////////////////////////////////// +///////////////////////////////////////////////////////////////////////////// + +QList QPrinterInfo::availablePrinters() +{ + QList printers; + + OSStatus status = noErr; + QCFType printerList; + status = PMServerCreatePrinterList(kPMServerLocal, &printerList); + if (status == noErr) { + CFIndex count = CFArrayGetCount(printerList); + for (CFIndex i=0; i(const_cast(CFArrayGetValueAtIndex(printerList, i))); + QString name = QCFString::toQString(PMPrinterGetName(printer)); + printers.append(QPrinterInfo(name)); + if (PMPrinterIsDefault(printer)) { + printers[i].d_ptr->m_default = true; + } + } + } + + return printers; +} + +QPrinterInfo QPrinterInfo::defaultPrinter(){ + QList printers = availablePrinters(); + for (int c = 0; c < printers.size(); ++c) { + if (printers[c].isDefault()) { + return printers[c]; + } + } + return QPrinterInfo(); +} + +///////////////////////////////////////////////////////////////////////////// +///////////////////////////////////////////////////////////////////////////// + +QPrinterInfo::QPrinterInfo(const QPrinter& prn) +{ + d_ptr = &nullQPrinterInfoPrivate; + QList list = availablePrinters(); + for (int c = 0; c < list.size(); ++c) { + if (prn.printerName() == list[c].printerName()) { + *this = list[c]; + return; + } + } + + *this = QPrinterInfo(); +} + +QPrinterInfo::~QPrinterInfo() +{ + if (d_ptr != &nullQPrinterInfoPrivate) + delete d_ptr; +} + +QPrinterInfo::QPrinterInfo() +{ + d_ptr = &nullQPrinterInfoPrivate; +} + +QPrinterInfo::QPrinterInfo(const QString& name) +{ + d_ptr = new QPrinterInfoPrivate(name); + d_ptr->q_ptr = this; +} + +QPrinterInfo::QPrinterInfo(const QPrinterInfo& src) +{ + d_ptr = &nullQPrinterInfoPrivate; + *this = src; +} + +QPrinterInfo& QPrinterInfo::operator=(const QPrinterInfo& src) +{ + Q_ASSERT(d_ptr); + if (d_ptr != &nullQPrinterInfoPrivate) + delete d_ptr; + d_ptr = new QPrinterInfoPrivate(*src.d_ptr); + d_ptr->q_ptr = this; + return *this; +} + +QString QPrinterInfo::printerName() const +{ + const Q_D(QPrinterInfo); + return d->m_name; +} + +bool QPrinterInfo::isNull() const +{ + const Q_D(QPrinterInfo); + return d->m_isNull; +} + +bool QPrinterInfo::isDefault() const +{ + const Q_D(QPrinterInfo); + return d->m_default; +} + +QList QPrinterInfo::supportedPaperSizes() const +{ +#if (MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_4) + return QList(); +#else + if (QSysInfo::MacintoshVersion <= QSysInfo::MV_10_4) + return QList(); + + const Q_D(QPrinterInfo); + + PMPrinter cfPrn = PMPrinterCreateFromPrinterID( + QCFString::toCFStringRef(d->m_name)); + + if (!cfPrn) return QList(); + + CFArrayRef array; + OSStatus status = PMPrinterGetPaperList(cfPrn, &array); + + if (status != 0) { + PMRelease(cfPrn); + return QList(); + } + + QList paperList; + int count = CFArrayGetCount(array); + for (int c = 0; c < count; c++) { + PMPaper paper = static_cast( + const_cast( + CFArrayGetValueAtIndex(array, c))); + double width, height; + status = PMPaperGetWidth(paper, &width); + status |= PMPaperGetHeight(paper, &height); + if (status != 0) continue; + + QSizeF size(width * 0.3527, height * 0.3527); + paperList.append(qSizeFTopaperSize(size)); + } + + PMRelease(cfPrn); + + return paperList; +#endif // MAC_OS_X_VERSION_MAX_ALLOWED +} + +///////////////////////////////////////////////////////////////////////////// +///////////////////////////////////////////////////////////////////////////// + +QPrinterInfoPrivate::QPrinterInfoPrivate() : + q_ptr(NULL), + m_default(false), + m_isNull(true) +{ +} + +QPrinterInfoPrivate::QPrinterInfoPrivate(const QString& name) : + q_ptr(NULL), + m_name(name), + m_default(false), + m_isNull(false) +{ +} + +QPrinterInfoPrivate::~QPrinterInfoPrivate() +{ +} + +#endif // QT_NO_PRINTER + +QT_END_NAMESPACE diff --git a/pool/shard008/C++/0096607_scraper.cpp b/pool/shard008/C++/0096607_scraper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b29b28bd29509054ceca057c73e58df937a28ae0 --- /dev/null +++ b/pool/shard008/C++/0096607_scraper.cpp @@ -0,0 +1,105 @@ +#include "scraper.h" +#include "logging.h" +#include + +Scraper::Scraper( QObject *parent ) + : QObject( parent ), + current_count( 0 ) { + hit_ratio = 3 / 4.0; + request_count = 0; + m_expressions = ( QStringList() << "-" + << "\\" + << "/" + << "!" + << "." + << "?" + << ":" + ); + network_manager = new QNetworkAccessManager( this ); + connect( network_manager, &QNetworkAccessManager::finished, this, &Scraper::processRequest ); + connect( network_manager, &QNetworkAccessManager::networkAccessibleChanged, this, &Scraper::handleNetworkChanged ); + +} + +Scraper::~Scraper() { + delete network_manager; +} + +void Scraper::setHitRatio( qreal ratio ) { + hit_ratio = ratio; +} + +void Scraper::setRequestCount( int count ) { + request_count = count; +} + +QStringList Scraper::expressions() { + return m_expressions; +} + +QNetworkAccessManager *Scraper::networkManager() { + return network_manager; +} + +void Scraper::setBaseUrl( QString base_url ) { + m_base_url = base_url; +} + +QString Scraper::baseUrl() { + return m_base_url; +} + +QString Scraper::cleanString( QString string ) { + QStringList str_list = string.split( " " ); + + for( int i = 0; i < str_list.length(); ++i ) { + if( str_list.at( i ).contains( "(" ) ) { + if( str_list.at( i ).contains( ")" ) ) { + str_list.removeAt( i ); + } else { + str_list.removeAll( "(" ); + } + } + } + + QString new_str = str_list.join( " " ); + + for( int i = 0; i < expressions().length(); i++ ) { + new_str.remove( expressions().at( i ) ); + } + + QString stringNormalized = new_str.normalized( QString::NormalizationForm_KD ); + stringNormalized.remove( QRegExp( "[^a-zA-Z\\s]" ) ); + + return stringNormalized.toLower(); +} + +void Scraper::processRequest( QNetworkReply *reply ) { + Q_UNUSED( reply ); +} + +void Scraper::getGameData( Scraper::ScraperContext context ) { + Q_UNUSED( context ); +} + +void Scraper::handleNetworkChanged( QNetworkAccessManager::NetworkAccessibility accessible ) { + QString result; + + if( accessible == QNetworkAccessManager::NotAccessible ) { + result = "The Network isn't working"; + } + + else if( accessible == QNetworkAccessManager::Accessible ) { + result = "The Network is running"; + } + + else { + result = "The Network is unknown"; + } + + qDebug() << result; + emit label( result ); + + +} + diff --git a/pool/shard008/C++/0096612_delegating_renderer_unittest.cc b/pool/shard008/C++/0096612_delegating_renderer_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..bd538862313b6ba88a6abbcde6aeb0622bcec668 --- /dev/null +++ b/pool/shard008/C++/0096612_delegating_renderer_unittest.cc @@ -0,0 +1,136 @@ +// Copyright 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "cc/output/delegating_renderer.h" + +#include "cc/test/fake_output_surface.h" +#include "cc/test/layer_tree_test.h" +#include "cc/test/render_pass_test_common.h" +#include "cc/test/render_pass_test_utils.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace cc { + +class DelegatingRendererTest : public LayerTreeTest { + public: + DelegatingRendererTest() : LayerTreeTest(), output_surface_(NULL) {} + virtual ~DelegatingRendererTest() {} + + virtual scoped_ptr CreateOutputSurface() OVERRIDE { + scoped_ptr context3d = + TestWebGraphicsContext3D::Create( + WebKit::WebGraphicsContext3D::Attributes()); + context3d_ = context3d.get(); + scoped_ptr output_surface = + FakeOutputSurface::CreateDelegating3d( + context3d.PassAs()); + output_surface_ = output_surface.get(); + return output_surface.PassAs(); + } + + protected: + TestWebGraphicsContext3D* context3d_; + FakeOutputSurface* output_surface_; +}; + +class DelegatingRendererTestDraw : public DelegatingRendererTest { + public: + virtual void BeginTest() OVERRIDE { + layer_tree_host()->SetPageScaleFactorAndLimits(1.f, 0.5f, 4.f); + PostSetNeedsCommitToMainThread(); + } + + virtual void AfterTest() OVERRIDE {} + + virtual bool PrepareToDrawOnThread( + LayerTreeHostImpl*, LayerTreeHostImpl::FrameData* frame, bool result) + OVERRIDE { + EXPECT_EQ(0u, output_surface_->num_sent_frames()); + + CompositorFrame& last_frame = output_surface_->last_sent_frame(); + EXPECT_FALSE(last_frame.delegated_frame_data); + EXPECT_FALSE(last_frame.gl_frame_data); + EXPECT_EQ(0.f, last_frame.metadata.min_page_scale_factor); + EXPECT_EQ(0.f, last_frame.metadata.max_page_scale_factor); + return true; + } + + virtual void DrawLayersOnThread(LayerTreeHostImpl* host_impl) OVERRIDE { + EXPECT_EQ(1u, output_surface_->num_sent_frames()); + + CompositorFrame& last_frame = output_surface_->last_sent_frame(); + DelegatedFrameData* last_frame_data = last_frame.delegated_frame_data.get(); + ASSERT_TRUE(last_frame.delegated_frame_data); + EXPECT_FALSE(last_frame.gl_frame_data); + EXPECT_EQ( + gfx::Rect(host_impl->device_viewport_size()).ToString(), + last_frame_data->render_pass_list.back()->output_rect.ToString()); + EXPECT_EQ(0.5f, last_frame.metadata.min_page_scale_factor); + EXPECT_EQ(4.f, last_frame.metadata.max_page_scale_factor); + + EXPECT_EQ( + 0u, last_frame.delegated_frame_data->resource_list.size()); + EXPECT_EQ(1u, last_frame.delegated_frame_data->render_pass_list.size()); + + EndTest(); + } +}; + +SINGLE_AND_MULTI_THREAD_TEST_F(DelegatingRendererTestDraw) + +class DelegatingRendererTestResources : public DelegatingRendererTest { + public: + virtual void BeginTest() OVERRIDE { + PostSetNeedsCommitToMainThread(); + } + + virtual void AfterTest() OVERRIDE {} + + virtual bool PrepareToDrawOnThread( + LayerTreeHostImpl* host_impl, + LayerTreeHostImpl::FrameData* frame, + bool result) OVERRIDE { + + frame->render_passes.clear(); + frame->render_passes_by_id.clear(); + + TestRenderPass* child_pass = addRenderPass( + frame->render_passes, + RenderPass::Id(2, 1), + gfx::Rect(3, 3, 10, 10), + gfx::Transform()); + child_pass->AppendOneOfEveryQuadType( + host_impl->resource_provider(), RenderPass::Id(0, 0)); + + TestRenderPass* pass = addRenderPass( + frame->render_passes, + RenderPass::Id(1, 1), + gfx::Rect(3, 3, 10, 10), + gfx::Transform()); + pass->AppendOneOfEveryQuadType( + host_impl->resource_provider(), child_pass->id); + return true; + } + + virtual void DrawLayersOnThread(LayerTreeHostImpl* host_impl) OVERRIDE { + EXPECT_EQ(1u, output_surface_->num_sent_frames()); + + CompositorFrame& last_frame = output_surface_->last_sent_frame(); + ASSERT_TRUE(last_frame.delegated_frame_data); + + EXPECT_EQ(2u, last_frame.delegated_frame_data->render_pass_list.size()); + // Each render pass has 7 resources in it. And the root render pass has a + // mask resource used when drawing the child render pass. The number 7 may + // change if AppendOneOfEveryQuadType is updated, and the value here should + // be updated accordingly. + EXPECT_EQ( + 15u, last_frame.delegated_frame_data->resource_list.size()); + + EndTest(); + } +}; + +SINGLE_AND_MULTI_THREAD_TEST_F(DelegatingRendererTestResources) + +} // namespace cc diff --git a/pool/shard008/C++/0096614_disk_backed_queue.cc b/pool/shard008/C++/0096614_disk_backed_queue.cc new file mode 100644 index 0000000000000000000000000000000000000000..7bc246cfe39be2db184ae20c7ca0032ac0f8b54e --- /dev/null +++ b/pool/shard008/C++/0096614_disk_backed_queue.cc @@ -0,0 +1,167 @@ +// Copyright 2010-2013 RethinkDB, all rights reserved. +#include "containers/disk_backed_queue.hpp" + +#include "arch/io/disk.hpp" +#include "buffer_cache/blob.hpp" +#include "buffer_cache/buffer_cache.hpp" +#include "buffer_cache/serialize_onto_blob.hpp" +#include "serializer/config.hpp" + +internal_disk_backed_queue_t::internal_disk_backed_queue_t(io_backender_t *io_backender, + const serializer_filepath_t &filename, + perfmon_collection_t *stats_parent) + : perfmon_membership(stats_parent, &perfmon_collection, + filename.permanent_path().c_str()), + queue_size(0), + head_block_id(NULL_BLOCK_ID), + tail_block_id(NULL_BLOCK_ID) { + filepath_file_opener_t file_opener(filename, io_backender); + standard_serializer_t::create(&file_opener, + standard_serializer_t::static_config_t()); + + serializer.init(new standard_serializer_t(standard_serializer_t::dynamic_config_t(), + &file_opener, + &perfmon_collection)); + + /* Remove the file we just created from the filesystem, so that it will + get deleted as soon as the serializer is destroyed or if the process + crashes. */ + file_opener.unlink_serializer_file(); + + /* Create the cache. */ + cache_t::create(serializer.get()); + + mirrored_cache_config_t cache_dynamic_config; + cache_dynamic_config.max_size = MEGABYTE; + cache_dynamic_config.max_dirty_size = MEGABYTE / 2; + cache.init(new cache_t(serializer.get(), cache_dynamic_config, &perfmon_collection)); +} + +internal_disk_backed_queue_t::~internal_disk_backed_queue_t() { } + +void internal_disk_backed_queue_t::push(const write_message_t &wm) { + mutex_t::acq_t mutex_acq(&mutex); + + // First, we need a transaction. + transaction_t txn(cache.get(), + rwi_write, + 2, + repli_timestamp_t::distant_past, + cache_order_source.check_in("push"), + WRITE_DURABILITY_SOFT /* No need for durability with unlinked dbq file. */); + + if (head_block_id == NULL_BLOCK_ID) { + add_block_to_head(&txn); + } + + scoped_ptr_t _head(new buf_lock_t(&txn, head_block_id, rwi_write)); + queue_block_t *head = reinterpret_cast(_head->get_data_write()); + + char buffer[MAX_REF_SIZE]; + memset(buffer, 0, MAX_REF_SIZE); + + blob_t blob(txn.get_cache()->get_block_size(), buffer, MAX_REF_SIZE); + + write_onto_blob(&txn, &blob, wm); + + if (static_cast((head->data + head->data_size) - reinterpret_cast(head)) + blob.refsize(cache->get_block_size()) > cache->get_block_size().value()) { + // The data won't fit in our current head block, so it's time to make a new one. + head = NULL; + _head.reset(); + add_block_to_head(&txn); + _head.init(new buf_lock_t(&txn, head_block_id, rwi_write)); + head = reinterpret_cast(_head->get_data_write()); + } + + memcpy(head->data + head->data_size, buffer, blob.refsize(cache->get_block_size())); + head->data_size += blob.refsize(cache->get_block_size()); + + queue_size++; +} + +void internal_disk_backed_queue_t::pop(buffer_group_viewer_t *viewer) { + guarantee(size() != 0); + mutex_t::acq_t mutex_acq(&mutex); + + char buffer[MAX_REF_SIZE]; + transaction_t txn(cache.get(), + rwi_write, + 2, + repli_timestamp_t::distant_past, + cache_order_source.check_in("pop"), + WRITE_DURABILITY_SOFT /* No durability for unlinked dbq file. */); + + scoped_ptr_t _tail(new buf_lock_t(&txn, tail_block_id, rwi_write)); + queue_block_t *tail = reinterpret_cast(_tail->get_data_write()); + rassert(tail->data_size != tail->live_data_offset); + + /* Grab the data from the blob and delete it. */ + + memcpy(buffer, tail->data + tail->live_data_offset, blob::ref_size(cache->get_block_size(), tail->data + tail->live_data_offset, MAX_REF_SIZE)); + std::vector data_vec; + + blob_t blob(txn.get_cache()->get_block_size(), buffer, MAX_REF_SIZE); + { + blob_acq_t acq_group; + buffer_group_t blob_group; + blob.expose_all(&txn, rwi_read, &blob_group, &acq_group); + + viewer->view_buffer_group(const_view(&blob_group)); + } + + /* Record how far along in the blob we are. */ + tail->live_data_offset += blob.refsize(cache->get_block_size()); + + blob.clear(&txn); + + queue_size--; + + /* If that was the last blob in this block move on to the next one. */ + if (tail->live_data_offset == tail->data_size) { + _tail.reset(); + remove_block_from_tail(&txn); + } +} + +bool internal_disk_backed_queue_t::empty() { + return queue_size == 0; +} + +int64_t internal_disk_backed_queue_t::size() { + return queue_size; +} + +void internal_disk_backed_queue_t::add_block_to_head(transaction_t *txn) { + buf_lock_t _new_head(txn); + queue_block_t *new_head = reinterpret_cast(_new_head.get_data_write()); + if (head_block_id == NULL_BLOCK_ID) { + rassert(tail_block_id == NULL_BLOCK_ID); + head_block_id = tail_block_id = _new_head.get_block_id(); + } else { + buf_lock_t _old_head(txn, head_block_id, rwi_write); + queue_block_t *old_head = reinterpret_cast(_old_head.get_data_write()); + rassert(old_head->next == NULL_BLOCK_ID); + old_head->next = _new_head.get_block_id(); + head_block_id = _new_head.get_block_id(); + } + + new_head->next = NULL_BLOCK_ID; + new_head->data_size = 0; + new_head->live_data_offset = 0; +} + +void internal_disk_backed_queue_t::remove_block_from_tail(transaction_t *txn) { + rassert(tail_block_id != NULL_BLOCK_ID); + buf_lock_t _old_tail(txn, tail_block_id, rwi_write); + queue_block_t *old_tail = reinterpret_cast(_old_tail.get_data_write()); + + if (old_tail->next == NULL_BLOCK_ID) { + rassert(head_block_id == _old_tail.get_block_id()); + tail_block_id = head_block_id = NULL_BLOCK_ID; + } else { + tail_block_id = old_tail->next; + } + + _old_tail.mark_deleted(); +} + diff --git a/pool/shard008/C++/0096615_ServerView.cpp b/pool/shard008/C++/0096615_ServerView.cpp new file mode 100644 index 0000000000000000000000000000000000000000..912774bdb640f0a4ed391780cff96e3878443882 --- /dev/null +++ b/pool/shard008/C++/0096615_ServerView.cpp @@ -0,0 +1,96 @@ +// ServerView.cpp : implementation of the CServerView class +// + +#include "stdafx.h" +#include "Server.h" + +#include "ServerDoc.h" +#include "ServerView.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// CServerView + +IMPLEMENT_DYNCREATE(CServerView, CEditView) + +BEGIN_MESSAGE_MAP(CServerView, CEditView) + //{{AFX_MSG_MAP(CServerView) + // NOTE - the ClassWizard will add and remove mapping macros here. + // DO NOT EDIT what you see in these blocks of generated code! + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// CServerView construction/destruction + +CServerView::CServerView() +{ + // TODO: add construction code here + +} + +CServerView::~CServerView() +{ +} + +BOOL CServerView::PreCreateWindow(CREATESTRUCT& cs) +{ + // TODO: Modify the Window class or styles here by modifying + // the CREATESTRUCT cs + + BOOL bPreCreated = CEditView::PreCreateWindow(cs); + cs.style &= ~(ES_AUTOHSCROLL|WS_HSCROLL); // Enable word-wrapping + cs.style |= ES_READONLY; + + return bPreCreated; +} + +///////////////////////////////////////////////////////////////////////////// +// CServerView drawing + +void CServerView::OnDraw(CDC* pDC) +{ + CServerDoc* pDoc = GetDocument(); + ASSERT_VALID(pDoc); + + // TODO: add draw code for native data here +} + +///////////////////////////////////////////////////////////////////////////// +// CServerView diagnostics + +#ifdef _DEBUG +void CServerView::AssertValid() const +{ + CEditView::AssertValid(); +} + +void CServerView::Dump(CDumpContext& dc) const +{ + CEditView::Dump(dc); +} + +CServerDoc* CServerView::GetDocument() // non-debug version is inline +{ + ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CServerDoc))); + return (CServerDoc*)m_pDocument; +} +#endif //_DEBUG + +///////////////////////////////////////////////////////////////////////////// +// CServerView message handlers + +void CServerView::AddLine(LPCTSTR strLine) +{ + CEdit& edit = GetEditCtrl(); + int LastLine=edit.GetLineCount() - 1; + + edit.SetSel(edit.LineIndex(LastLine),-1); + CString Line = strLine; + edit.ReplaceSel(Line+"\r\n"); +} diff --git a/pool/shard008/C++/0096625_test_put_object_async.cpp b/pool/shard008/C++/0096625_test_put_object_async.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5d21242ab967d40cce19b8242b93fea3274552f4 --- /dev/null +++ b/pool/shard008/C++/0096625_test_put_object_async.cpp @@ -0,0 +1,106 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX - License - Identifier: Apache - 2.0 + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +int main() +{ + Aws::SDKOptions options; + Aws::InitAPI(options); + { + // 1/4. Create the Amazon S3 bucket. + // Create a unique bucket name to increase the chance of success + // when trying to create the bucket. + // Format: "my-bucket-" + lowercase UUID. + Aws::S3::Model::BucketLocationConstraint region = + Aws::S3::Model::BucketLocationConstraint::us_east_1; + + Aws::Client::ClientConfiguration config; + config.region = "us-east-1"; + Aws::S3::S3Client s3_client(config); + + Aws::String uuid = Aws::Utils::UUID::RandomUUID(); + Aws::String bucket_name = "my-bucket-" + + Aws::Utils::StringUtils::ToLower(uuid.c_str()); + + Aws::S3::Model::CreateBucketRequest create_bucket_request; + create_bucket_request.SetBucket(bucket_name); + + Aws::S3::Model::CreateBucketOutcome create_bucket_outcome = + s3_client.CreateBucket(create_bucket_request); + + if (!create_bucket_outcome.IsSuccess()) + { + std::cout << "Error: PutObjectAsync test setup: Create bucket '" << + bucket_name << "': " << + create_bucket_outcome.GetError().GetMessage() << std::endl; + std::cout << "No cleanup needed." << std::endl; + + return 1; + } + + // 2/4. Add an object to the bucket. + char* file_name = "my-file.txt"; + + std::ofstream myFile(file_name); + myFile << "My content."; + myFile.close(); + + if (!AwsDoc::S3::PutObjectAsync(s3_client, bucket_name, file_name, "us-east-1")) + { + std::cout << "Error: PutObjectAsync test. To clean up, you must " + "delete the bucket '" << bucket_name << + "' yourself." << std::endl; + + return 1; + } + + // 3/4. Delete the object from the bucket. + Aws::S3::Model::DeleteObjectRequest delete_object_request; + delete_object_request.SetBucket(bucket_name); + delete_object_request.SetKey(file_name); + + Aws::S3::Model::DeleteObjectOutcome delete_object_outcome = + s3_client.DeleteObject(delete_object_request); + + if (!delete_object_outcome.IsSuccess()) + { + std::cout << "Error: PutObjectAsync test cleanup: Delete object '" << + file_name << "' from bucket '" << bucket_name << "': " << + delete_object_outcome.GetError().GetMessage() << std::endl; + std::cout << "To clean up, you must delete the bucket '" << + bucket_name << "' yourself." << std::endl; + + return 1; + } + + // 4/4. Delete the bucket. + Aws::S3::Model::DeleteBucketRequest delete_bucket_request; + delete_bucket_request.SetBucket(bucket_name); + + Aws::S3::Model::DeleteBucketOutcome delete_bucket_outcome = + s3_client.DeleteBucket(delete_bucket_request); + + if (!delete_bucket_outcome.IsSuccess()) + { + std::cout << "Error: PutObjectAsync test cleanup: Delete bucket: " << + delete_bucket_outcome.GetError().GetMessage() << std::endl; + std::cout << "To clean up, you must delete the bucket '" << + bucket_name << "' yourself." << std::endl; + + return 1; + } + } + Aws::ShutdownAPI(options); + + return 0; +} \ No newline at end of file diff --git a/pool/shard008/C/0133547_phy-hisi-inno-usb2.c b/pool/shard008/C/0133547_phy-hisi-inno-usb2.c new file mode 100644 index 0000000000000000000000000000000000000000..9b16f13b5ab29791c24ed529f59cf1564e701543 --- /dev/null +++ b/pool/shard008/C/0133547_phy-hisi-inno-usb2.c @@ -0,0 +1,185 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* + * HiSilicon INNO USB2 PHY Driver. + * + * Copyright (c) 2016-2017 HiSilicon Technologies Co., Ltd. + */ + +#include +#include +#include +#include +#include +#include +#include + +#define INNO_PHY_PORT_NUM 2 +#define REF_CLK_STABLE_TIME 100 /* unit:us */ +#define UTMI_CLK_STABLE_TIME 200 /* unit:us */ +#define TEST_CLK_STABLE_TIME 2 /* unit:ms */ +#define PHY_CLK_STABLE_TIME 2 /* unit:ms */ +#define UTMI_RST_COMPLETE_TIME 2 /* unit:ms */ +#define POR_RST_COMPLETE_TIME 300 /* unit:us */ +#define PHY_TEST_DATA GENMASK(7, 0) +#define PHY_TEST_ADDR GENMASK(15, 8) +#define PHY_TEST_PORT GENMASK(18, 16) +#define PHY_TEST_WREN BIT(21) +#define PHY_TEST_CLK BIT(22) /* rising edge active */ +#define PHY_TEST_RST BIT(23) /* low active */ +#define PHY_CLK_ENABLE BIT(2) + +struct hisi_inno_phy_port { + struct reset_control *utmi_rst; + struct hisi_inno_phy_priv *priv; +}; + +struct hisi_inno_phy_priv { + void __iomem *mmio; + struct clk *ref_clk; + struct reset_control *por_rst; + struct hisi_inno_phy_port ports[INNO_PHY_PORT_NUM]; +}; + +static void hisi_inno_phy_write_reg(struct hisi_inno_phy_priv *priv, + u8 port, u32 addr, u32 data) +{ + void __iomem *reg = priv->mmio; + u32 val; + + val = (data & PHY_TEST_DATA) | + ((addr << 8) & PHY_TEST_ADDR) | + ((port << 16) & PHY_TEST_PORT) | + PHY_TEST_WREN | PHY_TEST_RST; + writel(val, reg); + + val |= PHY_TEST_CLK; + writel(val, reg); + + val &= ~PHY_TEST_CLK; + writel(val, reg); +} + +static void hisi_inno_phy_setup(struct hisi_inno_phy_priv *priv) +{ + /* The phy clk is controlled by the port0 register 0x06. */ + hisi_inno_phy_write_reg(priv, 0, 0x06, PHY_CLK_ENABLE); + msleep(PHY_CLK_STABLE_TIME); +} + +static int hisi_inno_phy_init(struct phy *phy) +{ + struct hisi_inno_phy_port *port = phy_get_drvdata(phy); + struct hisi_inno_phy_priv *priv = port->priv; + int ret; + + ret = clk_prepare_enable(priv->ref_clk); + if (ret) + return ret; + udelay(REF_CLK_STABLE_TIME); + + reset_control_deassert(priv->por_rst); + udelay(POR_RST_COMPLETE_TIME); + + /* Set up phy registers */ + hisi_inno_phy_setup(priv); + + reset_control_deassert(port->utmi_rst); + udelay(UTMI_RST_COMPLETE_TIME); + + return 0; +} + +static int hisi_inno_phy_exit(struct phy *phy) +{ + struct hisi_inno_phy_port *port = phy_get_drvdata(phy); + struct hisi_inno_phy_priv *priv = port->priv; + + reset_control_assert(port->utmi_rst); + reset_control_assert(priv->por_rst); + clk_disable_unprepare(priv->ref_clk); + + return 0; +} + +static const struct phy_ops hisi_inno_phy_ops = { + .init = hisi_inno_phy_init, + .exit = hisi_inno_phy_exit, + .owner = THIS_MODULE, +}; + +static int hisi_inno_phy_probe(struct platform_device *pdev) +{ + struct device *dev = &pdev->dev; + struct device_node *np = dev->of_node; + struct hisi_inno_phy_priv *priv; + struct phy_provider *provider; + struct device_node *child; + struct resource *res; + int i = 0; + int ret; + + priv = devm_kzalloc(dev, sizeof(*priv), GFP_KERNEL); + if (!priv) + return -ENOMEM; + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + priv->mmio = devm_ioremap_resource(dev, res); + if (IS_ERR(priv->mmio)) { + ret = PTR_ERR(priv->mmio); + return ret; + } + + priv->ref_clk = devm_clk_get(dev, NULL); + if (IS_ERR(priv->ref_clk)) + return PTR_ERR(priv->ref_clk); + + priv->por_rst = devm_reset_control_get_exclusive(dev, NULL); + if (IS_ERR(priv->por_rst)) + return PTR_ERR(priv->por_rst); + + for_each_child_of_node(np, child) { + struct reset_control *rst; + struct phy *phy; + + rst = of_reset_control_get_exclusive(child, NULL); + if (IS_ERR(rst)) + return PTR_ERR(rst); + priv->ports[i].utmi_rst = rst; + priv->ports[i].priv = priv; + + phy = devm_phy_create(dev, child, &hisi_inno_phy_ops); + if (IS_ERR(phy)) + return PTR_ERR(phy); + + phy_set_bus_width(phy, 8); + phy_set_drvdata(phy, &priv->ports[i]); + i++; + + if (i > INNO_PHY_PORT_NUM) { + dev_warn(dev, "Support %d ports in maximum\n", i); + break; + } + } + + provider = devm_of_phy_provider_register(dev, of_phy_simple_xlate); + return PTR_ERR_OR_ZERO(provider); +} + +static const struct of_device_id hisi_inno_phy_of_match[] = { + { .compatible = "hisilicon,inno-usb2-phy", }, + { .compatible = "hisilicon,hi3798cv200-usb2-phy", }, + { }, +}; +MODULE_DEVICE_TABLE(of, hisi_inno_phy_of_match); + +static struct platform_driver hisi_inno_phy_driver = { + .probe = hisi_inno_phy_probe, + .driver = { + .name = "hisi-inno-phy", + .of_match_table = hisi_inno_phy_of_match, + } +}; +module_platform_driver(hisi_inno_phy_driver); + +MODULE_DESCRIPTION("HiSilicon INNO USB2 PHY Driver"); +MODULE_LICENSE("GPL v2"); diff --git a/pool/shard008/C/0133551_test-ssl-post.c b/pool/shard008/C/0133551_test-ssl-post.c new file mode 100644 index 0000000000000000000000000000000000000000..7b521475a32a969b26f96936446ff507363814c7 --- /dev/null +++ b/pool/shard008/C/0133551_test-ssl-post.c @@ -0,0 +1,111 @@ +#include "../http/gskhttpclient.h" +#include "../ssl/gskstreamssl.h" +#include "../gsksocketaddress.h" +#include "../gskstreamclient.h" +#include "../gskmemory.h" +#include "../gsknameresolver.h" +#include "../gskmain.h" + +static const char *host; +static const char *path; +static guint port = 443; +static const char *post_data_filename; + +static void +print_header_line (const char *text, gpointer data) +{ + g_print ("%s\n", text); +} + +static gboolean +handle_input_readable (GskStream *input, gpointer data) +{ + char buf[256]; + GError *error = NULL; + guint nread = gsk_stream_read (input, buf, sizeof(buf), &error); + if (error) + g_error ("error reading from stream: %s", error->message); + g_message ("got '%.*s'", nread,buf); + return TRUE; +} + +static gboolean +handle_input_shutdown (GskStream *input, gpointer data) +{ + g_message("handle_input_shutdown"); + g_object_unref (input); + return FALSE; +} +static void +handle_input_destroy (gpointer data) +{ + g_message("handle_input_destroy"); +} + + +static void +handle_response (GskHttpRequest *request, + GskHttpResponse *response, + GskStream *input, + gpointer hook_data) +{ + gsk_http_header_print (GSK_HTTP_HEADER (response), + print_header_line, NULL); + g_message("gsk_io_trap_readable"); + g_object_ref (input); + gsk_io_trap_readable (GSK_IO (input), handle_input_readable, handle_input_shutdown, NULL, handle_input_destroy); +} + +static void +handle_name_lookup_succeeded (GskSocketAddress *address, gpointer func_data) +{ + GskSocketAddress *addr = gsk_socket_address_ipv4_new (GSK_SOCKET_ADDRESS_IPV4 (address)->ip_address, port); + GError *error = NULL; + GskStream *client = gsk_stream_new_connecting (addr, &error); + GskHttpClient *http_client; + GskHttpRequest *http_request; + GskStream *ssl; + char *post_data; + gsize post_data_len; + GskStream *post_stream; + if (client == NULL) + g_error ("error connecting to %s: %s", gsk_socket_address_to_string (addr), error->message); + ssl = gsk_stream_ssl_new_client (NULL, NULL, NULL, client, &error); + if (ssl == NULL) + g_error ("error creating SSL stream: %s", error->message); + http_client = gsk_http_client_new (); + if (!gsk_stream_attach_pair (GSK_STREAM (http_client), GSK_STREAM (ssl), &error)) + g_error ("gsk_stream_attach_path: %s", error->message); + + if (!g_file_get_contents (post_data_filename, &post_data, &post_data_len, &error)) + g_error ("error reading post-data"); + post_stream = gsk_memory_slab_source_new (post_data, post_data_len, g_free, post_data); + http_request = gsk_http_request_new (GSK_HTTP_VERB_POST, path); + gsk_http_client_request (http_client, http_request, post_stream, + handle_response, NULL, NULL); +} + +static void +handle_name_lookup_failed (GError *error, gpointer func_data) +{ + g_error ("name lookup for %s failed: %s",host, error->message); +} + +int main (int argc, char **argv) +{ + gsk_init_without_threads (&argc, &argv); + if (argc != 4) + g_error("usage: %s HOST PATH POSTDATA", argv[0]); + + + host = argv[1]; + path = argv[2]; + post_data_filename = argv[3]; + + gsk_name_resolver_lookup (GSK_NAME_RESOLVER_FAMILY_IPV4, + host, + handle_name_lookup_succeeded, + handle_name_lookup_failed, + NULL, NULL); + return gsk_main_run(); +} diff --git a/pool/shard008/C/0133552_Example2.c b/pool/shard008/C/0133552_Example2.c new file mode 100644 index 0000000000000000000000000000000000000000..778217140eec7fc5da5a9057e17b4af694f21d83 --- /dev/null +++ b/pool/shard008/C/0133552_Example2.c @@ -0,0 +1,23 @@ +#include +#include +#include +float fadd(float a_firstValue, float a_secondValue); +int main(void) +{ + float m_firstValue = 41.0f, m_secondValue = 1.0f; + float m_resultValue; + + + m_resultValue = fadd(m_firstValue, m_secondValue); + + + printf("%lf\n", m_resultValue); + + + return 0; +} +float fadd(float a_firstValue, float a_secondValue) +{ + float a_resultValue = a_firstValue + a_secondValue; + return a_resultValue; +} \ No newline at end of file diff --git a/pool/shard008/C/0133558_resolve_local.c b/pool/shard008/C/0133558_resolve_local.c new file mode 100644 index 0000000000000000000000000000000000000000..703ec07431b6409cfac24fd999190ec46de0bb81 --- /dev/null +++ b/pool/shard008/C/0133558_resolve_local.c @@ -0,0 +1,179 @@ +/*++ +/* NAME +/* resolve_local 3 +/* SUMMARY +/* determine if domain resolves to local mail system +/* SYNOPSIS +/* #include +/* +/* void resolve_local_init() +/* +/* int resolve_local(domain) +/* const char *domain; +/* DESCRIPTION +/* resolve_local() determines if the named domain resolves to the +/* local mail system, either by case-insensitive exact match +/* against the domains, files or tables listed in $mydestination, +/* or by a match of an [address-literal] against of the network +/* addresses listed in $inet_interfaces or in $proxy_interfaces. +/* +/* resolve_local_init() performs initialization. If this routine is +/* not called explicitly ahead of time, it will be called on the fly. +/* BUGS +/* Calling resolve_local_init() on the fly is an incomplete solution. +/* It is bound to fail with applications that enter a chroot jail. +/* SEE ALSO +/* own_inet_addr(3), find out my own network interfaces +/* match_list(3), generic pattern matching engine +/* match_ops(3), generic pattern matching operators +/* LICENSE +/* .ad +/* .fi +/* The Secure Mailer license must be distributed with this software. +/* AUTHOR(S) +/* Wietse Venema +/* IBM T.J. Watson Research +/* P.O. Box 704 +/* Yorktown Heights, NY 10598, USA +/*--*/ + +/* System library. */ + +#include + +/* Utility library. */ + +#include +#include +#include +#include +#include + +/* Global library. */ + +#include +#include +#include + +/* Application-specific */ + +static STRING_LIST *resolve_local_list; + +/* resolve_local_init - initialize lookup table */ + +void resolve_local_init(void) +{ + if (resolve_local_list) + msg_panic("resolve_local_init: duplicate initialization"); + resolve_local_list = string_list_init(MATCH_FLAG_NONE, var_mydest); +} + +/* resolve_local - match domain against list of local destinations */ + +int resolve_local(const char *addr) +{ + char *saved_addr = mystrdup(addr); + char *dest; + const char *bare_dest; + struct addrinfo *res0 = 0; + ssize_t len; + + /* + * The optimizer will eliminate tests that always fail. + */ +#define RETURN(x) \ + do { \ + myfree(saved_addr); \ + if (res0) \ + freeaddrinfo(res0); \ + return(x); \ + } while (0) + + if (resolve_local_list == 0) + resolve_local_init(); + + /* + * Strip one trailing dot but not dot-dot. + * + * XXX This should not be distributed all over the code. Problem is, + * addresses can enter the system via multiple paths: networks, local + * forward/alias/include files, even as the result of address rewriting. + */ + len = strlen(saved_addr); + if (len == 0) + RETURN(0); + if (saved_addr[len - 1] == '.') + saved_addr[--len] = 0; + if (len == 0 || saved_addr[len - 1] == '.') + RETURN(0); + + /* + * Compare the destination against the list of destinations that we + * consider local. + */ + if (string_list_match(resolve_local_list, saved_addr)) + RETURN(1); + + /* + * Compare the destination against the list of interface addresses that + * we are supposed to listen on. + * + * The destination may be an IPv6 address literal that was buried somewhere + * inside a deeply recursively nested address. This information comes + * from an untrusted source, and Wietse is not confident that everyone's + * getaddrinfo() etc. implementation is sufficiently robust. The syntax + * is complex enough with null field compression and with IPv4-in-IPv6 + * addresses that errors are likely. + * + * The solution below is ad-hoc. We neutralize the string as soon as we + * realize that its contents could be harmful. We neutralize the string + * here, instead of neutralizing it in every resolve_local() caller. + * That's because resolve_local knows how the address is going to be + * parsed and converted into binary form. + * + * There are several more structural solutions to this. + * + * - One solution is to disallow address literals. This is not as bad as it + * seems: I have never seen actual legitimate use of address literals. + * + * - Another solution is to label each string with a trustworthiness label + * and to expect that all Postfix infrastructure will exercise additional + * caution when given a string with untrusted content. This is not likely + * to happen. + * + * FIX 200501 IPv6 patch did not require "IPv6:" prefix in numerical + * addresses. + */ + dest = saved_addr; + if (*dest == '[' && dest[len - 1] == ']') { + dest++; + dest[len -= 2] = 0; + if ((bare_dest = valid_mailhost_addr(dest, DO_GRIPE)) != 0 + && hostaddr_to_sockaddr(bare_dest, (char *) 0, 0, &res0) == 0) { + if (own_inet_addr(res0->ai_addr) || proxy_inet_addr(res0->ai_addr)) + RETURN(1); + } + } + + /* + * Must be remote, or a syntax error. + */ + RETURN(0); +} + +#ifdef TEST + +#include +#include + +int main(int argc, char **argv) +{ + if (argc != 2) + msg_fatal("usage: %s domain", argv[0]); + mail_conf_read(); + vstream_printf("%s\n", resolve_local(argv[1]) ? "yes" : "no"); + vstream_fflush(VSTREAM_OUT); + return (0); +} + +#endif diff --git a/pool/shard008/C/0133561_mcp9808.c b/pool/shard008/C/0133561_mcp9808.c new file mode 100644 index 0000000000000000000000000000000000000000..0c508c54693c448acec280e1d99a0be0343cb980 --- /dev/null +++ b/pool/shard008/C/0133561_mcp9808.c @@ -0,0 +1,26 @@ +#include "mcp9808.h" + +#include "twi_master.h" +#include + +#define ADDR 0x3e + +#define TEMP_REG 0x05 + + +uint16_t mcp9808_temp(void) { + uint8_t obuf[1] = { 0 }; + uint8_t ibuf[2] = { 0, 0 }; + obuf[0] = TEMP_REG; + twi_master_transfer(ADDR, obuf, 1, false); + twi_master_transfer(ADDR | 0x01, ibuf, 2, true); + + ibuf[0] &= 0x1f; // Clear flags + + //return ibuf[0] << 8 | ibuf[1]; + if (ibuf[0] & 0x10) { + return 256 - (((ibuf[0] & 0x0f) * 16) + (ibuf[1] / 16)); + } else { + return (ibuf[0] * 16) + (ibuf[1] / 16); + } +} diff --git a/pool/shard008/C/0133566_fil_euclidian.c b/pool/shard008/C/0133566_fil_euclidian.c new file mode 100644 index 0000000000000000000000000000000000000000..aa16e70cefe1417faa0db80244b6c16de4399b54 --- /dev/null +++ b/pool/shard008/C/0133566_fil_euclidian.c @@ -0,0 +1,92 @@ +/* + * MassFind: A Diamond application for exploration of breast tumors + * + * Copyright (c) 2006 Intel Corporation. All rights reserved. + * Additional copyrights may be listed below. + * + * This program and the accompanying materials are made available under + * the terms of the Eclipse Public License v1.0 which accompanies this + * distribution in the file named LICENSE. + * + */ + +#include +#include +#include +#include +#include + +#include "lib_filter.h" +#include "roi_features.h" +#include "fil_euclidian.h" + +#define MAX_ATTR_NAME 128 +#define MAX_ATTR_VALUE 4096 + +static +int f_init_euclidian(int numarg, const char * const *args, int blob_len, + const void *blob, const char *fname, void **data) +{ + euclidian_config_t *fconfig; + int i; + + /* + * save the features for the source object + */ + fconfig = (euclidian_config_t *)malloc(sizeof(*fconfig)); + assert(fconfig); + + fconfig->numFeatures = numarg; + fconfig->features = (float *) malloc(sizeof(float) * fconfig->numFeatures); + for (i = 0; i < fconfig->numFeatures; i++) { + fconfig->features[i] = atof(args[i]); + } + + /* + * save the data pointer + */ + *data = (void *) fconfig; + + return (0); +} + +static +int f_eval_euclidian(lf_obj_handle_t ohandle, void *f_data) +{ + int err; + int i; + euclidian_config_t *fconfig = (euclidian_config_t *) f_data; + size_t featureLen = MAX_ATTR_VALUE; + unsigned char featureStr[MAX_ATTR_VALUE]; + int numFeatures; + float f; + float distance = 0; + char fname[MAX_ATTR_NAME]; + + lf_log(LOGL_TRACE, "f_eval_euclidian: enter"); + + // extract the features for this object + err = lf_read_attr(ohandle, NUM_EDMF, &featureLen, featureStr); + assert(err == 0); + numFeatures = atoi((char *)featureStr); + assert(numFeatures == fconfig->numFeatures); + + for(i=0; ifeatures[i]),2); + } + int similarity = 100*exp(-distance); + + // save results as attributes + err = lf_write_attr(ohandle, "similarity", sizeof(int), + (unsigned char *) &similarity); + assert(err == 0); + + return similarity; +} + +LF_MAIN(f_init_euclidian, f_eval_euclidian) diff --git a/pool/shard008/C/0133568_30-1.c b/pool/shard008/C/0133568_30-1.c new file mode 100644 index 0000000000000000000000000000000000000000..3b41a665e412f3c15570cf7acb2eb5739902f43d --- /dev/null +++ b/pool/shard008/C/0133568_30-1.c @@ -0,0 +1,218 @@ +/* +* Copyright (c) 2005, Bull S.A.. All rights reserved. +* Created by: Sebastien Decugis + +* This program is free software; you can redistribute it and/or modify it +* under the terms of version 2 of the GNU General Public License as +* published by the Free Software Foundation. +* +* This program is distributed in the hope that it would be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +* +* You should have received a copy of the GNU General Public License along +* with this program; if not, write the Free Software Foundation, Inc., 59 +* Temple Place - Suite 330, Boston MA 02111-1307, USA. + +* This sample test aims to check the following assertions: +* +* sigaction returns -1 and errno is set to EINVAL if signal number is invalid +* or an attempt to do an operation which is not allowed is made. + +* The steps are: +* -> Try setting a signal handler for signal SIGRTMAX + 1 +* -> Try setting a signal handler for SIGKILL +* -> Try setting a signal handler for SIGSTOP +* -> Try ignoring SIGSTOP +* -> Try ignoring SIGKILL + +* The test fails if the signals are not delivered in FIFO order. +*/ + +/* We are testing conformance to IEEE Std 1003.1, 2003 Edition */ +#define _POSIX_C_SOURCE 200112L + +/******************************************************************************/ +/*************************** standard includes ********************************/ +/******************************************************************************/ +#include +#include +#include +#include +#include +#include + +#include +#include + +/******************************************************************************/ +/*************************** Test framework *******************************/ +/******************************************************************************/ +#include "../testfrmw/testfrmw.h" +#include "../testfrmw/testfrmw.c" +/* This header is responsible for defining the following macros: + * UNRESOLVED(ret, descr); + * where descr is a description of the error and ret is an int + * (error code for example) + * FAILED(descr); + * where descr is a short text saying why the test has failed. + * PASSED(); + * No parameter. + * + * Both three macros shall terminate the calling process. + * The testcase shall not terminate in any other maneer. + * + * The other file defines the functions + * void output_init() + * void output(char * string, ...) + * + * Those may be used to output information. + */ + +/******************************************************************************/ +/**************************** Configuration ***********************************/ +/******************************************************************************/ +#ifndef VERBOSE +#define VERBOSE 1 +#endif + +#define SIG_INVALID SIGRTMAX+10 + +/******************************************************************************/ +/*************************** Test case ***********************************/ +/******************************************************************************/ + +void handler(int signo) +{ + return ; +} + +/* main function */ +int main() +{ + int ret; + + struct sigaction sa; + + /* Initialize output */ + output_init(); + + /* Set the signal handler */ + sa.sa_flags = 0; + + sa.sa_handler = handler; + + ret = sigemptyset(&sa.sa_mask); + + if (ret != 0) + { + UNRESOLVED(ret, "Failed to empty signal set"); + } + + /* Install the signal handler for SIGRTMAX */ +#if VERBOSE > 0 + output("Trying to catch invalid signal %d\n", SIG_INVALID); + +#endif + ret = sigaction(SIG_INVALID, &sa, 0); + + if (ret == 0) + { + output("Is signal %d valid on this implementation?\n", SIG_INVALID); + FAILED("Setting handler for invalid signal did not fail"); + } + + if (errno != EINVAL) + { + output("Got error %d (%s) instead of %d (%s)\n", + errno, strerror(errno), EINVAL, strerror(EINVAL)); + FAILED("Wrong error code returned"); + } + + /* Install the signal handler for SIGKILL */ +#if VERBOSE > 0 + output("Trying to catch unauthorized signal SIGKILL (%d)\n", SIGKILL); + +#endif + ret = sigaction(SIGKILL, &sa, 0); + + if (ret == 0) + { + FAILED("Setting handler for SIGKILL did not fail"); + } + + if (errno != EINVAL) + { + output("Got error %d (%s) instead of %d (%s)\n", + errno, strerror(errno), EINVAL, strerror(EINVAL)); + FAILED("Wrong error code returned"); + } + + /* Install the signal handler for SIGSTOP */ +#if VERBOSE > 0 + output("Trying to catch unauthorized signal SIGSTOP (%d)\n", SIGSTOP); + +#endif + ret = sigaction(SIGSTOP, &sa, 0); + + if (ret == 0) + { + FAILED("Setting handler for SIGSTOP did not fail"); + } + + if (errno != EINVAL) + { + output("Got error %d (%s) instead of %d (%s)\n", + errno, strerror(errno), EINVAL, strerror(EINVAL)); + FAILED("Wrong error code returned"); + } + + sa.sa_handler = SIG_IGN; + + /* Ingrore SIGKILL */ +#if VERBOSE > 0 + output("Trying to ignore unauthorized signal SIGKILL (%d)\n", SIGKILL); + +#endif + ret = sigaction(SIGKILL, &sa, 0); + + if (ret == 0) + { + FAILED("Ignoring SIGKILL did not fail"); + } + + if (errno != EINVAL) + { + output("Got error %d (%s) instead of %d (%s)\n", + errno, strerror(errno), EINVAL, strerror(EINVAL)); + FAILED("Wrong error code returned"); + } + + /* Ignore SIGSTOP */ +#if VERBOSE > 0 + output("Trying to ignore unauthorized signal SIGSTOP (%d)\n", SIGSTOP); + +#endif + ret = sigaction(SIGSTOP, &sa, 0); + + if (ret == 0) + { + FAILED("Ignoring SIGSTOP did not fail"); + } + + if (errno != EINVAL) + { + output("Got error %d (%s) instead of %d (%s)\n", + errno, strerror(errno), EINVAL, strerror(EINVAL)); + FAILED("Wrong error code returned"); + } + + /* Test passed */ +#if VERBOSE > 0 + + output("Test passed\n"); + +#endif + + PASSED; +} \ No newline at end of file diff --git a/pool/shard008/C/0133569_getpeername_error.c b/pool/shard008/C/0133569_getpeername_error.c new file mode 100644 index 0000000000000000000000000000000000000000..9f3172e9eb5e8cfcb14c31b52ffffd813ed92264 --- /dev/null +++ b/pool/shard008/C/0133569_getpeername_error.c @@ -0,0 +1,16 @@ + +static struct sockaddr_storage name; + +int +main(int argc, const char *argv[]) +{ + socklen_t namelen; + int error; + + namelen = sizeof(name); + error = getpeername(1024, (struct sockaddr *)&name, &namelen); + if (error == 0) + return (1); + + return (0); +} diff --git a/pool/shard008/C/0133570_zif-update-info.c b/pool/shard008/C/0133570_zif-update-info.c new file mode 100644 index 0000000000000000000000000000000000000000..dccf5a088a4125ed2f46162aed048ada4638c93d --- /dev/null +++ b/pool/shard008/C/0133570_zif-update-info.c @@ -0,0 +1,322 @@ +/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- + * + * Copyright (C) 2010 Richard Hughes + * + * Licensed under the GNU General Public License Version 2 + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +/** + * SECTION:zif-update-info + * @short_description: Update information + */ + +#ifdef HAVE_CONFIG_H +# include +#endif + +#include +#include +#include + +#include "zif-update-info-private.h" + +#define ZIF_UPDATE_INFO_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), ZIF_TYPE_UPDATE_INFO, ZifUpdateInfoPrivate)) + +struct _ZifUpdateInfoPrivate +{ + ZifUpdateInfoKind kind; + gchar *url; + gchar *title; +}; + +enum { + PROP_0, + PROP_KIND, + PROP_URL, + PROP_TITLE, + PROP_LAST +}; + +G_DEFINE_TYPE (ZifUpdateInfo, zif_update_info, G_TYPE_OBJECT) + +/** + * zif_update_info_get_kind: + * @update_info: A #ZifUpdateInfo + * + * Gets the update info kind. + * + * Return value: The kind of update info, e.g. %ZIF_UPDATE_INFO_KIND_CVE. + * + * Since: 0.1.0 + **/ +ZifUpdateInfoKind +zif_update_info_get_kind (ZifUpdateInfo *update_info) +{ + g_return_val_if_fail (ZIF_IS_UPDATE_INFO (update_info), ZIF_UPDATE_INFO_KIND_LAST); + return update_info->priv->kind; +} + +/** + * zif_update_info_get_url: + * @update_info: A #ZifUpdateInfo + * + * Gets the URL for this update. + * + * Return value: A string value, or %NULL. + * + * Since: 0.1.0 + **/ +const gchar * +zif_update_info_get_url (ZifUpdateInfo *update_info) +{ + g_return_val_if_fail (ZIF_IS_UPDATE_INFO (update_info), NULL); + return update_info->priv->url; +} + +/** + * zif_update_info_get_title: + * @update_info: A #ZifUpdateInfo + * + * Gets the title for this update. + * + * Return value: A string value, or %NULL. + * + * Since: 0.1.0 + **/ +const gchar * +zif_update_info_get_title (ZifUpdateInfo *update_info) +{ + g_return_val_if_fail (ZIF_IS_UPDATE_INFO (update_info), NULL); + return update_info->priv->title; +} + +/** + * zif_update_info_set_kind: + * @update_info: A #ZifUpdateInfo + * @kind: A kind of update info, e.g. %ZIF_UPDATE_INFO_KIND_BUGZILLA + * + * Sets the update info kind. + * + * Since: 0.1.0 + **/ +void +zif_update_info_set_kind (ZifUpdateInfo *update_info, ZifUpdateInfoKind kind) +{ + g_return_if_fail (ZIF_IS_UPDATE_INFO (update_info)); + update_info->priv->kind = kind; +} + +/** + * zif_update_info_set_url: + * @update_info: A #ZifUpdateInfo + * @url: The update info URL + * + * Sets the update info URL. + * + * Since: 0.1.0 + **/ +void +zif_update_info_set_url (ZifUpdateInfo *update_info, const gchar *url) +{ + g_return_if_fail (ZIF_IS_UPDATE_INFO (update_info)); + g_return_if_fail (url != NULL); + g_return_if_fail (update_info->priv->url == NULL); + + update_info->priv->url = g_strdup (url); +} + +/** + * zif_update_info_set_title: + * @update_info: A #ZifUpdateInfo + * @title: The update info title + * + * Sets the update info title. + * + * Since: 0.1.0 + **/ +void +zif_update_info_set_title (ZifUpdateInfo *update_info, const gchar *title) +{ + g_return_if_fail (ZIF_IS_UPDATE_INFO (update_info)); + g_return_if_fail (title != NULL); + g_return_if_fail (update_info->priv->title == NULL); + + update_info->priv->title = g_strdup (title); +} + +/** + * zif_update_info_kind_to_string: + * @type: A #ZifUpdateInfoKind enumerated value + * + * Gets the string representation of a #ZifUpdateInfoKind. + * + * Return value: A string + **/ +const gchar * +zif_update_info_kind_to_string (ZifUpdateInfoKind kind) +{ + if (kind == ZIF_UPDATE_INFO_KIND_CVE) + return "cve"; + if (kind == ZIF_UPDATE_INFO_KIND_BUGZILLA) + return "bugzilla"; + if (kind == ZIF_UPDATE_INFO_KIND_VENDOR) + return "vendor"; + return "unknown"; +} + +/** + * zif_update_info_kind_from_string: + * @type: A #ZifUpdateInfoKind enumerated value + * + * Gets the string representation of a #ZifUpdateInfoKind. + * + * Return value: A string + **/ +ZifUpdateInfoKind +zif_update_info_kind_from_string (const gchar *type) +{ + if (g_strcmp0 (type, "cve") == 0) + return ZIF_UPDATE_INFO_KIND_CVE; + if (g_strcmp0 (type, "bugzilla") == 0) + return ZIF_UPDATE_INFO_KIND_BUGZILLA; + if (g_strcmp0 (type, "vendor") == 0) + return ZIF_UPDATE_INFO_KIND_VENDOR; + return ZIF_UPDATE_INFO_KIND_LAST; +} + +/** + * zif_update_info_get_property: + **/ +static void +zif_update_info_get_property (GObject *object, guint prop_id, GValue *value, GParamSpec *pspec) +{ + ZifUpdateInfo *update_info = ZIF_UPDATE_INFO (object); + ZifUpdateInfoPrivate *priv = update_info->priv; + + switch (prop_id) { + case PROP_KIND: + g_value_set_uint (value, priv->kind); + break; + case PROP_URL: + g_value_set_string (value, priv->url); + break; + case PROP_TITLE: + g_value_set_string (value, priv->title); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); + break; + } +} + +/** + * zif_update_info_set_property: + **/ +static void +zif_update_info_set_property (GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec) +{ +} + +/** + * zif_update_info_finalize: + **/ +static void +zif_update_info_finalize (GObject *object) +{ + ZifUpdateInfo *update_info; + + g_return_if_fail (object != NULL); + g_return_if_fail (ZIF_IS_UPDATE_INFO (object)); + update_info = ZIF_UPDATE_INFO (object); + + g_free (update_info->priv->url); + g_free (update_info->priv->title); + + G_OBJECT_CLASS (zif_update_info_parent_class)->finalize (object); +} + +/** + * zif_update_info_class_init: + **/ +static void +zif_update_info_class_init (ZifUpdateInfoClass *klass) +{ + GParamSpec *pspec; + GObjectClass *object_class = G_OBJECT_CLASS (klass); + object_class->finalize = zif_update_info_finalize; + object_class->get_property = zif_update_info_get_property; + object_class->set_property = zif_update_info_set_property; + + /** + * ZifUpdateInfo:kind: + * + * Since: 0.1.0 + */ + pspec = g_param_spec_uint ("kind", NULL, NULL, + 0, G_MAXUINT, 0, + G_PARAM_READABLE); + g_object_class_install_property (object_class, PROP_KIND, pspec); + + /** + * ZifUpdateInfo:url: + * + * Since: 0.1.0 + */ + pspec = g_param_spec_string ("url", NULL, NULL, + NULL, + G_PARAM_READABLE); + g_object_class_install_property (object_class, PROP_URL, pspec); + + /** + * ZifUpdateInfo:title: + * + * Since: 0.1.0 + */ + pspec = g_param_spec_string ("title", NULL, NULL, + NULL, + G_PARAM_READABLE); + g_object_class_install_property (object_class, PROP_TITLE, pspec); + g_type_class_add_private (klass, sizeof (ZifUpdateInfoPrivate)); +} + +/** + * zif_update_info_init: + **/ +static void +zif_update_info_init (ZifUpdateInfo *update_info) +{ + update_info->priv = ZIF_UPDATE_INFO_GET_PRIVATE (update_info); + update_info->priv->kind = ZIF_UPDATE_INFO_KIND_LAST; + update_info->priv->url = NULL; + update_info->priv->title = NULL; +} + +/** + * zif_update_info_new: + * + * Return value: A new #ZifUpdateInfo instance. + * + * Since: 0.1.0 + **/ +ZifUpdateInfo * +zif_update_info_new (void) +{ + ZifUpdateInfo *update_info; + update_info = g_object_new (ZIF_TYPE_UPDATE_INFO, NULL); + return ZIF_UPDATE_INFO (update_info); +} + diff --git a/pool/shard008/C/0133584_shape_i4.c b/pool/shard008/C/0133584_shape_i4.c new file mode 100644 index 0000000000000000000000000000000000000000..cd446f5f31365f29b6bcc762b18a76c23cc89266 --- /dev/null +++ b/pool/shard008/C/0133584_shape_i4.c @@ -0,0 +1,67 @@ +/* Implementation of the SHAPE intrinsic + Copyright (C) 2002-2013 Free Software Foundation, Inc. + Contributed by Paul Brook + +This file is part of the GNU Fortran runtime library (libgfortran). + +Libgfortran is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public +License as published by the Free Software Foundation; either +version 3 of the License, or (at your option) any later version. + +Libgfortran 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 General Public License for more details. + +Under Section 7 of GPL version 3, you are granted additional +permissions described in the GCC Runtime Library Exception, version +3.1, as published by the Free Software Foundation. + +You should have received a copy of the GNU General Public License and +a copy of the GCC Runtime Library Exception along with this program; +see the files COPYING3 and COPYING.RUNTIME respectively. If not, see +. */ + +#include "libgfortran.h" +#include +#include + + +#if defined (HAVE_GFC_INTEGER_4) + +extern void shape_4 (gfc_array_i4 * const restrict ret, + const gfc_array_i4 * const restrict array); +export_proto(shape_4); + +void +shape_4 (gfc_array_i4 * const restrict ret, + const gfc_array_i4 * const restrict array) +{ + int n; + index_type stride; + index_type extent; + int rank; + + rank = GFC_DESCRIPTOR_RANK (array); + + if (ret->base_addr == NULL) + { + GFC_DIMENSION_SET(ret->dim[0], 0, rank - 1, 1); + ret->offset = 0; + ret->base_addr = xmalloc (sizeof (GFC_INTEGER_4) * rank); + } + + stride = GFC_DESCRIPTOR_STRIDE(ret,0); + + if (GFC_DESCRIPTOR_EXTENT(ret,0) < 1) + return; + + for (n = 0; n < rank; n++) + { + extent = GFC_DESCRIPTOR_EXTENT(array,n); + ret->base_addr[n * stride] = extent > 0 ? extent : 0 ; + } +} + +#endif diff --git a/pool/shard008/C/0133586_test_parse.c b/pool/shard008/C/0133586_test_parse.c new file mode 100644 index 0000000000000000000000000000000000000000..2459fcac2cf8553be8e37ed1d950613a2aa1bc9f --- /dev/null +++ b/pool/shard008/C/0133586_test_parse.c @@ -0,0 +1,220 @@ +#include +#include +#include + +#include "../../src/parsers/parse.h" +#include "../minunit.h" + +int tests_run = 0; + +static char * +test_position_parse_ok() +{ + int res; + char *s; + nmea_position *pos = malloc(sizeof (nmea_position)); + + /* 3 digit degrees */ + s = strdup("12311.12"); + res = nmea_position_parse(s, pos); + mu_assert("should return return 0 when successfull", 0 == res); + mu_assert("pos->degrees should be 123", 123 == pos->degrees); + mu_assert("pos->minutes should be 11.12", 11.12 == pos->minutes); + free(s); + + /* 2 digit degrees */ + s = strdup("2621.44"); + res = nmea_position_parse(s, pos); + mu_assert("should return return 0 when successfull", 0 == res); + mu_assert("pos->degrees should be 123", 26 == pos->degrees); + mu_assert("pos->minutes should be 11.12", 21.44 == pos->minutes); + free(s); + + /* 1 digit degrees */ + s = strdup("901.01"); + res = nmea_position_parse(s, pos); + mu_assert("should return return 0 when successfull", 0 == res); + mu_assert("pos->degrees should be 123", 9 == pos->degrees); + mu_assert("pos->minutes should be 11.12", 1.01 == pos->minutes); + free(s); + + /* 0 decimals in minutes */ + s = strdup("901."); + res = nmea_position_parse(s, pos); + mu_assert("should return return 0 when successfull", 0 == res); + mu_assert("pos->degrees should be 123", 9 == pos->degrees); + mu_assert("pos->minutes should be 11.12", 1.0 == pos->minutes); + free(s); + + free(pos); + return 0; +} + +static char * +test_position_parse_fail() +{ + int res; + char *s; + nmea_position *pos = malloc(sizeof (nmea_position)); + + /* no minutes */ + s = strdup("123"); + res = nmea_position_parse(s, pos); + mu_assert("should return return -1 on failure", -1 == res); + free(s); + + /* empty string */ + s = strdup(""); + res = nmea_position_parse(s, pos); + mu_assert("should return return -1 on empty string", -1 == res); + free(s); + + /* NULL */ + res = nmea_position_parse(NULL, pos); + mu_assert("should return return -1 on NULL", -1 == res); + + free(pos); + return 0; +} + +static char * +test_cardinal_dir_parse_ok() +{ + nmea_cardinal_t card; + + /* North */ + card = nmea_cardinal_direction_parse("N"); + mu_assert("should return NMEA_CARDINAL_NORTH on \"N\"", NMEA_CARDINAL_DIR_NORTH == card); + + /* East */ + card = nmea_cardinal_direction_parse("E"); + mu_assert("should return NMEA_CARDINAL_EAST on \"E\"", NMEA_CARDINAL_DIR_EAST == card); + + /* South */ + card = nmea_cardinal_direction_parse("S"); + mu_assert("should return NMEA_CARDINAL_SOUTH on \"S\"", NMEA_CARDINAL_DIR_SOUTH == card); + + /* West */ + card = nmea_cardinal_direction_parse("W"); + mu_assert("should return NMEA_CARDINAL_WEST on \"W\"", NMEA_CARDINAL_DIR_WEST == card); + + return 0; +} + +static char * +test_cardinal_dir_parse_fail() +{ + nmea_cardinal_t card; + + /* Empty string */ + card = nmea_cardinal_direction_parse(""); + mu_assert("should return NMEA_CARDINAL_UNKNOWN on empty string", NMEA_CARDINAL_DIR_UNKNOWN == card); + + /* NULL */ + card = nmea_cardinal_direction_parse(NULL); + mu_assert("should return NMEA_CARDINAL_UNKNOWN on NULL", NMEA_CARDINAL_DIR_UNKNOWN == card); + + /* Unknown character (J) */ + card = nmea_cardinal_direction_parse("J"); + mu_assert("should return NMEA_CARDINAL_UNKNOWN on \"J\"", NMEA_CARDINAL_DIR_UNKNOWN == card); + + /* Unknown character (n) */ + card = nmea_cardinal_direction_parse("n"); + mu_assert("should return NMEA_CARDINAL_UNKNOWN on \"n\"", NMEA_CARDINAL_DIR_UNKNOWN == card); + + return 0; +} + +static char * +test_time_parse_ok() +{ + int rv; + struct tm t; + + /* Parse time, no leading zeros */ + rv = nmea_time_parse("171521", &t); + mu_assert("should return 0 on success", 0 == rv); + mu_assert("t.tm_sec should be 21", 21 == t.tm_sec); + mu_assert("t.tm_min should be 15", 15 == t.tm_min); + mu_assert("t.tm_hour should be 17", 17 == t.tm_hour); + + /* Parse time, with leading zeros */ + rv = nmea_time_parse("090801", &t); + mu_assert("should return 0 on success", 0 == rv); + mu_assert("t.tm_sec should be 1", 1 == t.tm_sec); + mu_assert("t.tm_min should be 8", 8 == t.tm_min); + mu_assert("t.tm_hour should be 9", 9 == t.tm_hour); + + return 0; +} + +static char * +test_time_parse_fail() +{ + int rv; + struct tm t; + + /* Invalid time, hours over 23 */ + rv = nmea_time_parse("240000", &t); + mu_assert("should return -1 when hours is over 23", -1 == rv); + + /* Invalid time, minutes over 59 */ + rv = nmea_time_parse("006000", &t); + mu_assert("should return -1 when minutes is over 59", -1 == rv); + + /* + * Invalid time, seconds over 61 (tm_sec is generally 0-59. The extra range is + * to accommodate for leap seconds in certain systems). + **/ + rv = nmea_time_parse("000062", &t); + mu_assert("should return -1 when seconds is over 59", -1 == rv); + + /* Too short string */ + rv = nmea_time_parse("2345", &t); + mu_assert("should return -1 on too short string", -1 == rv); + + /* Invalid characters */ + rv = nmea_time_parse("2345XX", &t); + mu_assert("should return -1 on invalid characters", -1 == rv); + + /* Empty string */ + rv = nmea_time_parse("", &t); + mu_assert("should return -1 on empty string", -1 == rv); + + /* NULL */ + rv = nmea_time_parse(NULL, &t); + mu_assert("should return -1 on NULL", -1 == rv); + + return 0; +} + +static char * +all_tests() +{ + mu_group("nmea_position_parse()"); + mu_run_test(test_position_parse_ok); + mu_run_test(test_position_parse_fail); + + mu_group("nmea_cardinal_dir_parse()"); + mu_run_test(test_cardinal_dir_parse_ok); + mu_run_test(test_cardinal_dir_parse_fail); + + mu_group("nmea_time_parse()"); + mu_run_test(test_time_parse_ok); + mu_run_test(test_time_parse_fail); + + return 0; +} + +int +main(void) +{ + tests_run = 0; + + char *result = all_tests(); + if (result != 0) { + exit(EXIT_FAILURE); + } + + exit(EXIT_SUCCESS); +} diff --git a/pool/shard008/C/0133588_winmx.c b/pool/shard008/C/0133588_winmx.c new file mode 100644 index 0000000000000000000000000000000000000000..f2cac7482141d1ccd01afe33ec58fe1ccbac6a82 --- /dev/null +++ b/pool/shard008/C/0133588_winmx.c @@ -0,0 +1,104 @@ +/* + * winmx.c + * + * Copyright (C) 2009-2011 by ipoque GmbH + * Copyright (C) 2011-15 - ntop.org + * + * This file is part of nDPI, an open source deep packet inspection + * library based on the OpenDPI and PACE technology by ipoque GmbH + * + * nDPI is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * nDPI 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 nDPI. If not, see . + * + */ + + +#include "ndpi_protocols.h" + +#ifdef NDPI_PROTOCOL_WINMX + + +static void ndpi_int_winmx_add_connection(struct ndpi_detection_module_struct + *ndpi_struct, struct ndpi_flow_struct *flow); + +static void ndpi_int_winmx_add_connection(struct ndpi_detection_module_struct + *ndpi_struct, struct ndpi_flow_struct *flow) +{ + ndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_WINMX, NDPI_PROTOCOL_UNKNOWN); +} + + +void ndpi_search_winmx_tcp(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) +{ + struct ndpi_packet_struct *packet = &flow->packet; + + // struct ndpi_id_struct *src=ndpi_struct->src; + // struct ndpi_id_struct *dst=ndpi_struct->dst; + + + if (flow->l4.tcp.winmx_stage == 0) { + if (packet->payload_packet_len == 1 || (packet->payload_packet_len > 1 && packet->payload[0] == 0x31)) { + return; + } + /* did not see this pattern in any trace that we have */ + if (((packet->payload_packet_len) == 4) + && (memcmp(packet->payload, "SEND", 4) == 0)) { + + NDPI_LOG(NDPI_PROTOCOL_WINMX, ndpi_struct, NDPI_LOG_DEBUG, "maybe WinMX Send\n"); + flow->l4.tcp.winmx_stage = 1; + return; + } + + if (((packet->payload_packet_len) == 3) + && (memcmp(packet->payload, "GET", 3) == 0)) { + NDPI_LOG(NDPI_PROTOCOL_WINMX, ndpi_struct, NDPI_LOG_DEBUG, "found winmx by GET\n"); + ndpi_int_winmx_add_connection(ndpi_struct, flow); + return; + } + + + if (packet->payload_packet_len == 149 && packet->payload[0] == '8') { + NDPI_LOG(NDPI_PROTOCOL_WINMX, ndpi_struct, NDPI_LOG_DEBUG, "maybe WinMX\n"); + if (get_u_int32_t(packet->payload, 17) == 0 + && get_u_int32_t(packet->payload, 21) == 0 + && get_u_int32_t(packet->payload, 25) == 0 + && get_u_int16_t(packet->payload, 39) == 0 && get_u_int16_t(packet->payload, 135) == htons(0x7edf) + && get_u_int16_t(packet->payload, 147) == htons(0xf792)) { + + NDPI_LOG(NDPI_PROTOCOL_WINMX, ndpi_struct, NDPI_LOG_DEBUG, + "found winmx by pattern in first packet\n"); + ndpi_int_winmx_add_connection(ndpi_struct, flow); + return; + } + } + /* did not see this pattern in any trace that we have */ + } else if (flow->l4.tcp.winmx_stage == 1) { + if (packet->payload_packet_len > 10 && packet->payload_packet_len < 1000) { + u_int16_t left = packet->payload_packet_len - 1; + while (left > 0) { + if (packet->payload[left] == ' ') { + NDPI_LOG(NDPI_PROTOCOL_WINMX, ndpi_struct, NDPI_LOG_DEBUG, "found winmx in second packet\n"); + ndpi_int_winmx_add_connection(ndpi_struct, flow); + return; + } else if (packet->payload[left] < '0' || packet->payload[left] > '9') { + break; + } + left--; + } + } + } + + NDPI_ADD_PROTOCOL_TO_BITMASK(flow->excluded_protocol_bitmask, NDPI_PROTOCOL_WINMX); +} + +#endif diff --git a/pool/shard008/C/0133589_altivec-cell-7.c b/pool/shard008/C/0133589_altivec-cell-7.c new file mode 100644 index 0000000000000000000000000000000000000000..cbe5fb9f8a70c298884200210fb6d0a6303cb483 --- /dev/null +++ b/pool/shard008/C/0133589_altivec-cell-7.c @@ -0,0 +1,28 @@ +/* { dg-do compile } */ +/* { dg-require-effective-target powerpc_altivec_ok } */ +/* { dg-options "-O2 -maltivec -mabi=altivec -mdejagnu-cpu=cell" } */ +/* { dg-final { scan-assembler-times "vor" 2 } } */ +#include + +/* Make sure that lvlx and lvrx are not combined into one insn and + we still get a vor. */ + +vector unsigned char +lvx_float (long off, float *p) +{ + vector unsigned char l, r; + + l = (vector unsigned char) vec_lvlx (off, p); + r = (vector unsigned char) vec_lvrx (off, p); + return vec_or(l, r); +} + +vector unsigned char +lvxl_float (long off, float *p) +{ + vector unsigned char l, r; + + l = (vector unsigned char) vec_lvlxl (off, p); + r = (vector unsigned char) vec_lvrxl (off, p); + return vec_or(l, r); +} diff --git a/pool/shard008/C/0133590_CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_45.c b/pool/shard008/C/0133590_CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_45.c new file mode 100644 index 0000000000000000000000000000000000000000..c77980af665b3e57107daa85388a6b5a3cd34db0 --- /dev/null +++ b/pool/shard008/C/0133590_CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_45.c @@ -0,0 +1,126 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_45.c +Label Definition File: CWE124_Buffer_Underwrite__malloc.label.xml +Template File: sources-sink-45.tmpl.c +*/ +/* + * @description + * CWE: 124 Buffer Underwrite + * BadSource: Set data pointer to before the allocated memory buffer + * GoodSource: Set data pointer to the allocated memory buffer + * Sinks: ncpy + * BadSink : Copy string to data using wcsncpy + * Flow Variant: 45 Data flow: data passed as a static global variable from one function to another in the same source file + * + * */ + +#include "std_testcase.h" + +#include + +static wchar_t * CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_45_badData; +static wchar_t * CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_45_goodG2BData; + +#ifndef OMITBAD + +static void badSink() +{ + wchar_t * data = CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_45_badData; + { + wchar_t source[100]; + wmemset(source, L'C', 100-1); /* fill with 'C's */ + source[100-1] = L'\0'; /* null terminate */ + /* POTENTIAL FLAW: Possibly copying data to memory before the destination buffer */ + wcsncpy(data, source, 100-1); + /* Ensure the destination buffer is null terminated */ + data[100-1] = L'\0'; + printWLine(data); + /* INCIDENTAL CWE-401: Memory Leak - data may not point to location + * returned by malloc() so can't safely call free() on it */ + } +} + +void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_45_bad() +{ + wchar_t * data; + data = NULL; + { + wchar_t * dataBuffer = (wchar_t *)malloc(100*sizeof(wchar_t)); + wmemset(dataBuffer, L'A', 100-1); + dataBuffer[100-1] = L'\0'; + /* FLAW: Set data pointer to before the allocated memory buffer */ + data = dataBuffer - 8; + } + CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_45_badData = data; + badSink(); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B() uses the GoodSource with the BadSink */ +static void goodG2BSink() +{ + wchar_t * data = CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_45_goodG2BData; + { + wchar_t source[100]; + wmemset(source, L'C', 100-1); /* fill with 'C's */ + source[100-1] = L'\0'; /* null terminate */ + /* POTENTIAL FLAW: Possibly copying data to memory before the destination buffer */ + wcsncpy(data, source, 100-1); + /* Ensure the destination buffer is null terminated */ + data[100-1] = L'\0'; + printWLine(data); + /* INCIDENTAL CWE-401: Memory Leak - data may not point to location + * returned by malloc() so can't safely call free() on it */ + } +} + +static void goodG2B() +{ + wchar_t * data; + data = NULL; + { + wchar_t * dataBuffer = (wchar_t *)malloc(100*sizeof(wchar_t)); + wmemset(dataBuffer, L'A', 100-1); + dataBuffer[100-1] = L'\0'; + /* FIX: Set data pointer to the allocated memory buffer */ + data = dataBuffer; + } + CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_45_goodG2BData = data; + goodG2BSink(); +} + +void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_45_good() +{ + goodG2B(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + * its own for testing or for building a binary to use in testing binary + * analysis tools. It is not used when compiling all the testcases as one + * application, which is how source code analysis tools are tested. + */ +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_45_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_45_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard008/C/0133592_symbol.c b/pool/shard008/C/0133592_symbol.c new file mode 100644 index 0000000000000000000000000000000000000000..7bde35f031e2f72b7afaeaed83304e1d1eb8b5e0 --- /dev/null +++ b/pool/shard008/C/0133592_symbol.c @@ -0,0 +1,122 @@ +#include "esther/symbol.h" + +#include "esther/esther.h" +#include "esther/lexer.h" +#include "esther/std_map.h" +#include "esther/std_string.h" +#include "esther/string.h" + +static struct std_map *idSymbol; + +Object *id_to_sym(Esther *es, ID id) { + if (!is_valid_id(id)) + return NULL; + + if (!idSymbol || !std_map_contains(idSymbol, (void *) id)) { + if (!idSymbol) + idSymbol = std_map_new(compare_id); + + Object *symbol = Symbol_new(es, id_to_str(id)); + std_map_set(idSymbol, (void *) id, symbol); + return symbol; + } + + return std_map_get(idSymbol, (void *) id); +} + +Object *str_to_sym(Esther *es, struct string str) { + return id_to_sym(es, str_to_id(str)); +} + +Object *cstr_to_sym(Esther *es, const char *str) { + return id_to_sym(es, cstr_to_id(str)); +} + +Object *Symbol_new(Esther *es, struct string name) { + Object *self = gc_alloc(sizeof(Symbol)); + Symbol_init(es, self, name); + return self; +} + +Object *Symbol_new_cstr(Esther *es, const char *name) { + Object *self = gc_alloc(sizeof(Symbol)); + Symbol_init_cstr(es, self, name); + return self; +} + +static ObjectVTable vtable_for_Symbol = { + .base = { + .base = { + .mapOnRefs = Object_virtual_mapOnRefs }, + .finalize = Object_virtual_finalize }, + .toString = Symbol_virtual_toString, + .inspect = Symbol_virtual_inspect, + .equals = Symbol_virtual_equals, + .less = Symbol_virtual_less, + .isTrue = Object_virtual_isTrue, + .clone = Object_virtual_clone_unimplemented +}; + +static void Symbol_init_id(Esther *es, Object *self, ID id) { + Object_init(es, self, TSymbol, Esther_getRootObject(es, cstr_to_id("Symbol"))); + + as_Symbol(self)->id = id; + + *(void **) self = &vtable_for_Symbol; +} + +Object *Symbol_new_id(Esther *es, ID id) { + if (!is_valid_id(id)) + return NULL; + + Object *self = gc_alloc(sizeof(Symbol)); + Symbol_init_id(es, self, id); + return self; +} + +void Symbol_init(Esther *es, Object *self, struct string name) { + Symbol_init_id(es, self, str_to_id(name)); +} + +void Symbol_init_cstr(Esther *es, Object *self, const char *name) { + Symbol_init_id(es, self, cstr_to_id(name)); +} + +ID Symbol_getId(Object *self) { + return as_Symbol(self)->id; +} + +Object *Symbol_virtual_toString(Esther *es, Object *self) { + return String_new(es, id_to_str(as_Symbol(self)->id)); +} + +Object *Symbol_virtual_inspect(Esther *es, Object *self) { + struct string value = id_to_str(as_Symbol(self)->id); + + if (value.size == 0) + return String_new_cstr(es, ":\"\""); + + Object *str = String_new_cstr(es, ":"); + + if (Lexer_isOneToken(es, es->lexer, value.data)) + String_append_std(str, value); + else { + String_append_char(str, '\"'); + + struct string escaped = string_escape(value); + String_append_std(str, escaped); + string_free(escaped); + + String_append_char(str, '\"'); + } + + return str; +} + +bool Symbol_virtual_equals(Object *self, Object *obj) { + return Object_getType(obj) == TSymbol ? as_Symbol(self)->id == as_Symbol(obj)->id : Object_virtual_equals(self, obj); +} + +bool Symbol_virtual_less(Object *self, Object *obj) { + return Object_getType(obj) == TSymbol ? as_Symbol(self)->id < as_Symbol(obj)->id : Object_virtual_less(self, obj); +} diff --git a/pool/shard008/C/0133593_ffi.c b/pool/shard008/C/0133593_ffi.c new file mode 100644 index 0000000000000000000000000000000000000000..bf420936dbd235eb93062e957433ee688caafe52 --- /dev/null +++ b/pool/shard008/C/0133593_ffi.c @@ -0,0 +1,226 @@ +/* ----------------------------------------------------------------------- + prep_cif.c - Copyright (c) 1996, 1998 Red Hat, Inc. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#include +#include + +#include +#include + +/* Round up to FFI_SIZEOF_ARG. */ +#define STACK_ARG_SIZE(x) ALIGN(x, FFI_SIZEOF_ARG) + +/* Perform machine independent initialization of aggregate type + specifications. */ + +static ffi_status +initialize_aggregate( +/*@out@*/ ffi_type* arg) +{ +/*@-usedef@*/ + + if (arg == NULL || arg->elements == NULL || + arg->size != 0 || arg->alignment != 0) + return FFI_BAD_TYPEDEF; + + ffi_type** ptr = &(arg->elements[0]); + + while ((*ptr) != NULL) + { + if (((*ptr)->size == 0) && (initialize_aggregate(*ptr) != FFI_OK)) + return FFI_BAD_TYPEDEF; + + /* Perform a sanity check on the argument type */ + FFI_ASSERT_VALID_TYPE(*ptr); + +#ifdef POWERPC_DARWIN + int curalign = (*ptr)->alignment; + + if (ptr != &(arg->elements[0])) + { + if (curalign > 4 && curalign != 16) + curalign = 4; + } + + arg->size = ALIGN(arg->size, curalign); + arg->size += (*ptr)->size; + arg->alignment = (arg->alignment > curalign) ? + arg->alignment : curalign; +#else + arg->size = ALIGN(arg->size, (*ptr)->alignment); + arg->size += (*ptr)->size; + arg->alignment = (arg->alignment > (*ptr)->alignment) ? + arg->alignment : (*ptr)->alignment; +#endif + + ptr++; + } + + /* Structure size includes tail padding. This is important for + structures that fit in one register on ABIs like the PowerPC64 + Linux ABI that right justify small structs in a register. + It's also needed for nested structure layout, for example + struct A { long a; char b; }; struct B { struct A x; char y; }; + should find y at an offset of 2*sizeof(long) and result in a + total size of 3*sizeof(long). */ + arg->size = ALIGN(arg->size, arg->alignment); + + if (arg->size == 0) + return FFI_BAD_TYPEDEF; + + return FFI_OK; + +/*@=usedef@*/ +} + +#ifndef __CRIS__ +/* The CRIS ABI specifies structure elements to have byte + alignment only, so it completely overrides this functions, + which assumes "natural" alignment and padding. */ + +/* Perform machine independent ffi_cif preparation, then call + machine dependent routine. */ + +#if defined(X86_DARWIN) + +static inline bool +struct_on_stack( + int size) +{ + if (size > 8) + return true; + + /* This is not what the ABI says, but is what is really implemented */ + switch (size) + { + case 1: + case 2: + case 4: + case 8: + return false; + + default: + return true; + } +} + +#endif // defined(X86_DARWIN) + +// Arguments' ffi_type->alignment must be nonzero. +ffi_status +ffi_prep_cif( +/*@out@*/ /*@partial@*/ ffi_cif* cif, + ffi_abi abi, + unsigned int nargs, +/*@dependent@*/ /*@out@*/ /*@partial@*/ ffi_type* rtype, +/*@dependent@*/ ffi_type** atypes) +{ + if (cif == NULL) + return FFI_BAD_TYPEDEF; + + if (abi <= FFI_FIRST_ABI || abi > FFI_DEFAULT_ABI) + return FFI_BAD_ABI; + + unsigned int bytes = 0; + unsigned int i; + ffi_type** ptr; + + cif->abi = abi; + cif->arg_types = atypes; + cif->nargs = nargs; + cif->rtype = rtype; + cif->flags = 0; + + /* Initialize the return type if necessary */ + /*@-usedef@*/ + if ((cif->rtype->size == 0) && (initialize_aggregate(cif->rtype) != FFI_OK)) + return FFI_BAD_TYPEDEF; + /*@=usedef@*/ + + /* Perform a sanity check on the return type */ + FFI_ASSERT_VALID_TYPE(cif->rtype); + + /* x86-64 and s390 stack space allocation is handled in prep_machdep. */ +#if !defined M68K && !defined __x86_64__ && !defined S390 && !defined PA + /* Make space for the return structure pointer */ + if (cif->rtype->type == FFI_TYPE_STRUCT +#ifdef SPARC + && (cif->abi != FFI_V9 || cif->rtype->size > 32) +#endif +#ifdef X86_DARWIN + && (struct_on_stack(cif->rtype->size)) +#endif + ) + bytes = STACK_ARG_SIZE(sizeof(void*)); +#endif + + for (ptr = cif->arg_types, i = cif->nargs; i > 0; i--, ptr++) + { + /* Initialize any uninitialized aggregate type definitions */ + if (((*ptr)->size == 0) && (initialize_aggregate((*ptr)) != FFI_OK)) + return FFI_BAD_TYPEDEF; + + if ((*ptr)->alignment == 0) + return FFI_BAD_TYPEDEF; + + /* Perform a sanity check on the argument type, do this + check after the initialization. */ + FFI_ASSERT_VALID_TYPE(*ptr); + +#if defined(X86_DARWIN) + { + int align = (*ptr)->alignment; + + if (align > 4) + align = 4; + + if ((align - 1) & bytes) + bytes = ALIGN(bytes, align); + + bytes += STACK_ARG_SIZE((*ptr)->size); + } +#elif !defined __x86_64__ && !defined S390 && !defined PA +#ifdef SPARC + if (((*ptr)->type == FFI_TYPE_STRUCT + && ((*ptr)->size > 16 || cif->abi != FFI_V9)) + || ((*ptr)->type == FFI_TYPE_LONGDOUBLE + && cif->abi != FFI_V9)) + bytes += sizeof(void*); + else +#endif + { + /* Add any padding if necessary */ + if (((*ptr)->alignment - 1) & bytes) + bytes = ALIGN(bytes, (*ptr)->alignment); + + bytes += STACK_ARG_SIZE((*ptr)->size); + } +#endif + } + + cif->bytes = bytes; + + /* Perform machine dependent cif processing */ + return ffi_prep_cif_machdep(cif); +} +#endif /* not __CRIS__ */ diff --git a/pool/shard008/C/0133595_single.c b/pool/shard008/C/0133595_single.c new file mode 100644 index 0000000000000000000000000000000000000000..292c9120a84abfd0e626faa3274838eb45c88795 --- /dev/null +++ b/pool/shard008/C/0133595_single.c @@ -0,0 +1,45 @@ +#include "clar_libgit2.h" +#include "posix.h" + +static void +cleanup__remove_file(void *_file) +{ + cl_must_pass(p_unlink((char *)_file)); +} + +/* test retrieving OID from a file apart from the ODB */ +void test_status_single__hash_single_file(void) +{ + static const char file_name[] = "new_file"; + static const char file_contents[] = "new_file\n"; + static const char file_hash[] = "d4fa8600b4f37d7516bef4816ae2c64dbf029e3a"; + + git_oid expected_id, actual_id; + + /* initialization */ + git_oid_fromstr(&expected_id, file_hash); + cl_git_mkfile(file_name, file_contents); + cl_set_cleanup(&cleanup__remove_file, (void *)file_name); + + cl_git_pass(git_odb_hashfile(&actual_id, file_name, GIT_OBJ_BLOB)); + cl_assert(git_oid_cmp(&expected_id, &actual_id) == 0); +} + +/* test retrieving OID from an empty file apart from the ODB */ +void test_status_single__hash_single_empty_file(void) +{ + static const char file_name[] = "new_empty_file"; + static const char file_contents[] = ""; + static const char file_hash[] = "e69de29bb2d1d6434b8b29ae775ad8c2e48c5391"; + + git_oid expected_id, actual_id; + + /* initialization */ + git_oid_fromstr(&expected_id, file_hash); + cl_git_mkfile(file_name, file_contents); + cl_set_cleanup(&cleanup__remove_file, (void *)file_name); + + cl_git_pass(git_odb_hashfile(&actual_id, file_name, GIT_OBJ_BLOB)); + cl_assert(git_oid_cmp(&expected_id, &actual_id) == 0); +} + diff --git a/pool/shard008/C/0133596_prep_nvram.c b/pool/shard008/C/0133596_prep_nvram.c new file mode 100644 index 0000000000000000000000000000000000000000..0aaee70d906c6eee5c117a8e860338b09580863f --- /dev/null +++ b/pool/shard008/C/0133596_prep_nvram.c @@ -0,0 +1,140 @@ +/* + * arch/ppc/platforms/prep_nvram.c + * + * Copyright (C) 1998 Corey Minyard + * + */ +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +static char nvramData[MAX_PREP_NVRAM]; +static NVRAM_MAP *nvram=(NVRAM_MAP *)&nvramData[0]; + +unsigned char __prep prep_nvram_read_val(int addr) +{ + outb(addr, PREP_NVRAM_AS0); + outb(addr>>8, PREP_NVRAM_AS1); + return inb(PREP_NVRAM_DATA); +} + +void __prep prep_nvram_write_val(int addr, + unsigned char val) +{ + outb(addr, PREP_NVRAM_AS0); + outb(addr>>8, PREP_NVRAM_AS1); + outb(val, PREP_NVRAM_DATA); +} + +void __init init_prep_nvram(void) +{ + unsigned char *nvp; + int i; + int nvramSize; + + /* + * The following could fail if the NvRAM were corrupt but + * we expect the boot firmware to have checked its checksum + * before boot + */ + nvp = (char *) &nvram->Header; + for (i=0; iHeader.GEAddress+nvram->Header.GELength; + if(nvramSize>MAX_PREP_NVRAM) + { + /* + * NvRAM is too large + */ + nvram->Header.GELength=0; + return; + } + + /* + * Read the remainder of the PReP NvRAM + */ + nvp = (char *) &nvram->GEArea[0]; + for (i=sizeof(HEADER); iGEArea)) < nvram->Header.GELength) + && (*cp == '\0')) + { + cp++; + } + + if ((cp - ((char *) nvram->GEArea)) < nvram->Header.GELength) { + return cp; + } else { + return NULL; + } +} + + + diff --git a/pool/shard008/C/0133604_pthread_mutex.c b/pool/shard008/C/0133604_pthread_mutex.c new file mode 100644 index 0000000000000000000000000000000000000000..69ddc7dbc82ca643dd8332b3943995166bfa5ee4 --- /dev/null +++ b/pool/shard008/C/0133604_pthread_mutex.c @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2017 Intel Corporation + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include +#include +#include "ksched.h" +#include "wait_q.h" + +int pthread_mutex_trylock(pthread_mutex_t *m) +{ + int key = irq_lock(), ret = -EBUSY; + + if (m->sem->count) { + m->sem->count = 0; + ret = 0; + } + + irq_unlock(key); + + return ret; +} diff --git a/pool/shard008/C/0133606_registers.c b/pool/shard008/C/0133606_registers.c new file mode 100644 index 0000000000000000000000000000000000000000..5d847bfa7175eecc0849fade1d84b7d883ea5262 --- /dev/null +++ b/pool/shard008/C/0133606_registers.c @@ -0,0 +1,152 @@ +/* Registers facility functions + Copyright (c) 1997-2004 Sandro Sigala. All rights reserved. + + This file is part of Zile. + + Zile is free software; you can redistribute it and/or modify it under + the terms of the GNU General Public License as published by the Free + Software Foundation; either version 2, or (at your option) any later + version. + + Zile 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 General Public License + for more details. + + You should have received a copy of the GNU General Public License + along with Zile; see the file COPYING. If not, write to the Free + Software Foundation, Fifth Floor, 51 Franklin Street, Boston, MA + 02111-1301, USA. */ + +#include "config.h" + +#include +#include +#include +#include + +#include "zile.h" +#include "extern.h" + +#define NUM_REGISTERS 256 + +static struct { + char *text; + size_t size; +} regs[NUM_REGISTERS]; + +DEFUN("copy-to-register", copy_to_register) +/*+ +Copy region into the user specified register. ++*/ +{ + Region r; + char *p; + int reg; + + minibuf_write("Copy to register: "); + term_refresh(); + if ((reg = getkey()) == KBD_CANCEL) + return cancel(); + minibuf_clear(); + reg %= NUM_REGISTERS; + + if (warn_if_no_mark()) + return FALSE; + + calculate_the_region(&r); + + p = copy_text_block(r.start.n, r.start.o, r.size); + if (regs[reg].text != NULL) + free(regs[reg].text); + regs[reg].text = p; + regs[reg].size = r.size; + + return TRUE; +} +END_DEFUN + +static void insert_register(int reg) +{ + undo_save(UNDO_REMOVE_BLOCK, cur_bp->pt, regs[reg].size, 0); + undo_nosave = TRUE; + insert_nstring(regs[reg].text, regs[reg].size); + undo_nosave = FALSE; +} + +DEFUN("insert-register", insert_register) +/*+ +Insert contents of the user specified register. +Puts point before and mark after the inserted text. ++*/ +{ + int reg, uni; + + if (warn_if_readonly_buffer()) + return FALSE; + + minibuf_write("Insert register: "); + term_refresh(); + if ((reg = getkey()) == KBD_CANCEL) + return cancel(); + minibuf_clear(); + reg %= NUM_REGISTERS; + + if (regs[reg].text == NULL) { + minibuf_error("Register does not contain text"); + return FALSE; + } + + set_mark_command(); + + undo_save(UNDO_START_SEQUENCE, cur_bp->pt, 0, 0); + for (uni = 0; uni < last_uniarg; ++uni) + insert_register(reg); + undo_save(UNDO_END_SEQUENCE, cur_bp->pt, 0, 0); + + exchange_point_and_mark(); + deactivate_mark(); + + return TRUE; +} +END_DEFUN + +static void write_registers_list(va_list ap) +{ + size_t i, count; + + (void)ap; + bprintf("%-8s %8s\n", "Register", "Size"); + bprintf("%-8s %8s\n", "--------", "----"); + for (i = count = 0; i < NUM_REGISTERS; ++i) + if (regs[i].text != NULL) { + astr as = astr_new(); + ++count; + if (isprint(i)) + astr_afmt(as, "`%c'", i); + else + astr_afmt(as, "`\\%o'", i); + bprintf("%-8s %8d\n", astr_cstr(as), regs[i].size); + astr_delete(as); + } + if (!count) + bprintf("No registers defined\n"); +} + +DEFUN("list-registers", list_registers) +/*+ +List defined registers. ++*/ +{ + write_temp_buffer("*Registers List*", write_registers_list); + return TRUE; +} +END_DEFUN + +void free_registers(void) +{ + int i; + for (i = 0; i < NUM_REGISTERS; ++i) + if (regs[i].text != NULL) + free(regs[i].text); +} diff --git a/pool/shard008/C/0133609_tst-dlmodcount.c b/pool/shard008/C/0133609_tst-dlmodcount.c new file mode 100644 index 0000000000000000000000000000000000000000..6cfa36683634251d477d7548a62ff51f9cdb3acd --- /dev/null +++ b/pool/shard008/C/0133609_tst-dlmodcount.c @@ -0,0 +1,109 @@ +/* Copyright (C) 2004-2015 Free Software Foundation, Inc. + This file is part of the GNU C Library. + Contributed by David Mosberger , 2004. + + The GNU C Library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + The GNU C 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 the GNU C Library; if not, see + . */ + +#include +#include +#include +#include + +#define SET 0 +#define ADD 1 +#define REMOVE 2 + +#define leq(l,r) (((r) - (l)) <= ~0ULL / 2) + +static int +callback (struct dl_phdr_info *info, size_t size, void *ptr) +{ + static int last_adds = 0, last_subs = 0; + intptr_t cmd = (intptr_t) ptr; + + printf (" size = %Zu\n", size); + if (size < (offsetof (struct dl_phdr_info, dlpi_subs) + + sizeof (info->dlpi_subs))) + { + fprintf (stderr, "dl_iterate_phdr failed to pass dlpi_adds/dlpi_subs\n"); + exit (5); + } + + printf (" dlpi_adds = %Lu dlpi_subs = %Lu\n", + info->dlpi_adds, info->dlpi_subs); + + switch (cmd) + { + case SET: + break; + + case ADD: + if (leq (info->dlpi_adds, last_adds)) + { + fprintf (stderr, "dlpi_adds failed to get incremented!\n"); + exit (3); + } + break; + + case REMOVE: + if (leq (info->dlpi_subs, last_subs)) + { + fprintf (stderr, "dlpi_subs failed to get incremented!\n"); + exit (4); + } + break; + } + last_adds = info->dlpi_adds; + last_subs = info->dlpi_subs; + return -1; +} + +static void * +load (const char *path) +{ + void *handle; + + printf ("loading `%s'\n", path); + handle = dlopen (path, RTLD_LAZY); + if (!handle) + exit (1); + dl_iterate_phdr (callback, (void *)(intptr_t) ADD); + return handle; +} + +static void +unload (const char *path, void *handle) +{ + printf ("unloading `%s'\n", path); + if (dlclose (handle) < 0) + exit (2); + dl_iterate_phdr (callback, (void *)(intptr_t) REMOVE); +} + +static int +do_test (void) +{ + void *handle1, *handle2; + + dl_iterate_phdr (callback, (void *)(intptr_t) SET); + handle1 = load ("firstobj.so"); + handle2 = load ("globalmod1.so"); + unload ("firstobj.so", handle1); + unload ("globalmod1.so", handle2); + return 0; +} + +#define TEST_FUNCTION do_test () +#include "../test-skeleton.c" diff --git a/pool/shard008/C/0133617_test-ftell.c b/pool/shard008/C/0133617_test-ftell.c new file mode 100644 index 0000000000000000000000000000000000000000..67b001728b853841a0d414b0d3541eddf7e58073 --- /dev/null +++ b/pool/shard008/C/0133617_test-ftell.c @@ -0,0 +1,107 @@ +/* Test of ftell() function. + Copyright (C) 2007-2019 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* Written by Bruno Haible , 2007. */ + +#include + +/* None of the files accessed by this test are large, so disable the + fseek link warning if we are not using the gnulib fseek module. */ +#define _GL_NO_LARGE_FILES +#include + +#include "signature.h" +SIGNATURE_CHECK (ftell, long, (FILE *)); + +#include "binary-io.h" +#include "macros.h" + +#ifndef FUNC_UNGETC_BROKEN +# define FUNC_UNGETC_BROKEN 0 +#endif + +int +main (int argc, char **argv) +{ + int ch; + /* Assume stdin is seekable iff argc > 1. */ + if (argc == 1) + { + ASSERT (ftell (stdin) == -1); + return 0; + } + + /* mingw ftell is unreliable on text mode input. */ + set_binary_mode (0, O_BINARY); + + /* Simple tests. */ + ASSERT (ftell (stdin) == 0); + + ch = fgetc (stdin); + ASSERT (ch == '#'); + ASSERT (ftell (stdin) == 1); + + /* Test ftell after ungetc of read input. */ + ch = ungetc ('#', stdin); + ASSERT (ch == '#'); + ASSERT (ftell (stdin) == 0); + + ch = fgetc (stdin); + ASSERT (ch == '#'); + ASSERT (ftell (stdin) == 1); + + /* Test ftell after fseek. */ + ASSERT (fseek (stdin, 2, SEEK_SET) == 0); + ASSERT (ftell (stdin) == 2); + + /* Test ftell after random ungetc. */ + ch = fgetc (stdin); + ASSERT (ch == '/'); + ch = ungetc ('@', stdin); + ASSERT (ch == '@'); + ASSERT (ftell (stdin) == 2); + + ch = fgetc (stdin); + ASSERT (ch == '@'); + ASSERT (ftell (stdin) == 3); + + if (2 < argc) + { + if (FUNC_UNGETC_BROKEN) + { + fputs ("Skipping test: ungetc cannot handle arbitrary bytes\n", + stderr); + return 77; + } + /* Test ftell after ungetc without read. */ + ASSERT (fseek (stdin, 0, SEEK_CUR) == 0); + ASSERT (ftell (stdin) == 3); + + ch = ungetc ('~', stdin); + ASSERT (ch == '~'); + ASSERT (ftell (stdin) == 2); + } + +#if !defined __MINT__ /* FreeMiNT has problems seeking past end of file */ + /* Test ftell beyond end of file. */ + ASSERT (fseek (stdin, 0, SEEK_END) == 0); + ch = ftell (stdin); + ASSERT (fseek (stdin, 10, SEEK_END) == 0); + ASSERT (ftell (stdin) == ch + 10); +#endif + + return 0; +} diff --git a/pool/shard008/C/0133625_mb837.c b/pool/shard008/C/0133625_mb837.c new file mode 100644 index 0000000000000000000000000000000000000000..d990f81a9f6c8ff42897e54474c4cd66aedf723c --- /dev/null +++ b/pool/shard008/C/0133625_mb837.c @@ -0,0 +1,258 @@ +/* + * (C) Copyright 2008-2011 STMicroelectronics. + * + * Sean McGoogan + * + * See file CREDITS for list of people who contributed to this + * project. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of + * the License, or (at your option) any later version. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, + * MA 02111-1307 USA + */ + +#include +#include +#include +#include +#include +#include + + + /* + * WARNING! WARNING! WARNING! WARNING! WARNING! + * ------------------------------------------------ + * + * The ethernet PHYs may be reset by one of two mechanisms: + * + * a) the EPLD on the MB705 peripheral board + * + * b) via the PCF8575 (IC12) PIO Extender. + * + * This code does *not* (currently) make any attempt to + * reset the PHYs, but relies on the MB705 to reset the + * PHYs on power-on, which (thus far) demonstrably works well! + * + * If an MB705 is *not* connected, then additional work + * is required, including fitting J14-A, and J14-B. + * We currently just issue a diagnostic to warn about this ... + */ +#if !defined(CONFIG_SH_MB705) +#warning Ethernet PHYs not reset without a MB705 present! +#endif + + +#if defined(CONFIG_SH_MB705) + /* + * More recent EPLD versions have the EPLD in EMI space, + * using CSCn (EMI Bank #2), nominally at physical 0x04800000. + */ +#if !defined(CFG_EPLD_PHYSICAL_BASE) +# define CFG_EPLD_PHYSICAL_BASE 0x04800000 /* CSCn (EMI Bank #2) */ +#endif /* CFG_EPLD_PHYSICAL_BASE */ + /* map the physical address to UN-cached virtual address */ +#if !defined(CFG_EPLD_BASE) +# define CFG_EPLD_BASE ( 0xa0000000 | (CFG_EPLD_PHYSICAL_BASE) ) +#endif /* CFG_EPLD_BASE */ + /* + * following are the offsets within the EMI EPLD (IC21), + * for the MB705 Peripheral board. + */ +#define EPLD_IDENT 0x00 /* EPLD Identifier Register */ +#define EPLD_TEST 0x02 /* EPLD Test Register */ +#define EPLD_SWITCH 0x04 /* EPLD Switch Register */ +#define EPLD_MISC 0x0a /* Miscellaneous Control Register */ +#endif /* CONFIG_SH_MB705 */ + + +#if defined(CONFIG_SH_MB705) +static inline void epld_write(unsigned long value, unsigned long offset) +{ + /* 16-bit write to EPLD registers */ + writew(value, CFG_EPLD_BASE + offset); +} + +static inline unsigned long epld_read(unsigned long offset) +{ + /* 16-bit read from EPLD registers */ + return readw(CFG_EPLD_BASE + offset); +} + +static int mb705_init_epld(void) +{ + const unsigned short test_value = 0x1234u; + unsigned short epld_reg; + unsigned short epld_version, board_version; + + /* write (anything) to the test register */ + epld_write(test_value, EPLD_TEST); + /* verify we got back an inverted result */ + epld_reg = epld_read(EPLD_TEST); + if (epld_reg != (test_value ^ 0xffffu)) { + printf("Failed EPLD test (offset=%02x, result=%04x)\n", + EPLD_TEST, epld_reg); + return 1; + } + + /* Assume we can trust the version register */ + epld_reg = epld_read(EPLD_IDENT); + board_version = epld_reg >> 4 & 0xfu; + epld_version = epld_reg & 0xfu; + + /* display the board revision, and EPLD version */ + printf("MB705: revision %c, EPLD version %02d\n", + board_version + 'A' - 1, + epld_version); + + /* return a "success" result */ + return 0; +} +#endif /* CONFIG_SH_MB705 */ + +void flashWriteEnable(void) +{ +#if defined(CONFIG_SH_MB705) + unsigned short epld_reg; + + /* Enable Vpp for writing to flash */ + epld_reg = epld_read(EPLD_MISC); + epld_reg |= 1u << 3; /* NandFlashWP = MISC[3] = 1 */ + epld_reg |= 1u << 2; /* NorFlashVpp = MISC[2] = 1 */ + epld_write(epld_reg, EPLD_MISC); +#endif /* CONFIG_SH_MB705 */ +} + +void flashWriteDisable(void) +{ +#if defined(CONFIG_SH_MB705) + unsigned short epld_reg; + + /* Disable Vpp for writing to flash */ + epld_reg = epld_read(EPLD_MISC); + epld_reg &= ~(1u << 3); /* NandFlashWP = MISC[3] = 0 */ + epld_reg &= ~(1u << 2); /* NorFlashVpp = MISC[2] = 0 */ + epld_write(epld_reg, EPLD_MISC); +#endif /* CONFIG_SH_MB705 */ +} + + +#define PIOALT(port, pin, alt, dir) \ +do \ +{ \ + stx7108_pioalt_select((port), (pin), (alt)); \ + stx7108_pioalt_pad((port), (pin), (dir)); \ +} while(0) + +static void configPIO(void) +{ + /* Setup PIOs for ASC device */ + +#if CFG_STM_ASC_BASE == ST40_ASC2_REGS_BASE + + /* Route UART2 via PIO14 for TX, RX, CTS & RTS (Alternative #1) */ + PIOALT(14, 4, 1, stm_pad_direction_output); /* UART2-TX */ + PIOALT(14, 5, 1, stm_pad_direction_input); /* UART2-RX */ + PIOALT(14, 6, 1, stm_pad_direction_output); /* UART2-RTS */ + PIOALT(14, 7, 1, stm_pad_direction_input); /* UART2-CTS */ + +#elif CFG_STM_ASC_BASE == ST40_ASC3_REGS_BASE + + /* Route UART3 via PIO21 for TX, RX, CTS & RTS (Alternative #2) */ + PIOALT(21, 0, 2, stm_pad_direction_output); /* UART3-TX */ + PIOALT(21, 1, 2, stm_pad_direction_input); /* UART3-RX */ + PIOALT(21, 3, 2, stm_pad_direction_output); /* UART3-RTS */ + PIOALT(21, 4, 2, stm_pad_direction_input); /* UART3-CTS */ + +#else +#error Unknown ASC port selected! +#endif /* CFG_STM_ASC_BASE == ST40_ASCx_REGS_BASE */ +} + +extern int board_init(void) +{ + configPIO(); + +#ifdef QQQ /* QQQ - DELETE */ +#if defined(CONFIG_SH_STM_SATA) + stx7105_configure_sata (); +#endif /* CONFIG_SH_STM_SATA */ +#endif /* QQQ - DELETE */ + +#ifdef CONFIG_DRIVER_NET_STM_GMAC +#if CFG_STM_STMAC_BASE == CFG_STM_STMAC0_BASE /* MII0, on CN18 */ + stx7108_configure_ethernet(0, &(struct stx7108_ethernet_config) { + .mode = stx7108_ethernet_mode_mii, + .ext_clk = 1, + .phy_bus = 0, }); +#elif CFG_STM_STMAC_BASE == CFG_STM_STMAC1_BASE /* MII1, on CN19 */ + stx7108_configure_ethernet(1, &(struct stx7108_ethernet_config) { + .mode = stx7108_ethernet_mode_mii, + .ext_clk = 1, + .phy_bus = 1, }); +#else +#error Unknown base address for the STM GMAC +#endif +#endif /* CONFIG_DRIVER_NET_STM_GMAC */ + +#if defined(CONFIG_CMD_I2C) + stx7108_configure_i2c(); +#endif /* CONFIG_CMD_I2C */ + + /* + * For accessing the EPLD (on EMI Bank #2 (CSnC)), we need to + * elongate the rising CSn time, otherwise we risk the FET switches + * not being enabled for long enough. + * Failure to do this correctly, can result in the + * mb705_init_epld() function failing to pass the TEST. + * + * The following is (now) known to work: + * + * set CSE2_TIME_WRITE = 0x1 [19:16] (rising-edge of CSn) + * + * Note with CSE2_TIME_WRITE=0x0, or CSE2_TIME_WRITE=0x2 + * then, the EPLD *write* can fail, and this is + * (bizarrely) a function of the PC's offset in the I$! + * + * An alternative solution may be to enable the FET switches + * permanently, by setting J5A and J5B as follows: + * J5A: remove (default is 2-3) + * J5B: 1-2 (default is 2-3) + */ +#if 1 + *ST40_EMI_BANK2_EMICONFIGDATA2 &= ~(0xfu << 16); + *ST40_EMI_BANK2_EMICONFIGDATA2 |= (0x1u << 16); +#endif + + return 0; +} + +int checkboard (void) +{ + printf ("\n\nBoard: STx7108-Mboard (MB837)" +#ifdef CONFIG_SH_SE_MODE + " [32-bit mode]" +#else + " [29-bit mode]" +#endif + "\n"); + +#if defined(CONFIG_SH_MB705) + /* + * initialize the EPLD on the MB705. + */ + mb705_init_epld(); +#endif /* CONFIG_SH_MB705 */ + + return 0; +} diff --git a/pool/shard008/C/0133626_control-notify.c b/pool/shard008/C/0133626_control-notify.c new file mode 100644 index 0000000000000000000000000000000000000000..a298cdc5bd60418170a07fa5240ed97f66061c2d --- /dev/null +++ b/pool/shard008/C/0133626_control-notify.c @@ -0,0 +1,203 @@ +/* $OpenBSD$ */ + +/* + * Copyright (c) 2012 Nicholas Marriott + * Copyright (c) 2012 George Nachman + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER + * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING + * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#include + +#include "tmux.h" + +#define CONTROL_SHOULD_NOTIFY_CLIENT(c) \ + ((c) != NULL && ((c)->flags & CLIENT_CONTROL)) + +void +control_notify_input(struct client *c, struct window_pane *wp, + struct evbuffer *input) +{ + u_char *buf; + size_t len; + struct evbuffer *message; + u_int i; + + if (c->session == NULL) + return; + + buf = EVBUFFER_DATA(input); + len = EVBUFFER_LENGTH(input); + + /* + * Only write input if the window pane is linked to a window belonging + * to the client's session. + */ + if (winlink_find_by_window(&c->session->windows, wp->window) != NULL) { + message = evbuffer_new(); + evbuffer_add_printf(message, "%%output %%%u ", wp->id); + for (i = 0; i < len; i++) { + if (buf[i] < ' ' || buf[i] == '\\') + evbuffer_add_printf(message, "\\%03o", buf[i]); + else + evbuffer_add_printf(message, "%c", buf[i]); + } + control_write_buffer(c, message); + evbuffer_free(message); + } +} + +void +control_notify_window_layout_changed(struct window *w) +{ + struct client *c; + struct session *s; + struct format_tree *ft; + struct winlink *wl; + u_int i; + const char *template; + + for (i = 0; i < ARRAY_LENGTH(&clients); i++) { + c = ARRAY_ITEM(&clients, i); + if (!CONTROL_SHOULD_NOTIFY_CLIENT(c) || c->session == NULL) + continue; + s = c->session; + + if (winlink_find_by_window_id(&s->windows, w->id) == NULL) + continue; + + /* + * When the last pane in a window is closed it won't have a + * layout root and we don't need to inform the client about the + * layout change because the whole window will go away soon. + */ + if (w->layout_root == NULL) + continue; + template = "%layout-change #{window_id} #{window_layout}"; + + ft = format_create(); + wl = winlink_find_by_window(&s->windows, w); + if (wl != NULL) { + format_winlink(ft, c->session, wl); + control_write(c, "%s", format_expand(ft, template)); + } + format_free(ft); + } +} + +void +control_notify_window_unlinked(unused struct session *s, struct window *w) +{ + struct client *c; + u_int i; + + for (i = 0; i < ARRAY_LENGTH(&clients); i++) { + c = ARRAY_ITEM(&clients, i); + if (!CONTROL_SHOULD_NOTIFY_CLIENT(c) || c->session == NULL) + continue; + + control_write(c, "%%window-close @%u", w->id); + } +} + +void +control_notify_window_linked(unused struct session *s, struct window *w) +{ + struct client *c; + struct session *cs; + u_int i; + + for (i = 0; i < ARRAY_LENGTH(&clients); i++) { + c = ARRAY_ITEM(&clients, i); + if (!CONTROL_SHOULD_NOTIFY_CLIENT(c) || c->session == NULL) + continue; + cs = c->session; + + if (winlink_find_by_window_id(&cs->windows, w->id) != NULL) + control_write(c, "%%window-add @%u", w->id); + else + control_write(c, "%%unlinked-window-add @%u", w->id); + } +} + +void +control_notify_window_renamed(struct window *w) +{ + struct client *c; + u_int i; + + for (i = 0; i < ARRAY_LENGTH(&clients); i++) { + c = ARRAY_ITEM(&clients, i); + if (!CONTROL_SHOULD_NOTIFY_CLIENT(c) || c->session == NULL) + continue; + + control_write(c, "%%window-renamed @%u %s", w->id, w->name); + } +} + +void +control_notify_attached_session_changed(struct client *c) +{ + struct session *s; + + if (!CONTROL_SHOULD_NOTIFY_CLIENT(c) || c->session == NULL) + return; + s = c->session; + + control_write(c, "%%session-changed $%u %s", s->id, s->name); +} + +void +control_notify_session_renamed(struct session *s) +{ + struct client *c; + u_int i; + + for (i = 0; i < ARRAY_LENGTH(&clients); i++) { + c = ARRAY_ITEM(&clients, i); + if (!CONTROL_SHOULD_NOTIFY_CLIENT(c)) + continue; + + control_write(c, "%%session-renamed $%u %s", s->id, s->name); + } +} + +void +control_notify_session_created(unused struct session *s) +{ + struct client *c; + u_int i; + + for (i = 0; i < ARRAY_LENGTH(&clients); i++) { + c = ARRAY_ITEM(&clients, i); + if (!CONTROL_SHOULD_NOTIFY_CLIENT(c)) + continue; + + control_write(c, "%%sessions-changed"); + } +} + +void +control_notify_session_close(unused struct session *s) +{ + struct client *c; + u_int i; + + for (i = 0; i < ARRAY_LENGTH(&clients); i++) { + c = ARRAY_ITEM(&clients, i); + if (!CONTROL_SHOULD_NOTIFY_CLIENT(c)) + continue; + + control_write(c, "%%sessions-changed"); + } +} diff --git a/pool/shard008/C/0133630_CWE190_Integer_Overflow__short_max_square_61a.c b/pool/shard008/C/0133630_CWE190_Integer_Overflow__short_max_square_61a.c new file mode 100644 index 0000000000000000000000000000000000000000..7286de943049f849efa006427ba06fb5509c577d --- /dev/null +++ b/pool/shard008/C/0133630_CWE190_Integer_Overflow__short_max_square_61a.c @@ -0,0 +1,110 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE190_Integer_Overflow__short_max_square_61a.c +Label Definition File: CWE190_Integer_Overflow.label.xml +Template File: sources-sinks-61a.tmpl.c +*/ +/* + * @description + * CWE: 190 Integer Overflow + * BadSource: max Set data to the max value for short + * GoodSource: Set data to a small, non-zero number (two) + * Sinks: square + * GoodSink: Ensure there will not be an overflow before squaring data + * BadSink : Square data, which can lead to overflow + * Flow Variant: 61 Data flow: data returned from one function to another in different source files + * + * */ + +#include "std_testcase.h" + +#include + +#ifndef OMITBAD + +/* bad function declaration */ +short CWE190_Integer_Overflow__short_max_square_61b_badSource(short data); + +void CWE190_Integer_Overflow__short_max_square_61_bad() +{ + short data; + data = 0; + data = CWE190_Integer_Overflow__short_max_square_61b_badSource(data); + { + /* POTENTIAL FLAW: if (data*data) > SHRT_MAX, this will overflow */ + short result = data * data; + printIntLine(result); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +short CWE190_Integer_Overflow__short_max_square_61b_goodG2BSource(short data); + +static void goodG2B() +{ + short data; + data = 0; + data = CWE190_Integer_Overflow__short_max_square_61b_goodG2BSource(data); + { + /* POTENTIAL FLAW: if (data*data) > SHRT_MAX, this will overflow */ + short result = data * data; + printIntLine(result); + } +} + +/* goodB2G uses the BadSource with the GoodSink */ +short CWE190_Integer_Overflow__short_max_square_61b_goodB2GSource(short data); + +static void goodB2G() +{ + short data; + data = 0; + data = CWE190_Integer_Overflow__short_max_square_61b_goodB2GSource(data); + /* FIX: Add a check to prevent an overflow from occurring */ + if (abs((long)data) <= (long)sqrt((double)SHRT_MAX)) + { + short result = data * data; + printIntLine(result); + } + else + { + printLine("data value is too large to perform arithmetic safely."); + } +} + +void CWE190_Integer_Overflow__short_max_square_61_good() +{ + goodG2B(); + goodB2G(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + its own for testing or for building a binary to use in testing binary + analysis tools. It is not used when compiling all the testcases as one + application, which is how source code analysis tools are tested. */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE190_Integer_Overflow__short_max_square_61_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE190_Integer_Overflow__short_max_square_61_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard008/C/0133632_up_checkstack.c b/pool/shard008/C/0133632_up_checkstack.c new file mode 100644 index 0000000000000000000000000000000000000000..eb5f22d7440dd082977eb21c362d159471918e55 --- /dev/null +++ b/pool/shard008/C/0133632_up_checkstack.c @@ -0,0 +1,198 @@ +/**************************************************************************** + * arch/avr/src/avr/up_checkstack.c + * + * Copyright (C) 2011, 2013-2014 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. 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. + * 3. Neither the name NuttX nor the names of its contributors may be + * used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include + +#include +#include +#include +#include + +#include + +#include "up_internal.h" +#include "sched/sched.h" + +/**************************************************************************** + * Pre-processor Definitions + ****************************************************************************/ + +#ifdef CONFIG_STACK_COLORATION + +/**************************************************************************** + * Public Data + ****************************************************************************/ + +/**************************************************************************** + * Private Functions + ****************************************************************************/ + +static size_t do_stackcheck(uintptr_t alloc, size_t size); + +/**************************************************************************** + * Name: do_stackcheck + * + * Description: + * Determine (approximately) how much stack has been used be searching the + * stack memory for a high water mark. That is, the deepest level of the + * stack that clobbered some recognizable marker in the stack memory. + * + * Input Parameters: + * alloc - Allocation base address of the stack + * size - The size of the stack in bytes + * + * Returned value: + * The estimated amount of stack space used. + * + ****************************************************************************/ + +static size_t do_stackcheck(uintptr_t alloc, size_t size) +{ + FAR uint8_t *ptr; + size_t mark; +#if 0 + int i; + int j; +#endif + + /* The AVR uses a push-down stack: the stack grows toward lower addresses + * in memory. We need to start at the lowest address in the stack memory + * allocation and search to higher addresses. The first byte we encounter + * that does not have the magic value is the high water mark. + */ + + for (ptr = (FAR uint8_t *)alloc, mark = size; + *ptr == STACK_COLOR && mark > 0; + ptr++, mark--); + + /* If the stack is completely used, then this might mean that the stack + * overflowed from above (meaning that the stack is too small), or may + * have been overwritten from below meaning that some other stack or data + * structure overflowed. + * + * If you see returned values saying that the entire stack is being used + * then enable the following logic to see it there are unused areas in the + * middle of the stack. + */ + +#if 0 + if (mark + 16 > size) + { + ptr = (FAR uint8_t *)alloc; + for (i = 0; i < size; i += 64) + { + for (j = 0; j < 64; j++) + { + int ch; + if (*ptr++ == STACK_COLOR) + { + ch = '.'; + } + else + { + ch = 'X'; + } + + up_putc(ch); + } + + up_putc('\n'); + } + } +#endif + + /* Return our guess about how much stack space was used */ + + return mark; +} + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: up_check_stack and friends + * + * Description: + * Determine (approximately) how much stack has been used be searching the + * stack memory for a high water mark. That is, the deepest level of the + * stack that clobbered some recognizable marker in the stack memory. + * + * Input Parameters: + * None + * + * Returned value: + * The estimated amount of stack space used. + * + ****************************************************************************/ + +size_t up_check_tcbstack(FAR struct tcb_s *tcb) +{ + return do_stackcheck((uintptr_t)tcb->stack_alloc_ptr, tcb->adj_stack_size); +} + +ssize_t up_check_tcbstack_remain(FAR struct tcb_s *tcb) +{ + return (ssize_t)tcb->adj_stack_size - (ssize_t)up_check_tcbstack(tcb); +} + +size_t up_check_stack(void) +{ + return up_check_tcbstack((FAR struct tcb_s*)g_readytorun.head); +} + +ssize_t up_check_stack_remain(void) +{ + return up_check_tcbstack_remain((FAR struct tcb_s*)g_readytorun.head); +} + +#if CONFIG_ARCH_INTERRUPTSTACK > 3 +size_t up_check_intstack(void) +{ + uintptr_t start = (uintptr_t)g_intstackbase - (CONFIG_ARCH_INTERRUPTSTACK & ~3); + return do_stackcheck(start, (CONFIG_ARCH_INTERRUPTSTACK & ~3)); +} + +size_t up_check_intstack_remain(void) +{ + return (CONFIG_ARCH_INTERRUPTSTACK & ~3) - up_check_intstack(); +} +#endif + +#endif /* CONFIG_STACK_COLORATION */ diff --git a/pool/shard008/C/0133633_sram.c b/pool/shard008/C/0133633_sram.c new file mode 100644 index 0000000000000000000000000000000000000000..531666c211f88cf789d47fd52a3576cdd858e9d5 --- /dev/null +++ b/pool/shard008/C/0133633_sram.c @@ -0,0 +1,194 @@ +/* + * linux/arch/arm/mach-mmp/sram.c + * + * based on mach-davinci/sram.c - DaVinci simple SRAM allocator + * + * Copyright (c) 2011 Marvell Semiconductors Inc. + * All Rights Reserved + * + * Add for mmp sram support - Leo Yan + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + */ + +#include +#include +#include +#include +#include +#include +#include + +#include + +struct sram_bank_info +{ + char *pool_name; + struct gen_pool *gpool; + int granularity; + + phys_addr_t sram_phys; + void __iomem *sram_virt; + u32 sram_size; + + struct list_head node; +}; + +static DEFINE_MUTEX(sram_lock); +static LIST_HEAD(sram_bank_list); + +struct gen_pool *sram_get_gpool(char *pool_name) +{ + struct sram_bank_info *info = NULL; + + if (!pool_name) + { + return NULL; + } + + mutex_lock(&sram_lock); + + list_for_each_entry(info, &sram_bank_list, node) + + if (!strcmp(pool_name, info->pool_name)) + { + break; + } + + mutex_unlock(&sram_lock); + + if (&info->node == &sram_bank_list) + { + return NULL; + } + + return info->gpool; +} +EXPORT_SYMBOL(sram_get_gpool); + +static int sram_probe(struct platform_device *pdev) +{ + struct sram_platdata *pdata = pdev->dev.platform_data; + struct sram_bank_info *info; + struct resource *res; + int ret = 0; + + if (!pdata || !pdata->pool_name) + { + return -ENODEV; + } + + info = kzalloc(sizeof(*info), GFP_KERNEL); + + if (!info) + { + return -ENOMEM; + } + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + + if (res == NULL) + { + dev_err(&pdev->dev, "no memory resource defined\n"); + ret = -ENODEV; + goto out; + } + + if (!resource_size(res)) + { + return 0; + } + + info->sram_phys = (phys_addr_t)res->start; + info->sram_size = resource_size(res); + info->sram_virt = ioremap(info->sram_phys, info->sram_size); + info->pool_name = kstrdup(pdata->pool_name, GFP_KERNEL); + info->granularity = pdata->granularity; + + info->gpool = gen_pool_create(ilog2(info->granularity), -1); + + if (!info->gpool) + { + dev_err(&pdev->dev, "create pool failed\n"); + ret = -ENOMEM; + goto create_pool_err; + } + + ret = gen_pool_add_virt(info->gpool, (unsigned long)info->sram_virt, + info->sram_phys, info->sram_size, -1); + + if (ret < 0) + { + dev_err(&pdev->dev, "add new chunk failed\n"); + ret = -ENOMEM; + goto add_chunk_err; + } + + mutex_lock(&sram_lock); + list_add(&info->node, &sram_bank_list); + mutex_unlock(&sram_lock); + + platform_set_drvdata(pdev, info); + + dev_info(&pdev->dev, "initialized\n"); + return 0; + +add_chunk_err: + gen_pool_destroy(info->gpool); +create_pool_err: + iounmap(info->sram_virt); + kfree(info->pool_name); +out: + kfree(info); + return ret; +} + +static int sram_remove(struct platform_device *pdev) +{ + struct sram_bank_info *info; + + info = platform_get_drvdata(pdev); + + if (info == NULL) + { + return -ENODEV; + } + + mutex_lock(&sram_lock); + list_del(&info->node); + mutex_unlock(&sram_lock); + + gen_pool_destroy(info->gpool); + iounmap(info->sram_virt); + kfree(info->pool_name); + kfree(info); + return 0; +} + +static const struct platform_device_id sram_id_table[] = +{ + { "asram", MMP_ASRAM }, + { "isram", MMP_ISRAM }, + { } +}; + +static struct platform_driver sram_driver = +{ + .probe = sram_probe, + .remove = sram_remove, + .driver = { + .name = "mmp-sram", + }, + .id_table = sram_id_table, +}; + +static int __init sram_init(void) +{ + return platform_driver_register(&sram_driver); +} +core_initcall(sram_init); + +MODULE_LICENSE("GPL"); diff --git a/pool/shard008/C/0133634_gnc-owner-xml-v2.c b/pool/shard008/C/0133634_gnc-owner-xml-v2.c new file mode 100644 index 0000000000000000000000000000000000000000..7a5ae646604678f1b0a1fea81874cb37a61b4e73 --- /dev/null +++ b/pool/shard008/C/0133634_gnc-owner-xml-v2.c @@ -0,0 +1,244 @@ +/********************************************************************\ + * gnc-owner-xml-v2.c -- owner xml i/o implementation * + * * + * Copyright (C) 2002 Derek Atkins * + * * + * This program is free software; you can redistribute it and/or * + * modify it under the terms of the GNU General Public License as * + * published by the Free Software Foundation; either version 2 of * + * the License, or (at your option) any later version. * + * * + * This program 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 General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License* + * along with this program; if not, contact: * + * * + * Free Software Foundation Voice: +1-617-542-5942 * + * 51 Franklin Street, Fifth Floor Fax: +1-617-542-2652 * + * Boston, MA 02110-1301, USA gnu@gnu.org * + * * +\********************************************************************/ + +#include "config.h" + +#include +#include +#include + +#include "gnc-xml-helper.h" + +#include "sixtp.h" +#include "sixtp-utils.h" +#include "sixtp-parsers.h" +#include "sixtp-utils.h" +#include "sixtp-dom-parsers.h" +#include "sixtp-dom-generators.h" + +#include "gnc-xml.h" +#include "io-gncxml-gen.h" +#include "io-gncxml-v2.h" + +#include "gnc-owner-xml-v2.h" +#include "gncCustomerP.h" +#include "gncJobP.h" +#include "gncVendorP.h" +#include "gncEmployeeP.h" + +static QofLogModule log_module = GNC_MOD_IO; + +const gchar *owner_version_string = "2.0.0"; + +/* ids */ +#define owner_type_string "owner:type" +#define owner_id_string "owner:id" + +xmlNodePtr +gnc_owner_to_dom_tree (const char *tag, GncOwner *owner) +{ + xmlNodePtr ret; + const char *type_str; + + switch (gncOwnerGetType (owner)) + { + case GNC_OWNER_CUSTOMER: + type_str = GNC_ID_CUSTOMER; + break; + case GNC_OWNER_JOB: + type_str = GNC_ID_JOB; + break; + case GNC_OWNER_VENDOR: + type_str = GNC_ID_VENDOR; + break; + case GNC_OWNER_EMPLOYEE: + type_str = GNC_ID_EMPLOYEE; + break; + default: + PWARN ("Invalid owner type: %d", gncOwnerGetType (owner)); + return NULL; + } + + ret = xmlNewNode(NULL, BAD_CAST tag); + xmlSetProp(ret, BAD_CAST "version", BAD_CAST owner_version_string); + + xmlAddChild (ret, text_to_dom_tree (owner_type_string, type_str)); + xmlAddChild (ret, guid_to_dom_tree (owner_id_string, + gncOwnerGetGUID (owner))); + + return ret; +} + +/***********************************************************************/ + +struct owner_pdata +{ + GncOwner *owner; + QofBook *book; +}; + +static gboolean +owner_type_handler (xmlNodePtr node, gpointer owner_pdata) +{ + struct owner_pdata *pdata = owner_pdata; + char* txt = dom_tree_to_text(node); + g_return_val_if_fail(txt, FALSE); + + if (!safe_strcmp (txt, GNC_ID_CUSTOMER)) + gncOwnerInitCustomer (pdata->owner, NULL); + else if (!safe_strcmp (txt, GNC_ID_JOB)) + gncOwnerInitJob (pdata->owner, NULL); + else if (!safe_strcmp (txt, GNC_ID_VENDOR)) + gncOwnerInitVendor (pdata->owner, NULL); + else if (!safe_strcmp (txt, GNC_ID_EMPLOYEE)) + gncOwnerInitEmployee (pdata->owner, NULL); + else + { + PWARN ("Unknown owner type: %s", txt); + g_free(txt); + return FALSE; + } + + g_free(txt); + return TRUE; +} + +static gboolean +owner_id_handler (xmlNodePtr node, gpointer owner_pdata) +{ + struct owner_pdata *pdata = owner_pdata; + GncGUID *guid; + + guid = dom_tree_to_guid(node); + g_return_val_if_fail (guid, FALSE); + + switch (gncOwnerGetType (pdata->owner)) + { + case GNC_OWNER_CUSTOMER: + { + GncCustomer *cust = gncCustomerLookup (pdata->book, guid); + if (!cust) + { + cust = gncCustomerCreate (pdata->book); + gncCustomerSetGUID (cust, guid); + } + gncOwnerInitCustomer (pdata->owner, cust); + break; + } + case GNC_OWNER_JOB: + { + GncJob *job = gncJobLookup (pdata->book, guid); + if (!job) + { + job = gncJobCreate (pdata->book); + gncJobSetGUID (job, guid); + } + gncOwnerInitJob (pdata->owner, job); + break; + } + case GNC_OWNER_VENDOR: + { + GncVendor *vendor = gncVendorLookup (pdata->book, guid); + if (!vendor) + { + vendor = gncVendorCreate (pdata->book); + gncVendorSetGUID (vendor, guid); + } + gncOwnerInitVendor (pdata->owner, vendor); + break; + } + case GNC_OWNER_EMPLOYEE: + { + GncEmployee *employee = gncEmployeeLookup (pdata->book, guid); + if (!employee) + { + employee = gncEmployeeCreate (pdata->book); + gncEmployeeSetGUID (employee, guid); + } + gncOwnerInitEmployee (pdata->owner, employee); + break; + } + default: + PWARN ("Invalid owner type: %d\n", gncOwnerGetType (pdata->owner)); + g_free (guid); + return FALSE; + } + + g_free (guid); + return TRUE; +} + +static struct dom_tree_handler owner_handlers_v2[] = +{ + { owner_type_string, owner_type_handler, 1, 0 }, + { owner_id_string, owner_id_handler, 1, 0 }, + { NULL, 0, 0, 0 } +}; + +gboolean +gnc_dom_tree_to_owner (xmlNodePtr node, GncOwner *owner, QofBook *book) +{ + struct owner_pdata owner_pdata; + gboolean successful; + + owner_pdata.owner = owner; + owner_pdata.book = book; + + successful = dom_tree_generic_parse (node, owner_handlers_v2, + &owner_pdata); + + if (!successful) + { + PERR ("failed to parse owner tree"); + } + + return successful; +} + +static gboolean +owner_ns(FILE *out) +{ + g_return_val_if_fail(out, FALSE); + return gnc_xml2_write_namespace_decl(out, "owner"); +} + +void +gnc_owner_xml_initialize (void) +{ + static GncXmlDataType_t be_data = + { + GNC_FILE_BACKEND_VERS, + "gnc:Owner", + NULL, /* parser_create */ + NULL, /* add_item */ + NULL, /* get_count */ + NULL, /* write */ + NULL, /* scrub */ + owner_ns, + }; + + qof_object_register_backend ("gnc:Owner", + GNC_FILE_BACKEND, + &be_data); +} diff --git a/pool/shard008/C/0133636_test_vfile.c b/pool/shard008/C/0133636_test_vfile.c new file mode 100644 index 0000000000000000000000000000000000000000..c1287d0245f2cb363d7191cc60d29a23979a72d4 --- /dev/null +++ b/pool/shard008/C/0133636_test_vfile.c @@ -0,0 +1,90 @@ +/* + $Id$ +*/ +#include +#include "test.h" + +//extern struct test_suite test_suite_match; + +extern struct test_case test_case_misc; + + +struct test_suite test_suite_vfile; +struct test_suite *suites[] = { + &test_suite_vfile, + NULL, +}; + +extern struct test_case test_case_misc_env; +struct test_case *misc_cases[] = { + &test_case_misc, + NULL, +}; + +Suite *make_suite(struct test_suite *tsuite) +{ + Suite *s = suite_create(tsuite->name); + int i = 0; + + while (tsuite->cases[i].name) { + TCase *tc = tcase_create(tsuite->cases[i].name); + tcase_add_test(tc, tsuite->cases[i].test_fn); + suite_add_tcase(s, tc); + i++; + } + return s; +} + +Suite *make_themisc_suite(void) +{ + Suite *s = suite_create("misc"); + int i = 0; + + while (misc_cases[i]) { + TCase *tc = tcase_create(misc_cases[i]->name); + tcase_add_test(tc, misc_cases[i]->test_fn); + suite_add_tcase(s, tc); + i++; + } + return s; +} + +/* + tc = tcase_create("op_ts_postconf"); + tcase_add_test(tc, test_op_ts_postconf); + suite_add_tcase (s, tc); + + return s; +} +*/ + +int main(int argc, char *argv[]) +{ + int i = 0, nerr = 0; + + //if (argc > 1 && n_str_eq(argv[1], "-v")) + + if (misc_cases[0]) { + Suite *s = make_themisc_suite(); + SRunner *sr = srunner_create(s); + srunner_run_all(sr, CK_NORMAL); + nerr += srunner_ntests_failed(sr); + srunner_free(sr); + } + + i = 0; + while (suites[i]) { + Suite *s = make_suite(suites[i]); + SRunner *sr = srunner_create(s); + printf("\n"); + srunner_run_all(sr, CK_NORMAL); + nerr += srunner_ntests_failed(sr); + srunner_free(sr); + i++; + } + + + + return (nerr == 0) ? EXIT_SUCCESS : EXIT_FAILURE; +} + diff --git a/pool/shard008/C/0133644_CWE78_OS_Command_Injection__char_connect_socket_w32_execv_02.c b/pool/shard008/C/0133644_CWE78_OS_Command_Injection__char_connect_socket_w32_execv_02.c new file mode 100644 index 0000000000000000000000000000000000000000..cee42a34776a30f6d0a98489f812ac7b3a634a69 --- /dev/null +++ b/pool/shard008/C/0133644_CWE78_OS_Command_Injection__char_connect_socket_w32_execv_02.c @@ -0,0 +1,224 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE78_OS_Command_Injection__char_connect_socket_w32_execv_02.c +Label Definition File: CWE78_OS_Command_Injection.strings.label.xml +Template File: sources-sink-02.tmpl.c +*/ +/* + * @description + * CWE: 78 OS Command Injection + * BadSource: connect_socket Read data using a connect socket (client side) + * GoodSource: Fixed string + * Sink: w32_execv + * BadSink : execute command with execv + * Flow Variant: 02 Control flow: if(1) and if(0) + * + * */ + +#include "std_testcase.h" + +#include + +#ifdef _WIN32 +#define COMMAND_INT_PATH "%WINDIR%\\system32\\cmd.exe" +#define COMMAND_INT "cmd.exe" +#define COMMAND_ARG1 "/c" +#define COMMAND_ARG2 "dir" +#define COMMAND_ARG3 data +#else /* NOT _WIN32 */ +#include +#define COMMAND_INT_PATH "/bin/sh" +#define COMMAND_INT "sh" +#define COMMAND_ARG1 "ls" +#define COMMAND_ARG2 "-la" +#define COMMAND_ARG3 data +#endif + +#ifdef _WIN32 +#include +#include +#include +#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */ +#define CLOSE_SOCKET closesocket +#else /* NOT _WIN32 */ +#include +#include +#include +#include +#define INVALID_SOCKET -1 +#define SOCKET_ERROR -1 +#define CLOSE_SOCKET close +#define SOCKET int +#endif + +#define TCP_PORT 27015 +#define IP_ADDRESS "127.0.0.1" + +#include +#define EXECV _execv + +#ifndef OMITBAD + +void CWE78_OS_Command_Injection__char_connect_socket_w32_execv_02_bad() +{ + char * data; + char dataBuffer[100] = ""; + data = dataBuffer; + if(1) + { + { +#ifdef _WIN32 + WSADATA wsaData; + int wsaDataInit = 0; +#endif + int recvResult; + struct sockaddr_in service; + char *replace; + SOCKET connectSocket = INVALID_SOCKET; + size_t dataLen = strlen(data); + do + { +#ifdef _WIN32 + if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) + { + break; + } + wsaDataInit = 1; +#endif + /* POTENTIAL FLAW: Read data using a connect socket */ + connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (connectSocket == INVALID_SOCKET) + { + break; + } + memset(&service, 0, sizeof(service)); + service.sin_family = AF_INET; + service.sin_addr.s_addr = inet_addr(IP_ADDRESS); + service.sin_port = htons(TCP_PORT); + if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) + { + break; + } + /* Abort on error or the connection was closed, make sure to recv one + * less char than is in the recv_buf in order to append a terminator */ + /* Abort on error or the connection was closed */ + recvResult = recv(connectSocket, (char *)(data + dataLen), sizeof(char) * (100 - dataLen - 1), 0); + if (recvResult == SOCKET_ERROR || recvResult == 0) + { + break; + } + /* Append null terminator */ + data[dataLen + recvResult / sizeof(char)] = '\0'; + /* Eliminate CRLF */ + replace = strchr(data, '\r'); + if (replace) + { + *replace = '\0'; + } + replace = strchr(data, '\n'); + if (replace) + { + *replace = '\0'; + } + } + while (0); + if (connectSocket != INVALID_SOCKET) + { + CLOSE_SOCKET(connectSocket); + } +#ifdef _WIN32 + if (wsaDataInit) + { + WSACleanup(); + } +#endif + } + } + { + char *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL}; + /* execv - specify the path where the command is located */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + EXECV(COMMAND_INT_PATH, args); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B1() - use goodsource and badsink by changing the 1 to 0 */ +static void goodG2B1() +{ + char * data; + char dataBuffer[100] = ""; + data = dataBuffer; + if(0) + { + /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ + printLine("Benign, fixed string"); + } + else + { + /* FIX: Append a fixed string to data (not user / external input) */ + strcat(data, "*.*"); + } + { + char *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL}; + /* execv - specify the path where the command is located */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + EXECV(COMMAND_INT_PATH, args); + } +} + +/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */ +static void goodG2B2() +{ + char * data; + char dataBuffer[100] = ""; + data = dataBuffer; + if(1) + { + /* FIX: Append a fixed string to data (not user / external input) */ + strcat(data, "*.*"); + } + { + char *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL}; + /* execv - specify the path where the command is located */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + EXECV(COMMAND_INT_PATH, args); + } +} + +void CWE78_OS_Command_Injection__char_connect_socket_w32_execv_02_good() +{ + goodG2B1(); + goodG2B2(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + * its own for testing or for building a binary to use in testing binary + * analysis tools. It is not used when compiling all the testcases as one + * application, which is how source code analysis tools are tested. + */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE78_OS_Command_Injection__char_connect_socket_w32_execv_02_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE78_OS_Command_Injection__char_connect_socket_w32_execv_02_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard008/C/0133646_serial.c b/pool/shard008/C/0133646_serial.c new file mode 100644 index 0000000000000000000000000000000000000000..eaebb8eb1ff6b8ade31dc1615358cd513eebac19 --- /dev/null +++ b/pool/shard008/C/0133646_serial.c @@ -0,0 +1,214 @@ + +#include +#include "hardware.h" +#include "serial.h" +#include "radio.h" + +#define SPI_BUF_LEN 220 + +volatile uint8_t __xdata spi_input_buf[SPI_BUF_LEN]; +volatile uint8_t input_size = 0; +volatile uint8_t input_head_idx = 0; +volatile uint8_t input_tail_idx = 0; + +volatile uint8_t __xdata spi_output_buf[SPI_BUF_LEN]; +volatile uint8_t output_size = 0; +volatile uint8_t output_head_idx = 0; +volatile uint8_t output_tail_idx = 0; + +volatile uint8_t ready_to_send = 0; + +volatile uint8_t serial_data_available; + +#define SPI_MODE_WAIT 0 +#define SPI_MODE_SIZE 1 +#define SPI_MODE_XFER 2 +volatile uint8_t spi_mode; + +volatile uint8_t master_send_size = 0; +volatile uint8_t slave_send_size = 0; + + +/*************************************************************************** + * + * SPI encoding: + * + * Master sends a 0x99 byte, followed by number of bytes that will be sent. + * Before second byte xfer, slave loads up buffer with number of bytes + * available. + * + */ + + +void configure_serial() +{ + + /*************************************************************************** + * Setup slave SPI on USART1, Alt 2 + * + * (SS): P1_4 + * (C): P1_5 + * (MO): P1_6 + * (MI): P1_7 + */ + + // configure USART1 for Alternative 2 => Port P1 (PERCFG.U1CFG = 1) + // To avoid potential I/O conflict with USART0: + // Configure USART0 for Alternative 1 => Port P0 (PERCFG.U0CFG = 0) + PERCFG = (PERCFG & ~PERCFG_U0CFG) | PERCFG_U1CFG; + + // Give priority to USART 1 over USART 0 for port 0 pins + P2DIR = 0x01; + + // Set pins 2, 3 and 5 as peripheral I/O and pin 4 as GPIO output + P1SEL = P1SEL | BIT4 | BIT5 | BIT6 | BIT7; + P1DIR = P1DIR & ~(BIT4 | BIT5 | BIT6 | BIT7); + + /*************************************************************************** + * Configure SPI + */ + + // Set USART to SPI mode and Slave mode + U1CSR = (U1CSR & ~U1CSR_MODE) | U1CSR_SLAVE; + + // Set: + // - mantissa value + // - exponent value + // - clock phase to be centered on first edge of SCK period + // - negative clock polarity (SCK low when idle) + // - bit order for transfers to LSB first + +// These values will give a baud rate of approx. 62.5kbps for 26 MHz clock +#define SPI_BAUD_M 59 +#define SPI_BAUD_E 11 + + U1BAUD = SPI_BAUD_M; + U1GCR = (U1GCR & ~(U1GCR_BAUD_E | U1GCR_CPOL | U1GCR_CPHA | U1GCR_ORDER)) + | SPI_BAUD_E; + + TCON &= ~BIT3; // Clear URX1IF + URX1IE = 1; // Enable URX1IE interrupt + + IRCON2 &= ~BIT2; // Clear UTX1IF + IEN2 |= BIT3; // Enable UTX1IE interrupt +} + +void rx1_isr(void) __interrupt URX1_VECTOR { + uint8_t value; + value = U1DBUF; + + if (spi_mode == SPI_MODE_WAIT && value == 0x99) { + if (ready_to_send) { + slave_send_size = output_size; + ready_to_send = 0; + } else { + slave_send_size = 0; + } + spi_mode = SPI_MODE_SIZE; + U1DBUF = slave_send_size; + return; + } + + if (spi_mode == SPI_MODE_SIZE) { + master_send_size = value; + if (master_send_size > 0 || slave_send_size > 0) { + spi_mode = SPI_MODE_XFER; + } else { + spi_mode = SPI_MODE_WAIT; + } + return; + } + + if (spi_mode == SPI_MODE_XFER && input_size < master_send_size) { + if (input_size < SPI_BUF_LEN) { + spi_input_buf[input_head_idx] = value; + input_head_idx++; + if (input_head_idx >= SPI_BUF_LEN) { + input_head_idx = 0; + } + input_size++; + if (input_size == master_send_size) { + master_send_size = 0; + serial_data_available = 1; + } + } + if (slave_send_size == 0 && master_send_size == 0) { + spi_mode = SPI_MODE_WAIT; + } + } +} + +void tx1_isr(void) __interrupt UTX1_VECTOR { + IRCON2 &= ~BIT2; // Clear UTX1IF + if (spi_mode == SPI_MODE_SIZE || spi_mode == SPI_MODE_XFER) { + if (slave_send_size > 0 && output_size > 0) { + slave_send_size--; + if (slave_send_size == 0 && master_send_size == 0) { + spi_mode = SPI_MODE_WAIT; + } + U1DBUF = spi_output_buf[output_tail_idx]; + output_size--; + output_tail_idx++; + if (output_tail_idx >= SPI_BUF_LEN) { + output_tail_idx = 0; + } + } else { + U1DBUF = 0x99; + } + } else { + U1DBUF = 0x99; + } +} + +uint8_t serial_rx_byte() { + uint8_t s_data; + while(!SERIAL_DATA_AVAILABLE); + s_data = spi_input_buf[input_tail_idx]; + input_tail_idx++; + if (input_tail_idx >= SPI_BUF_LEN) { + input_tail_idx = 0; + } + input_size--; + if (input_size == 0) { + serial_data_available = 0; + } + return s_data; +} + +uint16_t serial_rx_word() { + return (serial_rx_byte() << 8) + serial_rx_byte(); +} + +uint32_t serial_rx_long() { + return ((uint32_t)serial_rx_word() << 16) + serial_rx_word(); +} + +void serial_tx_byte(uint8_t tx_byte) { + if (output_size >= SPI_BUF_LEN) { + // drop oldest byte + output_size--; + output_tail_idx++; + if (output_tail_idx >= SPI_BUF_LEN) { + output_tail_idx = 0; + } + } + spi_output_buf[output_head_idx] = tx_byte; + if (tx_byte == 0) { + ready_to_send = 1; + } + output_head_idx++; + if (output_head_idx >= SPI_BUF_LEN) { + output_head_idx = 0; + } + output_size++; +} + +void serial_tx_str(const char *str) { + while(*str != 0) { + serial_tx_byte(*str); + str++; + } + serial_tx_byte(0); +} + + diff --git a/pool/shard008/C/0133648_northcluster.c b/pool/shard008/C/0133648_northcluster.c new file mode 100644 index 0000000000000000000000000000000000000000..eca122c056f1dbb613fcf7023022b209e1ab1742 --- /dev/null +++ b/pool/shard008/C/0133648_northcluster.c @@ -0,0 +1,151 @@ +/* + * This file is part of the coreboot project. + * + * Copyright (C) 2013 Google Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; version 2 of the License. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include +#include +#include +#include +#include + +#include +#include +#include + +/* Host Memory Map: + * + * +--------------------------+ BMBOUND_HI + * | Usable DRAM | + * +--------------------------+ 4GiB + * | PCI Address Space | + * +--------------------------+ BMBOUND + * | TPM | + * +--------------------------+ IMR2 + * | TXE | + * +--------------------------+ IMR1 + * | iGD | + * +--------------------------+ + * | GTT | + * +--------------------------+ SMMRRH, IRM0 + * | TSEG | + * +--------------------------+ SMMRRL + * | Usable DRAM | + * +--------------------------+ 0 + * + * Note that there are really only a few regions that need to enumerated w.r.t. + * coreboot's resrouce model: + * + * +--------------------------+ BMBOUND_HI + * | Cacheable/Usable | + * +--------------------------+ 4GiB + * + * +--------------------------+ BMBOUND + * | Uncacheable/Reserved | + * +--------------------------+ SMMRRH + * | Cacheable/Reserved | + * +--------------------------+ SMMRRL + * | Cacheable/Usable | + * +--------------------------+ 0 + */ +#define RES_IN_KiB(r) ((r) >> 10) + +static void nc_read_resources(device_t dev) +{ + unsigned long mmconf; + unsigned long bmbound; + unsigned long bmbound_hi; + unsigned long smmrrh; + unsigned long smmrrl; + unsigned long base_k, size_k; + const unsigned long four_gig_kib = (4 << (30 - 10)); + int index = 0; + + /* Read standard PCI resources. */ + pci_dev_read_resources(dev); + + /* PCIe memory-mapped config space access - 256 MiB. */ + mmconf = iosf_bunit_read(BUNIT_MMCONF_REG) & ~((1 << 28) - 1); + mmio_resource(dev, BUNIT_MMCONF_REG, RES_IN_KiB(mmconf), 256 * 1024); + + /* 0 -> SMM_DEFAULT_BASE cacheable ram. */ + ram_resource(dev, index++, 0, RES_IN_KiB(SMM_DEFAULT_BASE)); + /* Default SMM region is cacheable but reserved for coreboot */ + reserved_ram_resource(dev, index++, RES_IN_KiB(SMM_DEFAULT_BASE), + RES_IN_KiB(SMM_DEFAULT_SIZE)); + + /* SMM_DEFAULT_BASE + SMM_DEFAULT_SIZE - > 0xa0000 */ + base_k = RES_IN_KiB(SMM_DEFAULT_BASE + SMM_DEFAULT_SIZE); + size_k = RES_IN_KiB(0xa0000) - base_k; + ram_resource(dev, index++, base_k, size_k); + + /* The SMMRR registers are 1MiB granularity with smmrrh being + * inclusive of the SMM region. */ + smmrrl = (iosf_bunit_read(BUNIT_SMRRL) & 0xffff) << 10; + smmrrh = ((iosf_bunit_read(BUNIT_SMRRH) & 0xffff) + 1) << 10; + + /* 0xc0000 -> smrrl - cacheable and usable */ + base_k = RES_IN_KiB(0xc0000); + size_k = smmrrl - base_k; + ram_resource(dev, index++, base_k, size_k); + + if (smmrrh > smmrrl) + reserved_ram_resource(dev, index++, smmrrl, smmrrh - smmrrl); + + /* All address space between bmbound and smmrrh is unusable. */ + bmbound = RES_IN_KiB(iosf_bunit_read(BUNIT_BMBOUND) & ~((1 << 27) - 1)); + mmio_resource(dev, index++, smmrrh, bmbound - smmrrh); + + /* The BMBOUND_HI register matches register bits of 31:24 with address + * bits of 35:28. Therefore, shift register to align properly. */ + bmbound_hi = iosf_bunit_read(BUNIT_BMBOUND_HI) & ~((1 << 24) - 1); + bmbound_hi = RES_IN_KiB(bmbound_hi) << 4; + if (bmbound_hi > four_gig_kib) + ram_resource(dev, index++, four_gig_kib, + bmbound_hi - four_gig_kib); + + /* Reserve everything between A segment and 1MB: + * + * 0xa0000 - 0xbffff: legacy VGA + * 0xc0000 - 0xfffff: RAM + */ + mmio_resource(dev, index++, (0xa0000 >> 10), (0xc0000 - 0xa0000) >> 10); + reserved_ram_resource(dev, index++, (0xc0000 >> 10), + (0x100000 - 0xc0000) >> 10); +#if CONFIG_CHROMEOS_RAMOOPS + reserved_ram_resource(dev, index++, + CONFIG_CHROMEOS_RAMOOPS_RAM_START >> 10, + CONFIG_CHROMEOS_RAMOOPS_RAM_SIZE >> 10); +#endif +} + +static struct device_operations nc_ops = { + .read_resources = nc_read_resources, + .set_resources = NULL, + .enable_resources = NULL, + .init = NULL, + .enable = NULL, + .scan_bus = NULL, + .ops_pci = &soc_pci_ops, +}; + +static const struct pci_driver nc_driver __pci_driver = { + .ops = &nc_ops, + .vendor = PCI_VENDOR_ID_INTEL, + .device = SOC_DEVID, +}; + diff --git a/pool/shard008/C/0133651_CWE191_Integer_Underflow__short_rand_postdec_64b.c b/pool/shard008/C/0133651_CWE191_Integer_Underflow__short_rand_postdec_64b.c new file mode 100644 index 0000000000000000000000000000000000000000..39d694b3a0cc25c22f66cd947b061599c0a00001 --- /dev/null +++ b/pool/shard008/C/0133651_CWE191_Integer_Underflow__short_rand_postdec_64b.c @@ -0,0 +1,75 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE191_Integer_Underflow__short_rand_postdec_64b.c +Label Definition File: CWE191_Integer_Underflow.label.xml +Template File: sources-sinks-64b.tmpl.c +*/ +/* + * @description + * CWE: 191 Integer Underflow + * BadSource: rand Set data to result of rand() + * GoodSource: Set data to a small, non-zero number (negative two) + * Sinks: decrement + * GoodSink: Ensure there will not be an underflow before decrementing data + * BadSink : Decrement data, which can cause an Underflow + * Flow Variant: 64 Data flow: void pointer to data passed from one function to another in different source files + * + * */ + +#include "std_testcase.h" + +#ifndef OMITBAD + +void CWE191_Integer_Underflow__short_rand_postdec_64b_badSink(void * dataVoidPtr) +{ + /* cast void pointer to a pointer of the appropriate type */ + short * dataPtr = (short *)dataVoidPtr; + /* dereference dataPtr into data */ + short data = (*dataPtr); + { + /* POTENTIAL FLAW: Decrementing data could cause an underflow */ + data--; + short result = data; + printIntLine(result); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void CWE191_Integer_Underflow__short_rand_postdec_64b_goodG2BSink(void * dataVoidPtr) +{ + /* cast void pointer to a pointer of the appropriate type */ + short * dataPtr = (short *)dataVoidPtr; + /* dereference dataPtr into data */ + short data = (*dataPtr); + { + /* POTENTIAL FLAW: Decrementing data could cause an underflow */ + data--; + short result = data; + printIntLine(result); + } +} + +/* goodB2G uses the BadSource with the GoodSink */ +void CWE191_Integer_Underflow__short_rand_postdec_64b_goodB2GSink(void * dataVoidPtr) +{ + /* cast void pointer to a pointer of the appropriate type */ + short * dataPtr = (short *)dataVoidPtr; + /* dereference dataPtr into data */ + short data = (*dataPtr); + /* FIX: Add a check to prevent an underflow from occurring */ + if (data > SHRT_MIN) + { + data--; + short result = data; + printIntLine(result); + } + else + { + printLine("data value is too large to perform arithmetic safely."); + } +} + +#endif /* OMITGOOD */ diff --git a/pool/shard008/C/0133656_list_p.c b/pool/shard008/C/0133656_list_p.c new file mode 100644 index 0000000000000000000000000000000000000000..1de4f26a779efc3eae6ed5a2d40e3cdce54237a6 --- /dev/null +++ b/pool/shard008/C/0133656_list_p.c @@ -0,0 +1,99 @@ +#include "list_p_.h" + +#include + +void* list_iterator_get_(list_iterator it) +{ + return it->data; +} + +list_iterator list_head(list_p thisList) +{ + return thisList->head; +} + +list_iterator list_iterator_next(list_iterator it) +{ + return it->next; +} + +size_t list_size(list_p thisList) +{ + return thisList->size; +} + +void list_push_back_(list_p thislist_p, void* valuePtr) +{ + listNode* newNode = (listNode*)malloc(sizeof(listNode)); + newNode->data = valuePtr; + newNode->next = NULL; + if(thislist_p->tail != NULL) { + thislist_p->tail->next = newNode; + } else { + thislist_p->head = newNode; + } + thislist_p->tail = newNode; + ++thislist_p->size; +} + +void* list_at_(list_p thislist_p, size_t index) +{ + if(index >= thislist_p->size) { + return NULL; + } + listNode* cur = thislist_p->head; + for(size_t i = 0; i < index; ++i) { + cur = cur->next; + } + return cur->data; +} + +int list_removeAt(list_p thisList, size_t index) +{ + if(index >= thisList->size) { + return -1; + } + listNode** previous = &thisList->head; + listNode* cur = thisList->head; + for(size_t i = 0; i < index; ++i) { + previous = &cur->next; + cur = cur->next; + } + *previous = cur->next; + if(*previous == (listNode *)NULL) { + thisList->tail = (listNode *)NULL; + } + if(thisList->freeElem) { + thisList->freeElem(cur->data); + } + free(cur); + --thisList->size; + return 0; +} + +list_p new_list_p_(void (*freeElem)(void* elem)) +{ + list_p newList = (list_p) malloc(sizeof(struct list_p_)); + newList->head = NULL; + newList->tail = NULL; + newList->size = 0; + newList->freeElem = freeElem; + return newList; +} + +void free_list_p(list_p thislist) +{ + if(thislist == NULL) { + return; + } + if(thislist->freeElem) { + listNode* cur = thislist->head; + while(cur != NULL) { + thislist->freeElem(cur->data); + listNode* tmp = cur; + cur = cur->next; + free(tmp); + } + } + free(thislist); +} diff --git a/pool/shard008/C/0133661_dbgf_ml.c b/pool/shard008/C/0133661_dbgf_ml.c new file mode 100644 index 0000000000000000000000000000000000000000..dd8ae12875f7afc60be3a61cc18f5c8b41807abc --- /dev/null +++ b/pool/shard008/C/0133661_dbgf_ml.c @@ -0,0 +1,73 @@ +/* + This file is part of SUPPL - the supplemental library for DOS + Copyright (C) 1996-2000 Steffen Kaiser + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + 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 + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public + License along with this library; if not, write to the Free + Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. +*/ +/* $RCSfile: dbgf_ml.c,v $ + $Locker: $ $Name: $ $State: Exp $ + +ob(ject): suppl_log_match_list +su(bsystem): debug +ty(pe): L +sy(nopsis): +sh(ort description): Search a name within a log list and return its status +he(ader files): Searches for a name through a log list and return if + the name is enabled or disabled. If there is no entry of the name + within the list, the default status is returned. +lo(ng description): +pr(erequistes): list != NULL +va(lue): 0: disabled or \tok{str == NULL} + \item else: enabled +re(lated to): suppl_log_find_list +se(condary subsystems): +xr(ef): +im(port): +fi(le): +in(itialized by): +wa(rning): +bu(gs): +co(mpilers): + +*/ + +#include "initsupl.loc" + +#ifndef _MICROC_ +#endif +#include + +#include "suppldbg.loc" + +#ifdef RCS_Version +static char const rcsid[] = + "$Id: dbgf_ml.c,v 1.1 2006/06/17 03:25:00 blairdude Exp $"; +#endif + +int suppl_log_match_list(suppl_log_list_t *list + , suppl_log_csptr_t str) +{ int flg; + + assert(list); + + if(!str) + return 0; + + if((flg = suppl_log_find_list(list, str)) == 0) + /* no explicit entry --> return default */ + flg = list->suppl_l_name[0]; + + return flg == '+'; +} diff --git a/pool/shard008/C/0133662_trx.c b/pool/shard008/C/0133662_trx.c new file mode 100644 index 0000000000000000000000000000000000000000..aaca232b6f9a99e5d786fe4d19ff34f904e6bc42 --- /dev/null +++ b/pool/shard008/C/0133662_trx.c @@ -0,0 +1,270 @@ +/* + * trx.c + * + * Copyright (C) 2005 Mike Baker + * Copyright (C) 2008 Felix Fietkau + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include "mtd.h" +#include "crc32.h" + +#define TRX_MAGIC 0x30524448 /* "HDR0" */ +#define TRX_CRC32_DATA_OFFSET 12 /* First 12 bytes are not covered by CRC32 */ +#define TRX_CRC32_DATA_SIZE 16 +struct trx_header { + uint32_t magic; /* "HDR0" */ + uint32_t len; /* Length of file including header */ + uint32_t crc32; /* 32-bit CRC from flag_version to end of file */ + uint32_t flag_version; /* 0:15 flags, 16:31 version */ + uint32_t offsets[3]; /* Offsets of partitions from start of header */ +}; + +#define min(x,y) ({ \ + typeof(x) _x = (x); \ + typeof(y) _y = (y); \ + (void) (&_x == &_y); \ + _x < _y ? _x : _y; }) + +#if __BYTE_ORDER == __BIG_ENDIAN +#define STORE32_LE(X) ((((X) & 0x000000FF) << 24) | (((X) & 0x0000FF00) << 8) | (((X) & 0x00FF0000) >> 8) | (((X) & 0xFF000000) >> 24)) +#elif __BYTE_ORDER == __LITTLE_ENDIAN +#define STORE32_LE(X) (X) +#else +#error unknown endianness! +#endif + +ssize_t pread(int fd, void *buf, size_t count, off_t offset); +ssize_t pwrite(int fd, const void *buf, size_t count, off_t offset); + +int +trx_fixup(int fd, const char *name) +{ + struct mtd_info_user mtdInfo; + unsigned long len; + struct trx_header *trx; + void *ptr, *scan; + int bfd; + + if (ioctl(fd, MEMGETINFO, &mtdInfo) < 0) { + fprintf(stderr, "Failed to get mtd info\n"); + goto err; + } + + len = mtdInfo.size; + if (mtdInfo.size <= 0) { + fprintf(stderr, "Invalid MTD device size\n"); + goto err; + } + + bfd = mtd_open(name, true); + ptr = mmap(NULL, len, PROT_READ|PROT_WRITE, MAP_SHARED, bfd, 0); + if (!ptr || (ptr == (void *) -1)) { + perror("mmap"); + fprintf(stderr, "Mapping the TRX header failed\n"); + goto err1; + } + + trx = ptr; + if (trx->magic != TRX_MAGIC) { + fprintf(stderr, "TRX header not found\n"); + goto err; + } + + scan = ptr + offsetof(struct trx_header, flag_version); + trx->crc32 = crc32buf(scan, trx->len - (scan - ptr)); + msync(ptr, sizeof(struct trx_header), MS_SYNC|MS_INVALIDATE); + munmap(ptr, len); + close(bfd); + return 0; + +err1: + close(bfd); +err: + return -1; +} + +#ifndef target_ar71xx +int +trx_check(int imagefd, const char *mtd, char *buf, int *len) +{ + const struct trx_header *trx = (const struct trx_header *) buf; + int fd; + + if (strcmp(mtd, "firmware") != 0) + return 1; + + if (*len < 32) { + *len += read(imagefd, buf + *len, 32 - *len); + if (*len < 32) { + fprintf(stdout, "Could not get image header, file too small (%d bytes)\n", *len); + return 0; + } + } + + if (trx->magic != TRX_MAGIC || trx->len < sizeof(struct trx_header)) { + if (quiet < 2) { + fprintf(stderr, "Bad trx header\n"); + fprintf(stderr, "This is not the correct file format; refusing to flash.\n" + "Please specify the correct file or use -f to force.\n"); + } + return 0; + } + + /* check if image fits to mtd device */ + fd = mtd_check_open(mtd); + if(fd < 0) { + fprintf(stderr, "Could not open mtd device: %s\n", mtd); + exit(1); + } + + if(mtdsize < trx->len) { + fprintf(stderr, "Image too big for partition: %s\n", mtd); + close(fd); + return 0; + } + + close(fd); + return 1; +} +#endif + +int +mtd_fixtrx(const char *mtd, size_t offset, size_t data_size) +{ + size_t data_offset; + int fd; + struct trx_header *trx; + char *first_block; + char *buf, *to; + ssize_t res; + size_t block_offset; + + if (quiet < 2) + fprintf(stderr, "Trying to fix trx header in %s at 0x%x...\n", mtd, offset); + + fd = mtd_check_open(mtd); + if(fd < 0) { + fprintf(stderr, "Could not open mtd device: %s\n", mtd); + exit(1); + } + + data_offset = offset + TRX_CRC32_DATA_OFFSET; + if (data_size) + data_size += TRX_CRC32_DATA_SIZE; + else + data_size = erasesize - TRX_CRC32_DATA_OFFSET; + + block_offset = offset & ~(erasesize - 1); + offset -= block_offset; + + if (data_offset + data_size > mtdsize) { + fprintf(stderr, "Offset too large, device size 0x%x\n", mtdsize); + exit(1); + } + + first_block = malloc(erasesize); + if (!first_block) { + perror("malloc"); + exit(1); + } + + res = pread(fd, first_block, erasesize, block_offset); + if (res != erasesize) { + perror("pread"); + exit(1); + } + + trx = (struct trx_header *)(first_block + offset); + if (trx->magic != STORE32_LE(0x30524448)) { + fprintf(stderr, "No trx magic found\n"); + exit(1); + } + + buf = malloc(data_size); + if (!buf) { + perror("malloc"); + exit(1); + } + + to = buf; + while (data_size) { + size_t read_block_offset = data_offset & ~(erasesize - 1); + size_t read_chunk; + + read_chunk = erasesize - (data_offset & (erasesize - 1)); + read_chunk = min(read_chunk, data_size); + + /* Read from good blocks only to match CFE behavior */ + if (!mtd_block_is_bad(fd, read_block_offset)) { + res = pread(fd, to, read_chunk, data_offset); + if (res != read_chunk) { + perror("pread"); + exit(1); + } + to += read_chunk; + } + + data_offset += read_chunk; + data_size -= read_chunk; + } + data_size = to - buf; + + if (trx->len == STORE32_LE(data_size + TRX_CRC32_DATA_OFFSET) && + trx->crc32 == STORE32_LE(crc32buf(buf, data_size))) { + if (quiet < 2) + fprintf(stderr, "Header already fixed, exiting\n"); + close(fd); + return 0; + } + + trx->len = STORE32_LE(data_size + offsetof(struct trx_header, flag_version)); + + trx->crc32 = STORE32_LE(crc32buf(buf, data_size)); + if (mtd_erase_block(fd, block_offset)) { + fprintf(stderr, "Can't erease block at 0x%x (%s)\n", block_offset, strerror(errno)); + exit(1); + } + + if (quiet < 2) + fprintf(stderr, "New crc32: 0x%x, rewriting block\n", trx->crc32); + + if (pwrite(fd, first_block, erasesize, block_offset) != erasesize) { + fprintf(stderr, "Error writing block (%s)\n", strerror(errno)); + exit(1); + } + + if (quiet < 2) + fprintf(stderr, "Done.\n"); + + close (fd); + sync(); + return 0; + +} diff --git a/pool/shard008/C/0133663_socket.c b/pool/shard008/C/0133663_socket.c new file mode 100644 index 0000000000000000000000000000000000000000..90cd59682d1512f1e2b698ba322e599788076271 --- /dev/null +++ b/pool/shard008/C/0133663_socket.c @@ -0,0 +1,235 @@ +#include +#include "main.h" +#include "stm32l0xx_hal.h" +#include "socket.h" + +extern UART_HandleTypeDef huart4; +#define TIMEOUTLEFT(__timeout, __starttime) ((__timeout == HAL_MAX_DELAY) ? HAL_MAX_DELAY : (__timeout - (HAL_GetTick() - __starttime))) + +const char* SocketUDP = "UDP"; +const char* SocketTCP = "TCP"; +const char* ResponseOK = "OK\r\n"; +const char* ResponseSENDOK = "SEND OK\r\n"; +const char* ResponseERROR = "ERROR\r\n"; +const char* ResponseALREADYCONNECTED = "ALREADY CONNECTED\r\n\r\n"; + +static HAL_StatusTypeDef ESP8266GetResponse( + char* responseIn, + uint32_t respLenIn, + uint32_t* usedLen, + uint32_t timeout) +{ + HAL_StatusTypeDef retVal = HAL_OK; + uint32_t startTime = HAL_GetTick(); + char resp[256] = {0}; + char* response = (responseIn && respLenIn) ? responseIn : resp; + uint32_t responseLen = (responseIn && respLenIn) ? respLenIn : sizeof(resp); + uint32_t cursor = 0; + uint32_t newCursor = 0; + do + { + if((timeout != HAL_MAX_DELAY) && (startTime + timeout < HAL_GetTick())) return HAL_TIMEOUT; + cursor = newCursor; + fgets(&response[cursor], responseLen - cursor - 1, &__net); + if((!strcmp(&response[cursor], ResponseOK)) || (!strcmp(&response[cursor], ResponseSENDOK))) + { + break; + } + else if(!strcmp(&response[cursor], ResponseERROR)) + { + retVal = HAL_ERROR; + break; + } + newCursor = strlen(response); + } + while((newCursor + 1) < responseLen); + response[cursor] = '\0'; + if(usedLen) *usedLen = cursor; + return retVal; +} + +HAL_StatusTypeDef InitializeESP8266( + uint32_t* ip, + uint8_t* mac, + uint32_t timeout) +{ + HAL_StatusTypeDef retVal = HAL_OK; + uint32_t startTime = HAL_GetTick(); + + fprintf(&__net, "ATE0\r\n"); + if((retVal = ESP8266GetResponse(NULL, 0, NULL, TIMEOUTLEFT(timeout, startTime))) != HAL_OK) + { + return retVal; + } + + fprintf(&__net, "AT+CWMODE_DEF=1\r\n"); + if((retVal = ESP8266GetResponse(NULL, 0, NULL, TIMEOUTLEFT(timeout, startTime))) != HAL_OK) + { + return retVal; + } + + fprintf(&__net, "AT+CWJAP_DEF=\"MSFTGUEST\",\"\"\r\n"); + if((retVal = ESP8266GetResponse(NULL, 0, NULL, TIMEOUTLEFT(timeout, startTime))) != HAL_OK) + { + return retVal; + } + + fprintf(&__net, "AT+PING=\"pool.ntp.org\"\r\n"); + if((retVal = ESP8266GetResponse(NULL, 0, NULL, TIMEOUTLEFT(timeout, startTime))) != HAL_OK) + { + return retVal; + } + + fprintf(&__net, "AT+CIPMUX=1\r\n"); + if((retVal = ESP8266GetResponse(NULL, 0, NULL, TIMEOUTLEFT(timeout, startTime))) != HAL_OK) + { + return retVal; + } + + if((ip) || (mac)) + { + char response[100]; + uint32_t responseLen = 0; + uint32_t extracted[10] = {0}; + fprintf(&__net, "AT+CIFSR\r\n"); + if((retVal = ESP8266GetResponse(response, sizeof(response), &responseLen, TIMEOUTLEFT(timeout, startTime))) != HAL_OK) + { + return retVal; + } + if(sscanf(response, "+CIFSR:STAIP,\"%d.%d.%d.%d\"\r\n+CIFSR:STAMAC,\"%x:%x:%x:%x:%x:%x:\"\r\n", + &extracted[0], + &extracted[1], + &extracted[2], + &extracted[3], + &extracted[4], + &extracted[5], + &extracted[6], + &extracted[7], + &extracted[8], + &extracted[9]) != 10) + { + return HAL_ERROR; + } + if(ip) *ip = (extracted[0] << 24) | (extracted[1] << 16) | (extracted[2] << 8) | extracted[3]; + if(mac) for(uint32_t n = 0; n < 6; n++) mac[n] = (uint8_t)(extracted[n + 4] & 0x000000ff); + } + + return retVal; +} + +HAL_StatusTypeDef SocketOpen( + uint32_t handle, + const char* socketType, + const char* hostname, + uint32_t destinationPort, + uint32_t timeout) +{ + HAL_StatusTypeDef retVal = HAL_BUSY; + uint32_t startTime = HAL_GetTick(); + + do + { + char response[128]; + uint32_t responseLen; + fprintf(&__net, "AT+CIPSTART=%d,\"%s\",\"%s\",%d\r\n", handle, socketType, hostname, destinationPort); + if((retVal = ESP8266GetResponse(response, sizeof(response), &responseLen, TIMEOUTLEFT(timeout, startTime))) != HAL_OK) + { + if((!strcmp(response, ResponseALREADYCONNECTED)) && + ((retVal = SocketClose(handle, TIMEOUTLEFT(timeout, startTime))) == HAL_OK)) + { + retVal = HAL_BUSY; + continue; // Let's try again + } + goto Cleanup; + } + } + while(retVal != HAL_OK); + +Cleanup: + return retVal; +} + +HAL_StatusTypeDef SocketClose( + uint32_t handle, + uint32_t timeout) +{ + HAL_StatusTypeDef retVal = HAL_OK; + uint32_t startTime = HAL_GetTick(); + + fprintf(&__net, "AT+CIPCLOSE=%d\r\n", handle); + if((retVal = ESP8266GetResponse(NULL, 0, NULL, TIMEOUTLEFT(timeout, startTime))) != HAL_OK) + { + retVal = HAL_ERROR; + goto Cleanup; + } + +Cleanup: + return retVal; +} + +HAL_StatusTypeDef SocketSend( + uint32_t handle, + uint8_t* data, + uint32_t dataSize, + uint32_t timeout) +{ + HAL_StatusTypeDef retVal = HAL_OK; + uint32_t startTime = HAL_GetTick(); + + fprintf(&__net, "AT+CIPSEND=%d,%d\r\n", handle, dataSize); + if((retVal = ESP8266GetResponse(NULL, 0, NULL, TIMEOUTLEFT(timeout, startTime))) != HAL_OK) + { + retVal = HAL_ERROR; + goto Cleanup; + } + + if((fgetc(&__net) != '>') || (fgetc(&__net) != ' ')) + { + retVal = HAL_ERROR; + goto Cleanup; + } + + fwrite(data, 1, dataSize, &__net); + + if((retVal = ESP8266GetResponse(NULL, 0, NULL, TIMEOUTLEFT(timeout, startTime))) != HAL_OK) + { + retVal = HAL_ERROR; + goto Cleanup; + } +Cleanup: + return retVal; +} + +HAL_StatusTypeDef SocketReceive( + uint32_t handle, + uint8_t* data, + uint32_t dataSize, + uint32_t timeout) +{ + HAL_StatusTypeDef retVal = HAL_OK; + uint32_t startTime = HAL_GetTick(); + + uint32_t cursor = 0; + while(cursor < dataSize) + { + char hdr[20]; + uint32_t index = 0; + uint32_t hdl = 0; + uint32_t recLen = 0; + + if((timeout != HAL_MAX_DELAY) && (startTime + timeout < HAL_GetTick())) return HAL_TIMEOUT; + + while((hdr[index++] = (char)fgetc(&__net)) != ':'); + hdr[index] = '\0'; + if((sscanf(&hdr[2], "+IPD,%d,%d:", &hdl, &recLen) != 2) || (hdl != handle)) + { + retVal = HAL_ERROR; + goto Cleanup; + } + cursor += fread(data, 1, MIN(recLen, dataSize - cursor), &__net); + } + +Cleanup: + return retVal; +} + diff --git a/pool/shard008/C/0133664_tspi_dir.c b/pool/shard008/C/0133664_tspi_dir.c new file mode 100644 index 0000000000000000000000000000000000000000..10c0c38b5525fedd91327b484180ea0d9e6b68f4 --- /dev/null +++ b/pool/shard008/C/0133664_tspi_dir.c @@ -0,0 +1,105 @@ + +/* + * Licensed Materials - Property of IBM + * + * trousers - An open source TCG Software Stack + * + * (C) Copyright International Business Machines Corp. 2004-2006 + * + */ + +#include +#include +#include +#include + +#include "trousers/tss.h" +#include "trousers/trousers.h" +#include "trousers_types.h" +#include "spi_utils.h" +#include "capabilities.h" +#include "tsplog.h" +#include "obj.h" + + +TSS_RESULT +Tspi_TPM_DirWrite(TSS_HTPM hTPM, /* in */ + UINT32 ulDirIndex, /* in */ + UINT32 ulDirDataLength, /* in */ + BYTE * rgbDirData) /* in */ +{ + TSS_HCONTEXT tspContext; + TCPA_RESULT result; + TPM_AUTH auth; + TCPA_DIGEST hashDigest; + TSS_HPOLICY hPolicy; + TCPA_DIRVALUE dirValue = { { 0 } }; + Trspi_HashCtx hashCtx; + + if (rgbDirData == NULL && ulDirDataLength != 0) + return TSPERR(TSS_E_BAD_PARAMETER); + + if (ulDirDataLength > (UINT32)sizeof(TCPA_DIRVALUE)) + return TSPERR(TSS_E_BAD_PARAMETER); + + if ((result = obj_tpm_get_tsp_context(hTPM, &tspContext))) + return result; + + if ((result = obj_tpm_get_policy(hTPM, TSS_POLICY_USAGE, &hPolicy))) + return result; + + memcpy((BYTE *)&dirValue, rgbDirData, ulDirDataLength); + + /* hash to be used for the OIAP calc */ + result = Trspi_HashInit(&hashCtx, TSS_HASH_SHA1); + result |= Trspi_Hash_UINT32(&hashCtx, TPM_ORD_DirWriteAuth); + result |= Trspi_Hash_UINT32(&hashCtx, ulDirIndex); + result |= Trspi_HashUpdate(&hashCtx, (UINT32)sizeof(TCPA_DIRVALUE), (BYTE *)&dirValue); + if ((result |= Trspi_HashFinal(&hashCtx, hashDigest.digest))) + return result; + + /* hashDigest now has the hash result */ + if ((result = secret_PerformAuth_OIAP(hTPM, TPM_ORD_DirWriteAuth, hPolicy, FALSE, + &hashDigest, &auth))) + return result; + + if ((result = TCS_API(tspContext)->DirWriteAuth(tspContext, ulDirIndex, &dirValue, &auth))) + return result; + + result = Trspi_HashInit(&hashCtx, TSS_HASH_SHA1); + result |= Trspi_Hash_UINT32(&hashCtx, result); + result |= Trspi_Hash_UINT32(&hashCtx, TPM_ORD_DirWriteAuth); + if ((result |= Trspi_HashFinal(&hashCtx, hashDigest.digest))) + return result; + + return obj_policy_validate_auth_oiap(hPolicy, &hashDigest, &auth); +} + +TSS_RESULT +Tspi_TPM_DirRead(TSS_HTPM hTPM, /* in */ + UINT32 ulDirIndex, /* in */ + UINT32 * pulDirDataLength, /* out */ + BYTE ** prgbDirData) /* out */ +{ + TCPA_DIRVALUE dirValue; + TSS_RESULT result; + TSS_HCONTEXT tspContext; + + if (pulDirDataLength == NULL || prgbDirData == NULL) + return TSPERR(TSS_E_BAD_PARAMETER); + + if ((result = obj_tpm_get_tsp_context(hTPM, &tspContext))) + return result; + + if ((result = TCS_API(tspContext)->DirRead(tspContext, ulDirIndex, &dirValue))) + return result; + + *pulDirDataLength = 20; + *prgbDirData = calloc_tspi(tspContext, *pulDirDataLength); + if (*prgbDirData == NULL) { + LogError("malloc of %d bytes failed.", *pulDirDataLength); + return TSPERR(TSS_E_OUTOFMEMORY); + } + memcpy(*prgbDirData, dirValue.digest, *pulDirDataLength); + return TSS_SUCCESS; +} diff --git a/pool/shard008/C/0133665_test-c-mac.c b/pool/shard008/C/0133665_test-c-mac.c new file mode 100644 index 0000000000000000000000000000000000000000..b956f01ae470b486be370bc530c49489083e1565 --- /dev/null +++ b/pool/shard008/C/0133665_test-c-mac.c @@ -0,0 +1,82 @@ +#include +#include +#include "MinimalGenI_stub.h" + +char* slurp(const char* filename); + +extern void __stginit_MinimalGenI(void); + +void HsStart() +{ + int argc = 1; + char* argv[] = {"sortOfGHC", NULL}; // argv must end with NULL + + // Initialize Haskell runtime + char** args = argv; + hs_init(&argc, &args); + + // Tell Haskell about all root modules + hs_add_root(__stginit_MinimalGenI); +} + +void HsEnd() +{ + hs_exit(); +} + +int main(int argc, char *argv[]) { + char *macros_fn; + char *lexicon; + char *test_sem; + char *result; + void *geni_st; + + HsStart(); + if (argc < 4) { + printf("Usage: %s \n", argv[0]); + return 2; + } + + macros_fn=argv[1]; + lexicon=slurp(argv[2]); + test_sem=slurp(argv[3]); + + // go! + geni_st=geni_init(macros_fn); + if ( geni_st == NULL ) { + fprintf(stderr, "Could not initialise GenI wrapper"); + exit(1); + } + result=geni_realize(geni_st, lexicon, test_sem); + printf("%s", result); + geni_free(result); + + free(test_sem); + free(lexicon); + + HsEnd(); +} + +// this allocates a string you must free +char* slurp(const char* filename) { + char *contents; + FILE *fp; + + fp = fopen(filename, "r"); + if (fp == NULL) { + fprintf(stderr, "Could not open %s", filename); + exit(1); + } + fseek(fp, 0L, SEEK_END); + long s = ftell(fp); + rewind(fp); + contents = malloc(s); + if ( fp == NULL ) { + fprintf(stderr, "Could not read %s", filename); + exit(1); + } + fread(contents, s, 1, fp); + fclose(fp); + fp = NULL; + return contents; +} diff --git a/pool/shard008/C/0133666_app_message.c b/pool/shard008/C/0133666_app_message.c new file mode 100644 index 0000000000000000000000000000000000000000..f408f4694069419ed2457a41061b755a2a4cc3fa --- /dev/null +++ b/pool/shard008/C/0133666_app_message.c @@ -0,0 +1,119 @@ +#include pebble.h + +#define ACCEL_STEP_MS 300 + +Window *window; +static AppTimer *timer; + +// Key values for AppMessage Dictionary +enum { + STATUS_KEY = 0, + MESSAGE_KEY = 1, + BRI_KEY = 10, + HUE_KEY = 11, + SAT_KEY = 12 +}; + +int16_t normalize_int(int16_t data) +{ + //if (data < 0) + //{ + // data = - data; + //} + if (data > 1023) + { + data = 1023; + } + if (data < -1024) + { + data = -1024; + } + //data is between -1024 and 1023 + data += 1024; + //data is between 0 and 2047 + data /= 8; + APP_LOG(APP_LOG_LEVEL_DEBUG, "%d", data); + return data; +} + +// Write message to buffer & send +void send_message(AccelData acc){ + DictionaryIterator *iter; + + int16_t x = normalize_int(-acc.x); + int16_t y = normalize_int(acc.y); + int16_t z = normalize_int(acc.z); + + app_message_outbox_begin(&iter); + dict_write_uint8(iter, STATUS_KEY, 0x1); + dict_write_int16(iter, BRI_KEY, x); + dict_write_int16(iter, HUE_KEY, y); + dict_write_int16(iter, SAT_KEY, z); + + + dict_write_end(iter); + app_message_outbox_send(); +} + +// Called when a message is received from PebbleKitJS +static void in_received_handler(DictionaryIterator *received, void *context) { + Tuple *tuple; + + tuple = dict_find(received, STATUS_KEY); + if(tuple) { + APP_LOG(APP_LOG_LEVEL_DEBUG, "Received Status: %d", (int)tuple->value->uint32); + } + + tuple = dict_find(received, MESSAGE_KEY); + if(tuple) { + APP_LOG(APP_LOG_LEVEL_DEBUG, "Received Message: %s", tuple->value->cstring); + }} + +static void timer_callback(void *data) { + AccelData accel = (AccelData) { .x = 0, .y = 0, .z = 0 }; + + accel_service_peek(&accel); + + send_message(accel); + + timer = app_timer_register(ACCEL_STEP_MS, timer_callback, NULL); +} + +// Called when an incoming message from PebbleKitJS is dropped +static void in_dropped_handler(AppMessageResult reason, void *context) { +} + +// Called when PebbleKitJS does not acknowledge receipt of a message +static void out_failed_handler(DictionaryIterator *failed, AppMessageResult reason, void *context) { +} + +void init(void) { + window = window_create(); + window_stack_push(window, true); + + // Register AppMessage handlers + app_message_register_inbox_received(in_received_handler); + app_message_register_inbox_dropped(in_dropped_handler); + app_message_register_outbox_failed(out_failed_handler); + + app_message_open(app_message_inbox_size_maximum(), app_message_outbox_size_maximum()); + + + accel_data_service_subscribe(0, NULL); + + timer = app_timer_register(ACCEL_STEP_MS, timer_callback, NULL); + + //send_message(); +} + +void deinit(void) { + app_message_deregister_callbacks(); + accel_data_service_unsubscribe(); + window_destroy(window); +} + +int main( void ) { + init(); + app_event_loop(); + deinit(); +} \ No newline at end of file diff --git a/pool/shard008/C/0133673_oslmic.c b/pool/shard008/C/0133673_oslmic.c new file mode 100644 index 0000000000000000000000000000000000000000..401f300b70c4bc3e8e909556b847ca879d18f6a1 --- /dev/null +++ b/pool/shard008/C/0133673_oslmic.c @@ -0,0 +1,129 @@ +/******************************************************************************* + * Copyright (c) 2014-2015 IBM Corporation. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Zurich Research Lab - initial API, implementation and documentation + *******************************************************************************/ + +#include "lmic.h" +#include + +// RUNTIME STATE +static struct { + osjob_t* scheduledjobs; + osjob_t* runnablejobs; +} OS; + +void os_init () { + memset(&OS, 0x00, sizeof(OS)); + hal_init(); + radio_init(); + LMIC_init(); +} + +ostime_t os_getTime () { + return hal_ticks(); +} + +static u1_t unlinkjob (osjob_t** pnext, osjob_t* job) { + for( ; *pnext; pnext = &((*pnext)->next)) { + if(*pnext == job) { // unlink + *pnext = job->next; + return 1; + } + } + return 0; +} + +// clear scheduled job +void os_clearCallback (osjob_t* job) { + hal_disableIRQs(); + u1_t res = unlinkjob(&OS.scheduledjobs, job) || unlinkjob(&OS.runnablejobs, job); + hal_enableIRQs(); + #if LMIC_DEBUG_LEVEL > 1 + if (res) + lmic_printf("%d: Cleared job %p\n", os_getTime(), job); + #endif +} + +// schedule immediately runnable job +void os_setCallback (osjob_t* job, osjobcb_t cb) { + osjob_t** pnext; + hal_disableIRQs(); + // remove if job was already queued + os_clearCallback(job); + // fill-in job + job->func = cb; + job->next = NULL; + // add to end of run queue + for(pnext=&OS.runnablejobs; *pnext; pnext=&((*pnext)->next)); + *pnext = job; + hal_enableIRQs(); + #if LMIC_DEBUG_LEVEL > 1 + lmic_printf("%d: Scheduled job %p, cb %p ASAP\n", os_getTime(), job, cb); + #endif +} + +// schedule timed job +void os_setTimedCallback (osjob_t* job, ostime_t time, osjobcb_t cb) { + osjob_t** pnext; + hal_disableIRQs(); + // remove if job was already queued + os_clearCallback(job); + // fill-in job + job->deadline = time; + job->func = cb; + job->next = NULL; + // insert into schedule + for(pnext=&OS.scheduledjobs; *pnext; pnext=&((*pnext)->next)) { + if((*pnext)->deadline - time > 0) { // (cmp diff, not abs!) + // enqueue before next element and stop + job->next = *pnext; + break; + } + } + *pnext = job; + hal_enableIRQs(); + #if LMIC_DEBUG_LEVEL > 1 + lmic_printf("%d: Scheduled job %p, cb %p at %d\n", os_getTime(), job, cb, time); + #endif +} + +// execute jobs from timer and from run queue +void os_runloop () { + while(1) { + os_runloop_once(); + } +} + +void os_runloop_once() { + #if LMIC_DEBUG_LEVEL > 1 + bool has_deadline = false; + #endif + osjob_t* j = NULL; + hal_disableIRQs(); + // check for runnable jobs + if(OS.runnablejobs) { + j = OS.runnablejobs; + OS.runnablejobs = j->next; + } else if(OS.scheduledjobs && hal_checkTimer(OS.scheduledjobs->deadline)) { // check for expired timed jobs + j = OS.scheduledjobs; + OS.scheduledjobs = j->next; + #if LMIC_DEBUG_LEVEL > 1 + has_deadline = true; + #endif + } else { // nothing pending + hal_sleep(); // wake by irq (timer already restarted) + } + hal_enableIRQs(); + if(j) { // run job callback + #if LMIC_DEBUG_LEVEL > 1 + lmic_printf("%d: Running job %p, cb %p, deadline %d\n", os_getTime(), j, j->func, has_deadline ? j->deadline : 0); + #endif + j->func(j); + } +} diff --git a/pool/shard008/C/0133674_decompress_unxz.c b/pool/shard008/C/0133674_decompress_unxz.c new file mode 100644 index 0000000000000000000000000000000000000000..cd32cc745c35a467643f1bc9a9e05c645649ba94 --- /dev/null +++ b/pool/shard008/C/0133674_decompress_unxz.c @@ -0,0 +1,131 @@ +/* + * This file uses XZ Embedded library code which is written + * by Lasse Collin + * and Igor Pavlov + * + * See README file in unxz/ directory for more information. + * + * This file is: + * Copyright (C) 2010 Denys Vlasenko + * Licensed under GPLv2, see file LICENSE in this source tree. + */ +#include "libbb.h" +#include "bb_archive.h" + +#define XZ_FUNC FAST_FUNC +#define XZ_EXTERN static + +#define XZ_DEC_DYNALLOC + +/* Skip check (rather than fail) of unsupported hash functions */ +#define XZ_DEC_ANY_CHECK 1 + +/* We use our own crc32 function */ +#define XZ_INTERNAL_CRC32 0 +static uint32_t xz_crc32(const uint8_t *buf, size_t size, uint32_t crc) +{ + return ~crc32_block_endian0(~crc, buf, size, global_crc32_table); +} + +/* We use arch-optimized unaligned accessors */ +#define get_unaligned_le32(buf) ({ uint32_t v; move_from_unaligned32(v, buf); SWAP_LE32(v); }) +#define get_unaligned_be32(buf) ({ uint32_t v; move_from_unaligned32(v, buf); SWAP_BE32(v); }) +#define put_unaligned_le32(val, buf) move_to_unaligned32(buf, SWAP_LE32(val)) +#define put_unaligned_be32(val, buf) move_to_unaligned32(buf, SWAP_BE32(val)) + +#include "unxz/xz_dec_bcj.c" +#include "unxz/xz_dec_lzma2.c" +#include "unxz/xz_dec_stream.c" + +IF_DESKTOP(long long) int FAST_FUNC +unpack_xz_stream(transformer_state_t *xstate) +{ + enum xz_ret xz_result; + struct xz_buf iobuf; + struct xz_dec *state; + unsigned char *membuf; + IF_DESKTOP(long long) int total = 0; + + if (!global_crc32_table) + global_crc32_table = crc32_filltable(NULL, /*endian:*/ 0); + + memset(&iobuf, 0, sizeof(iobuf)); + membuf = xmalloc(2 * BUFSIZ); + iobuf.in = membuf; + iobuf.out = membuf + BUFSIZ; + iobuf.out_size = BUFSIZ; + + if (!xstate || xstate->signature_skipped) { + /* Preload XZ file signature */ + strcpy((char*)membuf, HEADER_MAGIC); + iobuf.in_size = HEADER_MAGIC_SIZE; + } /* else: let xz code read & check it */ + + /* Limit memory usage to about 64 MiB. */ + state = xz_dec_init(XZ_DYNALLOC, 64*1024*1024); + + xz_result = X_OK; + while (1) { + if (iobuf.in_pos == iobuf.in_size) { + int rd = safe_read(xstate->src_fd, membuf, BUFSIZ); + if (rd < 0) { + bb_error_msg(bb_msg_read_error); + total = -1; + break; + } + if (rd == 0 && xz_result == XZ_STREAM_END) + break; + iobuf.in_size = rd; + iobuf.in_pos = 0; + } + if (xz_result == XZ_STREAM_END) { + /* + * Try to start decoding next concatenated stream. + * Stream padding must always be a multiple of four + * bytes to preserve four-byte alignment. To keep the + * code slightly smaller, we aren't as strict here as + * the .xz spec requires. We just skip all zero-bytes + * without checking the alignment and thus can accept + * files that aren't valid, e.g. the XZ utils test + * files bad-0pad-empty.xz and bad-0catpad-empty.xz. + */ + do { + if (membuf[iobuf.in_pos] != 0) { + xz_dec_reset(state); + goto do_run; + } + iobuf.in_pos++; + } while (iobuf.in_pos < iobuf.in_size); + } + do_run: +// bb_error_msg(">in pos:%d size:%d out pos:%d size:%d", +// iobuf.in_pos, iobuf.in_size, iobuf.out_pos, iobuf.out_size); + xz_result = xz_dec_run(state, &iobuf); +// bb_error_msg(". + */ +#include "err_lib.h" +#include +#include +#include +#include + +#include "lib-ttycolor.h" +#include "mem_lib.h" + +static char* prg; + +void setName(char* name){ + prg = name; + +} + +void die(int val,char* msg,...){ + + va_list args; + va_start(args,msg); + + cprintferr(RED,"%s:",prg); + cvprintferr(RED,msg,args); + + va_end(args); + + releaseAll(); + + exit(val); + + +} + +void warn(char* msg,...){ + + va_list args; + va_start(args,msg); + + cprintferr(YELLOW,"%s:",prg); + cvprintferr(YELLOW,msg,args); + + va_end(args); +} + +char* getFileErrMsg(){ + + static char* out; + switch(errno){ + case EACCES: + out = "can't open %s: access denied\n"; + break; + case EMFILE: + out = "can't open %s: too much file already opened\n"; + break; + case EOVERFLOW: + out = "can't open %s: file too large\n"; + break; + case ELOOP: + out = "can't correctly find %s: there are loops in the path\n"; + break; + case ENAMETOOLONG: + out = "can't open %s:a component in the path is too long\n"; + break; + default: + out = "unknown error while opening %s : errno(%d)\n"; + } + return out; +} + +char* getChdirErrMsg(){ + + static char* out; + switch(errno){ + case EACCES: + out = "can't open %s: access denied\n"; + break; + case ENOENT: + out = "can't open %s: a component doesn't name an existing directory\n"; + break; + case ENOTDIR: + out = "can't open %s: it's not a directory\n"; + break; + case ELOOP: + out = "can't correctly find %s: there are loops in the path\n"; + break; + case ENAMETOOLONG: + out = "can't open %s:a component in the path is too long\n"; + break; + default: + out = "unknown error while opening %s : errno(%d)\n"; + } + return out; +} + + + diff --git a/pool/shard008/C/0133677_irobex_palm3.c b/pool/shard008/C/0133677_irobex_palm3.c new file mode 100644 index 0000000000000000000000000000000000000000..a819363273b78da8564afd0fc302e6e382f6622d --- /dev/null +++ b/pool/shard008/C/0133677_irobex_palm3.c @@ -0,0 +1,131 @@ +/** + \file apps/irobex_palm3.c + Demonstrates use of PUT command. + OpenOBEX test applications and sample code. + + Copyright (c) 1999, 2000 Pontus Fuchs, All Rights Reserved. + + OpenOBEX is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation; either version 2 of + the License, or (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public + License along with OpenOBEX. If not, see . + */ + +/* + The Palm 3 always sends a HEADER_CREATORID (0xcf). + + Start without arguments to receive a file. + Start with filename as argument to send a file. + */ + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include +#include "obex_put_common.h" +#include "obex_io.h" + +#include +#include + +#ifndef _WIN32 +#include +#include +#endif + +#define TRUE 1 +#define FALSE 0 + +obex_t *handle = NULL; +volatile int finished = FALSE; +extern int last_rsp; + +/* + * Function usage (void) + */ +static int usage(char *argv[]) { + printf ("Usage: %s [-h id] [name]\n", argv[0]); + printf (" where id is the header_creator_id (default: memo)\n"); + return -1; +} + +/* + * Function main (argc, ) + * + * Starts all the fun! + * + */ +int main(int argc, char *argv[]) +{ + obex_object_t *object; + int ret, exitval = EXIT_SUCCESS; + uint32_t creator_id = 0; + + printf("Send and receive files to Palm3\n"); + if ((argc < 1) || (argc > 4)) { + return usage(argv); + } + handle = OBEX_Init(OBEX_TRANS_IRDA, obex_event, 0); + + if (argc == 1) { + /* We are server*/ + + printf("Waiting for files\n"); + IrOBEX_ServerRegister(handle, "OBEX"); + + while (!finished) + OBEX_HandleInput(handle, 1); + } + else { + /* We are a client */ + + /* Check for parameters */ + if(argc > 2) { + if(strcmp("-h", argv[1]) || strlen(argv[2]) != 4) + return usage(argv); + creator_id = argv[2][0] << 24 | argv[2][1] << 16 | argv[2][2] << 8 | argv[2][3]; + printf("debug: %s %d;", argv[2], creator_id); + } + + /* Try to connect to peer */ + ret = IrOBEX_TransportConnect(handle, "OBEX"); + if (ret < 0) { + printf("Sorry, unable to connect!\n"); + return EXIT_FAILURE; + } + + object = OBEX_ObjectNew(handle, OBEX_CMD_CONNECT); + ret = do_sync_request(handle, object, FALSE); + if ((last_rsp != OBEX_RSP_SUCCESS) || (ret < 0)) { + printf("Sorry, unable to connect!\n"); + return EXIT_FAILURE; + } + if ((object = build_object_from_file(handle, argv[(creator_id ? 3 : 1)], creator_id))) { + ret = do_sync_request(handle, object, FALSE); + if ((last_rsp != OBEX_RSP_SUCCESS) || (ret < 0)) + exitval = EXIT_FAILURE; + } else + exitval = EXIT_FAILURE; + + object = OBEX_ObjectNew(handle, OBEX_CMD_DISCONNECT); + ret = do_sync_request(handle, object, FALSE); + if ((last_rsp != OBEX_RSP_SUCCESS) || (ret < 0)) + exitval = EXIT_FAILURE; + + if (exitval == EXIT_SUCCESS) + printf("PUT successful\n"); + else + printf("PUT failed\n"); + } +// sleep(1); + return exitval; +} diff --git a/pool/shard008/C/0133678_real_fft.c b/pool/shard008/C/0133678_real_fft.c new file mode 100644 index 0000000000000000000000000000000000000000..fc5be9a02c5362842196f3530dd0e657954c6154 --- /dev/null +++ b/pool/shard008/C/0133678_real_fft.c @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. + * + * Use of this source code is governed by a BSD-style license + * that can be found in the LICENSE file in the root of the source + * tree. An additional intellectual property rights grant can be found + * in the file PATENTS. All contributing project authors may + * be found in the AUTHORS file in the root of the source tree. + */ + +#include "webrtc/common_audio/signal_processing/include/real_fft.h" + +#include + +#include "webrtc/common_audio/signal_processing/include/signal_processing_library.h" + +struct RealFFT { + int order; +}; + +struct RealFFT* WebRtcSpl_CreateRealFFTC(int order) { + struct RealFFT* self = NULL; + + if (order > kMaxFFTOrder || order < 0) { + return NULL; + } + + self = malloc(sizeof(struct RealFFT)); + if (self == NULL) { + return NULL; + } + self->order = order; + + return self; +} + +void WebRtcSpl_FreeRealFFTC(struct RealFFT* self) { + if (self != NULL) { + free(self); + } +} + +// The C version FFT functions (i.e. WebRtcSpl_RealForwardFFTC and +// WebRtcSpl_RealInverseFFTC) are real-valued FFT wrappers for complex-valued +// FFT implementation in SPL. + +int WebRtcSpl_RealForwardFFTC(struct RealFFT* self, + const int16_t* real_data_in, + int16_t* complex_data_out) { + int i = 0; + int j = 0; + int result = 0; + int n = 1 << self->order; + // The complex-value FFT implementation needs a buffer to hold 2^order + // 16-bit COMPLEX numbers, for both time and frequency data. + int16_t complex_buffer[2 << kMaxFFTOrder]; + + // Insert zeros to the imaginary parts for complex forward FFT input. + for (i = 0, j = 0; i < n; i += 1, j += 2) { + complex_buffer[j] = real_data_in[i]; + complex_buffer[j + 1] = 0; + }; + + WebRtcSpl_ComplexBitReverse(complex_buffer, self->order); + result = WebRtcSpl_ComplexFFT(complex_buffer, self->order, 1); + + // For real FFT output, use only the first N + 2 elements from + // complex forward FFT. + memcpy(complex_data_out, complex_buffer, sizeof(int16_t) * (n + 2)); + + return result; +} + +int WebRtcSpl_RealInverseFFTC(struct RealFFT* self, + const int16_t* complex_data_in, + int16_t* real_data_out) { + int i = 0; + int j = 0; + int result = 0; + int n = 1 << self->order; + // Create the buffer specific to complex-valued FFT implementation. + int16_t complex_buffer[2 << kMaxFFTOrder]; + + // For n-point FFT, first copy the first n + 2 elements into complex + // FFT, then construct the remaining n - 2 elements by real FFT's + // conjugate-symmetric properties. + memcpy(complex_buffer, complex_data_in, sizeof(int16_t) * (n + 2)); + for (i = n + 2; i < 2 * n; i += 2) { + complex_buffer[i] = complex_data_in[2 * n - i]; + complex_buffer[i + 1] = -complex_data_in[2 * n - i + 1]; + } + + WebRtcSpl_ComplexBitReverse(complex_buffer, self->order); + result = WebRtcSpl_ComplexIFFT(complex_buffer, self->order, 1); + + // Strip out the imaginary parts of the complex inverse FFT output. + for (i = 0, j = 0; i < n; i += 1, j += 2) { + real_data_out[i] = complex_buffer[j]; + } + + return result; +} + +#if defined(WEBRTC_DETECT_ARM_NEON) || defined(WEBRTC_ARCH_ARM_NEON) +// TODO(kma): Replace the following function bodies into optimized functions +// for ARM Neon. +struct RealFFT* WebRtcSpl_CreateRealFFTNeon(int order) { + return WebRtcSpl_CreateRealFFTC(order); +} + +void WebRtcSpl_FreeRealFFTNeon(struct RealFFT* self) { + WebRtcSpl_FreeRealFFTC(self); +} + +int WebRtcSpl_RealForwardFFTNeon(struct RealFFT* self, + const int16_t* real_data_in, + int16_t* complex_data_out) { + return WebRtcSpl_RealForwardFFTC(self, real_data_in, complex_data_out); +} + +int WebRtcSpl_RealInverseFFTNeon(struct RealFFT* self, + const int16_t* complex_data_in, + int16_t* real_data_out) { + return WebRtcSpl_RealInverseFFTC(self, complex_data_in, real_data_out); +} +#endif // WEBRTC_DETECT_ARM_NEON || WEBRTC_ARCH_ARM_NEON diff --git a/pool/shard008/C/0133682_contig.c b/pool/shard008/C/0133682_contig.c new file mode 100644 index 0000000000000000000000000000000000000000..6daf15ac894059a109d0b047f3cf751686db2e9a --- /dev/null +++ b/pool/shard008/C/0133682_contig.c @@ -0,0 +1,299 @@ +/* + * This file is subject to the terms and conditions of the GNU General Public + * License. See the file "COPYING" in the main directory of this archive + * for more details. + * + * Copyright (C) 1998-2003 Hewlett-Packard Co + * David Mosberger-Tang + * Stephane Eranian + * Copyright (C) 2000, Rohit Seth + * Copyright (C) 1999 VA Linux Systems + * Copyright (C) 1999 Walt Drummond + * Copyright (C) 2003 Silicon Graphics, Inc. All rights reserved. + * + * Routines used by ia64 machines with contiguous (or virtually contiguous) + * memory. + */ +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#ifdef CONFIG_VIRTUAL_MEM_MAP +static unsigned long num_dma_physpages; +#endif + +/** + * show_mem - display a memory statistics summary + * + * Just walks the pages in the system and describes where they're allocated. + */ +void +show_mem (void) +{ + int i, total = 0, reserved = 0; + int shared = 0, cached = 0; + + printk("Mem-info:\n"); + show_free_areas(); + + printk("Free swap: %6ldkB\n", nr_swap_pages<<(PAGE_SHIFT-10)); + i = max_mapnr; + while (i-- > 0) { + if (!pfn_valid(i)) + continue; + total++; + if (PageReserved(mem_map+i)) + reserved++; + else if (PageSwapCache(mem_map+i)) + cached++; + else if (page_count(mem_map + i)) + shared += page_count(mem_map + i) - 1; + } + printk("%d pages of RAM\n", total); + printk("%d reserved pages\n", reserved); + printk("%d pages shared\n", shared); + printk("%d pages swap cached\n", cached); + printk("%ld pages in page table cache\n", pgtable_cache_size); +} + +/* physical address where the bootmem map is located */ +unsigned long bootmap_start; + +/** + * find_max_pfn - adjust the maximum page number callback + * @start: start of range + * @end: end of range + * @arg: address of pointer to global max_pfn variable + * + * Passed as a callback function to efi_memmap_walk() to determine the highest + * available page frame number in the system. + */ +int +find_max_pfn (unsigned long start, unsigned long end, void *arg) +{ + unsigned long *max_pfnp = arg, pfn; + + pfn = (PAGE_ALIGN(end - 1) - PAGE_OFFSET) >> PAGE_SHIFT; + if (pfn > *max_pfnp) + *max_pfnp = pfn; + return 0; +} + +/** + * find_bootmap_location - callback to find a memory area for the bootmap + * @start: start of region + * @end: end of region + * @arg: unused callback data + * + * Find a place to put the bootmap and return its starting address in + * bootmap_start. This address must be page-aligned. + */ +int +find_bootmap_location (unsigned long start, unsigned long end, void *arg) +{ + unsigned long needed = *(unsigned long *)arg; + unsigned long range_start, range_end, free_start; + int i; + +#if IGNORE_PFN0 + if (start == PAGE_OFFSET) { + start += PAGE_SIZE; + if (start >= end) + return 0; + } +#endif + + free_start = PAGE_OFFSET; + + for (i = 0; i < num_rsvd_regions; i++) { + range_start = max(start, free_start); + range_end = min(end, rsvd_region[i].start & PAGE_MASK); + + free_start = PAGE_ALIGN(rsvd_region[i].end); + + if (range_end <= range_start) + continue; /* skip over empty range */ + + if (range_end - range_start >= needed) { + bootmap_start = __pa(range_start); + return -1; /* done */ + } + + /* nothing more available in this segment */ + if (range_end == end) + return 0; + } + return 0; +} + +/** + * find_memory - setup memory map + * + * Walk the EFI memory map and find usable memory for the system, taking + * into account reserved areas. + */ +void +find_memory (void) +{ + unsigned long bootmap_size; + + reserve_memory(); + + /* first find highest page frame number */ + max_pfn = 0; + efi_memmap_walk(find_max_pfn, &max_pfn); + + /* how many bytes to cover all the pages */ + bootmap_size = bootmem_bootmap_pages(max_pfn) << PAGE_SHIFT; + + /* look for a location to hold the bootmap */ + bootmap_start = ~0UL; + efi_memmap_walk(find_bootmap_location, &bootmap_size); + if (bootmap_start == ~0UL) + panic("Cannot find %ld bytes for bootmap\n", bootmap_size); + + bootmap_size = init_bootmem(bootmap_start >> PAGE_SHIFT, max_pfn); + + /* Free all available memory, then mark bootmem-map as being in use. */ + efi_memmap_walk(filter_rsvd_memory, free_bootmem); + reserve_bootmem(bootmap_start, bootmap_size); + + find_initrd(); +} + +#ifdef CONFIG_SMP +/** + * per_cpu_init - setup per-cpu variables + * + * Allocate and setup per-cpu data areas. + */ +void * +per_cpu_init (void) +{ + void *cpu_data; + int cpu; + + /* + * get_free_pages() cannot be used before cpu_init() done. BSP + * allocates "NR_CPUS" pages for all CPUs to avoid that AP calls + * get_zeroed_page(). + */ + if (smp_processor_id() == 0) { + cpu_data = __alloc_bootmem(PERCPU_PAGE_SIZE * NR_CPUS, + PERCPU_PAGE_SIZE, __pa(MAX_DMA_ADDRESS)); + for (cpu = 0; cpu < NR_CPUS; cpu++) { + memcpy(cpu_data, __phys_per_cpu_start, __per_cpu_end - __per_cpu_start); + __per_cpu_offset[cpu] = (char *) cpu_data - __per_cpu_start; + cpu_data += PERCPU_PAGE_SIZE; + per_cpu(local_per_cpu_offset, cpu) = __per_cpu_offset[cpu]; + } + } + return __per_cpu_start + __per_cpu_offset[smp_processor_id()]; +} +#endif /* CONFIG_SMP */ + +static int +count_pages (u64 start, u64 end, void *arg) +{ + unsigned long *count = arg; + + *count += (end - start) >> PAGE_SHIFT; + return 0; +} + +#ifdef CONFIG_VIRTUAL_MEM_MAP +static int +count_dma_pages (u64 start, u64 end, void *arg) +{ + unsigned long *count = arg; + + if (start < MAX_DMA_ADDRESS) + *count += (min(end, MAX_DMA_ADDRESS) - start) >> PAGE_SHIFT; + return 0; +} +#endif + +/* + * Set up the page tables. + */ + +void +paging_init (void) +{ + unsigned long max_dma; + unsigned long zones_size[MAX_NR_ZONES]; +#ifdef CONFIG_VIRTUAL_MEM_MAP + unsigned long zholes_size[MAX_NR_ZONES]; + unsigned long max_gap; +#endif + + /* initialize mem_map[] */ + + memset(zones_size, 0, sizeof(zones_size)); + + num_physpages = 0; + efi_memmap_walk(count_pages, &num_physpages); + + max_dma = virt_to_phys((void *) MAX_DMA_ADDRESS) >> PAGE_SHIFT; + +#ifdef CONFIG_VIRTUAL_MEM_MAP + memset(zholes_size, 0, sizeof(zholes_size)); + + num_dma_physpages = 0; + efi_memmap_walk(count_dma_pages, &num_dma_physpages); + + if (max_low_pfn < max_dma) { + zones_size[ZONE_DMA] = max_low_pfn; + zholes_size[ZONE_DMA] = max_low_pfn - num_dma_physpages; + } else { + zones_size[ZONE_DMA] = max_dma; + zholes_size[ZONE_DMA] = max_dma - num_dma_physpages; + if (num_physpages > num_dma_physpages) { + zones_size[ZONE_NORMAL] = max_low_pfn - max_dma; + zholes_size[ZONE_NORMAL] = + ((max_low_pfn - max_dma) - + (num_physpages - num_dma_physpages)); + } + } + + max_gap = 0; + efi_memmap_walk(find_largest_hole, (u64 *)&max_gap); + if (max_gap < LARGE_GAP) { + vmem_map = (struct page *) 0; + free_area_init_node(0, &contig_page_data, zones_size, 0, + zholes_size); + } else { + unsigned long map_size; + + /* allocate virtual_mem_map */ + + map_size = PAGE_ALIGN(max_low_pfn * sizeof(struct page)); + vmalloc_end -= map_size; + vmem_map = (struct page *) vmalloc_end; + efi_memmap_walk(create_mem_map_page_table, NULL); + + NODE_DATA(0)->node_mem_map = vmem_map; + free_area_init_node(0, &contig_page_data, zones_size, + 0, zholes_size); + + printk("Virtual mem_map starts at 0x%p\n", mem_map); + } +#else /* !CONFIG_VIRTUAL_MEM_MAP */ + if (max_low_pfn < max_dma) + zones_size[ZONE_DMA] = max_low_pfn; + else { + zones_size[ZONE_DMA] = max_dma; + zones_size[ZONE_NORMAL] = max_low_pfn - max_dma; + } + free_area_init(zones_size); +#endif /* !CONFIG_VIRTUAL_MEM_MAP */ + zero_page_memmap_ptr = virt_to_page(ia64_imva(empty_zero_page)); +} diff --git a/pool/shard008/C/0133683_CWE122_Heap_Based_Buffer_Overflow__c_dest_char_cpy_41.c b/pool/shard008/C/0133683_CWE122_Heap_Based_Buffer_Overflow__c_dest_char_cpy_41.c new file mode 100644 index 0000000000000000000000000000000000000000..2ddc9171f94f995094d8b44d943089a6054d98b9 --- /dev/null +++ b/pool/shard008/C/0133683_CWE122_Heap_Based_Buffer_Overflow__c_dest_char_cpy_41.c @@ -0,0 +1,106 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE122_Heap_Based_Buffer_Overflow__c_dest_char_cpy_41.c +Label Definition File: CWE122_Heap_Based_Buffer_Overflow__c_dest.label.xml +Template File: sources-sink-41.tmpl.c +*/ +/* + * @description + * CWE: 122 Heap Based Buffer Overflow + * BadSource: Allocate using malloc() and set data pointer to a small buffer + * GoodSource: Allocate using malloc() and set data pointer to a large buffer + * Sink: cpy + * BadSink : Copy string to data using strcpy + * Flow Variant: 41 Data flow: data passed as an argument from one function to another in the same source file + * + * */ + +#include "std_testcase.h" + +#include + +#ifndef OMITBAD + +void CWE122_Heap_Based_Buffer_Overflow__c_dest_char_cpy_41_badSink(char * data) +{ + { + char source[100]; + memset(source, 'C', 100-1); /* fill with 'C's */ + source[100-1] = '\0'; /* null terminate */ + /* POTENTIAL FLAW: Possible buffer overflow if source is larger than data */ + strcpy(data, source); + printLine(data); + free(data); + } +} + +void CWE122_Heap_Based_Buffer_Overflow__c_dest_char_cpy_41_bad() +{ + char * data; + data = NULL; + /* FLAW: Allocate and point data to a small buffer that is smaller than the large buffer used in the sinks */ + data = (char *)malloc(50*sizeof(char)); + data[0] = '\0'; /* null terminate */ + CWE122_Heap_Based_Buffer_Overflow__c_dest_char_cpy_41_badSink(data); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +void CWE122_Heap_Based_Buffer_Overflow__c_dest_char_cpy_41_goodG2BSink(char * data) +{ + { + char source[100]; + memset(source, 'C', 100-1); /* fill with 'C's */ + source[100-1] = '\0'; /* null terminate */ + /* POTENTIAL FLAW: Possible buffer overflow if source is larger than data */ + strcpy(data, source); + printLine(data); + free(data); + } +} + +/* goodG2B uses the GoodSource with the BadSink */ +static void goodG2B() +{ + char * data; + data = NULL; + /* FIX: Allocate and point data to a large buffer that is at least as large as the large buffer used in the sink */ + data = (char *)malloc(100*sizeof(char)); + data[0] = '\0'; /* null terminate */ + CWE122_Heap_Based_Buffer_Overflow__c_dest_char_cpy_41_goodG2BSink(data); +} + +void CWE122_Heap_Based_Buffer_Overflow__c_dest_char_cpy_41_good() +{ + goodG2B(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + * its own for testing or for building a binary to use in testing binary + * analysis tools. It is not used when compiling all the testcases as one + * application, which is how source code analysis tools are tested. + */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE122_Heap_Based_Buffer_Overflow__c_dest_char_cpy_41_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE122_Heap_Based_Buffer_Overflow__c_dest_char_cpy_41_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard008/C/0133684_pci_mcfg.c b/pool/shard008/C/0133684_pci_mcfg.c new file mode 100644 index 0000000000000000000000000000000000000000..b5b376e081f550ac943728c944c12114a91563ba --- /dev/null +++ b/pool/shard008/C/0133684_pci_mcfg.c @@ -0,0 +1,92 @@ +/* + * Copyright (C) 2016 Broadcom + * Author: Jayachandran C + * Copyright (C) 2016 Semihalf + * Author: Tomasz Nowicki + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License, version 2, as + * published by the Free Software Foundation (the "GPL"). + * + * This program 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 + * General Public License version 2 (GPLv2) for more details. + * + * You should have received a copy of the GNU General Public License + * version 2 (GPLv2) along with this source code. + */ + +#define pr_fmt(fmt) "ACPI: " fmt + +#include +#include +#include + +/* Structure to hold entries from the MCFG table */ +struct mcfg_entry { + struct list_head list; + phys_addr_t addr; + u16 segment; + u8 bus_start; + u8 bus_end; +}; + +/* List to save MCFG entries */ +static LIST_HEAD(pci_mcfg_list); + +phys_addr_t pci_mcfg_lookup(u16 seg, struct resource *bus_res) +{ + struct mcfg_entry *e; + + /* + * We expect exact match, unless MCFG entry end bus covers more than + * specified by caller. + */ + list_for_each_entry(e, &pci_mcfg_list, list) { + if (e->segment == seg && e->bus_start == bus_res->start && + e->bus_end >= bus_res->end) + return e->addr; + } + + return 0; +} + +static __init int pci_mcfg_parse(struct acpi_table_header *header) +{ + struct acpi_table_mcfg *mcfg; + struct acpi_mcfg_allocation *mptr; + struct mcfg_entry *e, *arr; + int i, n; + + if (header->length < sizeof(struct acpi_table_mcfg)) + return -EINVAL; + + n = (header->length - sizeof(struct acpi_table_mcfg)) / + sizeof(struct acpi_mcfg_allocation); + mcfg = (struct acpi_table_mcfg *)header; + mptr = (struct acpi_mcfg_allocation *) &mcfg[1]; + + arr = kcalloc(n, sizeof(*arr), GFP_KERNEL); + if (!arr) + return -ENOMEM; + + for (i = 0, e = arr; i < n; i++, mptr++, e++) { + e->segment = mptr->pci_segment; + e->addr = mptr->address; + e->bus_start = mptr->start_bus_number; + e->bus_end = mptr->end_bus_number; + list_add(&e->list, &pci_mcfg_list); + } + + pr_info("MCFG table detected, %d entries\n", n); + return 0; +} + +/* Interface called by ACPI - parse and save MCFG table */ +void __init pci_mmcfg_late_init(void) +{ + int err = acpi_table_parse(ACPI_SIG_MCFG, pci_mcfg_parse); + if (err) + pr_err("Failed to parse MCFG (%d)\n", err); +} diff --git a/pool/shard008/C/0133685_main.c b/pool/shard008/C/0133685_main.c new file mode 100644 index 0000000000000000000000000000000000000000..fd29b3bd004a40443e118df0672b5c9b428a5e91 --- /dev/null +++ b/pool/shard008/C/0133685_main.c @@ -0,0 +1,80 @@ +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include + +#include "go.h" + +const char *cmds[] = { + "cat", + "import_games", + "extract_features", + NULL +}; + +int main(int argc, char **argv) { + srand(clock()); + if (sodium_init() == -1) { + perror("failure to initialize libsodium"); + return -1; + } + go_init(); + + if (argc < 2) { + fprintf(stderr, "Usage: kerplunk ...\n"); + return -1; + } + + // initialize lua VM + lua_State *L = lua_open(); + luaL_openlibs(L); + + // check command name + bool cmd_found = false; + for (size_t i = 0; cmds[i]; i++) { + if (!strcmp(cmds[i], argv[1])) { + cmd_found = true; + break; + } + } + + if (!cmd_found) { + fprintf(stderr, "unknown command %s\n", argv[1]); + return -1; + } + + // run bootstrap script + char buffer[100]; + snprintf(buffer, sizeof(buffer), "main=require(\"%s\").main\n", argv[1]); + if (luaL_dostring(L, buffer)) { + fprintf(stderr, "%s\n", lua_tostring(L, -1)); + return -1; + } + + // run script main + lua_getglobal(L, "main"); + for (int i = 2; i < argc; i++) { + lua_pushstring(L, argv[i]); + } + if (lua_pcall(L, argc-2, 1, 0)) { + luaL_error(L, "error running command %s main: %s", + argv[1], lua_tostring(L, -1)); + return -1; + } + + int retval = lua_tonumber(L, -1); + lua_pop(L, 1); + + lua_close(L); + + return retval; +} diff --git a/pool/shard008/C/0133688_eventunknown.c b/pool/shard008/C/0133688_eventunknown.c new file mode 100644 index 0000000000000000000000000000000000000000..ccc9acf639ec4e6e6648e194049d522cd50beb5c --- /dev/null +++ b/pool/shard008/C/0133688_eventunknown.c @@ -0,0 +1,55 @@ +/* + * Copyright (C) 2015 CloudGuard Software AG + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * 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. + */ + +#include "tester.h" + +#include +#include +#include +#include +#include + +static void srvcb(struct tester *t, int fd) +{ + tester_read_eventreg(fd, "nosuchevent"); + tester_write_eventunknown(fd); +} + +static void eventcb(struct davici_conn *c, int err, const char *name, + struct davici_response *res, void *user) +{ + struct tester *t = user; + + assert(strcmp(name, "nosuchevent") == 0); + assert(err == -ENOENT); + assert(res == NULL); + + tester_complete(t); +} + +int main(int argc, char *argv[]) +{ + struct tester *t; + struct davici_conn *c; + + t = tester_create(srvcb); + assert(davici_connect_unix(tester_getpath(t), + tester_davici_iocb, t, &c) >= 0); + assert(davici_register(c, "nosuchevent", eventcb, t) >= 0); + + tester_runio(t, c); + davici_disconnect(c); + tester_cleanup(t); + return 0; +} diff --git a/pool/shard008/C/0133689_tls_openssl_api.c b/pool/shard008/C/0133689_tls_openssl_api.c new file mode 100644 index 0000000000000000000000000000000000000000..c34829f0b2966c06e0ce68517739cf2ef950e50e --- /dev/null +++ b/pool/shard008/C/0133689_tls_openssl_api.c @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2018 Cisco and/or its affiliates. + * 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 +#include +#include +#include +#include + +/* define message IDs */ +#include +#include + +#define vl_print(handle, ...) vlib_cli_output (handle, __VA_ARGS__) + +#define REPLY_MSG_ID_BASE om->msg_id_base +#include + +extern openssl_main_t openssl_main; + +/* API message handler */ +static void +vl_api_tls_openssl_set_engine_t_handler (vl_api_tls_openssl_set_engine_t * mp) +{ + vl_api_tls_openssl_set_engine_reply_t *rmp; + openssl_main_t *om = &openssl_main; + char *engine, *alg; + char *ciphers; + int rv; + + ciphers = (char *) &mp->ciphers; + ciphers[63] = '\0'; + if (ciphers[0]) + tls_openssl_set_ciphers (ciphers); + + engine = (char *) mp->engine; + engine[63] = '\0'; + alg = (char *) mp->algorithm; + alg[63] = '\0'; + rv = openssl_engine_register (engine, alg, mp->async_enable); + om->async = mp->async_enable; + + REPLY_MACRO (VL_API_TLS_OPENSSL_SET_ENGINE_REPLY); +} + +#include +clib_error_t * +tls_openssl_api_init (vlib_main_t * vm) +{ + openssl_main_t *om = &openssl_main; + + /* Ask for a correctly-sized block of API message decode slots */ + om->msg_id_base = setup_message_id_table (); + + return 0; +} + +/* + * fd.io coding-style-patch-verification: ON + * + * Local Variables: + * eval: (c-set-style "gnu") + * End: + */ diff --git a/pool/shard008/C/0133690_sysinit_8xx.c b/pool/shard008/C/0133690_sysinit_8xx.c new file mode 100644 index 0000000000000000000000000000000000000000..ca4d732c01abc087b79219eb7747d50b26bf3d52 --- /dev/null +++ b/pool/shard008/C/0133690_sysinit_8xx.c @@ -0,0 +1,167 @@ +/* + * @brief LPC8xx Chip specific SystemInit + * + * @note + * Copyright(C) NXP Semiconductors, 2013 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#include "chip.h" + +/***************************************************************************** + * Private types/enumerations/variables + ****************************************************************************/ + +/* Enable this definition to use the ROM API for PLL setup */ +// #define USE_ROM_API + +/***************************************************************************** + * Public types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Private functions + ****************************************************************************/ + +/***************************************************************************** + * Public functions + ****************************************************************************/ + +/* Setup system clocking */ +void Chip_SetupXtalClocking(void) +{ +#if defined(USE_ROM_API) + uint32_t cmd[4], resp[2]; +#endif + + /* EXT oscillator < 15MHz */ + Chip_Clock_SetPLLBypass(false, false); + + /* Turn on the SYSOSC by clearing the power down bit */ + Chip_SYSCTL_PowerUp(SYSCTL_SLPWAKE_SYSOSC_PD); + + /* Select the PLL input to the external oscillator */ + Chip_Clock_SetSystemPLLSource(SYSCTL_PLLCLKSRC_SYSOSC); + + /* Setup FLASH access to 2 clocks (up to 30MHz) */ + Chip_FMC_SetFLASHAccess(FLASHTIM_30MHZ_CPU); + +#if defined(USE_ROM_API) + /* Use ROM API for setting up PLL */ + cmd[0] = Chip_Clock_GetMainOscRate() / 1000;/* in KHz */ + cmd[1] = 24000000 / 1000; /* 24MHz system clock rate */ + cmd[2] = CPU_FREQ_EQU; + cmd[2] = 24000000 / 10000; + LPC_PWRD_API->set_pll(cmd, resp); + + /* Dead loop on fail */ + while (resp[0] != PLL_CMD_SUCCESS) {} + +#else + /* Power down PLL to change the PLL divider ratio */ + Chip_SYSCTL_PowerDown(SYSCTL_SLPWAKE_SYSPLL_PD); + + /* Configure the PLL M and P dividers */ + /* Setup PLL for main oscillator rate (FCLKIN = 12MHz) * 2 = 324Hz + MSEL = 1 (this is pre-decremented), PSEL = 2 (for P = 4) + FCLKOUT = FCLKIN * (MSEL + 1) = 12MHz * 2 = 24MHz + FCCO = FCLKOUT * 2 * P = 24MHz * 2 * 4 = 192MHz (within FCCO range) */ + Chip_Clock_SetupSystemPLL(1, 2); + + /* Turn on the PLL by clearing the power down bit */ + Chip_SYSCTL_PowerUp(SYSCTL_SLPWAKE_SYSPLL_PD); + + /* Wait for PLL to lock */ + while (!Chip_Clock_IsSystemPLLLocked()) {} + + /* Set system clock divider to 1 */ + Chip_Clock_SetSysClockDiv(1); + + /* Set main clock source to the system PLL. This will drive 24MHz + for the main clock and 24MHz for the system clock */ + Chip_Clock_SetMainClockSource(SYSCTL_MAINCLKSRC_PLLOUT); +#endif +} + +/* Set up and initialize hardware prior to call to main */ +void Chip_SetupIrcClocking(void) +{ +#if defined(USE_ROM_API) + uint32_t cmd[4], resp[2]; +#endif + + /* Turn on the IRC by clearing the power down bit */ + Chip_SYSCTL_PowerUp(SYSCTL_SLPWAKE_IRC_PD); + + /* Select the PLL input in the IRC */ + Chip_Clock_SetSystemPLLSource(SYSCTL_PLLCLKSRC_IRC); + + /* Setup FLASH access to 2 clocks (up to 30MHz) */ + Chip_FMC_SetFLASHAccess(FLASHTIM_30MHZ_CPU); + +#if defined(USE_ROM_API) + /* Use ROM API for setting up PLL */ + cmd[0] = Chip_Clock_GetIntOscRate() / 1000; /* in KHz */ + cmd[1] = 24000000 / 1000; /* 24MHz system clock rate */ + cmd[2] = CPU_FREQ_EQU; + cmd[3] = 24000000 / 10000; /* Timeout */ + LPC_PWRD_API->set_pll(cmd, resp); + + /* Dead loop on fail */ + while (resp[0] != PLL_CMD_SUCCESS) {} + +#else + /* Power down PLL to change the PLL divider ratio */ + Chip_SYSCTL_PowerDown(SYSCTL_SLPWAKE_SYSPLL_PD); + + /* Configure the PLL M and P dividers */ + /* Setup PLL for main oscillator rate (FCLKIN = 12MHz) * 2 = 324Hz + MSEL = 1 (this is pre-decremented), PSEL = 2 (for P = 4) + FCLKOUT = FCLKIN * (MSEL + 1) = 12MHz * 5 = 60MHz + FCCO = FCLKOUT * 2 * P = 60MHz * 2 * (2 * P) = 240MHz (within FCCO range) */ + Chip_Clock_SetupSystemPLL(4, 1); + + /* Turn on the PLL by clearing the power down bit */ + Chip_SYSCTL_PowerUp(SYSCTL_SLPWAKE_SYSPLL_PD); + + /* Wait for PLL to lock */ + while (!Chip_Clock_IsSystemPLLLocked()) {} + + /* Set system clock divider to 1 */ + Chip_Clock_SetSysClockDiv(1); + + /* Set main clock source to the system PLL. This will drive 24MHz + for the main clock and 24MHz for the system clock */ + Chip_Clock_SetMainClockSource(SYSCTL_MAINCLKSRC_PLLOUT); +#endif +} + +/* Set up and initialize hardware prior to call to main */ +void Chip_SystemInit(void) +{ + /* Initial internal clocking */ + Chip_SetupIrcClocking(); +} diff --git a/pool/shard008/C/0133693_fletcher16.c b/pool/shard008/C/0133693_fletcher16.c new file mode 100644 index 0000000000000000000000000000000000000000..2144a3e2b4353fcedd014d7d6b574b3deb81ad7e --- /dev/null +++ b/pool/shard008/C/0133693_fletcher16.c @@ -0,0 +1,60 @@ +/* + * Copyright 2015 Eistec AB + * + * This file is subject to the terms and conditions of the GNU Lesser + * General Public License v2.1. See the file LICENSE in the top level + * directory for more details. + */ + +/** + * @ingroup sys_checksum_fletcher16 + * @{ + * + * @file + * @brief Fletcher16 implementation + * + * @author Joakim Nohlgård + * + * @} + */ + +#include "checksum/fletcher16.h" + +static inline void _reduce(fletcher16_ctx_t *ctx) +{ + ctx->sum1 = (ctx->sum1 & 0xff) + (ctx->sum1 >> 8); + ctx->sum2 = (ctx->sum2 & 0xff) + (ctx->sum2 >> 8); +} + +void fletcher16_init(fletcher16_ctx_t *ctx) +{ + ctx->sum1 = 0xff; + ctx->sum2 = 0xff; +} + +void fletcher16_update(fletcher16_ctx_t *ctx, const uint8_t *data, size_t len) +{ + while (len) { + size_t tlen = len > 20 ? 20 : len; + len -= tlen; + do { + ctx->sum2 += ctx->sum1 += *data++; + } while (--tlen); + _reduce(ctx); + } +} + +uint16_t fletcher16_finish(fletcher16_ctx_t *ctx) +{ + /* Second reduction step to reduce sums to 8 bits */ + _reduce(ctx); + return (ctx->sum2 << 8) | ctx->sum1; +} + +uint16_t fletcher16(const uint8_t *data, size_t bytes) +{ + fletcher16_ctx_t ctx; + fletcher16_init(&ctx); + fletcher16_update(&ctx, data, bytes); + return fletcher16_finish(&ctx); +} diff --git a/pool/shard008/C/0133695_date_service.c b/pool/shard008/C/0133695_date_service.c new file mode 100644 index 0000000000000000000000000000000000000000..05ba84d61a37ebd1c98d55a45489c3e33a0804dd --- /dev/null +++ b/pool/shard008/C/0133695_date_service.c @@ -0,0 +1,209 @@ +/* + * Copyright (c) 2020 Nick Ward + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include +#include +#include +#include +#include +#include + +#define HELP_NONE "[none]" +#define HELP_DATE_SET "[Y-m-d] " + +static void date_print(const struct shell *shell, struct tm *tm) +{ + shell_print(shell, + "%d-%02u-%02u " + "%02u:%02u:%02u UTC", + tm->tm_year + 1900, + tm->tm_mon + 1, + tm->tm_mday, + tm->tm_hour, + tm->tm_min, + tm->tm_sec); +} + +static int get_y_m_d(const struct shell *shell, struct tm *tm, char *date_str) +{ + int year; + int month; + int day; + char *endptr; + + endptr = NULL; + year = strtol(date_str, &endptr, 10); + if ((endptr == date_str) || (*endptr != '-')) { + return -EINVAL; + } + + date_str = endptr + 1; + + endptr = NULL; + month = strtol(date_str, &endptr, 10); + if ((endptr == date_str) || (*endptr != '-')) { + return -EINVAL; + } + + if ((month < 1) || (month > 12)) { + shell_error(shell, "Invalid month"); + return -EINVAL; + } + + date_str = endptr + 1; + + endptr = NULL; + day = strtol(date_str, &endptr, 10); + if ((endptr == date_str) || (*endptr != '\0')) { + return -EINVAL; + } + + /* Check day against maximum month length */ + if ((day < 1) || (day > 31)) { + shell_error(shell, "Invalid day"); + return -EINVAL; + } + + tm->tm_year = year - 1900; + tm->tm_mon = month - 1; + tm->tm_mday = day; + + return 0; +} + +/* + * For user convenience of small adjustments to time the time argument will + * accept H:M:S, :M:S or ::S where the missing field(s) will be filled in by + * the previous time state. + */ +static int get_h_m_s(const struct shell *shell, struct tm *tm, char *time_str) +{ + char *endptr; + + if (*time_str == ':') { + time_str++; + } else { + endptr = NULL; + tm->tm_hour = strtol(time_str, &endptr, 10); + if (endptr == time_str) { + return -EINVAL; + } else if (*endptr == ':') { + if ((tm->tm_hour < 0) || (tm->tm_hour > 23)) { + shell_error(shell, "Invalid hour"); + return -EINVAL; + } + + time_str = endptr + 1; + } else { + return -EINVAL; + } + } + + if (*time_str == ':') { + time_str++; + } else { + endptr = NULL; + tm->tm_min = strtol(time_str, &endptr, 10); + if (endptr == time_str) { + return -EINVAL; + } else if (*endptr == ':') { + if ((tm->tm_min < 0) || (tm->tm_min > 59)) { + shell_error(shell, "Invalid minute"); + return -EINVAL; + } + + time_str = endptr + 1; + } else { + return -EINVAL; + } + } + + endptr = NULL; + tm->tm_sec = strtol(time_str, &endptr, 10); + if ((endptr == time_str) || (*endptr != '\0')) { + return -EINVAL; + } + + /* Note range allows for a leap second */ + if ((tm->tm_sec < 0) || (tm->tm_sec > 60)) { + shell_error(shell, "Invalid second"); + return -EINVAL; + } + + return 0; +} + +static int cmd_date_set(const struct shell *shell, size_t argc, char **argv) +{ + struct timespec tp; + struct tm tm; + int ret; + + clock_gettime(CLOCK_REALTIME, &tp); + + gmtime_r(&tp.tv_sec, &tm); + + if (argc == 3) { + ret = get_y_m_d(shell, &tm, argv[1]); + if (ret != 0) { + shell_help(shell); + return -EINVAL; + } + ret = get_h_m_s(shell, &tm, argv[2]); + if (ret != 0) { + shell_help(shell); + return -EINVAL; + } + } else if (argc == 2) { + ret = get_h_m_s(shell, &tm, argv[1]); + if (ret != 0) { + shell_help(shell); + return -EINVAL; + } + } else { + shell_help(shell); + return -EINVAL; + } + + tp.tv_sec = timeutil_timegm(&tm); + if (tp.tv_sec == -1) { + shell_error(shell, "Failed to calculate seconds since Epoch"); + return -EINVAL; + } + tp.tv_nsec = 0; + + ret = clock_settime(CLOCK_REALTIME, &tp); + if (ret != 0) { + shell_error(shell, "Could not set date %d", ret); + return -EINVAL; + } + + date_print(shell, &tm); + + return 0; +} + +static int cmd_date_get(const struct shell *shell, size_t argc, char **argv) +{ + struct timespec tp; + struct tm tm; + + clock_gettime(CLOCK_REALTIME, &tp); + + gmtime_r(&tp.tv_sec, &tm); + + date_print(shell, &tm); + + return 0; +} + +SHELL_STATIC_SUBCMD_SET_CREATE(sub_date, + SHELL_CMD(set, NULL, HELP_DATE_SET, cmd_date_set), + SHELL_CMD(get, NULL, HELP_NONE, cmd_date_get), + SHELL_SUBCMD_SET_END /* Array terminated. */ +); + +SHELL_CMD_REGISTER(date, &sub_date, "Date commands", NULL); diff --git a/pool/shard008/C/0133697_procfs_vfsops.c b/pool/shard008/C/0133697_procfs_vfsops.c new file mode 100644 index 0000000000000000000000000000000000000000..8ed90970b04a4e51612df277a5658d4a533ab61d --- /dev/null +++ b/pool/shard008/C/0133697_procfs_vfsops.c @@ -0,0 +1,214 @@ +/* $OpenBSD: procfs_vfsops.c,v 1.9 1999/02/26 03:47:46 art Exp $ */ +/* $NetBSD: procfs_vfsops.c,v 1.25 1996/02/09 22:40:53 christos Exp $ */ + +/* + * Copyright (c) 1993 Jan-Simon Pendry + * Copyright (c) 1993 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Jan-Simon Pendry. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. 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. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University 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 REGENTS 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 REGENTS 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. + * + * @(#)procfs_vfsops.c 8.5 (Berkeley) 6/15/94 + */ + +/* + * procfs VFS interface + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include /* for PAGE_SIZE */ + +#if defined(UVM) +#include +#endif + +int procfs_mount __P((struct mount *, const char *, caddr_t, + struct nameidata *, struct proc *)); +int procfs_start __P((struct mount *, int, struct proc *)); +int procfs_unmount __P((struct mount *, int, struct proc *)); +int procfs_statfs __P((struct mount *, struct statfs *, struct proc *)); +/* + * VFS Operations. + * + * mount system call + */ +/* ARGSUSED */ +int +procfs_mount(mp, path, data, ndp, p) + struct mount *mp; + const char *path; + caddr_t data; + struct nameidata *ndp; + struct proc *p; +{ + size_t size; + + if (UIO_MX & (UIO_MX-1)) { + log(LOG_ERR, "procfs: invalid directory entry size"); + return (EINVAL); + } + + if (mp->mnt_flag & MNT_UPDATE) + return (EOPNOTSUPP); + + mp->mnt_flag |= MNT_LOCAL; + mp->mnt_data = 0; + vfs_getnewfsid(mp); + + (void) copyinstr(path, mp->mnt_stat.f_mntonname, MNAMELEN, &size); + bzero(mp->mnt_stat.f_mntonname + size, MNAMELEN - size); + bzero(mp->mnt_stat.f_mntfromname, MNAMELEN); + bcopy("procfs", mp->mnt_stat.f_mntfromname, sizeof("procfs")); + return (0); +} + +/* + * unmount system call + */ +int +procfs_unmount(mp, mntflags, p) + struct mount *mp; + int mntflags; + struct proc *p; +{ + int error; + extern int doforce; + int flags = 0; + + if (mntflags & MNT_FORCE) { + /* procfs can never be rootfs so don't check for it */ + if (!doforce) + return (EINVAL); + flags |= FORCECLOSE; + } + + if ((error = vflush(mp, 0, flags)) != 0) + return (error); + + return (0); +} + +int +procfs_root(mp, vpp) + struct mount *mp; + struct vnode **vpp; +{ + + return (procfs_allocvp(mp, vpp, 0, Proot)); +} + +/* ARGSUSED */ +int +procfs_start(mp, flags, p) + struct mount *mp; + int flags; + struct proc *p; +{ + + return (0); +} + +/* + * Get file system statistics. + */ +int +procfs_statfs(mp, sbp, p) + struct mount *mp; + struct statfs *sbp; + struct proc *p; +{ + struct vmtotal vmtotals; + +#if defined(UVM) + uvm_total(&vmtotals); +#else + vmtotal(&vmtotals); +#endif +#ifdef COMPAT_09 + sbp->f_type = 10; +#else + sbp->f_type = 0; +#endif + sbp->f_bsize = PAGE_SIZE; + sbp->f_iosize = PAGE_SIZE; + sbp->f_blocks = vmtotals.t_vm; + sbp->f_bfree = vmtotals.t_vm - vmtotals.t_avm; + sbp->f_bavail = 0; + sbp->f_files = maxproc; /* approx */ + sbp->f_ffree = maxproc - nprocs; /* approx */ + if (sbp != &mp->mnt_stat) { + bcopy(&mp->mnt_stat.f_fsid, &sbp->f_fsid, sizeof(sbp->f_fsid)); + bcopy(mp->mnt_stat.f_mntonname, sbp->f_mntonname, MNAMELEN); + bcopy(mp->mnt_stat.f_mntfromname, sbp->f_mntfromname, MNAMELEN); + } + strncpy(sbp->f_fstypename, mp->mnt_vfc->vfc_name, MFSNAMELEN); + return (0); +} + + +#define procfs_sync ((int (*) __P((struct mount *, int, struct ucred *, \ + struct proc *)))nullop) + +#define procfs_fhtovp ((int (*) __P((struct mount *, struct fid *, \ + struct mbuf *, struct vnode **, int *, struct ucred **)))eopnotsupp) +#define procfs_quotactl ((int (*) __P((struct mount *, int, uid_t, caddr_t, \ + struct proc *)))eopnotsupp) +#define procfs_sysctl ((int (*) __P((int *, u_int, void *, size_t *, void *, \ + size_t, struct proc *)))eopnotsupp) +#define procfs_vget ((int (*) __P((struct mount *, ino_t, struct vnode **))) \ + eopnotsupp) +#define procfs_vptofh ((int (*) __P((struct vnode *, struct fid *)))eopnotsupp) + +struct vfsops procfs_vfsops = { + procfs_mount, + procfs_start, + procfs_unmount, + procfs_root, + procfs_quotactl, + procfs_statfs, + procfs_sync, + procfs_vget, + procfs_fhtovp, + procfs_vptofh, + procfs_init, + procfs_sysctl +}; diff --git a/pool/shard008/C/0133702_gettingstarted_common.c b/pool/shard008/C/0133702_gettingstarted_common.c new file mode 100644 index 0000000000000000000000000000000000000000..c150eb20d0297eff70a3eeafe66cc1f686c902e2 --- /dev/null +++ b/pool/shard008/C/0133702_gettingstarted_common.c @@ -0,0 +1,241 @@ +/*- + * See the file LICENSE for redistribution information. + * + * Copyright (c) 2004, 2014 Oracle and/or its affiliates. All rights reserved. + */ + +#include "gettingstarted_common.h" + +int get_item_name(DB *, const DBT *, const DBT *, DBT *); + +/* + * Used to extract an inventory item's name from an + * inventory database record. This function is used to create + * keys for secondary database records. + */ +int +get_item_name(DB *dbp, const DBT *pkey, const DBT *pdata, DBT *skey) +{ + u_int offset; + + dbp = NULL; /* Not needed, unused. */ + pkey = NULL; + + /* + * First, obtain the buffer location where we placed the + * item's name. In this example, the item's name is located + * in the primary data. It is the first string in the + * buffer after the price (a float) and the quantity (an int). + * + * See load_inventory_database() in example_database_load.c + * for how we packed the inventory information into the + * data DBT. + */ + offset = sizeof(float) + sizeof(int); + + /* Check to make sure there's data */ + if (pdata->size < offset) + return (-1); /* Returning non-zero means that the + * secondary record is not created/updated. + */ + + /* Now set the secondary key's data to be the item name */ + memset(skey, 0, sizeof(DBT)); + skey->data = (u_int8_t *)pdata->data + offset; + skey->size = (u_int32_t)strlen(skey->data) + 1; + + return (0); +} + +/* Opens a database */ +int +open_database(DB **dbpp, /* The DB handle that we are opening */ + const char *file_name, /* The file in which the db lives */ + const char *program_name, /* Name of the program */ + FILE *error_file_pointer, + int is_secondary) +{ + DB *dbp; /* For convenience */ + u_int32_t open_flags; + int ret; + + /* Initialize the DB handle */ + ret = db_create(&dbp, NULL, 0); + if (ret != 0) { + fprintf(error_file_pointer, "%s: %s\n", program_name, + db_strerror(ret)); + return (ret); + } + /* Point to the memory malloc'd by db_create() */ + *dbpp = dbp; + + /* Set up error handling for this database */ + dbp->set_errfile(dbp, error_file_pointer); + dbp->set_errpfx(dbp, program_name); + + /* + * If this is a secondary database, then we want to allow + * sorted duplicates. + */ + if (is_secondary) { + ret = dbp->set_flags(dbp, DB_DUPSORT); + if (ret != 0) { + dbp->err(dbp, ret, "Attempt to set DUPSORT flags failed.", + file_name); + return (ret); + } + } + + /* Set the open flags */ + open_flags = DB_CREATE; /* Allow database creation */ + + /* Now open the database */ + ret = dbp->open(dbp, /* Pointer to the database */ + NULL, /* Txn pointer */ + file_name, /* File name */ + NULL, /* Logical db name */ + DB_BTREE, /* Database type (using btree) */ + open_flags, /* Open flags */ + 0); /* File mode. Using defaults */ + if (ret != 0) { + dbp->err(dbp, ret, "Database '%s' open failed.", file_name); + return (ret); + } + + return (0); +} + +/* opens all databases */ +int +databases_setup(STOCK_DBS *my_stock, const char *program_name, + FILE *error_file_pointer) +{ + int ret; + + /* Open the vendor database */ + ret = open_database(&(my_stock->vendor_dbp), + my_stock->vendor_db_name, + program_name, error_file_pointer, + PRIMARY_DB); + if (ret != 0) + /* + * Error reporting is handled in open_database() so just return + * the return code. + */ + return (ret); + + /* Open the inventory database */ + ret = open_database(&(my_stock->inventory_dbp), + my_stock->inventory_db_name, + program_name, error_file_pointer, + PRIMARY_DB); + if (ret != 0) + /* + * Error reporting is handled in open_database() so just return + * the return code. + */ + return (ret); + + /* + * Open the itemname secondary database. This is used to + * index the product names found in the inventory + * database. + */ + ret = open_database(&(my_stock->itemname_sdbp), + my_stock->itemname_db_name, + program_name, error_file_pointer, + SECONDARY_DB); + if (ret != 0) + /* + * Error reporting is handled in open_database() so just return + * the return code. + */ + return (ret); + + /* + * Associate the itemname db with its primary db + * (inventory db). + */ + my_stock->inventory_dbp->associate( + my_stock->inventory_dbp, /* Primary db */ + NULL, /* txn id */ + my_stock->itemname_sdbp, /* Secondary db */ + get_item_name, /* Secondary key creator */ + 0); /* Flags */ + + printf("databases opened successfully\n"); + return (0); +} + +/* Initializes the STOCK_DBS struct.*/ +void +initialize_stockdbs(STOCK_DBS *my_stock) +{ + my_stock->db_home_dir = DEFAULT_HOMEDIR; + my_stock->inventory_dbp = NULL; + my_stock->vendor_dbp = NULL; + my_stock->itemname_sdbp = NULL; + my_stock->inventory_db_name = NULL; + my_stock->vendor_db_name = NULL; + my_stock->itemname_db_name = NULL; +} + +/* Identify all the files that will hold our databases. */ +void +set_db_filenames(STOCK_DBS *my_stock) +{ + size_t size; + + /* Create the Inventory DB file name */ + size = strlen(my_stock->db_home_dir) + strlen(INVENTORYDB) + 1; + my_stock->inventory_db_name = malloc(size); + snprintf(my_stock->inventory_db_name, size, "%s%s", + my_stock->db_home_dir, INVENTORYDB); + + /* Create the Vendor DB file name */ + size = strlen(my_stock->db_home_dir) + strlen(VENDORDB) + 1; + my_stock->vendor_db_name = malloc(size); + snprintf(my_stock->vendor_db_name, size, "%s%s", + my_stock->db_home_dir, VENDORDB); + + /* Create the itemname DB file name */ + size = strlen(my_stock->db_home_dir) + strlen(ITEMNAMEDB) + 1; + my_stock->itemname_db_name = malloc(size); + snprintf(my_stock->itemname_db_name, size, "%s%s", + my_stock->db_home_dir, ITEMNAMEDB); + +} + +/* Closes all the databases and secondary databases. */ +int +databases_close(STOCK_DBS *my_stock) +{ + int ret; + /* + * Note that closing a database automatically flushes its cached data + * to disk, so no sync is required here. + */ + if (my_stock->itemname_sdbp != NULL) { + ret = my_stock->itemname_sdbp->close(my_stock->itemname_sdbp, 0); + if (ret != 0) + fprintf(stderr, "Itemname database close failed: %s\n", + db_strerror(ret)); + } + + if (my_stock->inventory_dbp != NULL) { + ret = my_stock->inventory_dbp->close(my_stock->inventory_dbp, 0); + if (ret != 0) + fprintf(stderr, "Inventory database close failed: %s\n", + db_strerror(ret)); + } + + if (my_stock->vendor_dbp != NULL) { + ret = my_stock->vendor_dbp->close(my_stock->vendor_dbp, 0); + if (ret != 0) + fprintf(stderr, "Vendor database close failed: %s\n", + db_strerror(ret)); + } + + printf("databases closed.\n"); + return (0); +} diff --git a/pool/shard008/C/0133704_Lab2XYZ.c b/pool/shard008/C/0133704_Lab2XYZ.c new file mode 100644 index 0000000000000000000000000000000000000000..963259dd30f08ab85cbc989172babfbbb2ab7f6e --- /dev/null +++ b/pool/shard008/C/0133704_Lab2XYZ.c @@ -0,0 +1,255 @@ +/* Lab to XYZ. + * + * Modified: + * 15/11/94 JC + * - ANSIfied + * - sets Type of output + * - better error messages + * 16/11/94 JC + * - partialed + * - in-line conversion + * 8/2/95 JC + * - new im_wrapone function + * 2/11/09 + * - gtkdoc + * - cleanups + * 18/9/12 + * - redone as a class + */ + +/* + + This file is part of VIPS. + + VIPS is free software; you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program 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 program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA + + */ + +/* + + These files are distributed with VIPS - http://www.vips.ecs.soton.ac.uk + + */ + +/* +#define VIPS_DEBUG + */ + +#ifdef HAVE_CONFIG_H +#include +#endif /*HAVE_CONFIG_H*/ +#include + +#include +#include + +#include +#include + +#include "pcolour.h" + +typedef struct _VipsLab2XYZ { + VipsColourSpace parent_instance; + + /* The colour temperature -- default to D65. + */ + VipsArea *temp; + + /* Broken out as xyz. + */ + double X0; + double Y0; + double Z0; + +} VipsLab2XYZ; + +typedef VipsColourSpaceClass VipsLab2XYZClass; + +G_DEFINE_TYPE( VipsLab2XYZ, vips_Lab2XYZ, VIPS_TYPE_COLOUR_SPACE ); + +/* Process a buffer of data. + */ +static void +vips_Lab2XYZ_line( VipsColour *colour, VipsPel *out, VipsPel **in, int width ) +{ + VipsLab2XYZ *Lab2XYZ = (VipsLab2XYZ *) colour; + float * restrict p = (float *) in[0]; + float * restrict q = (float *) out; + + int x; + + VIPS_DEBUG_MSG( "vips_Lab2XYZ_line: X0 = %g, Y0 = %g, Z0 = %g\n", + Lab2XYZ->X0, Lab2XYZ->Y0, Lab2XYZ->Z0 ); + + for( x = 0; x < width; x++ ) { + float L, a, b; + float X, Y, Z; + double cby, tmp; + + L = p[0]; + a = p[1]; + b = p[2]; + p += 3; + + if( L < 8.0 ) { + Y = (L * Lab2XYZ->Y0) / 903.3; + cby = 7.787 * (Y / Lab2XYZ->Y0) + 16.0 / 116.0; + } + else { + cby = (L + 16.0) / 116.0; + Y = Lab2XYZ->Y0 * cby * cby * cby; + } + + tmp = a / 500.0 + cby; + if( tmp < 0.2069 ) + X = Lab2XYZ->X0 * (tmp - 0.13793) / 7.787; + else + X = Lab2XYZ->X0 * tmp * tmp * tmp; + + tmp = cby - b / 200.0; + if( tmp < 0.2069 ) + Z = Lab2XYZ->Z0 * (tmp - 0.13793) / 7.787; + else + Z = Lab2XYZ->Z0 * tmp * tmp * tmp; + + /* Write. + */ + q[0] = X; + q[1] = Y; + q[2] = Z; + q += 3; + } +} + +static int +vips_Lab2XYZ_build( VipsObject *object ) +{ + VipsObjectClass *class = VIPS_OBJECT_GET_CLASS( object ); + VipsLab2XYZ *Lab2XYZ = (VipsLab2XYZ *) object; + + if( Lab2XYZ->temp ) { + if( vips_check_vector_length( class->nickname, + Lab2XYZ->temp->n, 3 ) ) + return( -1 ); + Lab2XYZ->X0 = ((double *) Lab2XYZ->temp->data)[0]; + Lab2XYZ->Y0 = ((double *) Lab2XYZ->temp->data)[1]; + Lab2XYZ->Z0 = ((double *) Lab2XYZ->temp->data)[2]; + } + + if( VIPS_OBJECT_CLASS( vips_Lab2XYZ_parent_class )->build( object ) ) + return( -1 ); + + return( 0 ); +} + +static void +vips_Lab2XYZ_class_init( VipsLab2XYZClass *class ) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS( class ); + VipsObjectClass *object_class = (VipsObjectClass *) class; + VipsColourClass *colour_class = VIPS_COLOUR_CLASS( class ); + + gobject_class->set_property = vips_object_set_property; + gobject_class->get_property = vips_object_get_property; + + object_class->nickname = "Lab2XYZ"; + object_class->description = _( "transform CIELAB to XYZ" ); + object_class->build = vips_Lab2XYZ_build; + + colour_class->process_line = vips_Lab2XYZ_line; + + VIPS_ARG_BOXED( class, "temp", 110, + _( "Temperature" ), + _( "Colour temperature" ), + VIPS_ARGUMENT_OPTIONAL_INPUT, + G_STRUCT_OFFSET( VipsLab2XYZ, temp ), + VIPS_TYPE_ARRAY_DOUBLE ); +} + +static void +vips_Lab2XYZ_init( VipsLab2XYZ *Lab2XYZ ) +{ + VipsColour *colour = VIPS_COLOUR( Lab2XYZ ); + + Lab2XYZ->X0 = VIPS_D65_X0; + Lab2XYZ->Y0 = VIPS_D65_Y0; + Lab2XYZ->Z0 = VIPS_D65_Z0; + + colour->interpretation = VIPS_INTERPRETATION_XYZ; +} + +/** + * vips_Lab2XYZ: + * @in: input image + * @out: output image + * + * optional arguments: + * + * @temp: colour temperature + * + * Turn Lab to XYZ. The colour temperature defaults to D65, but can be + * specified with @temp. + * + * Returns: 0 on success, -1 on error + */ +int +vips_Lab2XYZ( VipsImage *in, VipsImage **out, ... ) +{ + va_list ap; + int result; + + va_start( ap, out ); + result = vips_call_split( "Lab2XYZ", ap, in, out ); + va_end( ap ); + + return( result ); +} + +/** + * vips_col_Lab2XYZ: + * @L: Input CIE Lab value + * @a: Input CIE Lab value + * @b: Input CIE Lab value + * @X: Return CIE XYZ colour + * @Y: Return CIE XYZ colour + * @Z: Return CIE XYZ colour + * + * Calculate XYZ from Lab, D65. + * + * See also: vips_Lab2XYZ(). + */ +void +vips_col_Lab2XYZ( float L, float a, float b, float *X, float *Y, float *Z ) +{ + float in[3]; + float *x; + float out[3]; + VipsLab2XYZ Lab2XYZ; + + in[0] = L; + in[1] = a; + in[2] = b; + x = in; + Lab2XYZ.X0 = VIPS_D65_X0; + Lab2XYZ.Y0 = VIPS_D65_Y0; + Lab2XYZ.Z0 = VIPS_D65_Z0; + vips_Lab2XYZ_line( (VipsColour *) &Lab2XYZ, + (VipsPel *) out, (VipsPel **) &x, 1 ); + *X = out[0]; + *Y = out[1]; + *Z = out[2]; +} + diff --git a/pool/shard008/C/0133709_grl-tracker-request-queue.c b/pool/shard008/C/0133709_grl-tracker-request-queue.c new file mode 100644 index 0000000000000000000000000000000000000000..0805f02d6a25c39d3398b9a8d067c6192acfe3cf --- /dev/null +++ b/pool/shard008/C/0133709_grl-tracker-request-queue.c @@ -0,0 +1,229 @@ +/* + * Copyright (C) 2011 Intel Corporation. + * + * Contact: Iago Toral Quiroga + * + * Authors: Lionel Landwerlin + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public License + * as published by the Free Software Foundation; version 2.1 of + * the License, or (at your option) any later version. + * + * 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., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA + * + */ + +#include "grl-tracker.h" +#include "grl-tracker-request-queue.h" + +/**/ + +struct _GrlTrackerQueue { + GList *head; + GList *tail; + GHashTable *operations; + GHashTable *operations_ids; +}; + +/**/ + +static void +grl_tracker_op_terminate (GrlTrackerOp *os) +{ + if (os == NULL) + return; + + if (os->cursor) + g_object_unref (os->cursor); + + g_object_unref (os->cancel); + g_free (os->request); + + g_slice_free (GrlTrackerOp, os); +} + +static GrlTrackerOp * +grl_tracker_op_initiate (gchar *request, + GAsyncReadyCallback callback, + gpointer data) +{ + GrlTrackerOp *os = g_slice_new0 (GrlTrackerOp); + + os->request = request; + os->callback = callback; + os->data = data; + os->cancel = g_cancellable_new (); + + return os; +} + +GrlTrackerOp * +grl_tracker_op_initiate_query (guint operation_id, + gchar *request, + GAsyncReadyCallback callback, + gpointer data) +{ + GrlTrackerOp *os = grl_tracker_op_initiate (request, + callback, + data); + + os->type = GRL_TRACKER_OP_TYPE_QUERY; + os->operation_id = operation_id; + + /* g_hash_table_insert (grl_tracker_operations, */ + /* GSIZE_TO_POINTER (operation_id), os); */ + + return os; +} + +GrlTrackerOp * +grl_tracker_op_initiate_metadata (gchar *request, + GAsyncReadyCallback callback, + gpointer data) +{ + GrlTrackerOp *os = grl_tracker_op_initiate (request, + callback, + data); + + os->type = GRL_TRACKER_OP_TYPE_QUERY; + + return os; +} + +GrlTrackerOp * +grl_tracker_op_initiate_set_metadata (gchar *request, + GAsyncReadyCallback callback, + gpointer data) +{ + GrlTrackerOp *os = grl_tracker_op_initiate (request, + callback, + data); + + os->type = GRL_TRACKER_OP_TYPE_UPDATE; + + return os; +} + +static void +grl_tracker_op_start (GrlTrackerOp *os) +{ + switch (os->type) { + case GRL_TRACKER_OP_TYPE_QUERY: + tracker_sparql_connection_query_async (grl_tracker_connection, + os->request, + NULL, + os->callback, + os); + break; + + case GRL_TRACKER_OP_TYPE_UPDATE: + tracker_sparql_connection_update_async (grl_tracker_connection, + os->request, + G_PRIORITY_DEFAULT, + NULL, + os->callback, + os); + break; + + default: + g_assert_not_reached(); + break; + } +} + +/**/ + +GrlTrackerQueue * +grl_tracker_queue_new (void) +{ + GrlTrackerQueue *queue = g_new0 (GrlTrackerQueue, 1); + + queue->operations = g_hash_table_new (g_direct_hash, g_direct_equal); + queue->operations_ids = g_hash_table_new (g_direct_hash, g_direct_equal); + + return queue; +} + +void +grl_tracker_queue_push (GrlTrackerQueue *queue, + GrlTrackerOp *os) +{ + gboolean first = FALSE; + + queue->tail = g_list_append (queue->tail, os); + if (queue->tail->next) + queue->tail = queue->tail->next; + else { + queue->head = queue->tail; + first = TRUE; + } + + g_assert (queue->tail->next == NULL); + + g_hash_table_insert (queue->operations, os, queue->tail); + if (os->operation_id != 0) + g_hash_table_insert (queue->operations_ids, + GSIZE_TO_POINTER (os->operation_id), os); + + if (first) + grl_tracker_op_start (os); +} + +void +grl_tracker_queue_cancel (GrlTrackerQueue *queue, + GrlTrackerOp *os) +{ + GList *item = g_hash_table_lookup (queue->operations, os); + + if (!item) + return; + + g_cancellable_cancel (os->cancel); + + g_hash_table_remove (queue->operations, os); + if (os->operation_id != 0) + g_hash_table_remove (queue->operations_ids, + GSIZE_TO_POINTER (os->operation_id)); + + if (item == queue->head) { + queue->head = queue->head->next; + } + if (item == queue->tail) { + queue->tail = queue->tail->prev; + } + + if (item->prev) + item->prev->next = item->next; + if (item->next) + item->next->prev = item->prev; + + item->next = NULL; + item->prev = NULL; + g_list_free (item); +} + +void +grl_tracker_queue_done (GrlTrackerQueue *queue, + GrlTrackerOp *os) +{ + GrlTrackerOp *next_os; + + grl_tracker_queue_cancel (queue, os); + grl_tracker_op_terminate (os); + + if (!queue->head) + return; + + next_os = queue->head->data; + + grl_tracker_op_start (next_os); +} diff --git a/pool/shard008/C/0133710_BREthereumLESRandom.c b/pool/shard008/C/0133710_BREthereumLESRandom.c new file mode 100644 index 0000000000000000000000000000000000000000..918644a978c7b4f7ab947d9c414958ade5bc121c --- /dev/null +++ b/pool/shard008/C/0133710_BREthereumLESRandom.c @@ -0,0 +1,77 @@ +// +// BREthereumRandom.c +// breadwallet +// +// Created by Lamont Samuels on 4/24/18. +// Copyright © 2018-2019 Breadwinner AG. All rights reserved. +// +// See the LICENSE file at the project root for license information. +// See the CONTRIBUTORS file at the project root for a list of contributors. + +#include +#include +#include +#include +#include +#include "support/BRCrypto.h" +#include "BREthereumLESRandom.h" + +#define KECCAK_HASH_SIZE 32 +#define NONCE_SIZE 8 + +/* + * + * BREthereumRandomRecord contains fields needed by hmac-drbg + */ +struct BREthereumLESRandomRecord { + uint8_t k[KECCAK_HASH_SIZE]; + uint8_t v[KECCAK_HASH_SIZE]; +}; + +// +// Public functions +// +extern BREthereumLESRandomContext randomCreate(const void *seed, size_t seedLen) { + + BREthereumLESRandomContext ctx = (BREthereumLESRandomContext) calloc(1, sizeof(struct BREthereumLESRandomRecord)); + + uint32_t currTime = ((uint32_t)time(NULL)); + uint32_t curPid = (uint32_t)getpid(); + uint8_t nonce[NONCE_SIZE]; + + nonce[0] = (currTime >> 24) & 0xFF; + nonce[1] = (currTime >> 16) & 0xFF; + nonce[2] = (currTime >> 8) & 0xFF; + nonce[3] = currTime & 0xFF; + nonce[4] = (curPid >> 24) & 0xFF; + nonce[5] = (curPid >> 16) & 0xFF; + nonce[6] = (curPid >> 8) & 0xFF; + nonce[7] = curPid & 0xFF; + + // hmac-drbg with no prediction resistance or additional input + // K and V must point to buffers of size hashLen, and ps (personalization string) may be NULL + // to generate additional drbg output, use K and V from the previous call, and set seed, nonce and ps to NULL + uint8_t dummy; + //Run the DRB intially to set the K and V for subsequent calls to random context + BRHMACDRBG(&dummy, 0, ctx->k, ctx->v, BRKeccak256, KECCAK_HASH_SIZE, seed, seedLen, nonce, NONCE_SIZE, NULL, 0); + + return ctx; +} +extern void randomRelease(BREthereumLESRandomContext ctx) { + free(ctx); +} +extern void randomGenData(BREthereumLESRandomContext ctx, uint8_t* data, size_t dataSize) { + BRHMACDRBG(data, dataSize, ctx->k, ctx->v, BRKeccak256, KECCAK_HASH_SIZE, NULL, 0, NULL, 0, NULL, 0); +} +extern void randomGenPriKey(BREthereumLESRandomContext ctx, BRKey* key) { + + assert(key != NULL); + memset (key, 0, sizeof(BRKey)); + UInt256 secret; + BRHMACDRBG(secret.u8, 32, ctx->k, ctx->v, BRKeccak256, KECCAK_HASH_SIZE, NULL, 0, NULL, 0, NULL, 0); + BRKeySetSecret(key, &secret, 0); + var_clean(&secret); +} +extern void randomGenUInt256(BREthereumLESRandomContext ctx, UInt256* out) { + BRHMACDRBG(out->u8, 32, ctx->k, ctx->v, BRKeccak256, KECCAK_HASH_SIZE, NULL, 0, NULL, 0, NULL, 0); +} diff --git a/pool/shard008/C/0133712_nseval.c b/pool/shard008/C/0133712_nseval.c new file mode 100644 index 0000000000000000000000000000000000000000..7bcc68f57afa61d24d6d170e04bb9c2db8271900 --- /dev/null +++ b/pool/shard008/C/0133712_nseval.c @@ -0,0 +1,494 @@ +/******************************************************************************* + * + * Module Name: nseval - Object evaluation, includes control method execution + * + ******************************************************************************/ + +/* + * Copyright (C) 2000 - 2015, Intel Corp. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions, and the following disclaimer, + * without modification. + * 2. Redistributions in binary form must reproduce at minimum a disclaimer + * substantially similar to the "NO WARRANTY" disclaimer below + * ("Disclaimer") and any redistribution must be conditioned upon + * including a substantially similar Disclaimer requirement for further + * binary redistribution. + * 3. Neither the names of the above-listed copyright holders nor the names + * of any contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * Alternatively, this software may be distributed under the terms of the + * GNU General Public License ("GPL") version 2 as published by the Free + * Software Foundation. + * + * NO WARRANTY + * 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 MERCHANTIBILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDERS OR CONTRIBUTORS BE LIABLE FOR 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 DAMAGES. + */ + +#include +#include "accommon.h" +#include "acparser.h" +#include "acinterp.h" +#include "acnamesp.h" + +#define _COMPONENT ACPI_NAMESPACE +ACPI_MODULE_NAME("nseval") + +/* Local prototypes */ +static void +acpi_ns_exec_module_code(union acpi_operand_object *method_obj, + struct acpi_evaluate_info *info); + +/******************************************************************************* + * + * FUNCTION: acpi_ns_evaluate + * + * PARAMETERS: info - Evaluation info block, contains: + * prefix_node - Prefix or Method/Object Node to execute + * relative_path - Name of method to execute, If NULL, the + * Node is the object to execute + * parameters - List of parameters to pass to the method, + * terminated by NULL. Params itself may be + * NULL if no parameters are being passed. + * return_object - Where to put method's return value (if + * any). If NULL, no value is returned. + * parameter_type - Type of Parameter list + * return_object - Where to put method's return value (if + * any). If NULL, no value is returned. + * flags - ACPI_IGNORE_RETURN_VALUE to delete return + * + * RETURN: Status + * + * DESCRIPTION: Execute a control method or return the current value of an + * ACPI namespace object. + * + * MUTEX: Locks interpreter + * + ******************************************************************************/ + +acpi_status acpi_ns_evaluate(struct acpi_evaluate_info *info) +{ + acpi_status status; + + ACPI_FUNCTION_TRACE(ns_evaluate); + + if (!info) { + return_ACPI_STATUS(AE_BAD_PARAMETER); + } + + if (!info->node) { + /* + * Get the actual namespace node for the target object if we + * need to. Handles these cases: + * + * 1) Null node, valid pathname from root (absolute path) + * 2) Node and valid pathname (path relative to Node) + * 3) Node, Null pathname + */ + status = + acpi_ns_get_node(info->prefix_node, info->relative_pathname, + ACPI_NS_NO_UPSEARCH, &info->node); + if (ACPI_FAILURE(status)) { + return_ACPI_STATUS(status); + } + } + + /* + * For a method alias, we must grab the actual method node so that + * proper scoping context will be established before execution. + */ + if (acpi_ns_get_type(info->node) == ACPI_TYPE_LOCAL_METHOD_ALIAS) { + info->node = + ACPI_CAST_PTR(struct acpi_namespace_node, + info->node->object); + } + + /* Complete the info block initialization */ + + info->return_object = NULL; + info->node_flags = info->node->flags; + info->obj_desc = acpi_ns_get_attached_object(info->node); + + ACPI_DEBUG_PRINT((ACPI_DB_NAMES, "%s [%p] Value %p\n", + info->relative_pathname, info->node, + acpi_ns_get_attached_object(info->node))); + + /* Get info if we have a predefined name (_HID, etc.) */ + + info->predefined = + acpi_ut_match_predefined_method(info->node->name.ascii); + + /* Get the full pathname to the object, for use in warning messages */ + + info->full_pathname = acpi_ns_get_external_pathname(info->node); + if (!info->full_pathname) { + return_ACPI_STATUS(AE_NO_MEMORY); + } + + /* Count the number of arguments being passed in */ + + info->param_count = 0; + if (info->parameters) { + while (info->parameters[info->param_count]) { + info->param_count++; + } + + /* Warn on impossible argument count */ + + if (info->param_count > ACPI_METHOD_NUM_ARGS) { + ACPI_WARN_PREDEFINED((AE_INFO, info->full_pathname, + ACPI_WARN_ALWAYS, + "Excess arguments (%u) - using only %u", + info->param_count, + ACPI_METHOD_NUM_ARGS)); + + info->param_count = ACPI_METHOD_NUM_ARGS; + } + } + + /* + * For predefined names: Check that the declared argument count + * matches the ACPI spec -- otherwise this is a BIOS error. + */ + acpi_ns_check_acpi_compliance(info->full_pathname, info->node, + info->predefined); + + /* + * For all names: Check that the incoming argument count for + * this method/object matches the actual ASL/AML definition. + */ + acpi_ns_check_argument_count(info->full_pathname, info->node, + info->param_count, info->predefined); + + /* For predefined names: Typecheck all incoming arguments */ + + acpi_ns_check_argument_types(info); + + /* + * Three major evaluation cases: + * + * 1) Object types that cannot be evaluated by definition + * 2) The object is a control method -- execute it + * 3) The object is not a method -- just return it's current value + */ + switch (acpi_ns_get_type(info->node)) { + case ACPI_TYPE_DEVICE: + case ACPI_TYPE_EVENT: + case ACPI_TYPE_MUTEX: + case ACPI_TYPE_REGION: + case ACPI_TYPE_THERMAL: + case ACPI_TYPE_LOCAL_SCOPE: + /* + * 1) Disallow evaluation of certain object types. For these, + * object evaluation is undefined and not supported. + */ + ACPI_ERROR((AE_INFO, + "%s: Evaluation of object type [%s] is not supported", + info->full_pathname, + acpi_ut_get_type_name(info->node->type))); + + status = AE_TYPE; + goto cleanup; + + case ACPI_TYPE_METHOD: + /* + * 2) Object is a control method - execute it + */ + + /* Verify that there is a method object associated with this node */ + + if (!info->obj_desc) { + ACPI_ERROR((AE_INFO, + "%s: Method has no attached sub-object", + info->full_pathname)); + status = AE_NULL_OBJECT; + goto cleanup; + } + + ACPI_DEBUG_PRINT((ACPI_DB_EXEC, + "**** Execute method [%s] at AML address %p length %X\n", + info->full_pathname, + info->obj_desc->method.aml_start + 1, + info->obj_desc->method.aml_length - 1)); + + /* + * Any namespace deletion must acquire both the namespace and + * interpreter locks to ensure that no thread is using the portion of + * the namespace that is being deleted. + * + * Execute the method via the interpreter. The interpreter is locked + * here before calling into the AML parser + */ + acpi_ex_enter_interpreter(); + status = acpi_ps_execute_method(info); + acpi_ex_exit_interpreter(); + break; + + default: + /* + * 3) All other non-method objects -- get the current object value + */ + + /* + * Some objects require additional resolution steps (e.g., the Node + * may be a field that must be read, etc.) -- we can't just grab + * the object out of the node. + * + * Use resolve_node_to_value() to get the associated value. + * + * NOTE: we can get away with passing in NULL for a walk state because + * the Node is guaranteed to not be a reference to either a method + * local or a method argument (because this interface is never called + * from a running method.) + * + * Even though we do not directly invoke the interpreter for object + * resolution, we must lock it because we could access an op_region. + * The op_region access code assumes that the interpreter is locked. + */ + acpi_ex_enter_interpreter(); + + /* TBD: resolve_node_to_value has a strange interface, fix */ + + info->return_object = + ACPI_CAST_PTR(union acpi_operand_object, info->node); + + status = + acpi_ex_resolve_node_to_value(ACPI_CAST_INDIRECT_PTR + (struct acpi_namespace_node, + &info->return_object), NULL); + acpi_ex_exit_interpreter(); + + if (ACPI_FAILURE(status)) { + goto cleanup; + } + + ACPI_DEBUG_PRINT((ACPI_DB_NAMES, "Returned object %p [%s]\n", + info->return_object, + acpi_ut_get_object_type_name(info-> + return_object))); + + status = AE_CTRL_RETURN_VALUE; /* Always has a "return value" */ + break; + } + + /* + * For predefined names, check the return value against the ACPI + * specification. Some incorrect return value types are repaired. + */ + (void)acpi_ns_check_return_value(info->node, info, info->param_count, + status, &info->return_object); + + /* Check if there is a return value that must be dealt with */ + + if (status == AE_CTRL_RETURN_VALUE) { + + /* If caller does not want the return value, delete it */ + + if (info->flags & ACPI_IGNORE_RETURN_VALUE) { + acpi_ut_remove_reference(info->return_object); + info->return_object = NULL; + } + + /* Map AE_CTRL_RETURN_VALUE to AE_OK, we are done with it */ + + status = AE_OK; + } + + ACPI_DEBUG_PRINT((ACPI_DB_NAMES, + "*** Completed evaluation of object %s ***\n", + info->relative_pathname)); + +cleanup: + /* + * Namespace was unlocked by the handling acpi_ns* function, so we + * just free the pathname and return + */ + ACPI_FREE(info->full_pathname); + info->full_pathname = NULL; + return_ACPI_STATUS(status); +} + +/******************************************************************************* + * + * FUNCTION: acpi_ns_exec_module_code_list + * + * PARAMETERS: None + * + * RETURN: None. Exceptions during method execution are ignored, since + * we cannot abort a table load. + * + * DESCRIPTION: Execute all elements of the global module-level code list. + * Each element is executed as a single control method. + * + ******************************************************************************/ + +void acpi_ns_exec_module_code_list(void) +{ + union acpi_operand_object *prev; + union acpi_operand_object *next; + struct acpi_evaluate_info *info; + u32 method_count = 0; + + ACPI_FUNCTION_TRACE(ns_exec_module_code_list); + + /* Exit now if the list is empty */ + + next = acpi_gbl_module_code_list; + if (!next) { + return_VOID; + } + + /* Allocate the evaluation information block */ + + info = ACPI_ALLOCATE(sizeof(struct acpi_evaluate_info)); + if (!info) { + return_VOID; + } + + /* Walk the list, executing each "method" */ + + while (next) { + prev = next; + next = next->method.mutex; + + /* Clear the link field and execute the method */ + + prev->method.mutex = NULL; + acpi_ns_exec_module_code(prev, info); + method_count++; + + /* Delete the (temporary) method object */ + + acpi_ut_remove_reference(prev); + } + + ACPI_INFO((AE_INFO, + "Executed %u blocks of module-level executable AML code", + method_count)); + + ACPI_FREE(info); + acpi_gbl_module_code_list = NULL; + return_VOID; +} + +/******************************************************************************* + * + * FUNCTION: acpi_ns_exec_module_code + * + * PARAMETERS: method_obj - Object container for the module-level code + * info - Info block for method evaluation + * + * RETURN: None. Exceptions during method execution are ignored, since + * we cannot abort a table load. + * + * DESCRIPTION: Execute a control method containing a block of module-level + * executable AML code. The control method is temporarily + * installed to the root node, then evaluated. + * + ******************************************************************************/ + +static void +acpi_ns_exec_module_code(union acpi_operand_object *method_obj, + struct acpi_evaluate_info *info) +{ + union acpi_operand_object *parent_obj; + struct acpi_namespace_node *parent_node; + acpi_object_type type; + acpi_status status; + + ACPI_FUNCTION_TRACE(ns_exec_module_code); + + /* + * Get the parent node. We cheat by using the next_object field + * of the method object descriptor. + */ + parent_node = ACPI_CAST_PTR(struct acpi_namespace_node, + method_obj->method.next_object); + type = acpi_ns_get_type(parent_node); + + /* + * Get the region handler and save it in the method object. We may need + * this if an operation region declaration causes a _REG method to be run. + * + * We can't do this in acpi_ps_link_module_code because + * acpi_gbl_root_node->Object is NULL at PASS1. + */ + if ((type == ACPI_TYPE_DEVICE) && parent_node->object) { + method_obj->method.dispatch.handler = + parent_node->object->device.handler; + } + + /* Must clear next_object (acpi_ns_attach_object needs the field) */ + + method_obj->method.next_object = NULL; + + /* Initialize the evaluation information block */ + + ACPI_MEMSET(info, 0, sizeof(struct acpi_evaluate_info)); + info->prefix_node = parent_node; + + /* + * Get the currently attached parent object. Add a reference, because the + * ref count will be decreased when the method object is installed to + * the parent node. + */ + parent_obj = acpi_ns_get_attached_object(parent_node); + if (parent_obj) { + acpi_ut_add_reference(parent_obj); + } + + /* Install the method (module-level code) in the parent node */ + + status = acpi_ns_attach_object(parent_node, method_obj, + ACPI_TYPE_METHOD); + if (ACPI_FAILURE(status)) { + goto exit; + } + + /* Execute the parent node as a control method */ + + status = acpi_ns_evaluate(info); + + ACPI_DEBUG_PRINT((ACPI_DB_INIT, "Executed module-level code at %p\n", + method_obj->method.aml_start)); + + /* Delete a possible implicit return value (in slack mode) */ + + if (info->return_object) { + acpi_ut_remove_reference(info->return_object); + } + + /* Detach the temporary method object */ + + acpi_ns_detach_object(parent_node); + + /* Restore the original parent object */ + + if (parent_obj) { + status = acpi_ns_attach_object(parent_node, parent_obj, type); + } else { + parent_node->type = (u8)type; + } + +exit: + if (parent_obj) { + acpi_ut_remove_reference(parent_obj); + } + return_VOID; +} diff --git a/pool/shard008/C/0133715_output-json-nfs.c b/pool/shard008/C/0133715_output-json-nfs.c new file mode 100644 index 0000000000000000000000000000000000000000..5274adc58190654c58e86c1646e30faf0372cb4c --- /dev/null +++ b/pool/shard008/C/0133715_output-json-nfs.c @@ -0,0 +1,152 @@ +/* Copyright (C) 2015-2018 Open Information Security Foundation + * + * You can copy, redistribute or modify this Program under the terms of + * the GNU General Public License version 2 as published by the Free + * Software Foundation. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * version 2 along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + */ + +/** + * \file + * + * \author Victor Julien + * + * Implement JSON/eve logging app-layer NFS. + */ + +#include "suricata-common.h" +#include "debug.h" +#include "detect.h" +#include "pkt-var.h" +#include "conf.h" + +#include "threads.h" +#include "threadvars.h" +#include "tm-threads.h" + +#include "util-unittest.h" +#include "util-buffer.h" +#include "util-debug.h" +#include "util-byte.h" + +#include "output.h" +#include "output-json.h" + +#include "app-layer.h" +#include "app-layer-parser.h" + +#include "output-json-nfs.h" + +#ifdef HAVE_RUST +#ifdef HAVE_LIBJANSSON +#include "rust.h" +#include "rust-nfs-log-gen.h" + +json_t *JsonNFSAddMetadataRPC(const Flow *f, uint64_t tx_id) +{ + NFSState *state = FlowGetAppState(f); + if (state) { + NFSTransaction *tx = AppLayerParserGetTx(f->proto, ALPROTO_NFS, state, tx_id); + if (tx) { + return rs_rpc_log_json_response(tx); + } + } + + return NULL; +} + +json_t *JsonNFSAddMetadata(const Flow *f, uint64_t tx_id) +{ + NFSState *state = FlowGetAppState(f); + if (state) { + NFSTransaction *tx = AppLayerParserGetTx(f->proto, ALPROTO_NFS, state, tx_id); + if (tx) { + return rs_nfs_log_json_response(state, tx); + } + } + + return NULL; +} + +static int JsonNFSLogger(ThreadVars *tv, void *thread_data, + const Packet *p, Flow *f, void *state, void *tx, uint64_t tx_id) +{ + NFSTransaction *nfstx = tx; + OutputJsonThreadCtx *thread = thread_data; + + if (rs_nfs_tx_logging_is_filtered(state, nfstx)) + return TM_ECODE_OK; + + json_t *js = CreateJSONHeader(p, LOG_DIR_PACKET, "nfs"); + if (unlikely(js == NULL)) { + return TM_ECODE_FAILED; + } + + JsonAddCommonOptions(&thread->ctx->cfg, p, f, js); + + json_t *rpcjs = rs_rpc_log_json_response(tx); + if (unlikely(rpcjs == NULL)) { + goto error; + } + json_object_set_new(js, "rpc", rpcjs); + + json_t *nfsjs = rs_nfs_log_json_response(state, tx); + if (unlikely(nfsjs == NULL)) { + goto error; + } + json_object_set_new(js, "nfs", nfsjs); + + MemBufferReset(thread->buffer); + OutputJSONBuffer(js, thread->ctx->file_ctx, &thread->buffer); + + json_decref(js); + return TM_ECODE_OK; + +error: + json_decref(js); + return TM_ECODE_FAILED; +} + +static OutputInitResult NFSLogInitSub(ConfNode *conf, + OutputCtx *parent_ctx) +{ + AppLayerParserRegisterLogger(IPPROTO_TCP, ALPROTO_NFS); + AppLayerParserRegisterLogger(IPPROTO_UDP, ALPROTO_NFS); + return OutputJsonLogInitSub(conf, parent_ctx); +} + +void JsonNFSLogRegister(void) +{ + /* Register as an eve sub-module. */ + OutputRegisterTxSubModule(LOGGER_JSON_NFS, "eve-log", "JsonNFSLog", + "eve-log.nfs", NFSLogInitSub, ALPROTO_NFS, + JsonNFSLogger, JsonLogThreadInit, + JsonLogThreadDeinit, NULL); + + SCLogDebug("NFS JSON logger registered."); +} + +#else /* No JSON support. */ + +void JsonNFSLogRegister(void) +{ +} + +#endif /* HAVE_LIBJANSSON */ + +#else /* no rust */ + +void JsonNFSLogRegister(void) +{ +} + +#endif /* HAVE_RUST */ diff --git a/pool/shard008/C/0133718_space.c b/pool/shard008/C/0133718_space.c new file mode 100644 index 0000000000000000000000000000000000000000..f8a40d77bbb680e6e9aa2155aab6fa3d16d3eb67 --- /dev/null +++ b/pool/shard008/C/0133718_space.c @@ -0,0 +1,140 @@ +#include +#include "space.h" +#include "body.h" +#include "simple_logger.h" + +#include + +struct Space_S +{ + GList *bodylist; /**steps = steps; + space->stepFactor = 1.0/steps; +} + +void space_remove_body(Space *space,Body *body) +{ + if (!space)return; + if (!body)return; + space->bodylist = g_list_remove(space->bodylist,body); +} + +void space_add_body(Space *space,Body *body) +{ + if (!space)return; + if (!body)return; + space->bodylist = g_list_append(space->bodylist,body); +} + + +static void space_body_update(Space *space,Body *body) +{ + GList *it; + Cube a,b; + Body *other; + Vec3D stepVector; + Vec3D stepOffVector; + + if ((!body) || (body->_done))return; + + vec3d_scale(stepVector,body->velocity,space->stepFactor); + vec3d_negate(stepOffVector,stepVector); + + vec3d_add(body->position,body->position,stepVector); + + a.x = body->position.x + body->bounds.x; + a.y = body->position.y + body->bounds.y; + a.z = body->position.z + body->bounds.z; + a.w = body->bounds.w; + a.h = body->bounds.h; + a.d = body->bounds.d; + + for (it = space->bodylist;it != NULL;it = g_list_next(it)) + { + if (!it->data)continue; + if (it->data == body)continue; + /*check for collision*/ + other = (Body *)it->data; + vec3d_cpy(b,other->position); + b.w = other->bounds.w; + b.h = other->bounds.h; + b.d = other->bounds.d; + vec3d_add(b,b,other->bounds); + if (cube_cube_intersection(a,b)) + { + /*call touch functions*/ + /*back the fuck off*/ + vec3d_cpy(body->_stepOffVector,stepOffVector); + body->_done = 1; + body->_needsBackoff = 1; + if (body->touch.function) + { + body->touch.function(body->touch.data,other); + } + } + } +} + +static void space_update(Space *space) +{ + GList *it; + for (it = space->bodylist;it != NULL;it = g_list_next(it)) + { + if (!it->data)continue; + space_body_update(space,(Body*)it->data); + } + for (it = space->bodylist;it != NULL;it = g_list_next(it)) + { + if (!it->data)continue; + body_process((Body *)it->data); + } +} + +void space_do_step(Space *space) +{ + GList *it; + + if (!space)return; + if (space->stepstaken == space->steps) + { + space->stepstaken = 0; + + for (it = space->bodylist;it != NULL;it = g_list_next(it)) + { + if (!it->data)continue; + body_reset((Body *)it->data); + } + } + /*run one iteration of space update*/ + space_update(space); + /*for each body, update it a little*/ + space->stepstaken++; +} + +void space_free(Space *space) +{ + if (!space)return; + free(space); +} + +/*eol@eof*/ diff --git a/pool/shard008/C/0133724_network.c b/pool/shard008/C/0133724_network.c new file mode 100644 index 0000000000000000000000000000000000000000..17b6a5bd332cef47370a9afb8944654397af40cc --- /dev/null +++ b/pool/shard008/C/0133724_network.c @@ -0,0 +1,150 @@ +/* + * Copyright (C) 2013, Jules Colding . + * + * All Rights Reserved. + */ + +/* + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * (1) Redistributions of source code must retain the above + * copyright notice, this list of conditions and the following + * disclaimer. + * + * (2) 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. + * + * (3) Neither the name of the copyright holder 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 AUTHOR ``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. + */ + +#ifdef HAVE_CONFIG_H + #include "ac_config.h" +#endif +#ifdef __linux__ + #include + #include +#endif +#include +#include +#include "network.h" + +int +send_all(int sock, + const uint8_t * const buf, + const int len) +{ + int total = 0; + int bytesleft = len; + int n; + + while (total < len) { + n = send(sock, buf + total, bytesleft, 0); + if (-1 == n) { + return 0; + } + total += n; + bytesleft -= n; + } + + return 1; +} + +int +set_recv_timeout(int sock, + const time_t time_out) +{ + struct timeval t; + + t.tv_sec = time_out; + t.tv_usec = 0; + + if (setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &t, sizeof(struct timeval))) { + return 0; + } + + return 1; +} + +int +set_send_timeout(int sock, + const time_t time_out) +{ + struct timeval t; + + t.tv_sec = time_out; + t.tv_usec = 0; + + if (setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &t, sizeof(struct timeval))) { + return 0; + } + + return 1; +} + +int +set_min_recv_sice(int sock, + const int ipc_header_size) +{ + if (setsockopt(sock, SOL_SOCKET, SO_RCVLOWAT, &ipc_header_size, sizeof(ipc_header_size))) { + return 0; + } + + return 1; +} + +int +set_non_blocking(int sock) +{ + int flags; + + flags = fcntl(sock, F_GETFL, 0); + if (-1 == flags) { + return 0; + } + + flags = fcntl(sock, F_SETFL, flags | O_NONBLOCK); + if (-1 == flags) { + return 0; + } + + return 1; +} + +int +set_blocking(int sock) +{ + int flags; + + flags = fcntl(sock, F_GETFL, 0); + if (-1 == flags) { + return 0; + } + flags &= ~O_NONBLOCK; + + flags = fcntl(sock, F_SETFL, flags); + if (-1 == flags) { + return 0; + } + + return 1; +} diff --git a/pool/shard008/C/0133725_utils.c b/pool/shard008/C/0133725_utils.c new file mode 100644 index 0000000000000000000000000000000000000000..00c028f6ae8c12bd94024e0312e5927e5c7bffc6 --- /dev/null +++ b/pool/shard008/C/0133725_utils.c @@ -0,0 +1,46 @@ +/* + * Implementation of utility functions for the ls program + * author: Ali Scott + */ + +#include +#include +#include +#include +#include + +/* + * returns the input string in lower case + */ +char* strtolower(const char* s, char* t) { + strncpy(t, s, strlen(t) + 1); + int i = 0; + while(t[i] != '\0') { + t[i] = tolower(t[i]); + i++; + } + return t; +} + +/* + * returns the string length of an integer + */ +int intlen(int i) { + if (i < 0) + return 1 + intlen(-i); + else if (i == 0) + return 1; + else + return floor(log10((double) i)) + 1; +} + +/* + * prints n spaces + */ +void printspaces(int n) { + int i; + for (i = 0; i < n; i++) + printf(" "); +} + + diff --git a/pool/shard008/C/0133731_xilinx_timer.c b/pool/shard008/C/0133731_xilinx_timer.c new file mode 100644 index 0000000000000000000000000000000000000000..0755e1b1ad216fc797782fc2345ff4caf12ae717 --- /dev/null +++ b/pool/shard008/C/0133731_xilinx_timer.c @@ -0,0 +1,247 @@ +/* + * QEMU model of the Xilinx timer block. + * + * Copyright (c) 2009 Edgar E. Iglesias. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "sysbus.h" +#include "qemu-timer.h" +#include "ptimer.h" + +#define D(x) + +#define R_TCSR 0 +#define R_TLR 1 +#define R_TCR 2 +#define R_MAX 4 + +#define TCSR_MDT (1<<0) +#define TCSR_UDT (1<<1) +#define TCSR_GENT (1<<2) +#define TCSR_CAPT (1<<3) +#define TCSR_ARHT (1<<4) +#define TCSR_LOAD (1<<5) +#define TCSR_ENIT (1<<6) +#define TCSR_ENT (1<<7) +#define TCSR_TINT (1<<8) +#define TCSR_PWMA (1<<9) +#define TCSR_ENALL (1<<10) + +struct xlx_timer +{ + QEMUBH *bh; + ptimer_state *ptimer; + void *parent; + int nr; /* for debug. */ + + unsigned long timer_div; + + uint32_t regs[R_MAX]; +}; + +struct timerblock +{ + SysBusDevice busdev; + MemoryRegion mmio; + qemu_irq irq; + uint32_t nr_timers; + uint32_t freq_hz; + struct xlx_timer *timers; +}; + +static inline unsigned int timer_from_addr(target_phys_addr_t addr) +{ + /* Timers get a 4x32bit control reg area each. */ + return addr >> 2; +} + +static void timer_update_irq(struct timerblock *t) +{ + unsigned int i, irq = 0; + uint32_t csr; + + for (i = 0; i < t->nr_timers; i++) { + csr = t->timers[i].regs[R_TCSR]; + irq |= (csr & TCSR_TINT) && (csr & TCSR_ENIT); + } + + /* All timers within the same slave share a single IRQ line. */ + qemu_set_irq(t->irq, !!irq); +} + +static uint64_t +timer_read(void *opaque, target_phys_addr_t addr, unsigned int size) +{ + struct timerblock *t = opaque; + struct xlx_timer *xt; + uint32_t r = 0; + unsigned int timer; + + addr >>= 2; + timer = timer_from_addr(addr); + xt = &t->timers[timer]; + /* Further decoding to address a specific timers reg. */ + addr &= 0x3; + switch (addr) + { + case R_TCR: + r = ptimer_get_count(xt->ptimer); + if (!(xt->regs[R_TCSR] & TCSR_UDT)) + r = ~r; + D(qemu_log("xlx_timer t=%d read counter=%x udt=%d\n", + timer, r, xt->regs[R_TCSR] & TCSR_UDT)); + break; + default: + if (addr < ARRAY_SIZE(xt->regs)) + r = xt->regs[addr]; + break; + + } + D(printf("%s timer=%d %x=%x\n", __func__, timer, addr * 4, r)); + return r; +} + +static void timer_enable(struct xlx_timer *xt) +{ + uint64_t count; + + D(printf("%s timer=%d down=%d\n", __func__, + xt->nr, xt->regs[R_TCSR] & TCSR_UDT)); + + ptimer_stop(xt->ptimer); + + if (xt->regs[R_TCSR] & TCSR_UDT) + count = xt->regs[R_TLR]; + else + count = ~0 - xt->regs[R_TLR]; + ptimer_set_count(xt->ptimer, count); + ptimer_run(xt->ptimer, 1); +} + +static void +timer_write(void *opaque, target_phys_addr_t addr, + uint64_t val64, unsigned int size) +{ + struct timerblock *t = opaque; + struct xlx_timer *xt; + unsigned int timer; + uint32_t value = val64; + + addr >>= 2; + timer = timer_from_addr(addr); + xt = &t->timers[timer]; + D(printf("%s addr=%x val=%x (timer=%d off=%d)\n", + __func__, addr * 4, value, timer, addr & 3)); + /* Further decoding to address a specific timers reg. */ + addr &= 3; + switch (addr) + { + case R_TCSR: + if (value & TCSR_TINT) + value &= ~TCSR_TINT; + + xt->regs[addr] = value; + if (value & TCSR_ENT) + timer_enable(xt); + break; + + default: + if (addr < ARRAY_SIZE(xt->regs)) + xt->regs[addr] = value; + break; + } + timer_update_irq(t); +} + +static const MemoryRegionOps timer_ops = { + .read = timer_read, + .write = timer_write, + .endianness = DEVICE_NATIVE_ENDIAN, + .valid = { + .min_access_size = 4, + .max_access_size = 4 + } +}; + +static void timer_hit(void *opaque) +{ + struct xlx_timer *xt = opaque; + struct timerblock *t = xt->parent; + D(printf("%s %d\n", __func__, timer)); + xt->regs[R_TCSR] |= TCSR_TINT; + + if (xt->regs[R_TCSR] & TCSR_ARHT) + timer_enable(xt); + timer_update_irq(t); +} + +static int xilinx_timer_init(SysBusDevice *dev) +{ + struct timerblock *t = FROM_SYSBUS(typeof (*t), dev); + unsigned int i; + + /* All timers share a single irq line. */ + sysbus_init_irq(dev, &t->irq); + + /* Init all the ptimers. */ + t->timers = g_malloc0(sizeof t->timers[0] * t->nr_timers); + for (i = 0; i < t->nr_timers; i++) { + struct xlx_timer *xt = &t->timers[i]; + + xt->parent = t; + xt->nr = i; + xt->bh = qemu_bh_new(timer_hit, xt); + xt->ptimer = ptimer_init(xt->bh); + ptimer_set_freq(xt->ptimer, t->freq_hz); + } + + memory_region_init_io(&t->mmio, &timer_ops, t, "xilinx-timer", + R_MAX * 4 * t->nr_timers); + sysbus_init_mmio(dev, &t->mmio); + return 0; +} + +static Property xilinx_timer_properties[] = { + DEFINE_PROP_UINT32("frequency", struct timerblock, freq_hz, 0), + DEFINE_PROP_UINT32("nr-timers", struct timerblock, nr_timers, 0), + DEFINE_PROP_END_OF_LIST(), +}; + +static void xilinx_timer_class_init(ObjectClass *klass, void *data) +{ + SysBusDeviceClass *k = SYS_BUS_DEVICE_CLASS(klass); + + k->init = xilinx_timer_init; +} + +static DeviceInfo xilinx_timer_info = { + .name = "xilinx,timer", + .size = sizeof(struct timerblock), + .props = xilinx_timer_properties, + .class_init = xilinx_timer_class_init, +}; + +static void xilinx_timer_register(void) +{ + sysbus_register_withprop(&xilinx_timer_info); +} + +device_init(xilinx_timer_register) diff --git a/pool/shard008/C/0133732_dtsubtable.c b/pool/shard008/C/0133732_dtsubtable.c new file mode 100644 index 0000000000000000000000000000000000000000..67fcb9d2265678b2d110db39a1c5be78574a8bb8 --- /dev/null +++ b/pool/shard008/C/0133732_dtsubtable.c @@ -0,0 +1,379 @@ +/****************************************************************************** + * + * Module Name: dtsubtable.c - handling of subtables within ACPI tables + * + *****************************************************************************/ + +/* + * Copyright (C) 2000 - 2013, Intel Corp. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions, and the following disclaimer, + * without modification. + * 2. Redistributions in binary form must reproduce at minimum a disclaimer + * substantially similar to the "NO WARRANTY" disclaimer below + * ("Disclaimer") and any redistribution must be conditioned upon + * including a substantially similar Disclaimer requirement for further + * binary redistribution. + * 3. Neither the names of the above-listed copyright holders nor the names + * of any contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * Alternatively, this software may be distributed under the terms of the + * GNU General Public License ("GPL") version 2 as published by the Free + * Software Foundation. + * + * NO WARRANTY + * 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 MERCHANTIBILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDERS OR CONTRIBUTORS BE LIABLE FOR 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 DAMAGES. + */ + +#define __DTSUBTABLE_C__ + +#include +#include + +#define _COMPONENT DT_COMPILER + ACPI_MODULE_NAME ("dtsubtable") + + +/****************************************************************************** + * + * FUNCTION: DtCreateSubtable + * + * PARAMETERS: Buffer - Input buffer + * Length - Buffer length + * RetSubtable - Returned newly created subtable + * + * RETURN: None + * + * DESCRIPTION: Create a subtable that is not listed with ACPI_DMTABLE_INFO + * For example, FACS has 24 bytes reserved at the end + * and it's not listed at AcpiDmTableInfoFacs + * + *****************************************************************************/ + +void +DtCreateSubtable ( + UINT8 *Buffer, + UINT32 Length, + DT_SUBTABLE **RetSubtable) +{ + DT_SUBTABLE *Subtable; + + + Subtable = UtLocalCalloc (sizeof (DT_SUBTABLE)); + + /* Create a new buffer for the subtable data */ + + Subtable->Buffer = UtLocalCalloc (Length); + ACPI_MEMCPY (Subtable->Buffer, Buffer, Length); + + Subtable->Length = Length; + Subtable->TotalLength = Length; + + *RetSubtable = Subtable; +} + + +/****************************************************************************** + * + * FUNCTION: DtInsertSubtable + * + * PARAMETERS: ParentTable - The Parent of the new subtable + * Subtable - The new subtable to insert + * + * RETURN: None + * + * DESCRIPTION: Insert the new subtable to the parent table + * + *****************************************************************************/ + +void +DtInsertSubtable ( + DT_SUBTABLE *ParentTable, + DT_SUBTABLE *Subtable) +{ + DT_SUBTABLE *ChildTable; + + + Subtable->Peer = NULL; + Subtable->Parent = ParentTable; + Subtable->Depth = ParentTable->Depth + 1; + + /* Link the new entry into the child list */ + + if (!ParentTable->Child) + { + ParentTable->Child = Subtable; + } + else + { + /* Walk to the end of the child list */ + + ChildTable = ParentTable->Child; + while (ChildTable->Peer) + { + ChildTable = ChildTable->Peer; + } + + /* Add new subtable at the end of the child list */ + + ChildTable->Peer = Subtable; + } +} + + +/****************************************************************************** + * + * FUNCTION: DtPushSubtable + * + * PARAMETERS: Subtable - Subtable to push + * + * RETURN: None + * + * DESCRIPTION: Push a subtable onto a subtable stack + * + *****************************************************************************/ + +void +DtPushSubtable ( + DT_SUBTABLE *Subtable) +{ + + Subtable->StackTop = Gbl_SubtableStack; + Gbl_SubtableStack = Subtable; +} + + +/****************************************************************************** + * + * FUNCTION: DtPopSubtable + * + * PARAMETERS: None + * + * RETURN: None + * + * DESCRIPTION: Pop a subtable from a subtable stack. Uses global SubtableStack + * + *****************************************************************************/ + +void +DtPopSubtable ( + void) +{ + DT_SUBTABLE *Subtable; + + + Subtable = Gbl_SubtableStack; + + if (Subtable) + { + Gbl_SubtableStack = Subtable->StackTop; + } +} + + +/****************************************************************************** + * + * FUNCTION: DtPeekSubtable + * + * PARAMETERS: None + * + * RETURN: The subtable on top of stack + * + * DESCRIPTION: Get the subtable on top of stack + * + *****************************************************************************/ + +DT_SUBTABLE * +DtPeekSubtable ( + void) +{ + + return (Gbl_SubtableStack); +} + + +/****************************************************************************** + * + * FUNCTION: DtGetNextSubtable + * + * PARAMETERS: ParentTable - Parent table whose children we are + * getting + * ChildTable - Previous child that was found. + * The NEXT child will be returned + * + * RETURN: Pointer to the NEXT child or NULL if none is found. + * + * DESCRIPTION: Return the next peer subtable within the tree. + * + *****************************************************************************/ + +DT_SUBTABLE * +DtGetNextSubtable ( + DT_SUBTABLE *ParentTable, + DT_SUBTABLE *ChildTable) +{ + ACPI_FUNCTION_ENTRY (); + + + if (!ChildTable) + { + /* It's really the parent's _scope_ that we want */ + + return (ParentTable->Child); + } + + /* Otherwise just return the next peer (NULL if at end-of-list) */ + + return (ChildTable->Peer); +} + + +/****************************************************************************** + * + * FUNCTION: DtGetParentSubtable + * + * PARAMETERS: Subtable - Current subtable + * + * RETURN: Parent of the given subtable + * + * DESCRIPTION: Get the parent of the given subtable in the tree + * + *****************************************************************************/ + +DT_SUBTABLE * +DtGetParentSubtable ( + DT_SUBTABLE *Subtable) +{ + + if (!Subtable) + { + return (NULL); + } + + return (Subtable->Parent); +} + + +/****************************************************************************** + * + * FUNCTION: DtGetSubtableLength + * + * PARAMETERS: Field - Current field list pointer + * Info - Data table info + * + * RETURN: Subtable length + * + * DESCRIPTION: Get length of bytes needed to compile the subtable + * + *****************************************************************************/ + +UINT32 +DtGetSubtableLength ( + DT_FIELD *Field, + ACPI_DMTABLE_INFO *Info) +{ + UINT32 ByteLength = 0; + UINT8 Step; + UINT8 i; + + + /* Walk entire Info table; Null name terminates */ + + for (; Info->Name; Info++) + { + if (Info->Opcode == ACPI_DMT_EXTRA_TEXT) + { + continue; + } + + if (!Field) + { + goto Error; + } + + ByteLength += DtGetFieldLength (Field, Info); + + switch (Info->Opcode) + { + case ACPI_DMT_GAS: + + Step = 5; + break; + + case ACPI_DMT_HESTNTFY: + + Step = 9; + break; + + default: + + Step = 1; + break; + } + + for (i = 0; i < Step; i++) + { + if (!Field) + { + goto Error; + } + + Field = Field->Next; + } + } + + return (ByteLength); + +Error: + if (!Field) + { + sprintf (MsgBuffer, "Found NULL field - Field name \"%s\" needed", + Info->Name); + DtFatal (ASL_MSG_COMPILER_INTERNAL, NULL, MsgBuffer); + } + + return (ASL_EOF); +} + + +/****************************************************************************** + * + * FUNCTION: DtSetSubtableLength + * + * PARAMETERS: Subtable - Subtable + * + * RETURN: None + * + * DESCRIPTION: Set length of the subtable into its length field + * + *****************************************************************************/ + +void +DtSetSubtableLength ( + DT_SUBTABLE *Subtable) +{ + + if (!Subtable->LengthField) + { + return; + } + + ACPI_MEMCPY (Subtable->LengthField, &Subtable->TotalLength, + Subtable->SizeOfLengthField); +} diff --git a/pool/shard008/C/0133736_Indent.c b/pool/shard008/C/0133736_Indent.c new file mode 100644 index 0000000000000000000000000000000000000000..95c6e03d74d976d27bb6c78eb1cc3daee52cabad --- /dev/null +++ b/pool/shard008/C/0133736_Indent.c @@ -0,0 +1,78 @@ +/*------------------------------------------------------------------------- + Copyright (C) 2008, Charles Wang + Author: Charles Wang + License: LGPLv2 (see LICENSE-LGPL) +-------------------------------------------------------------------------*/ +#include "Indent.h" +#include "ScanInput.h" + +#define START_INDENT_SPACE 32 +CcsBool_t CcsIndent_Init(CcsIndent_t * self, const CcsIndentInfo_t * info) +{ + self->info = info; + self->lineStart = TRUE; + if (!(self->indent = CcsMalloc(sizeof(int) * START_INDENT_SPACE))) + return FALSE; + self->indentUsed = self->indent; + self->indentLast = self->indent + START_INDENT_SPACE; + *self->indentUsed++ = 0; + self->indentLimit = -1; + return TRUE; +} +void CcsIndent_Destruct(CcsIndent_t * self) +{ + CcsFree(self->indent); +} + +void CcsIndent_SetLimit(CcsIndent_t * self, const CcsToken_t * indentIn) +{ + self->indentLimit = indentIn->loc.col; +} + +CcsToken_t * +CcsIndent_Generator(CcsIndent_t * self, CcsScanInput_t * input) +{ + int newLen; int * newIndent, * curIndent; + CcsToken_t * head, * cur; + + if (!self->lineStart) return NULL; + CcsAssert(self->indent < self->indentUsed); + /* Skip blank lines. */ + if (input->ch == '\r' || input->ch == '\n') return NULL; + /* Dump all required IndentOut when EoF encountered. */ + if (input->ch == EoF) { + head = NULL; + while (self->indent < self->indentUsed - 1) { + cur = CcsScanInput_NewToken(input, self->info->kIndentOut); + cur->next = head; head = cur; + --self->indentUsed; + } + return head; + } + if (self->indentLimit != -1 && input->col >= self->indentLimit) return NULL; + self->indentLimit = -1; + self->lineStart = FALSE; + if (input->col > self->indentUsed[-1]) { + if (self->indentUsed == self->indentLast) { + newLen = (self->indentLast - self->indent) + START_INDENT_SPACE; + newIndent = CcsRealloc(self->indent, sizeof(int) * newLen); + if (!newIndent) return NULL; + self->indentUsed = newIndent + (self->indentUsed - self->indent); + self->indentLast = newIndent + newLen; + self->indent = newIndent; + } + CcsAssert(self->indentUsed < self->indentLast); + *self->indentUsed++ = input->col; + return CcsScanInput_NewToken(input, self->info->kIndentIn); + } + for (curIndent = self->indentUsed - 1; input->col < *curIndent; --curIndent); + if (input->col > *curIndent) + return CcsScanInput_NewToken(input, self->info->kIndentErr); + head = NULL; + while (curIndent < self->indentUsed - 1) { + cur = CcsScanInput_NewToken(input, self->info->kIndentOut); + cur->next = head; head = cur; + --self->indentUsed; + } + return head; +} diff --git a/pool/shard008/C/0133737_mach-tl-wr1041n-v2.c b/pool/shard008/C/0133737_mach-tl-wr1041n-v2.c new file mode 100644 index 0000000000000000000000000000000000000000..f79f1558628c32d296cd0e7a139aa8e0c072d34c --- /dev/null +++ b/pool/shard008/C/0133737_mach-tl-wr1041n-v2.c @@ -0,0 +1,157 @@ +/* + * TP-LINK TL-WR1041 v2 board support + * + * Copyright (C) 2010-2012 Gabor Juhos + * Copyright (C) 2011-2012 Anan Huang + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 as published + * by the Free Software Foundation. + */ + +#include +#include +#include +#include +#include + +#include + +#include "common.h" +#include "dev-ap9x-pci.h" +#include "dev-eth.h" +#include "dev-gpio-buttons.h" +#include "dev-leds-gpio.h" +#include "dev-m25p80.h" +#include "dev-spi.h" +#include "dev-wmac.h" +#include "machtypes.h" + +#define TL_WR1041NV2_GPIO_BTN_RESET 14 +#define TL_WR1041NV2_GPIO_LED_WPS 13 +#define TL_WR1041NV2_GPIO_LED_WLAN 11 + +#define TL_WR1041NV2_GPIO_LED_SYSTEM 12 + +#define TL_WR1041NV2_KEYS_POLL_INTERVAL 20 /* msecs */ +#define TL_WR1041NV2_KEYS_DEBOUNCE_INTERVAL (3 * TL_WR1041NV2_KEYS_POLL_INTERVAL) + +#define TL_WR1041NV2_PCIE_CALDATA_OFFSET 0x5000 + +static const char *tl_wr1041nv2_part_probes[] = { + "tp-link", + NULL, +}; + +static struct flash_platform_data tl_wr1041nv2_flash_data = { + .part_probes = tl_wr1041nv2_part_probes, +}; + +static struct gpio_led tl_wr1041nv2_leds_gpio[] __initdata = { + { + .name = "tp-link:green:system", + .gpio = TL_WR1041NV2_GPIO_LED_SYSTEM, + .active_low = 1, + }, { + .name = "tp-link:green:wps", + .gpio = TL_WR1041NV2_GPIO_LED_WPS, + .active_low = 1, + }, { + .name = "tp-link:green:wlan", + .gpio = TL_WR1041NV2_GPIO_LED_WLAN, + .active_low = 1, + } +}; + +static struct gpio_keys_button tl_wr1041nv2_gpio_keys[] __initdata = { + { + .desc = "reset", + .type = EV_KEY, + .code = KEY_RESTART, + .debounce_interval = TL_WR1041NV2_KEYS_DEBOUNCE_INTERVAL, + .gpio = TL_WR1041NV2_GPIO_BTN_RESET, + .active_low = 1, + } +}; + +static const struct ar8327_led_info tl_wr1041n_leds_ar8327[] = { + AR8327_LED_INFO(PHY0_0, HW, "tp-link:green:wan"), + AR8327_LED_INFO(PHY1_0, HW, "tp-link:green:lan1"), + AR8327_LED_INFO(PHY2_0, HW, "tp-link:green:lan2"), + AR8327_LED_INFO(PHY3_0, HW, "tp-link:green:lan3"), + AR8327_LED_INFO(PHY4_0, HW, "tp-link:green:lan4"), +}; + +static struct ar8327_led_cfg wr1041n_v2_ar8327_led_cfg = { + .led_ctrl0 = 0xcf35cf35, /* LED0: blink at 10/100/1000M */ + .led_ctrl1 = 0xcf35cf35, /* LED1: blink at 10/100/1000M: anyway, no LED1 on tl-wr1041n */ + .led_ctrl2 = 0xcf35cf35, /* LED2: blink at 10/100/1000M: anyway, no LED2 on tl-wr1041n */ + .led_ctrl3 = 0x03ffff00, /* Pattern enabled for LED 0-2 of port 1-3 */ + .open_drain = true, +}; + +static struct ar8327_pad_cfg db120_ar8327_pad0_cfg = { + .mode = AR8327_PAD_MAC_RGMII, + .txclk_delay_en = true, + .rxclk_delay_en = true, + .txclk_delay_sel = AR8327_CLK_DELAY_SEL1, + .rxclk_delay_sel = AR8327_CLK_DELAY_SEL2, +}; + +static struct ar8327_platform_data db120_ar8327_data = { + .pad0_cfg = &db120_ar8327_pad0_cfg, + .port0_cfg = { + .force_link = 1, + .speed = AR8327_PORT_SPEED_1000, + .duplex = 1, + .txpause = 1, + .rxpause = 1, + }, + .led_cfg = &wr1041n_v2_ar8327_led_cfg, + .num_leds = ARRAY_SIZE(tl_wr1041n_leds_ar8327), + .leds = tl_wr1041n_leds_ar8327 +}; + +static struct mdio_board_info db120_mdio0_info[] = { + { + .bus_id = "ag71xx-mdio.0", + .phy_addr = 0, + .platform_data = &db120_ar8327_data, + }, +}; + +static void __init tl_wr1041nv2_setup(void) +{ + u8 *mac = (u8 *) KSEG1ADDR(0x1f01fc00); + u8 *ee = (u8 *) KSEG1ADDR(0x1fff1000); + + ath79_register_m25p80(&tl_wr1041nv2_flash_data); + + ath79_register_leds_gpio(-1, ARRAY_SIZE(tl_wr1041nv2_leds_gpio), + tl_wr1041nv2_leds_gpio); + ath79_register_gpio_keys_polled(-1, TL_WR1041NV2_KEYS_POLL_INTERVAL, + ARRAY_SIZE(tl_wr1041nv2_gpio_keys), + tl_wr1041nv2_gpio_keys); + ath79_register_wmac(ee, mac); + + ath79_setup_ar934x_eth_cfg(AR934X_ETH_CFG_RGMII_GMAC0 | + AR934X_ETH_CFG_SW_ONLY_MODE); + + ath79_register_mdio(1, 0x0); + ath79_register_mdio(0, 0x0); + + ath79_init_mac(ath79_eth0_data.mac_addr, mac, 1); + + mdiobus_register_board_info(db120_mdio0_info, + ARRAY_SIZE(db120_mdio0_info)); + + /* GMAC0 is connected to an AR8327 switch */ + ath79_eth0_data.phy_if_mode = PHY_INTERFACE_MODE_RGMII; + ath79_eth0_data.phy_mask = BIT(0); + ath79_eth0_data.mii_bus_dev = &ath79_mdio0_device.dev; + ath79_eth0_pll_data.pll_1000 = 0x06000000; + ath79_register_eth(0); +} + +MIPS_MACHINE(ATH79_MACH_TL_WR1041N_V2, "TL-WR1041N-v2", + "TP-LINK TL-WR1041N v2", tl_wr1041nv2_setup); diff --git a/pool/shard008/C/0133745_combine_image_channels.c b/pool/shard008/C/0133745_combine_image_channels.c new file mode 100644 index 0000000000000000000000000000000000000000..e3e4fdb411a25383fd4efaa2ab65d8bfbf15ad3d --- /dev/null +++ b/pool/shard008/C/0133745_combine_image_channels.c @@ -0,0 +1,211 @@ +#include +#include +#include +#include +#include +#if defined(_WIN32) || defined(_WIN64) + #define PCRE_STATIC + #include +#else + #include +#endif +#include +#include +#include "tz_string.h" +#include "tz_mc_stack.h" +#include "tz_image_io.h" + +char** get_image_paths(const char *dir_name, const char *pattern, int *n) +{ + *n = dir_fnum_p(dir_name, pattern); + if (*n == 0) { + return NULL; + } + + char** filepaths = (char**) malloc(sizeof(char*) * (*n)); + int i; + for (i = 0; i < *n; ++i) { + filepaths[i] = (char*) Guarded_Malloc(sizeof(char) * 500, "filepath"); + } + + DIR *dir = opendir(dir_name); + struct dirent *ent = readdir(dir); + int index = 0; + + /* allocate a string for storing full path. 100 is just an initial guess */ + char *prefix = (char *) Guarded_Malloc(strlen(dir_name) + 100, + "Dir_Neurochain"); + strcpy(prefix, dir_name); + if (prefix[strlen(prefix)-1]!='/') { + strcat(prefix, "/"); + } + printf("%s\n", prefix); + + regex_t preg; + regcomp(&preg, pattern, REG_BASIC); + + while (ent != NULL) { + if (regexec(&preg, ent->d_name, 0, NULL, REG_BASIC) ==0) { + if (strncasecmp(ent->d_name, "tileselection", 13) != 0) { + strcpy(filepaths[index], prefix); + strcat(filepaths[index], ent->d_name); + printf("%s\n", filepaths[index]); + index++; + } else { + (*n)--; + } + } + ent = readdir(dir); + } + free(prefix); + closedir(dir); + + regfree(&preg); + + return filepaths; +} + +int compare_string_by_num(const void *a, const void *b) +{ + if (strlen(*(char**)a) > strlen(*(char**)b)) { + return 1; + } else if (strlen(*(char**)a) < strlen(*(char**)b)) { + return -1; + } else { + char *acopy = *(char**)a; + char *bcopy = *(char**)b; + while(*acopy == *bcopy) { + acopy++; + bcopy++; + } + int a1 = atoi(acopy); + int b1 = atoi(bcopy); + if (a1 < b1) { + return -1; + } else if (a1 > b1) { + return 1; + } else { + return 0; + } + } +} + +/* same as fopen, but create folder when needed */ +FILE *open_file(const char *path, const char *mode) +{ + FILE *fp = fopen(path, mode); + if (fp == NULL) { + int errsv = errno; + /*perror("fopen");*/ + if (errsv == ENOENT) { + /*printf("The directory does not exist. Creating new directory ...\n");*/ + int pos; + char *pathcopy = malloc(strlen(path)+1); + strcpy(pathcopy, path); + for (pos=1; pos] [-redgreenimagefolder ]", + "[-blueimagefolder ]", NULL}; + Process_Arguments(argc, argv, Spec, 1); + + int nredgreenimage; + int nblueimage; + char** redgreenfilepath = get_image_paths(Get_String_Arg("-redgreenimagefolder"), ".*\\.lsm", &nredgreenimage); + char** bluefilepath = get_image_paths(Get_String_Arg("-blueimagefolder"), ".*\\.lsm", &nblueimage); + + + if (redgreenfilepath == NULL || bluefilepath == NULL) { + printf("no image!\n"); + return 1; + } else if (nredgreenimage != nblueimage) { + printf("image number don't match, abort! red: %d, blue: %d\n", nredgreenimage, nblueimage); + return 1; + } else { + printf("%d images\n", nblueimage); + } + + qsort(redgreenfilepath, nblueimage, sizeof(char*), compare_string_by_num); + qsort(bluefilepath, nblueimage, sizeof(char*), compare_string_by_num); + + char prefix[500]; + char outfilepath[500]; + char filenamenoext[500]; + int k; + for (k = 0; k < nblueimage; ++k) { + strcpy(prefix, Get_String_Arg("-outfolder")); + strcpy(filenamenoext, redgreenfilepath[k]); + char *end = strrchr(filenamenoext, '.'); + if (end != NULL) { + *end = '\0'; + } + else { + printf("something stange happens..\n"); + } + char *start = strrchr(filenamenoext, '/'); + if (start != NULL) { + start++; + } + else { + start = filenamenoext; + } + if (prefix[strlen(prefix)-1]=='/') { + sprintf(outfilepath, "%s%s.tif", prefix, start); + } else { + sprintf(outfilepath, "%s/%s.tif", prefix, start); + } + + FILE* fp = open_file(outfilepath, "wb"); + fclose(fp); + + Mc_Stack* mc_stack1 = Read_Mc_Stack(redgreenfilepath[k], -1); + Mc_Stack* mc_stack2 = Read_Mc_Stack(bluefilepath[k], -1); + + Mc_Stack* mc_stack = Combine_Mc_Stack(mc_stack1, mc_stack2); + Write_Mc_Stack(outfilepath, mc_stack, NULL); + printf("Write %s done!\n", outfilepath); + Kill_Mc_Stack(mc_stack1); + Kill_Mc_Stack(mc_stack2); + Kill_Mc_Stack(mc_stack); + } + + free(redgreenfilepath); + free(bluefilepath); + + return 0; +} + diff --git a/pool/shard008/C/0133747_test_dump.c b/pool/shard008/C/0133747_test_dump.c new file mode 100644 index 0000000000000000000000000000000000000000..363dd10ba3fe40c4e3fab44198c033e83bc92ef2 --- /dev/null +++ b/pool/shard008/C/0133747_test_dump.c @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2009-2011 Petri Lehtinen + * + * Jansson is free software; you can redistribute it and/or modify + * it under the terms of the MIT license. See LICENSE for details. + */ + +#include +#include +#include "util.h" + +int main() +{ + json_t *json; + char *result; + + /* Encode an empty object/array, add an item, encode again */ + + json = json_object(); + result = json_dumps(json, 0); + if(!result || strcmp(result, "{}")) + fail("json_dumps failed"); + free(result); + + json_object_set_new(json, "foo", json_integer(5)); + result = json_dumps(json, 0); + if(!result || strcmp(result, "{\"foo\": 5}")) + fail("json_dumps failed"); + free(result); + + json_decref(json); + + json = json_array(); + result = json_dumps(json, 0); + if(!result || strcmp(result, "[]")) + fail("json_dumps failed"); + free(result); + + json_array_append_new(json, json_integer(5)); + result = json_dumps(json, 0); + if(!result || strcmp(result, "[5]")) + fail("json_dumps failed"); + free(result); + + json_decref(json); + + /* Construct a JSON object/array with a circular reference: + + object: {"a": {"b": {"c": }}} + array: [[[]]] + + Encode it, remove the circular reference and encode again. + */ + json = json_object(); + json_object_set_new(json, "a", json_object()); + json_object_set_new(json_object_get(json, "a"), "b", json_object()); + json_object_set(json_object_get(json_object_get(json, "a"), "b"), "c", + json_object_get(json, "a")); + + if(json_dumps(json, 0)) + fail("json_dumps encoded a circular reference!"); + + json_object_del(json_object_get(json_object_get(json, "a"), "b"), "c"); + + result = json_dumps(json, 0); + if(!result || strcmp(result, "{\"a\": {\"b\": {}}}")) + fail("json_dumps failed!"); + free(result); + + json_decref(json); + + json = json_array(); + json_array_append_new(json, json_array()); + json_array_append_new(json_array_get(json, 0), json_array()); + json_array_append(json_array_get(json_array_get(json, 0), 0), + json_array_get(json, 0)); + + if(json_dumps(json, 0)) + fail("json_dumps encoded a circular reference!"); + + json_array_remove(json_array_get(json_array_get(json, 0), 0), 0); + + result = json_dumps(json, 0); + if(!result || strcmp(result, "[[[]]]")) + fail("json_dumps failed!"); + free(result); + + json_decref(json); + + return 0; +} diff --git a/pool/shard008/C/0133748_calc_auc.c b/pool/shard008/C/0133748_calc_auc.c new file mode 100644 index 0000000000000000000000000000000000000000..23f12f52b842dcf3b589df0869dd72a82d32193d --- /dev/null +++ b/pool/shard008/C/0133748_calc_auc.c @@ -0,0 +1,115 @@ +#include +#include +#include +#include "dataIO.h" +#include "params.h" + + +int main(int argc, char **argv){ + + struct Set *S; + struct PARAMS P; + FILE *fptr; + double *cache; + long int i; + struct HistList *H; + double val; + int num; + long int tp_,fp_,tn_,fn_; + float tp,fp,tn,fn,accuracy; + double auc; + int cacheId; + + + //inits + P.numViews=1; + P.verbose=0; + P.partition=0; + + + if(argc != 3) { + printf("usage:\ncalc_auc \n"); + exit(1); + } + + strcpy(P.inputFILE,argv[1]); + strcpy(P.valuesFILE,argv[2]); + + S = load_svmlight_name(&P, P.inputFILE); + + + fptr = fopen(P.valuesFILE, "r"); + if (!fptr) { + printf("cannot open values file"); + exit(1); + } + + cache=(double*)malloc(sizeof(double)*S->N); + for(i=0;iN;i++) { + if(fscanf(fptr," %lf",&cache[i]) == EOF) { + printf("error: values file does contain less entries than data file\n"); + exit(1); + } + } + if(fscanf(fptr," %lf",&cache[i]) != EOF) { + printf("error: values file does contain more entries than data file\n"); + exit(1); + } + fclose(fptr); + + + tp_=fp_=tn_=fn_=0; + H=NewHistList(); + + auc=0; + tp_=tn_=fn_=fp_=0; + + cacheId = 0; + for(i=0;iN;i++){ + val=0; + num=0; + val+=cache[cacheId]; + num++; + + val=val/num; + + if (val>=0){ + if (S->example[i]->trueLabel==+1){ + InsertPos(H,val); + tp_++; + } + else { + InsertNeg(H,val); + fp_++; + } + } + else if (S->example[i]->trueLabel==+1){ + InsertPos(H,val); + fn_++; + } + else { + InsertNeg(H,val); + tn_++; + } + cacheId++; + } + + accuracy=(float)(tp_+tn_)/(float)S->N; + tp=(float)tp_/(float)S->N; + fp=(float)fp_/(float)S->N; + fn=(float)fn_/(float)S->N; + tn=(float)tn_/(float)S->N; + + // accuracy + //printf("acc: %f %f %f %f %f \n",accuracy,tp,fp,fn,tn); + + auc=PrintROCcurve(NULL,H,0); + + printf("auc: %f\n",auc); + + DeleteHistList(H); + + return 1; +} + + diff --git a/pool/shard008/C/0133749_timer_test.c b/pool/shard008/C/0133749_timer_test.c new file mode 100644 index 0000000000000000000000000000000000000000..47575e06ab961468158c15847006183c69151cf7 --- /dev/null +++ b/pool/shard008/C/0133749_timer_test.c @@ -0,0 +1,83 @@ +/* + * Copyright 2013 anthony cantor + * This file is part of aug. + * + * aug is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * aug 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with aug. If not, see . + */ +#include +#include +#include +#include + +#include "util.h" +#include "timer.h" + +struct aug_test { + void (*fn)(); + int amt; +}; + +void test1() { + struct aug_timer tmr1; + struct timeval elapsed; + + diag("++++test1++++"); + diag("test basic functionality/sanity"); + + ok1(timer_init(&tmr1) == 0); + diag("sleep 50000"); + usleep(50000); + + ok1(timer_elapsed(&tmr1, &elapsed) == 0); + + ok1(timer_thresh(&tmr1, 0, 50000) == 1); + ok1(timer_thresh(&tmr1, 0, 51000) == 0); + ok1(timer_thresh(&tmr1, 0, 55000) == 0); + ok1(timer_thresh(&tmr1, 0, 60000) == 0); + ok1(timer_thresh(&tmr1, 0, 75000) == 0); + ok1(timer_thresh(&tmr1, 0, 100000) == 0); + + diag("elapsed: %d,%d", (int) elapsed.tv_sec, (int) elapsed.tv_usec); + ok1( elapsed.tv_sec == 0 ); + ok1( elapsed.tv_usec > 49999 ); + ok1( elapsed.tv_usec < 50500 ); + +#define TEST1AMT 1 + 1 + 6 + 3 + diag("----test1----\n#"); + +} + +int main() +{ + int i, len, total_tests; +#define TESTN(_num) {test##_num, TEST##_num##AMT} + struct aug_test tests[] = { + TESTN(1) + }; + + total_tests = 0; + len = AUG_ARRAY_SIZE(tests); + for(i = 0; i < len; i++) { + total_tests += tests[i].amt; + } + + plan_tests(total_tests); + + for(i = 0; i < len; i++) { + (*tests[i].fn)(); + } + + return exit_status(); +} + diff --git a/pool/shard008/C/0133753_init.c b/pool/shard008/C/0133753_init.c new file mode 100644 index 0000000000000000000000000000000000000000..22a345145e7f3c19f9c69eb9da10728efb14c992 --- /dev/null +++ b/pool/shard008/C/0133753_init.c @@ -0,0 +1,75 @@ +/* + (c) Copyright 2001-2008 The world wide DirectFB Open Source Community (directfb.org) + (c) Copyright 2000-2004 Convergence (integrated media) GmbH + + All rights reserved. + + Written by Denis Oliver Kropp , + Andreas Hundt , + Sven Neumann , + Ville Syrjälä and + Claudio Ciccani . + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + 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. +*/ + +#include + +#include + +#include + +#include "init.h" + + +void DFBResult__init( void ); +void DFBResult__deinit( void ); + +/**********************************************************************************************************************/ + +typedef void (*Func)( void ); + + +static Func init_funcs[] = { + DFBResult__init, + Core_TLS__init, +}; + +static Func deinit_funcs[] = { + Core_TLS__deinit, + DFBResult__deinit, +}; + +/**********************************************************************************************************************/ + +void +__DFB_init_all() +{ + size_t i; + + for (i=0; i, et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at http://curl.haxx.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ***************************************************************************/ + +#include "setup.h" + +#include "llist.h" +#include "curl_memory.h" + +/* this must be the last include file */ +#include "memdebug.h" + +/* + * @unittest: 1300 + */ +static void +llist_init(struct curl_llist *l, curl_llist_dtor dtor) +{ + l->size = 0; + l->dtor = dtor; + l->head = NULL; + l->tail = NULL; +} + +struct curl_llist * +Curl_llist_alloc(curl_llist_dtor dtor) +{ + struct curl_llist *list; + + list = malloc(sizeof(struct curl_llist)); + if(!list) + return NULL; + + llist_init(list, dtor); + + return list; +} + +/* + * Curl_llist_insert_next() + * + * Inserts a new list element after the given one 'e'. If the given existing + * entry is NULL and the list already has elements, the new one will be + * inserted first in the list. + * + * Returns: 1 on success and 0 on failure. + * + * @unittest: 1300 + */ +int +Curl_llist_insert_next(struct curl_llist *list, struct curl_llist_element *e, + const void *p) +{ + struct curl_llist_element *ne = malloc(sizeof(struct curl_llist_element)); + if(!ne) + return 0; + + ne->ptr = (void *) p; + if(list->size == 0) { + list->head = ne; + list->head->prev = NULL; + list->head->next = NULL; + list->tail = ne; + } + else { + /* if 'e' is NULL here, we insert the new element first in the list */ + ne->next = e?e->next:list->head; + ne->prev = e; + if(!e) { + list->head->prev = ne; + list->head = ne; + } + else if(e->next) { + e->next->prev = ne; + } + else { + list->tail = ne; + } + if(e) + e->next = ne; + } + + ++list->size; + + return 1; +} + +/* + * @unittest: 1300 + */ +int +Curl_llist_remove(struct curl_llist *list, struct curl_llist_element *e, + void *user) +{ + if(e == NULL || list->size == 0) + return 1; + + if(e == list->head) { + list->head = e->next; + + if(list->head == NULL) + list->tail = NULL; + else + e->next->prev = NULL; + } + else { + e->prev->next = e->next; + if(!e->next) + list->tail = e->prev; + else + e->next->prev = e->prev; + } + + list->dtor(user, e->ptr); + + e->ptr = NULL; + e->prev = NULL; + e->next = NULL; + + free(e); + --list->size; + + return 1; +} + +void +Curl_llist_destroy(struct curl_llist *list, void *user) +{ + if(list) { + while(list->size > 0) + Curl_llist_remove(list, list->tail, user); + + free(list); + } +} + +size_t +Curl_llist_count(struct curl_llist *list) +{ + return list->size; +} + +/* + * @unittest: 1300 + */ +int Curl_llist_move(struct curl_llist *list, struct curl_llist_element *e, + struct curl_llist *to_list, + struct curl_llist_element *to_e) +{ + /* Remove element from list */ + if(e == NULL || list->size == 0) + return 0; + + if(e == list->head) { + list->head = e->next; + + if(list->head == NULL) + list->tail = NULL; + else + e->next->prev = NULL; + } + else { + e->prev->next = e->next; + if(!e->next) + list->tail = e->prev; + else + e->next->prev = e->prev; + } + + --list->size; + + /* Add element to to_list after to_e */ + if(to_list->size == 0) { + to_list->head = e; + to_list->head->prev = NULL; + to_list->head->next = NULL; + to_list->tail = e; + } + else { + e->next = to_e->next; + e->prev = to_e; + if(to_e->next) { + to_e->next->prev = e; + } + else { + to_list->tail = e; + } + to_e->next = e; + } + + ++to_list->size; + + return 1; +} diff --git a/pool/shard008/C/0133758_CWE121_Stack_Based_Buffer_Overflow__CWE135_65b.c b/pool/shard008/C/0133758_CWE121_Stack_Based_Buffer_Overflow__CWE135_65b.c new file mode 100644 index 0000000000000000000000000000000000000000..65c30c87675adb95d4252d25a2a99ddc3095c6c9 --- /dev/null +++ b/pool/shard008/C/0133758_CWE121_Stack_Based_Buffer_Overflow__CWE135_65b.c @@ -0,0 +1,69 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE121_Stack_Based_Buffer_Overflow__CWE135_65b.c +Label Definition File: CWE121_Stack_Based_Buffer_Overflow__CWE135.label.xml +Template File: sources-sinks-65b.tmpl.c +*/ +/* + * @description + * CWE: 121 Stack Based Buffer Overflow + * BadSource: Void pointer to a wchar_t array + * GoodSource: Void pointer to a char array + * Sinks: + * GoodSink: Allocate memory using wcslen() and copy data + * BadSink : Allocate memory using strlen() and copy data + * Flow Variant: 65 Data/control flow: data passed as an argument from one function to a function in a different source file called via a function pointer + * + * */ + +#include "std_testcase.h" + +#include + +#define WIDE_STRING L"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" +#define CHAR_STRING "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + +#ifndef OMITBAD + +void CWE121_Stack_Based_Buffer_Overflow__CWE135_65b_badSink(void * data) +{ + { + /* POTENTIAL FLAW: treating pointer as a char* when it may point to a wide string */ + size_t dataLen = strlen((char *)data); + void * dest = (void *)calloc(dataLen+1, 1); + memcpy(dest, data, (dataLen+1)); + printLine((char *)dest); + free(dest); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void CWE121_Stack_Based_Buffer_Overflow__CWE135_65b_goodG2BSink(void * data) +{ + { + /* POTENTIAL FLAW: treating pointer as a char* when it may point to a wide string */ + size_t dataLen = strlen((char *)data); + void * dest = (void *)calloc(dataLen+1, 1); + memcpy(dest, data, (dataLen+1)); + printLine((char *)dest); + free(dest); + } +} + +/* goodB2G uses the BadSource with the GoodSink */ +void CWE121_Stack_Based_Buffer_Overflow__CWE135_65b_goodB2GSink(void * data) +{ + { + /* FIX: treating pointer like a wchar_t* */ + size_t dataLen = wcslen((wchar_t *)data); + void * dest = (void *)calloc(dataLen+1, sizeof(wchar_t)); + memcpy(dest, data, (dataLen+1)*sizeof(wchar_t)); + printWLine((wchar_t *)dest); + free(dest); + } +} + +#endif /* OMITGOOD */ diff --git a/pool/shard008/C/0133769_main.c b/pool/shard008/C/0133769_main.c new file mode 100644 index 0000000000000000000000000000000000000000..a0d94bc8568335be6aa741b4286abe8b7a613f69 --- /dev/null +++ b/pool/shard008/C/0133769_main.c @@ -0,0 +1,52 @@ +#include +#include +#include +#include + +#include "sha1.h" + +static uint8_t buf[65536]; + +static void sumfile(int fd, const char *name) +{ + SHA1Context ctx; + uint8_t digest[20]; + char digeststr[41] = {}; + int len; + + SHA1Reset(&ctx); + + while((len = read(fd, buf, sizeof(buf))) > 0) { + SHA1Input(&ctx, buf, len); + } + + SHA1Finish(&ctx, digest); + + for(int j = 0; j < 20; j++) { + digeststr[j * 2 + 0] = "0123456789abcdef"[digest[j] >> 4]; + digeststr[j * 2 + 1] = "0123456789abcdef"[digest[j] & 15]; + } + + printf("%s %s\n", digeststr, name); +} + + + +int main(int argc, char **argv) +{ + if(argc < 2) { + sumfile(0, "-"); + return 0; + } + for(int i = 1; i < argc; i++) { + int fd = open(argv[1], O_RDONLY); + if(fd == -1) { + printf("Unable to open %s\n", argv[i]); + exit(1); + } + sumfile(fd, argv[i]); + close(fd); + } + return 0; +} + diff --git a/pool/shard008/C/0133778_cally-clone.c b/pool/shard008/C/0133778_cally-clone.c new file mode 100644 index 0000000000000000000000000000000000000000..3f2704919004d5ac50fdba46e67a0c018a1ae2c3 --- /dev/null +++ b/pool/shard008/C/0133778_cally-clone.c @@ -0,0 +1,131 @@ +/* CALLY - The Clutter Accessibility Implementation Library + * + * Copyright (C) 2010 Igalia, S.L. + * + * Author: Alejandro Piñeiro Iglesias + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * 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. + */ + +/** + * SECTION:cally-clone + * @Title: CallyClone + * @short_description: Implementation of the ATK interfaces for a #ClutterClone + * @see_also: #ClutterClone + * + * #CallyClone implements the required ATK interfaces of #ClutterClone + * + * In particular it sets a proper role for the clone, as just a image, + * as it is the sanest and simplest approach. + */ + +/* Design rationale for CallyClone: + * + * In the old times, it was just ClutterCloneTexture. So, from a a11y POV + * CallyCloneTexture was just another image, like ClutterTexture, and if + * it was a clone was irrevelant. So on cally-0.8, CallyCloneTexture + * expose a object with role ATK_ROLE_IMAGE. But now, ClutterClone is more + * general. You can clone any object, including groups, and made things + * like have one text entry, and a clone with different properties in the + * same window, updated both at once. + * + * The question is if the idea is have a ClutterClone as a "first-class" + * citizen inside the stage hierarchy (full clone), or it is just supposed + * to be a mirror image of the original object. + * + * In the case of the a11y POV this would mean that if the text changes on + * the source, the clone should emit as well the text-changing signals. + * + * As ClutterClone smartly just paint the same object with different + * parameters, this would mean that it should be the cally object the one + * that should replicate the source clutter hierarchy to do that, + * something that just sound crazy. + * + * Taking into account that: + * + * - ClutterClone doesn't re-emit mirrored signals from the source + * I think that likely the answer would be "yes, it is just a + * mirrored image, not a real full clone". + * + * - You can't interact directly with the clone (ie: focus, and so on). + * Its basic usage (right now) is clone textures. + * + * Any other solution could be overwhelming. + * + * I think that the final solution would be that ClutterClone from the + * a11y POV should still be managed as a image (with the proper properties, + * position, size, etc.). + */ + +#include "cally-clone.h" +#include "cally-actor-private.h" + +/* AtkObject */ +static void cally_clone_real_initialize (AtkObject *obj, + gpointer data); + +G_DEFINE_TYPE (CallyClone, cally_clone, CALLY_TYPE_ACTOR) + +static void +cally_clone_class_init (CallyCloneClass *klass) +{ +/* GObjectClass *gobject_class = G_OBJECT_CLASS (klass); */ + AtkObjectClass *class = ATK_OBJECT_CLASS (klass); + + class->initialize = cally_clone_real_initialize; +} + +static void +cally_clone_init (CallyClone *clone) +{ + /* nothing to do yet */ +} + +/** + * cally_clone_new: + * @actor: a #ClutterActor + * + * Creates a new #CallyClone for the given @actor. @actor must be a + * #ClutterClone. + * + * Return value: the newly created #AtkObject + * + * Since: 1.4 + */ +AtkObject* +cally_clone_new (ClutterActor *actor) +{ + GObject *object = NULL; + AtkObject *accessible = NULL; + + g_return_val_if_fail (CLUTTER_IS_CLONE (actor), NULL); + + object = g_object_new (CALLY_TYPE_CLONE, NULL); + + accessible = ATK_OBJECT (object); + atk_object_initialize (accessible, actor); + + return accessible; +} + +static void +cally_clone_real_initialize (AtkObject *obj, + gpointer data) +{ + ATK_OBJECT_CLASS (cally_clone_parent_class)->initialize (obj, data); + + obj->role = ATK_ROLE_IMAGE; +} diff --git a/pool/shard008/C/0133783_pcie.c b/pool/shard008/C/0133783_pcie.c new file mode 100644 index 0000000000000000000000000000000000000000..355332d502cb538cdec53e796bdf70b993f381ae --- /dev/null +++ b/pool/shard008/C/0133783_pcie.c @@ -0,0 +1,215 @@ +/* + * arch/arm/mach-dove/pcie.c + * + * PCIe functions for Marvell Dove 88AP510 SoC + * + * This file is licensed under the terms of the GNU General Public + * License version 2. This program is licensed "as is" without any + * warranty of any kind, whether express or implied. + */ + +#include +#include +#include