diff --git a/pool/shard010/C++/0111158_CompressRGB.cpp b/pool/shard010/C++/0111158_CompressRGB.cpp new file mode 100644 index 0000000000000000000000000000000000000000..35239c4518eb32913fdb5ee6eb2bbad7f53f6594 --- /dev/null +++ b/pool/shard010/C++/0111158_CompressRGB.cpp @@ -0,0 +1,140 @@ +// Copyright NVIDIA Corporation 2007 -- Ignacio Castano +// +// 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 + +#include +#include +#include + +#include "CompressRGB.h" +#include "CompressionOptions.h" +#include "OutputOptions.h" + +using namespace nv; +using namespace nvtt; + +namespace +{ + + inline uint computePitch(uint w, uint bitsize) + { + uint p = w * ((bitsize + 7) / 8); + + // Align to 32 bits. + return ((p + 3) / 4) * 4; + } + + inline void convert_to_a8r8g8b8(const void * src, void * dst, uint w) + { + memcpy(dst, src, 4 * w); + } + + inline void convert_to_x8r8g8b8(const void * src, void * dst, uint w) + { + memcpy(dst, src, 4 * w); + } + +} // namespace + + +// Pixel format converter. +void nv::compressRGB(const Image * image, const OutputOptions::Private & outputOptions, const CompressionOptions::Private & compressionOptions) +{ + nvCheck(image != NULL); + + const uint w = image->width(); + const uint h = image->height(); + + const uint bitCount = compressionOptions.bitcount; + nvCheck(bitCount == 8 || bitCount == 16 || bitCount == 24 || bitCount == 32); + + const uint byteCount = bitCount / 8; + + const uint rmask = compressionOptions.rmask; + uint rshift, rsize; + PixelFormat::maskShiftAndSize(rmask, &rshift, &rsize); + + const uint gmask = compressionOptions.gmask; + uint gshift, gsize; + PixelFormat::maskShiftAndSize(gmask, &gshift, &gsize); + + const uint bmask = compressionOptions.bmask; + uint bshift, bsize; + PixelFormat::maskShiftAndSize(bmask, &bshift, &bsize); + + const uint amask = compressionOptions.amask; + uint ashift, asize; + PixelFormat::maskShiftAndSize(amask, &ashift, &asize); + + // Determine pitch. + uint pitch = computePitch(w, compressionOptions.bitcount); + + uint8 * dst = (uint8 *)mem::malloc(pitch + 4); + + for (uint y = 0; y < h; y++) + { + const Color32 * src = image->scanline(y); + + if (bitCount == 32 && rmask == 0xFF0000 && gmask == 0xFF00 && bmask == 0xFF && amask == 0xFF000000) + { + convert_to_a8r8g8b8(src, dst, w); + } + else if (bitCount == 32 && rmask == 0xFF0000 && gmask == 0xFF00 && bmask == 0xFF && amask == 0) + { + convert_to_x8r8g8b8(src, dst, w); + } + else + { + // Generic pixel format conversion. + for (uint x = 0; x < w; x++) + { + uint c = 0; + c |= PixelFormat::convert(src[x].r, 8, rsize) << rshift; + c |= PixelFormat::convert(src[x].g, 8, gsize) << gshift; + c |= PixelFormat::convert(src[x].b, 8, bsize) << bshift; + c |= PixelFormat::convert(src[x].a, 8, asize) << ashift; + + // Output one byte at a time. + for (uint i = 0; i < byteCount; i++) + { + *(dst + x * byteCount + i) = (c >> (i * 8)) & 0xFF; + } + } + + // Zero padding. + for (uint x = w * byteCount; x < pitch; x++) + { + *(dst + x) = 0; + } + } + + if (outputOptions.outputHandler != NULL) + { + outputOptions.outputHandler->writeData(dst, pitch); + } + } + + mem::free(dst); +} + diff --git a/pool/shard010/C++/0111161_Server.cpp b/pool/shard010/C++/0111161_Server.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0bf2b641fd3313cb97aa6c0072fc71373c398a5f --- /dev/null +++ b/pool/shard010/C++/0111161_Server.cpp @@ -0,0 +1,132 @@ +//Based of off WTFIAWS' code + + + +#include + +#include +#include +#include +#include +#include + +#include "Server.h" +#include "header.h" + +static const char *server_domain = "http://localhost"; + +using boost::asio::ip::tcp; + +Server::Server(boost::asio::io_service& io_service, Config *conf) { + service_ = &io_service; + port_ = conf->get_port(); + handlers_ = conf->get_handlers(); +} + +std::string Server::get_prefix(std::string full_path) { + if(full_path.at(0) != '/') { + return full_path; + } else { + size_t found = full_path.find("/", 1); + if(found != std::string::npos) { + return full_path.substr(0, found); + } else { + return full_path; + } + } +} + +void Server::run() { + fprintf(stderr, "Starting server at %s:%d\n", server_domain, port_); + tcp::acceptor a(*service_, tcp::endpoint(tcp::v4(), port_)); + boost::thread q(boost::bind(&Server::end, this)); + while(true) { + sock_ptr sock(new tcp::socket(*service_)); + a.accept(*sock); + boost::thread t(boost::bind(&Server::session, sock, this)); + } +} + +const HTTPRequest Server::parseRequest(std::istream &stream) { + HTTPRequest request; + int content_length; + std::string s; + + stream >> request.method; + stream >> request.path; + stream >> s; // Get rid of the HTTP version + + std::string header_name, header_value; + stream.ignore(1, '\n'); // don't care about newlines + while(stream.peek() != 13) { // while next character is not carriage return + std::pair header; + getline(stream, header.first, ':'); + stream.ignore(1, ' '); // ignore whitespace + getline(stream, header.second, '\r'); + stream.ignore(1, '\n'); // don't care about newlines + if(header.first == "Content-Length") { + content_length = stoi(header_value); + } + request.headers.push_back(header); + } + stream.ignore(2, '\n'); // Get rid of empty lines at the end + if (content_length != 0) { + request.request_body.resize(content_length); + stream.read(&request.request_body[0], content_length); + } + return request; +} + +void Server::session(sock_ptr sock, Server *s) { + try { + // Read request into buffer + char req_buf[max_length]; + + boost::system::error_code error; + size_t length = sock->read_some(boost::asio::buffer(req_buf), error); + if (error) + throw boost::system::system_error(error); + + std::stringstream stream(std::string(req_buf, length)); + + // Create HTTP request from read request + const HTTPRequest request = s->parseRequest(stream); + std::string prefix = s->get_prefix(request.path); + + using namespace boost::asio; + if(s->handlers_.count(prefix) > 0) { + std::string response = s->handlers_[prefix]->HandleRequest(request); + write(*sock, buffer(response, response.size())); + } else { + write(*sock, buffer(status_strings::not_found, + status_strings::not_found.size())); + } + + // 404 ERROR if we reach here + #ifdef DEBUG + fprintf(stderr, "DEBUG: Unrecognized request type.\n\n"); + #endif + + } + catch (std::exception& e) { + std::cerr << "Exception in thread: " << e.what() << "\n"; + } +} + +/** + * Throws an ExitErrorException which should be caught to quit all + * server threads. + */ +void Server::end() +{ + std::string quit; + while (quit != "q") + { + printf("Enter q to quit the server: "); + // Release control to server + boost::this_thread::sleep_for(boost::chrono::milliseconds(10)); + std::cin >> quit; + } + // If we reach here, the user entered "q" + throw ExitServerException(); +} \ No newline at end of file diff --git a/pool/shard010/C++/0111165_Base32Test.cpp b/pool/shard010/C++/0111165_Base32Test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4bc1c33d4f32b37f018c78d7e1d0adcc1e630dad --- /dev/null +++ b/pool/shard010/C++/0111165_Base32Test.cpp @@ -0,0 +1,184 @@ +// +// Base32Test.cpp +// +// $Id: //poco/1.4/Foundation/testsuite/src/Base32Test.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#include "Base32Test.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/Base32Encoder.h" +#include "Poco/Base32Decoder.h" +#include "Poco/Exception.h" +#include + + +using Poco::Base32Encoder; +using Poco::Base32Decoder; +using Poco::DataFormatException; + + +Base32Test::Base32Test(const std::string& name): CppUnit::TestCase(name) +{ +} + + +Base32Test::~Base32Test() +{ +} + + +void Base32Test::testEncoder() +{ + { + std::ostringstream str; + Base32Encoder encoder(str); + encoder << std::string("\00\01\02\03\04\05", 6); + encoder.close(); + assert (str.str() == "AAAQEAYEAU======"); + } + { + std::ostringstream str; + Base32Encoder encoder(str); + encoder << std::string("\00\01\02\03", 4); + encoder.close(); + assert (str.str() == "AAAQEAY="); + } + { + std::ostringstream str; + Base32Encoder encoder(str, false); + encoder << "ABCDEF"; + encoder.close(); + assert (str.str() == "IFBEGRCFIY"); + } + { + std::ostringstream str; + Base32Encoder encoder(str); + encoder << "ABCDEF"; + encoder.close(); + assert (str.str() == "IFBEGRCFIY======"); + } + { + std::ostringstream str; + Base32Encoder encoder(str); + encoder << "ABCDE"; + encoder.close(); + assert (str.str() == "IFBEGRCF"); + } +} + + +void Base32Test::testDecoder() +{ + { + std::istringstream istr("AAAQEAYEAU======"); + Base32Decoder decoder(istr); + assert (decoder.good() && decoder.get() == 0); + assert (decoder.good() && decoder.get() == 1); + assert (decoder.good() && decoder.get() == 2); + assert (decoder.good() && decoder.get() == 3); + assert (decoder.good() && decoder.get() == 4); + assert (decoder.good() && decoder.get() == 5); + assert (decoder.good() && decoder.get() == -1); + } + { + std::istringstream istr("AAAQEAYE"); + Base32Decoder decoder(istr); + assert (decoder.good() && decoder.get() == 0); + assert (decoder.good() && decoder.get() == 1); + assert (decoder.good() && decoder.get() == 2); + assert (decoder.good() && decoder.get() == 3); + assert (decoder.good() && decoder.get() == 4); + assert (decoder.good() && decoder.get() == -1); + } + { + std::istringstream istr("AAAQEAY="); + Base32Decoder decoder(istr); + assert (decoder.good() && decoder.get() == 0); + assert (decoder.good() && decoder.get() == 1); + assert (decoder.good() && decoder.get() == 2); + assert (decoder.good() && decoder.get() == 3); + assert (decoder.good() && decoder.get() == -1); + } + { + std::istringstream istr("IFBEGRCFIY======"); + Base32Decoder decoder(istr); + std::string s; + decoder >> s; + assert (s == "ABCDEF"); + assert (decoder.eof()); + assert (!decoder.fail()); + } + { + std::istringstream istr("QUJD#REVG"); + Base32Decoder decoder(istr); + std::string s; + try + { + decoder >> s; + assert (decoder.bad()); + } + catch (DataFormatException&) + { + } + assert (!decoder.eof()); + } +} + + +void Base32Test::testEncodeDecode() +{ + { + std::stringstream str; + Base32Encoder encoder(str); + encoder << "The quick brown fox "; + encoder << "jumped over the lazy dog."; + encoder.close(); + Base32Decoder decoder(str); + std::string s; + int c = decoder.get(); + while (c != -1) { s += char(c); c = decoder.get(); } + assert (s == "The quick brown fox jumped over the lazy dog."); + } + { + std::string src; + for (int i = 0; i < 255; ++i) src += char(i); + std::stringstream str; + Base32Encoder encoder(str); + encoder.write(src.data(), (std::streamsize) src.size()); + encoder.close(); + Base32Decoder decoder(str); + std::string s; + int c = decoder.get(); + while (c != -1) { s += char(c); c = decoder.get(); } + assert (s == src); + } +} + + +void Base32Test::setUp() +{ +} + + +void Base32Test::tearDown() +{ +} + + +CppUnit::Test* Base32Test::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("Base32Test"); + + CppUnit_addTest(pSuite, Base32Test, testEncoder); + CppUnit_addTest(pSuite, Base32Test, testDecoder); + CppUnit_addTest(pSuite, Base32Test, testEncodeDecode); + + return pSuite; +} diff --git a/pool/shard010/C++/0111171_output_accel_angle.cpp b/pool/shard010/C++/0111171_output_accel_angle.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e43a8bc4f2b773e339de7dc4fbc3d36e14153c06 --- /dev/null +++ b/pool/shard010/C++/0111171_output_accel_angle.cpp @@ -0,0 +1,20 @@ +/*******output 3axis_acceleration[G]*******/ +#include "ros/ros.h" +#include "accel_angle.h" +#include + +void chatterCallback(const openreroc_posturesensor::accel_angle msg_a_ang) +{ + printf("accel_x:%f\n ", msg_a_ang.ac_x_ang); + printf("accel_y:%f\n", msg_a_ang.ac_y_ang); + printf("accel_z:%f\n", msg_a_ang.ac_z_ang); +} + +int main(int argc, char **argv) +{ + ros::init(argc, argv, "output_accel_angle"); + ros::NodeHandle n; + ros::Subscriber sub = n.subscribe("accel_angle_value", 1000, chatterCallback); + ros::spin(); + return 0; +} diff --git a/pool/shard010/C++/0111173_webfilesystem_impl.cc b/pool/shard010/C++/0111173_webfilesystem_impl.cc new file mode 100644 index 0000000000000000000000000000000000000000..e05ded3733d9d8f42be30235e8a2f349f5cc4495 --- /dev/null +++ b/pool/shard010/C++/0111173_webfilesystem_impl.cc @@ -0,0 +1,144 @@ +// 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 "content/child/fileapi/webfilesystem_impl.h" + +#include "base/bind.h" +#include "content/child/child_thread.h" +#include "content/child/fileapi/file_system_dispatcher.h" +#include "content/child/fileapi/webfilesystem_callback_adapters.h" +#include "content/child/fileapi/webfilewriter_impl.h" +#include "third_party/WebKit/public/web/WebFileSystemCallbacks.h" +#include "third_party/WebKit/public/platform/WebFileInfo.h" +#include "third_party/WebKit/public/platform/WebString.h" +#include "third_party/WebKit/public/platform/WebURL.h" +#include "webkit/glue/webkit_glue.h" + +using WebKit::WebFileInfo; +using WebKit::WebFileSystemCallbacks; +using WebKit::WebFileSystemEntry; +using WebKit::WebString; +using WebKit::WebURL; +using WebKit::WebVector; + +namespace content { + +WebFileSystemImpl::WebFileSystemImpl() { +} + +void WebFileSystemImpl::move(const WebURL& src_path, + const WebURL& dest_path, + WebFileSystemCallbacks* callbacks) { + FileSystemDispatcher* dispatcher = + ChildThread::current()->file_system_dispatcher(); + dispatcher->Move(GURL(src_path), + GURL(dest_path), + base::Bind(&FileStatusCallbackAdapter, callbacks)); +} + +void WebFileSystemImpl::copy(const WebURL& src_path, + const WebURL& dest_path, + WebFileSystemCallbacks* callbacks) { + FileSystemDispatcher* dispatcher = + ChildThread::current()->file_system_dispatcher(); + dispatcher->Copy(GURL(src_path), + GURL(dest_path), + base::Bind(&FileStatusCallbackAdapter, callbacks)); +} + +void WebFileSystemImpl::remove(const WebURL& path, + WebFileSystemCallbacks* callbacks) { + FileSystemDispatcher* dispatcher = + ChildThread::current()->file_system_dispatcher(); + dispatcher->Remove( + GURL(path), + false /* recursive */, + base::Bind(&FileStatusCallbackAdapter, callbacks)); +} + +void WebFileSystemImpl::removeRecursively(const WebURL& path, + WebFileSystemCallbacks* callbacks) { + FileSystemDispatcher* dispatcher = + ChildThread::current()->file_system_dispatcher(); + dispatcher->Remove( + GURL(path), + true /* recursive */, + base::Bind(&FileStatusCallbackAdapter, callbacks)); +} + +void WebFileSystemImpl::readMetadata(const WebURL& path, + WebFileSystemCallbacks* callbacks) { + FileSystemDispatcher* dispatcher = + ChildThread::current()->file_system_dispatcher(); + dispatcher->ReadMetadata( + GURL(path), + base::Bind(&ReadMetadataCallbackAdapter, callbacks), + base::Bind(&FileStatusCallbackAdapter, callbacks)); +} + +void WebFileSystemImpl::createFile(const WebURL& path, + bool exclusive, + WebFileSystemCallbacks* callbacks) { + FileSystemDispatcher* dispatcher = + ChildThread::current()->file_system_dispatcher(); + dispatcher->Create( + GURL(path), exclusive, false /* directory */, false /* recursive */, + base::Bind(&FileStatusCallbackAdapter, callbacks)); +} + +void WebFileSystemImpl::createDirectory(const WebURL& path, + bool exclusive, + WebFileSystemCallbacks* callbacks) { + FileSystemDispatcher* dispatcher = + ChildThread::current()->file_system_dispatcher(); + dispatcher->Create( + GURL(path), exclusive, true /* directory */, false /* recursive */, + base::Bind(&FileStatusCallbackAdapter, callbacks)); +} + +void WebFileSystemImpl::fileExists(const WebURL& path, + WebFileSystemCallbacks* callbacks) { + FileSystemDispatcher* dispatcher = + ChildThread::current()->file_system_dispatcher(); + dispatcher->Exists( + GURL(path), false /* directory */, + base::Bind(&FileStatusCallbackAdapter, callbacks)); +} + +void WebFileSystemImpl::directoryExists(const WebURL& path, + WebFileSystemCallbacks* callbacks) { + FileSystemDispatcher* dispatcher = + ChildThread::current()->file_system_dispatcher(); + dispatcher->Exists( + GURL(path), true /* directory */, + base::Bind(&FileStatusCallbackAdapter, callbacks)); +} + +void WebFileSystemImpl::readDirectory(const WebURL& path, + WebFileSystemCallbacks* callbacks) { + FileSystemDispatcher* dispatcher = + ChildThread::current()->file_system_dispatcher(); + dispatcher->ReadDirectory( + GURL(path), + base::Bind(&ReadDirectoryCallbackAdapater, callbacks), + base::Bind(&FileStatusCallbackAdapter, callbacks)); +} + +WebKit::WebFileWriter* WebFileSystemImpl::createFileWriter( + const WebURL& path, WebKit::WebFileWriterClient* client) { + return new WebFileWriterImpl(GURL(path), client); +} + +void WebFileSystemImpl::createSnapshotFileAndReadMetadata( + const WebKit::WebURL& path, + WebKit::WebFileSystemCallbacks* callbacks) { + FileSystemDispatcher* dispatcher = + ChildThread::current()->file_system_dispatcher(); + dispatcher->CreateSnapshotFile( + GURL(path), + base::Bind(&CreateSnapshotFileCallbackAdapter, callbacks), + base::Bind(&FileStatusCallbackAdapter, callbacks)); +} + +} // namespace content diff --git a/pool/shard010/C++/0111175_WiggleRangeParser.cc b/pool/shard010/C++/0111175_WiggleRangeParser.cc new file mode 100644 index 0000000000000000000000000000000000000000..e3b1464629be5e87dd1251c3128332510473934e --- /dev/null +++ b/pool/shard010/C++/0111175_WiggleRangeParser.cc @@ -0,0 +1,19 @@ +class WiggleRangeParser : public WiggleParser { +public: + WiggleRangeParser() : + max_(-numeric_limits::max()), + min_(numeric_limits::max()) { + } + + void addValue(int base, float value) { + max_ = max(value, max_); + min_ = min(value, min_); + } + + float getMax() { return max_; } + float getMin() { return min_; } + +private: + float max_; + float min_; +}; diff --git a/pool/shard010/C++/0111180_testopenstreetmap.cpp b/pool/shard010/C++/0111180_testopenstreetmap.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e49bfdbe4828f3d73c547c358b87a053b589495f --- /dev/null +++ b/pool/shard010/C++/0111180_testopenstreetmap.cpp @@ -0,0 +1,193 @@ +/*************************************************************************** + testopenstreetmap.cpp + -------------------------------------- + Date : January 2013 + Copyright : (C) 2013 by Martin Dobias + Email : wonder dot sk at gmail dot com + *************************************************************************** + * * + * 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 +#include + +#include +//#include + +#include "openstreetmap/qgsosmdatabase.h" +#include "openstreetmap/qgsosmdownload.h" +#include "openstreetmap/qgsosmimport.h" + +class TestOpenStreetMap : public QObject +{ + Q_OBJECT + private slots: + void initTestCase();// will be called before the first testfunction is executed. + void cleanupTestCase();// will be called after the last testfunction was executed. + void init() ;// will be called before each testfunction is executed. + void cleanup() ;// will be called after every testfunction. + /** Our tests proper begin here */ + void download(); + void importAndQueries(); + private: + +}; + +void TestOpenStreetMap::initTestCase() +{ + // + // Runs once before any tests are run + // + // init QGIS's paths - true means that all path will be inited from prefix + QgsApplication::init(); + //QgsApplication::initQgis(); + //QgsApplication::showSettings(); + + //create some objects that will be used in all tests... + //create a map layer that will be used in all tests... + //QString myBaseFileName( TEST_DATA_DIR ); //defined in CmakeLists.txt +} +void TestOpenStreetMap::cleanupTestCase() +{ + +} +void TestOpenStreetMap::init() +{ + +} +void TestOpenStreetMap::cleanup() +{ +} + + +void TestOpenStreetMap::download() +{ + QgsRectangle rect( 7.148, 51.249, 7.152, 51.251 ); + + // start download + QgsOSMDownload download; + download.setQuery( QgsOSMDownload::queryFromRect( rect ) ); + download.setOutputFileName( "/tmp/dl-test.osm" ); + bool res = download.start(); + QVERIFY( res ); + + // wait for finished() signal + int timeout = 15000; // in miliseconds - max waiting time + int waitTime = 500; // in miliseconds - unit waiting time + QSignalSpy spy( &download, SIGNAL( finished() ) ); + while ( timeout > 0 && spy.count() == 0 ) + { + QTest::qWait( waitTime ); + timeout -= waitTime; + } + + QVERIFY( spy.count() != 0 ); + + if ( download.hasError() ) + qDebug( "ERROR: %s", download.errorString().toAscii().data() ); +} + + +void TestOpenStreetMap::importAndQueries() +{ + QString dbFilename = "/tmp/testdata.db"; + QString xmlFilename = TEST_DATA_DIR "/openstreetmap/testdata.xml"; + + QgsOSMXmlImport import( xmlFilename, dbFilename ); + bool res = import.import(); + if ( import.hasError() ) + qDebug( "XML ERR: %s", import.errorString().toAscii().data() ); + QCOMPARE( res, true ); + QCOMPARE( import.hasError(), false ); + + qDebug( "import finished" ); + + QgsOSMDatabase db( dbFilename ); + bool dbopenRes = db.open(); + if ( !db.errorString().isEmpty() ) + qDebug( "DB ERR: %s", db.errorString().toAscii().data() ); + QCOMPARE( dbopenRes, true ); + + // query node + + QgsOSMNode n = db.node( 11111 ); + QCOMPARE( n.isValid(), true ); + QCOMPARE( n.point().x(), 14.4277148 ); + QCOMPARE( n.point().y(), 50.0651387 ); + + QgsOSMNode nNot = db.node( 22222 ); + QCOMPARE( nNot.isValid(), false ); + + // query node tags + + QgsOSMTags tags = db.tags( false, 11111 ); + QCOMPARE( tags.count(), 7 ); + QCOMPARE( tags.value( "addr:postcode" ), QString( "12800" ) ); + + QgsOSMTags tags2 = db.tags( false, 360769661 ); + QCOMPARE( tags2.count(), 0 ); + QCOMPARE( tags2.value( "addr:postcode" ), QString() ); + + QgsOSMTags tagsNot = db.tags( false, 22222 ); + QCOMPARE( tagsNot.count(), 0 ); + + // list nodes + + QgsOSMNodeIterator nodes = db.listNodes(); + QCOMPARE( nodes.next().id(), ( qint64 )11111 ); + QCOMPARE( nodes.next().id(), ( qint64 )360769661 ); + nodes.close(); + + // query way + + QgsOSMWay w = db.way( 32137532 ); + QCOMPARE( w.isValid(), true ); + QCOMPARE( w.nodes().count(), 5 ); + QCOMPARE( w.nodes()[0], ( qint64 )360769661 ); + QCOMPARE( w.nodes()[1], ( qint64 )360769664 ); + + QgsOSMWay wNot = db.way( 1234567 ); + QCOMPARE( wNot.isValid(), false ); + + // query way tags + + QgsOSMTags tagsW = db.tags( true, 32137532 ); + QCOMPARE( tagsW.count(), 3 ); + QCOMPARE( tagsW.value( "building" ), QString( "yes" ) ); + + QgsOSMTags tagsWNot = db.tags( true, 1234567 ); + QCOMPARE( tagsWNot.count(), 0 ); + + // list ways + + QgsOSMWayIterator ways = db.listWays(); + QCOMPARE( ways.next().id(), ( qint64 )32137532 ); + QCOMPARE( ways.next().isValid(), false ); + ways.close(); + + bool exportRes1 = db.exportSpatiaLite( QgsOSMDatabase::Point, "sl_points", QStringList( "addr:postcode" ) ); + //bool exportRes = db.exportSpatiaLite( QStringList("amenity") << "name" << "highway" ); + if ( !db.errorString().isEmpty() ) + qDebug( "EXPORT-1 ERR: %s", db.errorString().toAscii().data() ); + QCOMPARE( exportRes1, true ); + + + bool exportRes2 = db.exportSpatiaLite( QgsOSMDatabase::Polyline, "sl_lines", QStringList( "building" ) ); + //bool exportRes2 = db.exportSpatiaLite( QStringList("amenity") << "name" << "highway" ); + if ( !db.errorString().isEmpty() ) + qDebug( "EXPORT-2 ERR: %s", db.errorString().toAscii().data() ); + QCOMPARE( exportRes2, true ); + + + // TODO: test exported data +} + + +QTEST_MAIN( TestOpenStreetMap ) + +#include "testopenstreetmap.moc" diff --git a/pool/shard010/C++/0111181_LengthNormWriter.cpp b/pool/shard010/C++/0111181_LengthNormWriter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..635983fca5cc4ef69e61e8bc358e51b86386fff7 --- /dev/null +++ b/pool/shard010/C++/0111181_LengthNormWriter.cpp @@ -0,0 +1,102 @@ +// +// Copyright(C) 2005--2011 FirteX Development Team. +// All rights reserved. +// This file is part of FirteX (www.firtex.org) +// +// Use of the FirteX is subject to the terms of the software license set forth in +// the LICENSE file included with this software, and also available at +// http://www.firtex.org/license.html +// +// Author : Ruijie Guo +// Email : ruijieguo@gmail.com +// Created : 2006/1/4 +// + +#include "firtex/index/LengthNormWriter.h" +#include "firtex/utility/NumberFormatter.h" +#include "firtex/store/OutputStream.h" +#include "firtex/index/LengthNormEncoder.h" + +FX_NS_USE(store); +FX_NS_USE(utility); +FX_NS_USE(document); + +using namespace std; + +FX_NS_DEF(index); + +SETUP_STREAM_LOGGER(index, LengthNormWriter); + +LengthNormWriter::LengthNormWriter(const FileSystemPtr& pFileSys) + : m_pFileSys(pFileSys) +{ +} + +LengthNormWriter::~LengthNormWriter(void) +{ +} + +void LengthNormWriter::init(const DocumentSchema* pDocSchema) +{ + DocumentSchema::Iterator iter = pDocSchema->iterator(); + while (iter.hasNext()) + { + const FieldSchema* pFieldSchema = iter.next(); + fieldid_t fieldId = pFieldSchema->getId(); + if (pFieldSchema->isIndexed() && pFieldSchema->hasLengthNorm()) + { + if (fieldId >= (fieldid_t)m_lengthNorm.size()) + { + m_lengthNorm.resize((size_t)fieldId + 1); + } + m_lengthNorm[fieldId].reset(new LengthNorm(FdIndexType::INT32)); + m_lengthNorm[fieldId]->init(pFieldSchema); + } + } +} + +void LengthNormWriter::addField(docid_t docId, const AnalyzedField* pField) +{ + fieldid_t fieldId = pField->getId(); + FIRTEX_ASSERT2(m_lengthNorm[fieldId]); + + const AnalyzedField::TokenView* pTokenView = pField->getTokenView(); + + int32_t length = (pTokenView == NULL) ? 1 : + (int32_t)pTokenView->getNumTokens(); + int32_t norm = LengthNormEncoder::encode(length, pField->getBoost()); + + FIRTEX_ASSERT2(docId >= (docid_t)m_lengthNorm[fieldId]->size()); + m_lengthNorm[fieldId]->setValue(docId, norm); +} + +void LengthNormWriter::commitBarrel(const std::string& sSuffix) +{ + for (fieldid_t fieldId = 0; fieldId < (fieldid_t)m_lengthNorm.size(); + fieldId++) + { + if (m_lengthNorm[fieldId]) + { + m_lengthNorm[fieldId]->commit(m_pFileSys, NORM_FILEEXT, sSuffix); + } + } + m_lengthNorm.clear(); +} + +LengthNormIteratorPtr LengthNormWriter::iterator(fieldid_t fieldId) const +{ + if (fieldId > 0 && fieldId < (fieldid_t)m_lengthNorm.size()) + { + ForwardIndexIteratorPtr pIt = m_lengthNorm[fieldId]->iterator(); + LengthNormIteratorPtr pNormIt = std::dynamic_pointer_cast(pIt); + if (!pNormIt) + { + FIRTEX_THROW(CastException, "Invalid length norm iterator for field: [%d]", + fieldId); + } + } + return LengthNormIteratorPtr(); +} + +FX_NS_END + diff --git a/pool/shard010/C++/0111182_GSGrid_Residuals.cpp b/pool/shard010/C++/0111182_GSGrid_Residuals.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ab2ff5ef50c5f549cca40f5996258c6faf0f5fa6 --- /dev/null +++ b/pool/shard010/C++/0111182_GSGrid_Residuals.cpp @@ -0,0 +1,230 @@ + +/////////////////////////////////////////////////////////// +// // +// SAGA // +// // +// System for Automated Geoscientific Analyses // +// // +// Module Library: // +// Geostatistics_Grid // +// // +//-------------------------------------------------------// +// // +// GSGrid_Residuals.cpp // +// // +// Copyright (C) 2003 by // +// Olaf Conrad // +// // +//-------------------------------------------------------// +// // +// This file is part of 'SAGA - System for Automated // +// Geoscientific Analyses'. SAGA 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. // +// // +// SAGA 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. // +// // +//-------------------------------------------------------// +// // +// e-mail: oconrad@saga-gis.org // +// // +// contact: Olaf Conrad // +// Institute of Geography // +// University of Goettingen // +// Goldschmidtstr. 5 // +// 37077 Goettingen // +// Germany // +// // +/////////////////////////////////////////////////////////// + +//--------------------------------------------------------- + + +/////////////////////////////////////////////////////////// +// // +// // +// // +/////////////////////////////////////////////////////////// + +//--------------------------------------------------------- +#include "GSGrid_Residuals.h" + + +/////////////////////////////////////////////////////////// +// // +// // +// // +/////////////////////////////////////////////////////////// + +//--------------------------------------------------------- +CGSGrid_Residuals::CGSGrid_Residuals(void) +{ + //----------------------------------------------------- + // 1. Info... + + Set_Name (_TL("Residual Analysis (Grid)")); + + Set_Author (SG_T("O.Conrad (c) 2003")); + + Set_Description (_TW("Relations of each grid cell to its neighborhood. " + "Wilson & Gallant (2000) used this type of calculation in terrain analysis.\n" + "\n" + "Reference:\n" + "- Wilson, J.P., Gallant, J.C., [Eds.] (2000): " + "'Terrain analysis - principles and applications', " + "New York, John Wiley & Sons, Inc.\n" + )); + + + //----------------------------------------------------- + // 2. Parameters... + + Parameters.Add_Grid( NULL, "GRID" , _TL("Grid") , _TL(""), PARAMETER_INPUT); + + Parameters.Add_Grid( NULL, "MEAN" , _TL("Mean Value") , _TL(""), PARAMETER_OUTPUT); + Parameters.Add_Grid( NULL, "DIFF" , _TL("Difference from Mean Value") , _TL(""), PARAMETER_OUTPUT); + Parameters.Add_Grid( NULL, "STDDEV" , _TL("Standard Deviation") , _TL(""), PARAMETER_OUTPUT); + Parameters.Add_Grid( NULL, "RANGE" , _TL("Value Range") , _TL(""), PARAMETER_OUTPUT); + Parameters.Add_Grid( NULL, "MIN" , _TL("Minimum Value") , _TL(""), PARAMETER_OUTPUT); + Parameters.Add_Grid( NULL, "MAX" , _TL("Maximum Value") , _TL(""), PARAMETER_OUTPUT); + Parameters.Add_Grid( NULL, "DEVMEAN" , _TL("Deviation from Mean Value") , _TL(""), PARAMETER_OUTPUT); + Parameters.Add_Grid( NULL, "PERCENT" , _TL("Percentile") , _TL(""), PARAMETER_OUTPUT); + + Parameters.Add_Value( NULL, "RADIUS" , _TL("Radius (Cells)") , _TL(""), PARAMETER_TYPE_Int, 7, 1, true); + + Parameters.Add_Parameters( + NULL, "WEIGHTING" , _TL("Weighting"), + _TL("") + )->asParameters()->Assign(m_Cells.Get_Weighting().Get_Parameters()); +} + + +/////////////////////////////////////////////////////////// +// // +// // +// // +/////////////////////////////////////////////////////////// + +//--------------------------------------------------------- +bool CGSGrid_Residuals::On_Execute(void) +{ + m_pGrid = Parameters("GRID") ->asGrid(); + + m_pMean = Parameters("MEAN") ->asGrid(); + m_pDiff = Parameters("DIFF") ->asGrid(); + m_pStdDev = Parameters("STDDEV") ->asGrid(); + m_pRange = Parameters("RANGE") ->asGrid(); + m_pMin = Parameters("MIN") ->asGrid(); + m_pMax = Parameters("MAX") ->asGrid(); + m_pDevMean = Parameters("DEVMEAN") ->asGrid(); + m_pPercent = Parameters("PERCENT") ->asGrid(); + + DataObject_Set_Colors(m_pDiff , 100, SG_COLORS_RED_GREY_BLUE, true); + DataObject_Set_Colors(m_pStdDev , 100, SG_COLORS_RED_GREY_BLUE, true); + DataObject_Set_Colors(m_pRange , 100, SG_COLORS_RED_GREY_BLUE, true); + DataObject_Set_Colors(m_pMin , 100, SG_COLORS_RED_GREY_BLUE, true); + DataObject_Set_Colors(m_pMax , 100, SG_COLORS_RED_GREY_BLUE, true); + DataObject_Set_Colors(m_pDevMean, 100, SG_COLORS_RED_GREY_BLUE, true); + DataObject_Set_Colors(m_pPercent, 100, SG_COLORS_RED_GREY_BLUE, true); + + //----------------------------------------------------- + m_Cells.Get_Weighting().Set_Parameters(Parameters("WEIGHTING")->asParameters()); + + if( !m_Cells.Set_Radius(Parameters("RADIUS")->asInt()) ) + { + return( false ); + } + + //----------------------------------------------------- + for(int y=0; yis_InGrid(x, y) ) + { + int i, ix, iy, nLower; + double z, iz, id, iw; + + CSG_Simple_Statistics Statistics; + + for(i=0, nLower=0, z=m_pGrid->asDouble(x, y); i 0.0 && m_pGrid->is_InGrid(ix, iy) ) + { + Statistics.Add_Value(iz = m_pGrid->asDouble(ix, iy), iw); + + if( z > iz ) + { + nLower++; + } + } + } + + //------------------------------------------------- + if( Statistics.Get_Weights() > 0.0 ) + { + m_pMean ->Set_Value(x, y, Statistics.Get_Mean()); + m_pDiff ->Set_Value(x, y, z - Statistics.Get_Mean()); + m_pStdDev ->Set_Value(x, y, Statistics.Get_StdDev()); + m_pRange ->Set_Value(x, y, Statistics.Get_Range()); + m_pMin ->Set_Value(x, y, Statistics.Get_Minimum()); + m_pMax ->Set_Value(x, y, Statistics.Get_Maximum()); + m_pDevMean ->Set_Value(x, y, Statistics.Get_StdDev() > 0.0 ? ((z - Statistics.Get_Mean()) / Statistics.Get_StdDev()) : 0.0); + m_pPercent ->Set_Value(x, y, 100.0 * nLower / (double)Statistics.Get_Count()); + + return( true ); + } + } + + //----------------------------------------------------- + m_pMean ->Set_NoData(x, y); + m_pDiff ->Set_NoData(x, y); + m_pStdDev ->Set_NoData(x, y); + m_pRange ->Set_NoData(x, y); + m_pMin ->Set_NoData(x, y); + m_pMax ->Set_NoData(x, y); + m_pDevMean ->Set_NoData(x, y); + m_pPercent ->Set_NoData(x, y); + + return( false ); +} + + +/////////////////////////////////////////////////////////// +// // +// // +// // +/////////////////////////////////////////////////////////// + +//--------------------------------------------------------- diff --git a/pool/shard010/C++/0111185_get_reference_vreg_jni.cc b/pool/shard010/C++/0111185_get_reference_vreg_jni.cc new file mode 100644 index 0000000000000000000000000000000000000000..8108c97f7712a0aa7ba47fa3ff7d146c3b0809b0 --- /dev/null +++ b/pool/shard010/C++/0111185_get_reference_vreg_jni.cc @@ -0,0 +1,88 @@ +/* + * Copyright (C) 2015 The Android Open Source Project + * + * 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 "arch/context.h" +#include "art_method-inl.h" +#include "jni.h" +#include "scoped_thread_state_change.h" +#include "stack.h" +#include "thread.h" + +namespace art { + +namespace { + +class TestVisitor : public StackVisitor { + public: + TestVisitor(Thread* thread, Context* context, mirror::Object* this_value) + SHARED_REQUIRES(Locks::mutator_lock_) + : StackVisitor(thread, context, StackVisitor::StackWalkKind::kIncludeInlinedFrames), + this_value_(this_value), + found_method_index_(0) {} + + bool VisitFrame() SHARED_REQUIRES(Locks::mutator_lock_) { + ArtMethod* m = GetMethod(); + std::string m_name(m->GetName()); + + if (m_name.compare("testThisWithInstanceCall") == 0) { + found_method_index_ = 1; + uint32_t value = 0; + CHECK(GetVReg(m, 1, kReferenceVReg, &value)); + CHECK_EQ(reinterpret_cast(value), this_value_); + CHECK_EQ(GetThisObject(), this_value_); + } else if (m_name.compare("testThisWithStaticCall") == 0) { + found_method_index_ = 2; + uint32_t value = 0; + CHECK(GetVReg(m, 1, kReferenceVReg, &value)); + } else if (m_name.compare("testParameter") == 0) { + found_method_index_ = 3; + uint32_t value = 0; + CHECK(GetVReg(m, 1, kReferenceVReg, &value)); + } else if (m_name.compare("testObjectInScope") == 0) { + found_method_index_ = 4; + uint32_t value = 0; + CHECK(GetVReg(m, 0, kReferenceVReg, &value)); + } + + return true; + } + + mirror::Object* this_value_; + + // Value returned to Java to ensure the methods testSimpleVReg and testPairVReg + // have been found and tested. + jint found_method_index_; +}; + +extern "C" JNIEXPORT jint JNICALL Java_Main_doNativeCallRef(JNIEnv*, jobject value) { + ScopedObjectAccess soa(Thread::Current()); + std::unique_ptr context(Context::Create()); + TestVisitor visitor(soa.Self(), context.get(), soa.Decode(value)); + visitor.WalkStack(); + return visitor.found_method_index_; +} + +extern "C" JNIEXPORT jint JNICALL Java_Main_doStaticNativeCallRef(JNIEnv*, jclass) { + ScopedObjectAccess soa(Thread::Current()); + std::unique_ptr context(Context::Create()); + TestVisitor visitor(soa.Self(), context.get(), nullptr); + visitor.WalkStack(); + return visitor.found_method_index_; +} + +} // namespace + +} // namespace art diff --git a/pool/shard010/C++/0111194_editaddressdialog.cpp b/pool/shard010/C++/0111194_editaddressdialog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b72339abebfc07b15da02320074b24c48eedc45c --- /dev/null +++ b/pool/shard010/C++/0111194_editaddressdialog.cpp @@ -0,0 +1,137 @@ +#include "editaddressdialog.h" +#include "ui_editaddressdialog.h" + +#include "addresstablemodel.h" +#include "guiutil.h" + +#include +#include + +EditAddressDialog::EditAddressDialog(Mode mode, QWidget *parent) : + QDialog(parent), + ui(new Ui::EditAddressDialog), mapper(0), mode(mode), model(0) +{ + ui->setupUi(this); + + GUIUtil::setupAddressWidget(ui->addressEdit, this); + + switch(mode) + { + case NewReceivingAddress: + setWindowTitle(tr("New receiving address")); + ui->addressEdit->setEnabled(false); + break; + case NewSendingAddress: + setWindowTitle(tr("New sending address")); + break; + case EditReceivingAddress: + setWindowTitle(tr("Edit receiving address")); + ui->addressEdit->setEnabled(false); + break; + case EditSendingAddress: + setWindowTitle(tr("Edit sending address")); + break; + } + + mapper = new QDataWidgetMapper(this); + mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); +} + +EditAddressDialog::~EditAddressDialog() +{ + delete ui; +} + +void EditAddressDialog::setModel(AddressTableModel *model) +{ + this->model = model; + if(!model) + return; + + mapper->setModel(model); + mapper->addMapping(ui->labelEdit, AddressTableModel::Label); + mapper->addMapping(ui->addressEdit, AddressTableModel::Address); +} + +void EditAddressDialog::loadRow(int row) +{ + mapper->setCurrentIndex(row); +} + +bool EditAddressDialog::saveCurrentRow() +{ + if(!model) + return false; + + switch(mode) + { + case NewReceivingAddress: + case NewSendingAddress: + address = model->addRow( + mode == NewSendingAddress ? AddressTableModel::Send : AddressTableModel::Receive, + ui->labelEdit->text(), + ui->addressEdit->text()); + break; + case EditReceivingAddress: + case EditSendingAddress: + if(mapper->submit()) + { + address = ui->addressEdit->text(); + } + break; + } + return !address.isEmpty(); +} + +void EditAddressDialog::accept() +{ + if(!model) + return; + + if(!saveCurrentRow()) + { + switch(model->getEditStatus()) + { + case AddressTableModel::OK: + // Failed with unknown reason. Just reject. + break; + case AddressTableModel::NO_CHANGES: + // No changes were made during edit operation. Just reject. + break; + case AddressTableModel::INVALID_ADDRESS: + QMessageBox::warning(this, windowTitle(), + tr("The entered address \"%1\" is not a valid Syscoin address.").arg(ui->addressEdit->text()), + QMessageBox::Ok, QMessageBox::Ok); + break; + case AddressTableModel::DUPLICATE_ADDRESS: + QMessageBox::warning(this, windowTitle(), + tr("The entered address \"%1\" is already in the address book.").arg(ui->addressEdit->text()), + QMessageBox::Ok, QMessageBox::Ok); + break; + case AddressTableModel::WALLET_UNLOCK_FAILURE: + QMessageBox::critical(this, windowTitle(), + tr("Could not unlock wallet."), + QMessageBox::Ok, QMessageBox::Ok); + break; + case AddressTableModel::KEY_GENERATION_FAILURE: + QMessageBox::critical(this, windowTitle(), + tr("New key generation failed."), + QMessageBox::Ok, QMessageBox::Ok); + break; + + } + return; + } + QDialog::accept(); +} + +QString EditAddressDialog::getAddress() const +{ + return address; +} + +void EditAddressDialog::setAddress(const QString &address) +{ + this->address = address; + ui->addressEdit->setText(address); +} diff --git a/pool/shard010/C++/0111200_HardwareTimer.cpp b/pool/shard010/C++/0111200_HardwareTimer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4f68ad7248072ddbedf1dfc911d232bb29eb6bcd --- /dev/null +++ b/pool/shard010/C++/0111200_HardwareTimer.cpp @@ -0,0 +1,156 @@ +/****************************************************************************** + * The MIT License + * + * Copyright (c) 2010 Bryan Newbold. + * + * 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 + +#include +#include // for noInterrupts(), interrupts() +#include +#include // for CYCLES_PER_MICROSECOND + +// TODO [0.1.0] Remove deprecated pieces + +/* + * Evil hack to infer this->dev from timerNum in the HardwareTimer + * constructor. See: + * + * http://www.parashift.com/c++-faq-lite/pointers-to-members.html#faq-33.2 + * http://yosefk.com/c++fqa/function.html#fqa-33.2 + */ + +extern "C" { + static timer_dev **this_devp; + static rcc_clk_id this_id; + static void set_this_dev(timer_dev *dev) { + if (dev->clk_id == this_id) { + *this_devp = dev; + } + } +} + +/* + * HardwareTimer routines + */ + +HardwareTimer::HardwareTimer(uint8 timerNum) { + rcc_clk_id timerID = (rcc_clk_id)(RCC_TIMER1 + (timerNum - 1)); + this->dev = NULL; + noInterrupts(); // Hack to ensure we're the only ones using + // set_this_dev() and friends. TODO: use a lock. + this_id = timerID; + this_devp = &this->dev; + timer_foreach(set_this_dev); + interrupts(); + ASSERT(this->dev != NULL); +} + +void HardwareTimer::pause(void) { + timer_pause(this->dev); +} + +void HardwareTimer::resume(void) { + timer_resume(this->dev); +} + +uint32 HardwareTimer::getPrescaleFactor(void) { + return timer_get_prescaler(this->dev) + 1; +} + +void HardwareTimer::setPrescaleFactor(uint32 factor) { + timer_set_prescaler(this->dev, (uint16)(factor - 1)); +} + +uint16 HardwareTimer::getOverflow() { + return timer_get_reload(this->dev); +} + +void HardwareTimer::setOverflow(uint16 val) { + timer_set_reload(this->dev, val); +} + +uint16 HardwareTimer::getCount(void) { + return timer_get_count(this->dev); +} + +void HardwareTimer::setCount(uint16 val) { + uint16 ovf = this->getOverflow(); + timer_set_count(this->dev, min(val, ovf)); +} + +#define MAX_RELOAD ((1 << 16) - 1) +uint16 HardwareTimer::setPeriod(uint32 microseconds) { + // Not the best way to handle this edge case? + if (!microseconds) { + this->setPrescaleFactor(1); + this->setOverflow(1); + return this->getOverflow(); + } + + uint32 period_cyc = microseconds * CYCLES_PER_MICROSECOND; + uint16 prescaler = (uint16)(period_cyc / MAX_RELOAD + 1); + uint16 overflow = (uint16)((period_cyc + (prescaler / 2)) / prescaler); + this->setPrescaleFactor(prescaler); + this->setOverflow(overflow); + return overflow; +} + +void HardwareTimer::setMode(int channel, timer_mode mode) { + timer_set_mode(this->dev, (uint8)channel, (timer_mode)mode); +} + +uint16 HardwareTimer::getCompare(int channel) { + return timer_get_compare(this->dev, (uint8)channel); +} + +void HardwareTimer::setCompare(int channel, uint16 val) { + uint16 ovf = this->getOverflow(); + timer_set_compare(this->dev, (uint8)channel, min(val, ovf)); +} + +void HardwareTimer::attachInterrupt(int channel, voidFuncPtr handler) { + timer_attach_interrupt(this->dev, (uint8)channel, handler); +} + +void HardwareTimer::detachInterrupt(int channel) { + timer_detach_interrupt(this->dev, (uint8)channel); +} + +void HardwareTimer::refresh(void) { + timer_generate_update(this->dev); +} + +/* -- Deprecated predefined instances -------------------------------------- */ + +HardwareTimer Timer1(1); +HardwareTimer Timer2(2); +HardwareTimer Timer3(3); +HardwareTimer Timer4(4); +#ifdef STM32_HIGH_DENSITY +HardwareTimer Timer5(5); +HardwareTimer Timer6(6); +HardwareTimer Timer7(7); +HardwareTimer Timer8(8); +#endif diff --git a/pool/shard010/C++/0111202_LinkerObject.cpp b/pool/shard010/C++/0111202_LinkerObject.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8b7d9e06a1920f948b859c26aed35dbd9252b13a --- /dev/null +++ b/pool/shard010/C++/0111202_LinkerObject.cpp @@ -0,0 +1,79 @@ +/* + This file is part of solidity. + + solidity 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. + + solidity 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 solidity. If not, see . +*/ +/** @file LinkerObject.cpp + * @author Christian R + * @date 2015 + */ + +#include +#include + +using namespace dev; +using namespace dev::eth; +using namespace std; + +void LinkerObject::append(LinkerObject const& _other) +{ + for (auto const& ref: _other.linkReferences) + linkReferences[ref.first + bytecode.size()] = ref.second; + bytecode += _other.bytecode; +} + +void LinkerObject::link(map const& _libraryAddresses) +{ + std::map remainingRefs; + for (auto const& linkRef: linkReferences) + if (h160 const* address = matchLibrary(linkRef.second, _libraryAddresses)) + copy(address->data(), address->data() + 20, bytecode.begin() + linkRef.first); + else + remainingRefs.insert(linkRef); + linkReferences.swap(remainingRefs); +} + +string LinkerObject::toHex() const +{ + string hex = dev::toHex(bytecode); + for (auto const& ref: linkReferences) + { + size_t pos = ref.first * 2; + string const& name = ref.second; + hex[pos] = hex[pos + 1] = hex[pos + 38] = hex[pos + 39] = '_'; + for (size_t i = 0; i < 36; ++i) + hex[pos + 2 + i] = i < name.size() ? name[i] : '_'; + } + return hex; +} + +h160 const* +LinkerObject::matchLibrary( + string const& _linkRefName, + map const& _libraryAddresses +) +{ + auto it = _libraryAddresses.find(_linkRefName); + if (it != _libraryAddresses.end()) + return &it->second; + // If the user did not supply a fully qualified library name, + // try to match only the simple libary name + size_t colon = _linkRefName.find(':'); + if (colon == string::npos) + return nullptr; + it = _libraryAddresses.find(_linkRefName.substr(colon + 1)); + if (it != _libraryAddresses.end()) + return &it->second; + return nullptr; +} diff --git a/pool/shard010/C++/0111204_VRMarker.cpp b/pool/shard010/C++/0111204_VRMarker.cpp new file mode 100644 index 0000000000000000000000000000000000000000..41cb21ff7d7a603596cdab4f593124c0160e7663 --- /dev/null +++ b/pool/shard010/C++/0111204_VRMarker.cpp @@ -0,0 +1,55 @@ +// Copyright 2016 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 "modules/vr/VRMarker.h" + +namespace blink { + +VRMarker::VRMarker(): m_type(0), m_id(0) +{ + m_position = DOMFloat32Array::create(3); + m_orientation = DOMFloat32Array::create(4); +} + +unsigned VRMarker::type() const +{ + return m_type; +} + +unsigned VRMarker::id() const +{ + return m_id; +} + +String VRMarker::content() const +{ + return m_content; +} + +DOMFloat32Array* VRMarker::position() const +{ + return m_position; +} + +DOMFloat32Array* VRMarker::orientation() const +{ + return m_orientation; +} + +void VRMarker::setMarker(const device::mojom::blink::VRMarkerPtr& markerPtr) +{ + m_type = markerPtr->type; + m_id = markerPtr->id; + m_content = markerPtr->content; + memcpy(m_position->data(), &(markerPtr->position.front()), 3 * sizeof(float)); + memcpy(m_orientation->data(), &(markerPtr->orientation.front()), 4 * sizeof(float)); +} + +DEFINE_TRACE(VRMarker) +{ + visitor->trace(m_position); + visitor->trace(m_orientation); +} + +} // namespace blink diff --git a/pool/shard010/C++/0111207_EnhancedPositionClient.cpp b/pool/shard010/C++/0111207_EnhancedPositionClient.cpp new file mode 100644 index 0000000000000000000000000000000000000000..df377649e235b9afdb713936876f5e057051cd05 --- /dev/null +++ b/pool/shard010/C++/0111207_EnhancedPositionClient.cpp @@ -0,0 +1,95 @@ +/* Copyright (C) 2014 Mentor Graphics + * Author: Marco Residori(marco_residori@mentor.com) + * 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 http://mozilla.org/MPL/2.0/. */ + +#include +#include +#include "log.h" + +DLT_DECLARE_CONTEXT(gCtx); + +using namespace org::genivi::EnhancedPositionService; +using namespace org::genivi::EnhancedPositionService::EnhancedPositionServiceTypes; + +void getPositionInfoAsyncCallback(const CommonAPI::CallStatus& callStatus, const EnhancedPositionServiceTypes::Timestamp& timestamp, const EnhancedPositionServiceTypes::PositionInfo& posInfo) +{ + if (callStatus != CommonAPI::CallStatus::SUCCESS) { + LOG_ERROR_MSG(gCtx,"Remote call failed!\n"); + return; + } + + for ( auto it = posInfo.begin(); it != posInfo.end(); ++it ) { + if (it->first == PositionInfoKey::LATITUDE) + { + LOG_INFO(gCtx,"LAT=%lf", it->second.get()); + } + if (it->first == PositionInfoKey::LONGITUDE) + { + LOG_INFO(gCtx,"LON=%lf", it->second.get()); + } + if (it->first == PositionInfoKey::ALTITUDE) + { + LOG_INFO(gCtx,"ALT=%lf", it->second.get()); + } + if (it->first == PositionInfoKey::SPEED) + { + LOG_INFO(gCtx,"SPEED=%lf", it->second.get()); + } + if (it->first == PositionInfoKey::CLIMB) + { + LOG_INFO(gCtx,"CLIMB=%lf", it->second.get()); + } + if (it->first == PositionInfoKey::HEADING) + { + LOG_INFO(gCtx,"HEADING=%lf", it->second.get()); + } + } +} + +void positionUpdate(std::shared_ptr proxy, const EnhancedPositionServiceTypes::Bitmask& changedValues) +{ + LOG_INFO_MSG(gCtx,"Position Update"); + + if(proxy == NULL) + { + LOG_ERROR_MSG(gCtx,"Null pointer!"); + return; + } + + std::function fcb = getPositionInfoAsyncCallback; + + proxy->GetPositionInfoAsync(changedValues,getPositionInfoAsyncCallback); + +} + +int main() { + + DLT_REGISTER_APP("ENHC","ENHANCED-POSITION-CLIENT"); + DLT_REGISTER_CONTEXT(gCtx,"ENHC","Global Context"); + + std::shared_ptr < CommonAPI::Runtime > runtime = CommonAPI::Runtime::load(); + std::shared_ptr < CommonAPI::Factory > factory = runtime->createFactory(); + + const std::string& serviceAddress = "local:org.genivi.positioning.EnhancedPosition:org.genivi.positioning.EnhancedPosition"; + std::shared_ptr myProxy = factory->buildProxy(serviceAddress); + + LOG_INFO_MSG(gCtx,"EnhancedPositionClient"); + + while (!myProxy->isAvailable()) { + usleep(10); + } + + myProxy->getPositionUpdateEvent().subscribe([&](const EnhancedPositionServiceTypes::Bitmask& changedValues) { + positionUpdate(myProxy, changedValues); + }); + + while (true) { + std::this_thread::sleep_for(std::chrono::seconds(5)); + } + + return 0; +} diff --git a/pool/shard010/C++/0111208_CWE23_Relative_Path_Traversal__wchar_t_listen_socket_fopen_45.cpp b/pool/shard010/C++/0111208_CWE23_Relative_Path_Traversal__wchar_t_listen_socket_fopen_45.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8da124f83238a8cc96740141c91be473ad313b54 --- /dev/null +++ b/pool/shard010/C++/0111208_CWE23_Relative_Path_Traversal__wchar_t_listen_socket_fopen_45.cpp @@ -0,0 +1,228 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE23_Relative_Path_Traversal__wchar_t_listen_socket_fopen_45.cpp +Label Definition File: CWE23_Relative_Path_Traversal.label.xml +Template File: sources-sink-45.tmpl.cpp +*/ +/* + * @description + * CWE: 23 Relative Path Traversal + * BadSource: listen_socket Read data using a listen socket (server side) + * GoodSource: Use a fixed file name + * Sinks: fopen + * BadSink : Open the file named in data using fopen() + * 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" + +#ifdef _WIN32 +#define BASEPATH L"c:\\temp\\" +#else +#include +#define BASEPATH L"/tmp/" +#endif + +#ifdef _WIN32 +#include +#include +#include +#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */ +#define CLOSE_SOCKET closesocket +#else +#include +#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 LISTEN_BACKLOG 5 + +#ifdef _WIN32 +#define FOPEN _wfopen +#else +#define FOPEN fopen +#endif + +namespace CWE23_Relative_Path_Traversal__wchar_t_listen_socket_fopen_45 +{ + +static wchar_t * badData; +static wchar_t * goodG2BData; + +#ifndef OMITBAD + +static void badSink() +{ + wchar_t * data = badData; + { + FILE *pFile = NULL; + /* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */ + pFile = FOPEN(data, L"wb+"); + if (pFile != NULL) + { + fclose(pFile); + } + } +} + +void bad() +{ + wchar_t * data; + wchar_t dataBuffer[FILENAME_MAX] = BASEPATH; + data = dataBuffer; + { +#ifdef _WIN32 + WSADATA wsaData; + int wsaDataInit = 0; +#endif + int recvResult; + struct sockaddr_in service; + wchar_t *replace; + SOCKET listenSocket = INVALID_SOCKET; + SOCKET acceptSocket = INVALID_SOCKET; + size_t dataLen = wcslen(data); + do + { +#ifdef _WIN32 + if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) + { + break; + } + wsaDataInit = 1; +#endif + /* POTENTIAL FLAW: Read data using a listen socket */ + listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (listenSocket == INVALID_SOCKET) + { + break; + } + memset(&service, 0, sizeof(service)); + service.sin_family = AF_INET; + service.sin_addr.s_addr = INADDR_ANY; + service.sin_port = htons(TCP_PORT); + if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) + { + break; + } + if (listen(listenSocket, LISTEN_BACKLOG) == SOCKET_ERROR) + { + break; + } + acceptSocket = accept(listenSocket, NULL, NULL); + if (acceptSocket == SOCKET_ERROR) + { + break; + } + /* Abort on error or the connection was closed */ + recvResult = recv(acceptSocket, (char *)(data + dataLen), sizeof(wchar_t) * (FILENAME_MAX - dataLen - 1), 0); + if (recvResult == SOCKET_ERROR || recvResult == 0) + { + break; + } + /* Append null terminator */ + data[dataLen + recvResult / sizeof(wchar_t)] = L'\0'; + /* Eliminate CRLF */ + replace = wcschr(data, L'\r'); + if (replace) + { + *replace = L'\0'; + } + replace = wcschr(data, L'\n'); + if (replace) + { + *replace = L'\0'; + } + } + while (0); + if (listenSocket != INVALID_SOCKET) + { + CLOSE_SOCKET(listenSocket); + } + if (acceptSocket != INVALID_SOCKET) + { + CLOSE_SOCKET(acceptSocket); + } +#ifdef _WIN32 + if (wsaDataInit) + { + WSACleanup(); + } +#endif + } + badData = data; + badSink(); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B() uses the GoodSource with the BadSink */ +static void goodG2BSink() +{ + wchar_t * data = goodG2BData; + { + FILE *pFile = NULL; + /* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */ + pFile = FOPEN(data, L"wb+"); + if (pFile != NULL) + { + fclose(pFile); + } + } +} + +static void goodG2B() +{ + wchar_t * data; + wchar_t dataBuffer[FILENAME_MAX] = BASEPATH; + data = dataBuffer; + /* FIX: Use a fixed file name */ + wcscat(data, L"file.txt"); + goodG2BData = data; + goodG2BSink(); +} + +void good() +{ + goodG2B(); +} + +#endif /* OMITGOOD */ + +} /* close namespace */ + +/* 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 + +using namespace CWE23_Relative_Path_Traversal__wchar_t_listen_socket_fopen_45; /* so that we can use good and bad easily */ + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard010/C++/0111210_catalog_proxy.cpp b/pool/shard010/C++/0111210_catalog_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9cc03ddb325dd442e79885db5dd885233b1ad150 --- /dev/null +++ b/pool/shard010/C++/0111210_catalog_proxy.cpp @@ -0,0 +1,92 @@ +//===----------------------------------------------------------------------===// +// +// Peloton +// +// catalog_proxy.cpp +// +// Identification: src/codegen/proxy/catalog_proxy.cpp +// +// Copyright (c) 2015-2017, Carnegie Mellon University Database Group +// +//===----------------------------------------------------------------------===// + +#include "codegen/proxy/catalog_proxy.h" + +#include "codegen/proxy/data_table_proxy.h" +#include "storage/storage_manager.h" + +namespace peloton { +namespace codegen { + +//===----------------------------------------------------------------------===// +// Return the LLVM type that matches the memory layout of our Database class +//===----------------------------------------------------------------------===// +llvm::Type* CatalogProxy::GetType(CodeGen& codegen) { + static const std::string kCatalogTypeName = + "peloton::storage::StorageManager"; + // Check if the type is already registered in the module, if so return it + auto* catalog_type = codegen.LookupTypeByName(kCatalogTypeName); + if (catalog_type != nullptr) { + return catalog_type; + } + + // Right now we don't need to define each individual field of storage::Catalog + // since we only invoke functions on the class. + static constexpr uint64_t catalog_obj_size = + sizeof(storage::StorageManager); + /* + static constexpr uint64_t catalog_obj_size = sizeof(std::atomic) + + sizeof(lookup_dir) + + sizeof(std::mutex) + + sizeof(std::vector) + + sizeof(std::mutex); + static_assert( + catalog_obj_size == sizeof(catalog::Catalog), + "LLVM memory layout of catalog::Catalog doesn't match precompiled" + "version. Did you forget to update codegen/catalog_proxy.h?"); + */ + auto* byte_arr_type = + llvm::ArrayType::get(codegen.Int8Type(), catalog_obj_size); + catalog_type = llvm::StructType::create(codegen.GetContext(), {byte_arr_type}, + kCatalogTypeName); + return catalog_type; +} + +//===----------------------------------------------------------------------===// +// Return the symbol of the Catalog::GetTableWithOid() function +//===----------------------------------------------------------------------===// +const std::string& CatalogProxy::_GetTableWithOid::GetFunctionName() { + static const std::string kGetTableByIdFnName = +#ifdef __APPLE__ + "_ZNK7peloton7storage14StorageManager15GetTableWithOidEjj"; +#else + "_ZNK7peloton7storage14StorageManager15GetTableWithOidEjj"; +#endif + return kGetTableByIdFnName; +} + +//===----------------------------------------------------------------------===// +// Return the LLVM function definition for Catalog::GetTableWithOid() +//===----------------------------------------------------------------------===// +llvm::Function* CatalogProxy::_GetTableWithOid::GetFunction(CodeGen& codegen) { + const std::string& fn_name = GetFunctionName(); + + // Has the function already been registered? + llvm::Function* llvm_fn = codegen.LookupFunction(fn_name); + if (llvm_fn != nullptr) { + return llvm_fn; + } + + // The function hasn't been registered, let's do it now + llvm::Type* catalog_type = CatalogProxy::GetType(codegen); + llvm::Type* table_type = DataTableProxy::GetType(codegen); + std::vector fn_args{catalog_type->getPointerTo(), + codegen.Int32Type(), // database id + codegen.Int32Type()}; // table id + llvm::FunctionType* fn_type = + llvm::FunctionType::get(table_type->getPointerTo(), fn_args, false); + return codegen.RegisterFunction(fn_name, fn_type); +} + +} // namespace codegen +} // namespace peloton diff --git a/pool/shard010/C++/0111212_helpers.cpp b/pool/shard010/C++/0111212_helpers.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7efe642eb629480616c80ebf8946e6c6e2c1eb05 --- /dev/null +++ b/pool/shard010/C++/0111212_helpers.cpp @@ -0,0 +1,59 @@ +#include "helpers.h" +#include // trim() +#include + +/***************************** LOCAL FUNCTIONS *******************************/ + +/****************************************************************************** + * http://stackoverflow.com/questions/236129/how-to-split-a-string-in-c + ******************************************************************************/ +std::vector& split(const std::string& s, char delim, std::vector& elems) +{ + std::stringstream ss(s); + std::string item; + while (std::getline(ss, item, delim)) + if (!item.empty()) // don't add "" + elems.push_back(item); + + return elems; +} + +/*************************** HELPERS.H FUNCTIONS *****************************/ + +// use boost for trimming... +void trim(std::string& str) +{ + boost::trim(str); +} + +/****************************************************************************** + * split() + * http://stackoverflow.com/questions/236129/how-to-split-a-string-in-c + ******************************************************************************/ +std::vector split(const std::string& s, char delim) +{ + std::vector elems; + split(s, delim, elems); + return elems; +} + +/****************************************************************************** + * shortName() + * - returns the short version of the given filename + * - example: "./plugins/hello.so" => "hello" + ******************************************************************************/ +std::string shortName(const std::string& filename) +{ + std::string result = filename; + std::string::size_type pos = result.find_last_of("/") + 1; // strip leading dirs + result = result.substr(pos); + std::string extension = ".so"; // strip .so extension (if any) + pos = result.find(extension); + if (pos != std::string::npos) + result = result.substr(0, pos); + extension = ".dll"; // strip .dll extension (if any) + pos = result.find(extension); + if (pos != std::string::npos) + result = result.substr(0, pos); + return result; +} diff --git a/pool/shard010/C++/0111214_DWARFDebugArangeSet.cpp b/pool/shard010/C++/0111214_DWARFDebugArangeSet.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b1eb27299efb87ff89601574729059770a7aa801 --- /dev/null +++ b/pool/shard010/C++/0111214_DWARFDebugArangeSet.cpp @@ -0,0 +1,274 @@ +//===-- DWARFDebugArangeSet.cpp ---------------------------------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#include "DWARFDebugArangeSet.h" + +#include +#include "lldb/Core/Stream.h" +#include "SymbolFileDWARF.h" + +using namespace lldb_private; + +DWARFDebugArangeSet::DWARFDebugArangeSet() : + m_offset(DW_INVALID_OFFSET), + m_header(), + m_arange_descriptors() +{ + m_header.length = 0; + m_header.version = 0; + m_header.cu_offset = 0; + m_header.addr_size = 0; + m_header.seg_size = 0; +} + +void +DWARFDebugArangeSet::Clear() +{ + m_offset = DW_INVALID_OFFSET; + m_header.length = 0; + m_header.version = 0; + m_header.cu_offset = 0; + m_header.addr_size = 0; + m_header.seg_size = 0; + m_arange_descriptors.clear(); +} + +void +DWARFDebugArangeSet::SetHeader +( + uint16_t version, + uint32_t cu_offset, + uint8_t addr_size, + uint8_t seg_size +) +{ + m_header.version = version; + m_header.cu_offset = cu_offset; + m_header.addr_size = addr_size; + m_header.seg_size = seg_size; +} + +void +DWARFDebugArangeSet::Compact() +{ + if (m_arange_descriptors.empty()) + return; + + // Iterate through all arange descriptors and combine any ranges that + // overlap or have matching boundaries. The m_arange_descriptors are assumed + // to be in ascending order after being built by adding descriptors + // using the AddDescriptor method. + uint32_t i = 0; + while (i + 1 < m_arange_descriptors.size()) + { + if (m_arange_descriptors[i].end_address() >= m_arange_descriptors[i+1].address) + { + // The current range ends at or exceeds the start of the next address range. + // Compute the max end address between the two and use that to make the new + // length. + const dw_addr_t max_end_addr = std::max(m_arange_descriptors[i].end_address(), m_arange_descriptors[i+1].end_address()); + m_arange_descriptors[i].length = max_end_addr - m_arange_descriptors[i].address; + // Now remove the next entry as it was just combined with the previous one. + m_arange_descriptors.erase(m_arange_descriptors.begin()+i+1); + } + else + { + // Discontiguous address range, just proceed to the next one. + ++i; + } + } +} +//---------------------------------------------------------------------- +// Compare function DWARFDebugArangeSet::Descriptor structures +//---------------------------------------------------------------------- +static bool DescriptorLessThan (const DWARFDebugArangeSet::Descriptor& range1, const DWARFDebugArangeSet::Descriptor& range2) +{ + return range1.address < range2.address; +} + +//---------------------------------------------------------------------- +// Add a range descriptor and keep things sorted so we can easily +// compact the ranges before being saved or used. +//---------------------------------------------------------------------- +void +DWARFDebugArangeSet::AddDescriptor(const DWARFDebugArangeSet::Descriptor& range) +{ + if (m_arange_descriptors.empty()) + { + m_arange_descriptors.push_back(range); + return; + } + + DescriptorIter end = m_arange_descriptors.end(); + DescriptorIter pos = lower_bound(m_arange_descriptors.begin(), end, range, DescriptorLessThan); + const dw_addr_t range_end_addr = range.end_address(); + if (pos != end) + { + const dw_addr_t found_end_addr = pos->end_address(); + if (range.address < pos->address) + { + if (range_end_addr < pos->address) + { + // Non-contiguous entries, add this one before the found entry + m_arange_descriptors.insert(pos, range); + } + else if (range_end_addr == pos->address) + { + // The top end of 'range' is the lower end of the entry + // pointed to by 'pos'. We can combine range with the + // entry we found by setting the starting address and + // increasing the length since they don't overlap. + pos->address = range.address; + pos->length += range.length; + } + else + { + // We can combine these two and make sure the largest end + // address is used to make end address. + pos->address = range.address; + pos->length = std::max(found_end_addr, range_end_addr) - pos->address; + } + } + else if (range.address == pos->address) + { + pos->length = std::max(pos->length, range.length); + } + } + else + { + // NOTE: 'pos' points to entry past the end which is ok for insert, + // don't use otherwise!!! + const dw_addr_t max_addr = m_arange_descriptors.back().end_address(); + if (max_addr < range.address) + { + // Non-contiguous entries, add this one before the found entry + m_arange_descriptors.insert(pos, range); + } + else if (max_addr == range.address) + { + m_arange_descriptors.back().length += range.length; + } + else + { + m_arange_descriptors.back().length = std::max(max_addr, range_end_addr) - m_arange_descriptors.back().address; + } + } +} + +bool +DWARFDebugArangeSet::Extract(const DataExtractor &data, lldb::offset_t *offset_ptr) +{ + if (data.ValidOffset(*offset_ptr)) + { + m_arange_descriptors.clear(); + m_offset = *offset_ptr; + + // 7.20 Address Range Table + // + // Each set of entries in the table of address ranges contained in + // the .debug_aranges section begins with a header consisting of: a + // 4-byte length containing the length of the set of entries for this + // compilation unit, not including the length field itself; a 2-byte + // version identifier containing the value 2 for DWARF Version 2; a + // 4-byte offset into the.debug_infosection; a 1-byte unsigned integer + // containing the size in bytes of an address (or the offset portion of + // an address for segmented addressing) on the target system; and a + // 1-byte unsigned integer containing the size in bytes of a segment + // descriptor on the target system. This header is followed by a series + // of tuples. Each tuple consists of an address and a length, each in + // the size appropriate for an address on the target architecture. + m_header.length = data.GetU32(offset_ptr); + m_header.version = data.GetU16(offset_ptr); + m_header.cu_offset = data.GetU32(offset_ptr); + m_header.addr_size = data.GetU8(offset_ptr); + m_header.seg_size = data.GetU8(offset_ptr); + + + // The first tuple following the header in each set begins at an offset + // that is a multiple of the size of a single tuple (that is, twice the + // size of an address). The header is padded, if necessary, to the + // appropriate boundary. + const uint32_t header_size = *offset_ptr - m_offset; + const uint32_t tuple_size = m_header.addr_size << 1; + uint32_t first_tuple_offset = 0; + while (first_tuple_offset < header_size) + first_tuple_offset += tuple_size; + + *offset_ptr = m_offset + first_tuple_offset; + + Descriptor arangeDescriptor; + + assert(sizeof(arangeDescriptor.address) == sizeof(arangeDescriptor.length)); + assert(sizeof(arangeDescriptor.address) >= m_header.addr_size); + + while (data.ValidOffset(*offset_ptr)) + { + arangeDescriptor.address = data.GetMaxU64(offset_ptr, m_header.addr_size); + arangeDescriptor.length = data.GetMaxU64(offset_ptr, m_header.addr_size); + + // Each set of tuples is terminated by a 0 for the address and 0 + // for the length. + if (arangeDescriptor.address || arangeDescriptor.length) + m_arange_descriptors.push_back(arangeDescriptor); + else + break; // We are done if we get a zero address and length + } + + return !m_arange_descriptors.empty(); + } + return false; +} + + +dw_offset_t +DWARFDebugArangeSet::GetOffsetOfNextEntry() const +{ + return m_offset + m_header.length + 4; +} + + +void +DWARFDebugArangeSet::Dump(Stream *s) const +{ + s->Printf("Address Range Header: length = 0x%8.8x, version = 0x%4.4x, cu_offset = 0x%8.8x, addr_size = 0x%2.2x, seg_size = 0x%2.2x\n", + m_header.length ,m_header.version, m_header.cu_offset, m_header.addr_size, m_header.seg_size); + + const uint32_t hex_width = m_header.addr_size * 2; + DescriptorConstIter pos; + DescriptorConstIter end = m_arange_descriptors.end(); + for (pos = m_arange_descriptors.begin(); pos != end; ++pos) + s->Printf("[0x%*.*" PRIx64 " - 0x%*.*" PRIx64 ")\n", + hex_width, hex_width, pos->address, + hex_width, hex_width, pos->end_address()); +} + + +class DescriptorContainsAddress +{ +public: + DescriptorContainsAddress (dw_addr_t address) : m_address(address) {} + bool operator() (const DWARFDebugArangeSet::Descriptor& desc) const + { + return (m_address >= desc.address) && (m_address < (desc.address + desc.length)); + } + private: + const dw_addr_t m_address; +}; + +dw_offset_t +DWARFDebugArangeSet::FindAddress(dw_addr_t address) const +{ + DescriptorConstIter end = m_arange_descriptors.end(); + DescriptorConstIter pos = std::find_if( m_arange_descriptors.begin(), end, // Range + DescriptorContainsAddress(address));// Predicate + if (pos != end) + return m_header.cu_offset; + + return DW_INVALID_OFFSET; +} diff --git a/pool/shard010/C++/0111216_lru.cc b/pool/shard010/C++/0111216_lru.cc new file mode 100644 index 0000000000000000000000000000000000000000..a84e08bdd1d748537278ccb9e428bad0721c0f3c --- /dev/null +++ b/pool/shard010/C++/0111216_lru.cc @@ -0,0 +1,62 @@ +/* + * \brief Least-recently-used cache replacement strategy + * \author Stefan Kalkowski + * \date 2013-12-05 + */ + +/* + * Copyright (C) 2013 Genode Labs GmbH + * + * This file is part of the Genode OS framework, which is distributed + * under the terms of the GNU General Public License version 2. + */ +#include +#include "lru.h" +#include "driver.h" + +typedef Driver::Chunk_level_4 Chunk; + +static const Lru_policy::Element *lru = 0; +static Genode::List lru_list; + + +static void lru_access(const Lru_policy::Element *e) +{ + if (e == lru) return; + + if (e->next()) lru_list.remove(e); + + lru_list.insert(e, lru); + lru = e; +} + + +void Lru_policy::read(const Lru_policy::Element *e) { + lru_access(e); } + + +void Lru_policy::write(const Lru_policy::Element *e) { + lru_access(e); } + + +void Lru_policy::flush(Cache::size_t size) +{ + Cache::size_t s = 0; + for (Lru_policy::Element *e = lru_list.first(); + e && ((size == 0) || (s < size)); + e = lru_list.first(), s += sizeof(Chunk)) { + Chunk *cb = static_cast(e); + e = e->next(); + try { + cb->free(Driver::CACHE_BLK_SIZE, + cb->base_offset()); + lru_list.remove(cb); + } catch(Chunk::Dirty_chunk &e) { + cb->sync(e.size, e.off); + } + } + + if (!lru_list.first()) lru = 0; + + if (s < size) throw Block::Driver::Request_congestion(); +} diff --git a/pool/shard010/C++/0111221_mirror_layer_impl.cc b/pool/shard010/C++/0111221_mirror_layer_impl.cc new file mode 100644 index 0000000000000000000000000000000000000000..743a80b2f809e61e9babc15ef23bc6a912f1b4df --- /dev/null +++ b/pool/shard010/C++/0111221_mirror_layer_impl.cc @@ -0,0 +1,91 @@ +// Copyright 2019 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/layers/mirror_layer_impl.h" + +#include + +#include "cc/trees/effect_node.h" +#include "cc/trees/layer_tree_impl.h" +#include "cc/trees/occlusion.h" +#include "components/viz/common/quads/compositor_render_pass_draw_quad.h" + +namespace cc { + +MirrorLayerImpl::MirrorLayerImpl(LayerTreeImpl* tree_impl, int id) + : LayerImpl(tree_impl, id) {} + +MirrorLayerImpl::~MirrorLayerImpl() = default; + +std::unique_ptr MirrorLayerImpl::CreateLayerImpl( + LayerTreeImpl* tree_impl) { + return MirrorLayerImpl::Create(tree_impl, id()); +} + +void MirrorLayerImpl::AppendQuads(viz::CompositorRenderPass* render_pass, + AppendQuadsData* append_quads_data) { + // TODO(mohsen): Currently, effects on the mirrored layer (e.g mask and + // opacity) are ignored. Consider applying them here. + + auto* mirrored_layer = layer_tree_impl()->LayerById(mirrored_layer_id_); + auto* mirrored_render_surface = + GetEffectTree().GetRenderSurface(mirrored_layer->effect_tree_index()); + gfx::Rect content_rect = mirrored_render_surface->content_rect(); + + gfx::Rect unoccluded_content_rect = + draw_properties().occlusion_in_content_space.GetUnoccludedContentRect( + content_rect); + if (unoccluded_content_rect.IsEmpty()) + return; + + const bool contents_opaque = false; + viz::SharedQuadState* shared_quad_state = + render_pass->CreateAndAppendSharedQuadState(); + // TODO(crbug.com/1196414): Support 2D scales in mirror layers. + PopulateScaledSharedQuadStateWithContentRects( + shared_quad_state, mirrored_layer->GetIdealContentsScaleKey(), + content_rect, content_rect, contents_opaque); + + AppendDebugBorderQuad(render_pass, content_rect, shared_quad_state, + append_quads_data); + + viz::ResourceId mask_resource_id = viz::kInvalidResourceId; + gfx::RectF mask_uv_rect; + gfx::Size mask_texture_size; + + auto* mirrored_effect_node = mirrored_render_surface->OwningEffectNode(); + auto* quad = + render_pass->CreateAndAppendDrawQuad(); + quad->SetNew(shared_quad_state, content_rect, unoccluded_content_rect, + mirrored_layer_render_pass_id(), mask_resource_id, mask_uv_rect, + mask_texture_size, mirrored_effect_node->surface_contents_scale, + gfx::PointF(), gfx::RectF(gfx::Rect(content_rect.size())), + !layer_tree_impl()->settings().enable_edge_anti_aliasing, 0.f); +} + +void MirrorLayerImpl::PushPropertiesTo(LayerImpl* layer) { + LayerImpl::PushPropertiesTo(layer); + + auto* mirror_layer = static_cast(layer); + mirror_layer->SetMirroredLayerId(mirrored_layer_id_); +} + +gfx::Rect MirrorLayerImpl::GetDamageRect() const { + // TOOD(mohsen): Currently, the whole layer is marked as damaged. We should + // only consider the damage from the mirrored layer. + return gfx::Rect(bounds()); +} + +gfx::Rect MirrorLayerImpl::GetEnclosingVisibleRectInTargetSpace() const { + const LayerImpl* mirrored_layer = + layer_tree_impl()->LayerById(mirrored_layer_id_); + return GetScaledEnclosingVisibleRectInTargetSpace( + mirrored_layer->GetIdealContentsScaleKey()); +} + +const char* MirrorLayerImpl::LayerTypeAsString() const { + return "cc::MirrorLayerImpl"; +} + +} // namespace cc diff --git a/pool/shard010/C++/0111222_switch.cc b/pool/shard010/C++/0111222_switch.cc new file mode 100644 index 0000000000000000000000000000000000000000..bb8c9856742963b73f2f03ed21e59624611b65d7 --- /dev/null +++ b/pool/shard010/C++/0111222_switch.cc @@ -0,0 +1,217 @@ + /*// us file is part of NOX. + * + * NOX 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. + * + * NOX 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 NOX. If not, see . + */ +#include +#include +#include +#include +#include +#include +#include + +#include "openflow-default.hh" +#include "assert.hh" +#include "component.hh" +#include "flow.hh" +#include "fnv_hash.hh" +#include "hash_set.hh" +#include "ofp-msg-event.hh" +#include "vlog.hh" +#include "flowmod.hh" +#include "datapath-join.hh" +#include + +#include +#include "netinet++/ethernetaddr.hh" +#include "netinet++/ethernet.hh" + +#include "../../../oflib/ofl-actions.h" +#include "../../../oflib/ofl-messages.h" + +using namespace vigil; +using namespace vigil::container; +using namespace std; + +namespace { + +struct Mac_source +{ + /* Key. */ + datapathid datapath_id; /* Switch. */ + ethernetaddr mac; /* Source MAC. */ + + /* Value. */ + mutable int port; /* Port where packets from 'mac' were seen. */ + + Mac_source() : port(-1) { } + Mac_source(datapathid datapath_id_, ethernetaddr mac_) + : datapath_id(datapath_id_), mac(mac_), port(-1) + { } +}; + +bool operator==(const Mac_source& a, const Mac_source& b) +{ + return a.datapath_id == b.datapath_id && a.mac == b.mac; +} + +bool operator!=(const Mac_source& a, const Mac_source& b) +{ + return !(a == b); +} + +struct Hash_mac_source +{ + std::size_t operator()(const Mac_source& val) const { + uint32_t x; + x = vigil::fnv_hash(&val.datapath_id, sizeof val.datapath_id); + x = vigil::fnv_hash(val.mac.octet, sizeof val.mac.octet, x); + return x; + } +}; + +Vlog_module log("switch"); + +class Switch + : public Component +{ +public: + Switch(const Context* c, + const json_object*) + : Component(c) { } + + void configure(const Configuration*); + + void install(); + + Disposition handle(const Event&); + //Disposition handle_dp_join(const Event& e); +private: + typedef hash_set Source_table; + Source_table sources; + + /* Set up a flow when we know the destination of a packet? This should + * ordinarily be true; it is only usefully false for debugging purposes. */ + bool setup_flows; +}; + +void +Switch::configure(const Configuration* conf) { + setup_flows = true; // default value + BOOST_FOREACH (const std::string& arg, conf->get_arguments()) { + if (arg == "noflow") { + setup_flows = false; + } else { + VLOG_WARN(log, "argument \"%s\" not supported", arg.c_str()); + } + } + + register_handler(Ofp_msg_event::get_name(OFPT_PACKET_IN), boost::bind(&Switch::handle, this, _1)); + +} + +void +Switch::install() { + +} + +Disposition +Switch::handle(const Event& e) +{ + const Ofp_msg_event& pi = assert_cast(e); + + struct ofl_msg_packet_in *in = (struct ofl_msg_packet_in *)**pi.msg; + Flow *flow = new Flow((struct ofl_match*) in->match); + + /* drop all LLDP packets */ + uint16_t dl_type; + flow->get_Field("eth_type",&dl_type); + if (dl_type == ethernet::LLDP){ + return CONTINUE; + } + + uint32_t in_port; + flow->get_Field("in_port", &in_port); + + + /* Learn the source. */ + uint8_t eth_src[6]; + flow->get_Field("eth_src", eth_src); + ethernetaddr dl_src(eth_src); + if (!dl_src.is_multicast()) { + Mac_source src(pi.dpid, dl_src); + Source_table::iterator i = sources.insert(src).first; + + if (i->port != in_port) { + i->port = in_port; + VLOG_DBG(log, "learned that "EA_FMT" is on datapath %s port %d", + EA_ARGS(&dl_src), pi.dpid.string().c_str(), + (int) in_port); + } + } else { + VLOG_DBG(log, "multicast packet source "EA_FMT, EA_ARGS(&dl_src)); + } + + /* Figure out the destination. */ + int out_port = -1; /* Flood by default. */ + uint8_t eth_dst[6]; + flow->get_Field("eth_dst", eth_dst); + ethernetaddr dl_dst(eth_dst); + if (!dl_dst.is_multicast()) { + Mac_source dst(pi.dpid, dl_dst); + Source_table::iterator i(sources.find(dst)); + if (i != sources.end()) { + out_port = i->port; + } + } + + /* Set up a flow if the output port is known. */ + if (setup_flows && out_port != -1) { + + + Flow f; + f.Add_Field("in_port", in_port); + f.Add_Field("eth_src", eth_src); + f.Add_Field("eth_dst",eth_dst); + Actions *acts = new Actions(); + acts->CreateOutput(out_port); + Instruction *inst = new Instruction(); + inst->CreateApply(acts); + FlowMod *mod = new FlowMod(0x00ULL,0x00ULL, 0,OFPFC_ADD, 1, OFP_FLOW_PERMANENT, OFP_DEFAULT_PRIORITY,in->buffer_id, + OFPP_ANY, OFPG_ANY, ofd_flow_mod_flags()); + mod->AddMatch(&f.match); + mod->AddInstructions(inst); + send_openflow_msg(pi.dpid, (struct ofl_msg_header *)&mod->fm_msg, 0/*xid*/, true/*block*/); + } + /* Send out packet if necessary. */ + if (!setup_flows || out_port == -1 || in->buffer_id == UINT32_MAX) { + if (in->buffer_id == UINT32_MAX) { + if (in->total_len != in->data_length) { + /* Control path didn't buffer the packet and didn't send us + * the whole thing--what gives? */ + VLOG_DBG(log, "total_len=%"PRIu16" data_len=%zu\n", + in->total_len, in->data_length); + return CONTINUE; + } + send_openflow_pkt(pi.dpid, Nonowning_buffer(in->data, in->data_length), in_port, out_port == -1 ? OFPP_FLOOD : out_port, true/*block*/); + } else { + send_openflow_pkt(pi.dpid, in->buffer_id, in_port, out_port == -1 ? OFPP_FLOOD : out_port, true/*block*/); + } + } + return CONTINUE; +} + +REGISTER_COMPONENT(container::Simple_component_factory, Switch); + +} // unnamed namespacennamed namespace diff --git a/pool/shard010/C++/0111225_bitcoind.cpp b/pool/shard010/C++/0111225_bitcoind.cpp new file mode 100644 index 0000000000000000000000000000000000000000..69479e14a7325ed2a9a2004254b2e967d14e2a95 --- /dev/null +++ b/pool/shard010/C++/0111225_bitcoind.cpp @@ -0,0 +1,141 @@ +// Copyright (c) 2009-2010 Satoshi Nakamoto +// Copyright (c) 2009-2012 The Bitcoin developers +// Distributed under the MIT/X11 software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "init.h" +#include "bitcoinrpc.h" +#include + +void DetectShutdownThread(boost::thread_group* threadGroup) +{ + bool shutdown = ShutdownRequested(); + // Tell the main threads to shutdown. + while (!shutdown) + { + MilliSleep(200); + shutdown = ShutdownRequested(); + } + if (threadGroup) + threadGroup->interrupt_all(); +} + +////////////////////////////////////////////////////////////////////////////// +// +// Start +// +bool AppInit(int argc, char* argv[]) +{ + boost::thread_group threadGroup; + boost::thread* detectShutdownThread = NULL; + + bool fRet = false; + try + { + // + // Parameters + // + // If Qt is used, parameters/fireflycoin.conf are parsed in qt/bitcoin.cpp's main() + ParseParameters(argc, argv); + if (!boost::filesystem::is_directory(GetDataDir(false))) + { + fprintf(stderr, "Error: Specified directory does not exist\n"); + Shutdown(); + } + ReadConfigFile(mapArgs, mapMultiArgs); + + if (mapArgs.count("-?") || mapArgs.count("--help")) + { + // First part of help message is specific to fireflycoind / RPC client + std::string strUsage = _("FireFlyCoin version") + " " + FormatFullVersion() + "\n\n" + + _("Usage:") + "\n" + + " fireflycoind [options] " + "\n" + + " fireflycoind [options] [params] " + _("Send command to -server or fireflycoind") + "\n" + + " fireflycoind [options] help " + _("List commands") + "\n" + + " fireflycoind [options] help " + _("Get help for a command") + "\n"; + + strUsage += "\n" + HelpMessage(); + + fprintf(stdout, "%s", strUsage.c_str()); + return false; + } + + // Command-line RPC + for (int i = 1; i < argc; i++) + if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "fireflycoin:")) + fCommandLine = true; + + if (fCommandLine) + { + if (!SelectParamsFromCommandLine()) { + fprintf(stderr, "Error: invalid combination of -regtest and -testnet.\n"); + return false; + } + int ret = CommandLineRPC(argc, argv); + exit(ret); + } +#if !defined(WIN32) + fDaemon = GetBoolArg("-daemon", false); + if (fDaemon) + { + // Daemonize + pid_t pid = fork(); + if (pid < 0) + { + fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno); + return false; + } + if (pid > 0) // Parent process, pid is child process id + { + CreatePidFile(GetPidFile(), pid); + return true; + } + // Child process falls through to rest of initialization + + pid_t sid = setsid(); + if (sid < 0) + fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno); + } +#endif + + detectShutdownThread = new boost::thread(boost::bind(&DetectShutdownThread, &threadGroup)); + fRet = AppInit2(threadGroup); + } + catch (std::exception& e) { + PrintExceptionContinue(&e, "AppInit()"); + } catch (...) { + PrintExceptionContinue(NULL, "AppInit()"); + } + if (!fRet) { + if (detectShutdownThread) + detectShutdownThread->interrupt(); + threadGroup.interrupt_all(); + } + + if (detectShutdownThread) + { + detectShutdownThread->join(); + delete detectShutdownThread; + detectShutdownThread = NULL; + } + Shutdown(); + + return fRet; +} + +extern void noui_connect(); +int main(int argc, char* argv[]) +{ + bool fRet = false; + fHaveGUI = false; + + // Connect fireflycoind signal handlers + noui_connect(); + + fRet = AppInit(argc, argv); + + if (fRet && fDaemon) + return 0; + + return (fRet ? 0 : 1); +} diff --git a/pool/shard010/C++/0111231_chapter24_ex10.cpp b/pool/shard010/C++/0111231_chapter24_ex10.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d5e5dcb33c0f376304c8c5ae7f80155b39787af4 --- /dev/null +++ b/pool/shard010/C++/0111231_chapter24_ex10.cpp @@ -0,0 +1,48 @@ +// Chapter 24, exercise 10: test rand(); write a program that takes two integers +// n and d and calls randint(n) d times; output the number of draws for each +// [0:n) and see if there are any obvious biases + +#include +#include +#include +#include +#include + +using namespace std; + +inline int randint(int max) { return rand()%max; } + +inline int randint(int min, int max) { return randint(max-min)+min; } + +int main() +try +{ + while (true) { + cout << "Enter biggest number: "; + int n; + cin >> n; + cout << "Enter number of draws (0 to exit): "; + int d; + cin >> d; + if (d==0) break; + srand(time(0)); + + int r = 0; + map histo; + for (int i = 0; i. +*/ +#include "../loop/loop_main.h" +#include "../class/class_main.h" +#include "../net/net_main.h" +#include "../client/c_main.h" +#include "../net/net_const.h" +#include "c_net_engine.h" + +extern bool once_per_second; +extern bool terminate; + +array_id_t host_info_id = 0; +array_id_t self_info_id = 0; +extern array_id_t self_id; + +extern int_ argc_; +extern char **argv_; + +net_t *net = nullptr; + +static loop_t *net_loop_mt; + +static void net_module_loop(){ + net->loop(); +} + +static void net_connect_send(){ + ((net_ip_connection_info_t*)find_pointer(host_info_id, "net_ip_connection_info_t"))->array.print(); + std::string packet = ((net_ip_connection_info_t*)find_pointer(self_info_id, "net_ip_connection_info_t"))->array.gen_updated_string(INT_MAX) + NET_JOIN; + net->write(packet, 0, host_info_id); +} + +static void net_connect_receive(std::string connecting_packet){ + if(connecting_packet != ""){ + connecting_packet.erase(connecting_packet.begin()+connecting_packet.find_first_of(NET_JOIN)); + self_id = std::stoi(connecting_packet); + } +} + +static void net_receive_engine(){ + for(int_ i = 0;i < 512;i++){ + std::string a = net->read(); + if(a.find_first_of(NET_JOIN) != std::string::npos){ + printf_("DEBUG: Received the NET_JOIN packet\n", PRINTF_DEBUG); + net_connect_receive(a); + }else if(a != ""){ + update_class_data(a, ~0); + }else{ + break; + } + } +} + +static void net_send_engine(){ + try{ + client_t *client_tmp = (client_t*)find_pointer(self_id, "client_t"); + throw_if_nullptr(client_tmp); + client_tmp->array.data_lock.lock(); + int_ what_to_update; + if(likely(once_per_second == false)){ + client_tmp->array.updated(&what_to_update); + }else{ + what_to_update = INT_MIN; + } + std::string data = client_tmp->array.gen_updated_string(what_to_update); + client_tmp->array.data_lock.unlock(); + net->write(data.c_str(), 0, host_info_id); + }catch(const std::logic_error &e){ + printf_("WARNING: self_id isn't valid, this should pass\n", PRINTF_UNLIKELY_WARN); + } +} + +void net_init(){ + loop_add(loop, loop_generate_entry(0, "net_engine", net_engine)); + net_loop_mt = new loop_t; + loop_add(net_loop_mt, loop_generate_entry(LOOP_CODE_PARTIAL_MT, "net_module_loop", net_module_loop)); + loop_add(net_loop_mt, loop_generate_entry(LOOP_CODE_PARTIAL_MT, "net_receive_engine", net_receive_engine)); + loop_add(net_loop_mt, loop_generate_entry(LOOP_CODE_PARTIAL_MT, "net_send_engine", net_send_engine)); + net_ip_connection_info_t *self_info = new net_ip_connection_info_t; + net_ip_connection_info_t *host_info = new net_ip_connection_info_t; + self_info->array.data_lock.lock(); + host_info->array.data_lock.lock(); + host_info_id = host_info->array.id; + self_info_id = self_info->array.id; + host_info->ip = "127.0.0.1"; // don't delete the host + self_info->ip = "127.0.0.1"; // the IP address that the server should be sending data to + host_info->port = NET_SERVER_PORT; + self_info->port = NET_CLIENT_PORT; + self_info->array.data_lock.unlock(); + host_info->array.data_lock.unlock(); + bool force_ip = false; + for(int_ i = 0;i < argc_;i++){ + std::string next_item; + if(i+1 < argc_){ + next_item = argv_[i+1]; + }else{ + next_item = ""; + } + if(strcmp(argv_[i], (char*)"--net-ip-server-ip") == 0){ + host_info->ip = (std::string)argv_[i+1]; + }else if(strcmp(argv_[i], (char*)"--net-ip-server-port") == 0){ + host_info->port = atoi((char*)argv_[i+1]); + }else if(strcmp(argv_[i], (char*)"--net-ip-client-ip") == 0){ + if(next_item != ""){ + force_ip = true; + self_info->ip = next_item.c_str(); + } + }else if(strcmp(argv_[i], (char*)"--net-ip-client-port") == 0){ + if(next_item != ""){ + self_info->port = atoi(next_item.c_str()); + } + } + if(next_item == ""){ + printf("There is no next object\n"); + } + } + if(force_ip == false){ + self_info->array.data_lock.lock(); + self_info->ip = net_gen_ip_address(host_info->ip); + self_info->array.data_lock.unlock(); + } + net = new net_t(); + net->set_inbound_info(self_info_id); + net_connect_send(); +} + +void net_engine(){ + loop_run(net_loop_mt); + /* + net_connect_receive is called from inside this loop. + there is no need for first-run code or anything like it + */ +} + +void net_close(){ + if(likely(net != nullptr)){ + delete net; + net = nullptr; + } + loop_del(net_loop_mt, net_module_loop); + loop_del(net_loop_mt, net_send_engine); + loop_del(net_loop_mt, net_receive_engine); + loop_del(loop, net_engine); +} diff --git a/pool/shard010/C++/0111234_print_preview_data_source.cc b/pool/shard010/C++/0111234_print_preview_data_source.cc new file mode 100644 index 0000000000000000000000000000000000000000..808231b346460c69c1fe4fc64d015cf66b59564c --- /dev/null +++ b/pool/shard010/C++/0111234_print_preview_data_source.cc @@ -0,0 +1,178 @@ +// 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/ui/webui/print_preview/print_preview_data_source.h" + +#include +#include + +#include "base/message_loop.h" +#include "base/string_number_conversions.h" +#include "base/string_piece.h" +#include "base/string_split.h" +#include "base/string_util.h" +#include "base/utf_string_conversions.h" +#include "base/values.h" +#include "chrome/browser/printing/print_preview_data_service.h" +#include "chrome/common/url_constants.h" +#include "grit/browser_resources.h" +#include "grit/chromium_strings.h" +#include "grit/generated_resources.h" +#include "grit/google_chrome_strings.h" +#include "ui/base/l10n/l10n_util.h" +#include "ui/base/resource/resource_bundle.h" + +namespace { + +#if defined(OS_MACOSX) +// U+0028 U+21E7 U+2318 U+0050 U+0029 in UTF8 +const char kAdvancedPrintShortcut[] = "\x28\xE2\x8c\xA5\xE2\x8C\x98\x50\x29"; +#elif defined(OS_WIN) +const char kAdvancedPrintShortcut[] = "(Ctrl+Shift+P)"; +#else +const char kAdvancedPrintShortcut[] = "(Shift+Ctrl+P)"; +#endif + +}; // namespace + +PrintPreviewDataSource::PrintPreviewDataSource(bool is_dummy) + : ChromeWebUIDataSource(chrome::kChromeUIPrintHost) { + Init(is_dummy); +} + +void PrintPreviewDataSource::Init(bool is_dummy) { + if (is_dummy) { + AddLocalizedString("intentionallyBlankText", + IDS_PRINT_PREVIEW_INTENTIONALLY_BLANK); + } + + AddLocalizedString("title", IDS_PRINT_PREVIEW_TITLE); + AddLocalizedString("loading", IDS_PRINT_PREVIEW_LOADING); + AddLocalizedString("noPlugin", IDS_PRINT_PREVIEW_NO_PLUGIN); + AddLocalizedString("launchNativeDialog", IDS_PRINT_PREVIEW_NATIVE_DIALOG); + AddLocalizedString("previewFailed", IDS_PRINT_PREVIEW_FAILED); + AddLocalizedString("invalidPrinterSettings", + IDS_PRINT_PREVIEW_INVALID_PRINTER_SETTINGS); + AddLocalizedString("printButton", IDS_PRINT_PREVIEW_PRINT_BUTTON); + AddLocalizedString("saveButton", IDS_PRINT_PREVIEW_SAVE_BUTTON); + AddLocalizedString("cancelButton", IDS_PRINT_PREVIEW_CANCEL_BUTTON); + AddLocalizedString("printing", IDS_PRINT_PREVIEW_PRINTING); + AddLocalizedString("printingToPDFInProgress", + IDS_PRINT_PREVIEW_PRINTING_TO_PDF_IN_PROGRESS); +#if defined(OS_MACOSX) + AddLocalizedString("openingPDFInPreview", + IDS_PRINT_PREVIEW_OPENING_PDF_IN_PREVIEW); +#endif + AddLocalizedString("destinationLabel", IDS_PRINT_PREVIEW_DESTINATION_LABEL); + AddLocalizedString("copiesLabel", IDS_PRINT_PREVIEW_COPIES_LABEL); + AddLocalizedString("examplePageRangeText", + IDS_PRINT_PREVIEW_EXAMPLE_PAGE_RANGE_TEXT); + AddLocalizedString("layoutLabel", IDS_PRINT_PREVIEW_LAYOUT_LABEL); + AddLocalizedString("optionAllPages", IDS_PRINT_PREVIEW_OPTION_ALL_PAGES); + AddLocalizedString("optionBw", IDS_PRINT_PREVIEW_OPTION_BW); + AddLocalizedString("optionCollate", IDS_PRINT_PREVIEW_OPTION_COLLATE); + AddLocalizedString("optionColor", IDS_PRINT_PREVIEW_OPTION_COLOR); + AddLocalizedString("optionLandscape", IDS_PRINT_PREVIEW_OPTION_LANDSCAPE); + AddLocalizedString("optionPortrait", IDS_PRINT_PREVIEW_OPTION_PORTRAIT); + AddLocalizedString("optionTwoSided", IDS_PRINT_PREVIEW_OPTION_TWO_SIDED); + AddLocalizedString("pagesLabel", IDS_PRINT_PREVIEW_PAGES_LABEL); + AddLocalizedString("pageRangeTextBox", IDS_PRINT_PREVIEW_PAGE_RANGE_TEXT); + AddLocalizedString("pageRangeRadio", IDS_PRINT_PREVIEW_PAGE_RANGE_RADIO); + AddLocalizedString("printToPDF", IDS_PRINT_PREVIEW_PRINT_TO_PDF); + AddLocalizedString("printPreviewTitleFormat", IDS_PRINT_PREVIEW_TITLE_FORMAT); + AddLocalizedString("printPreviewSummaryFormatShort", + IDS_PRINT_PREVIEW_SUMMARY_FORMAT_SHORT); + AddLocalizedString("printPreviewSummaryFormatLong", + IDS_PRINT_PREVIEW_SUMMARY_FORMAT_LONG); + AddLocalizedString("printPreviewSheetsLabelSingular", + IDS_PRINT_PREVIEW_SHEETS_LABEL_SINGULAR); + AddLocalizedString("printPreviewSheetsLabelPlural", + IDS_PRINT_PREVIEW_SHEETS_LABEL_PLURAL); + AddLocalizedString("printPreviewPageLabelSingular", + IDS_PRINT_PREVIEW_PAGE_LABEL_SINGULAR); + AddLocalizedString("printPreviewPageLabelPlural", + IDS_PRINT_PREVIEW_PAGE_LABEL_PLURAL); + const string16 shortcut_text(UTF8ToUTF16(kAdvancedPrintShortcut)); +#if defined(OS_CHROMEOS) + AddString("cloudPrintDialogOption", l10n_util::GetStringFUTF16( + IDS_PRINT_PREVIEW_CLOUD_DIALOG_OPTION, + l10n_util::GetStringUTF16(IDS_GOOGLE_CLOUD_PRINT), + shortcut_text)); + AddLocalizedString("printWithCloudPrint", + IDS_PRINT_PREVIEW_MORE_PRINTERS); +#else + AddString("systemDialogOption", l10n_util::GetStringFUTF16( + IDS_PRINT_PREVIEW_SYSTEM_DIALOG_OPTION, + shortcut_text)); + AddString("printWithCloudPrint", l10n_util::GetStringFUTF16( + IDS_PRINT_PREVIEW_PRINT_WITH_CLOUD_PRINT, + l10n_util::GetStringUTF16(IDS_GOOGLE_CLOUD_PRINT))); +#endif +#if defined(OS_MACOSX) + AddLocalizedString("openPdfInPreviewOption", + IDS_PRINT_PREVIEW_OPEN_PDF_IN_PREVIEW_APP); +#endif + AddString("printWithCloudPrintWait", l10n_util::GetStringFUTF16( + IDS_PRINT_PREVIEW_PRINT_WITH_CLOUD_PRINT_WAIT, + l10n_util::GetStringUTF16(IDS_GOOGLE_CLOUD_PRINT))); + AddLocalizedString("pageRangeInstruction", + IDS_PRINT_PREVIEW_PAGE_RANGE_INSTRUCTION); + AddLocalizedString("copiesInstruction", IDS_PRINT_PREVIEW_COPIES_INSTRUCTION); + AddLocalizedString("signIn", IDS_PRINT_PREVIEW_SIGN_IN); + AddLocalizedString("managePrinters", IDS_PRINT_PREVIEW_MANAGE_PRINTERS); + AddLocalizedString("incrementTitle", IDS_PRINT_PREVIEW_INCREMENT_TITLE); + AddLocalizedString("decrementTitle", IDS_PRINT_PREVIEW_DECREMENT_TITLE); + AddLocalizedString("printPagesLabel", IDS_PRINT_PREVIEW_PRINT_PAGES_LABEL); + AddLocalizedString("optionsLabel", IDS_PRINT_PREVIEW_OPTIONS_LABEL); + AddLocalizedString("optionHeaderFooter", + IDS_PRINT_PREVIEW_OPTION_HEADER_FOOTER); + AddLocalizedString("marginsLabel", IDS_PRINT_PREVIEW_MARGINS_LABEL); + AddLocalizedString("defaultMargins", IDS_PRINT_PREVIEW_DEFAULT_MARGINS); + AddLocalizedString("noMargins", IDS_PRINT_PREVIEW_NO_MARGINS); + AddLocalizedString("customMargins", IDS_PRINT_PREVIEW_CUSTOM_MARGINS); + AddLocalizedString("minimumMargins", IDS_PRINT_PREVIEW_MINIMUM_MARGINS); + AddLocalizedString("top", IDS_PRINT_PREVIEW_TOP_MARGIN_LABEL); + AddLocalizedString("bottom", IDS_PRINT_PREVIEW_BOTTOM_MARGIN_LABEL); + AddLocalizedString("left", IDS_PRINT_PREVIEW_LEFT_MARGIN_LABEL); + AddLocalizedString("right", IDS_PRINT_PREVIEW_RIGHT_MARGIN_LABEL); + + set_json_path("strings.js"); + if (is_dummy) { + add_resource_path("print_preview_dummy.js", IDR_PRINT_PREVIEW_DUMMY_JS); + set_default_resource(IDR_PRINT_PREVIEW_DUMMY_HTML); + } else { + add_resource_path("print_preview.js", IDR_PRINT_PREVIEW_JS); + set_default_resource(IDR_PRINT_PREVIEW_HTML); + } +} + +PrintPreviewDataSource::~PrintPreviewDataSource() { +} + +void PrintPreviewDataSource::StartDataRequest(const std::string& path, + bool is_incognito, + int request_id) { + // Parent class handles most requests except for the print preview data. + if (!EndsWith(path, "/print.pdf", true)) { + ChromeWebUIDataSource::StartDataRequest(path, is_incognito, request_id); + return; + } + + // Print Preview data. + scoped_refptr data; + std::vector url_substr; + base::SplitString(path, '/', &url_substr); + int page_index = 0; + if (url_substr.size() == 3 && base::StringToInt(url_substr[1], &page_index)) { + PrintPreviewDataService::GetInstance()->GetDataEntry( + url_substr[0], page_index, &data); + } + if (data.get()) { + SendResponse(request_id, data); + return; + } + // Invalid request. + scoped_refptr empty_bytes(new RefCountedBytes); + SendResponse(request_id, empty_bytes); +} diff --git a/pool/shard010/C++/0111244_CWE121_Stack_Based_Buffer_Overflow__CWE193_wchar_t_declare_loop_82a.cpp b/pool/shard010/C++/0111244_CWE121_Stack_Based_Buffer_Overflow__CWE193_wchar_t_declare_loop_82a.cpp new file mode 100644 index 0000000000000000000000000000000000000000..334d780873933d1252eadfda41a26684df4b6ca4 --- /dev/null +++ b/pool/shard010/C++/0111244_CWE121_Stack_Based_Buffer_Overflow__CWE193_wchar_t_declare_loop_82a.cpp @@ -0,0 +1,94 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE121_Stack_Based_Buffer_Overflow__CWE193_wchar_t_declare_loop_82a.cpp +Label Definition File: CWE121_Stack_Based_Buffer_Overflow__CWE193.label.xml +Template File: sources-sink-82a.tmpl.cpp +*/ +/* + * @description + * CWE: 121 Stack Based Buffer Overflow + * BadSource: Point data to a buffer that does not have space for a NULL terminator + * GoodSource: Point data to a buffer that includes space for a NULL terminator + * Sinks: loop + * BadSink : Copy array to data using a loop + * Flow Variant: 82 Data flow: data passed in a parameter to an virtual method called via a pointer + * + * */ + +#include "std_testcase.h" +#include "CWE121_Stack_Based_Buffer_Overflow__CWE193_wchar_t_declare_loop_82.h" + +namespace CWE121_Stack_Based_Buffer_Overflow__CWE193_wchar_t_declare_loop_82 +{ + +#ifndef OMITBAD + +void bad() +{ + wchar_t * data; + wchar_t dataBadBuffer[10]; + wchar_t dataGoodBuffer[10+1]; + /* FLAW: Set a pointer to a buffer that does not leave room for a NULL terminator when performing + * string copies in the sinks */ + data = dataBadBuffer; + data[0] = L'\0'; /* null terminate */ + CWE121_Stack_Based_Buffer_Overflow__CWE193_wchar_t_declare_loop_82_base* baseObject = new CWE121_Stack_Based_Buffer_Overflow__CWE193_wchar_t_declare_loop_82_bad; + baseObject->action(data); + delete baseObject; +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +static void goodG2B() +{ + wchar_t * data; + wchar_t dataBadBuffer[10]; + wchar_t dataGoodBuffer[10+1]; + /* FIX: Set a pointer to a buffer that leaves room for a NULL terminator when performing + * string copies in the sinks */ + data = dataGoodBuffer; + data[0] = L'\0'; /* null terminate */ + CWE121_Stack_Based_Buffer_Overflow__CWE193_wchar_t_declare_loop_82_base* baseObject = new CWE121_Stack_Based_Buffer_Overflow__CWE193_wchar_t_declare_loop_82_goodG2B; + baseObject->action(data); + delete baseObject; +} + +void good() +{ + goodG2B(); +} + +#endif /* OMITGOOD */ + +} /* close namespace */ + +/* 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 + +using namespace CWE121_Stack_Based_Buffer_Overflow__CWE193_wchar_t_declare_loop_82; /* so that we can use good and bad easily */ + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard010/C++/0111246_call_combiner.cc b/pool/shard010/C++/0111246_call_combiner.cc new file mode 100644 index 0000000000000000000000000000000000000000..b5910b42e421897fa238f2f7c2011129c78d7ec7 --- /dev/null +++ b/pool/shard010/C++/0111246_call_combiner.cc @@ -0,0 +1,214 @@ +/* + * + * Copyright 2017 gRPC 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 "src/core/lib/iomgr/call_combiner.h" + +#include + +#include +#include "src/core/lib/debug/stats.h" +#include "src/core/lib/profiling/timers.h" + +grpc_core::TraceFlag grpc_call_combiner_trace(false, "call_combiner"); + +static grpc_error* decode_cancel_state_error(gpr_atm cancel_state) { + if (cancel_state & 1) { + return (grpc_error*)(cancel_state & ~(gpr_atm)1); + } + return GRPC_ERROR_NONE; +} + +static gpr_atm encode_cancel_state_error(grpc_error* error) { + return (gpr_atm)1 | (gpr_atm)error; +} + +void grpc_call_combiner_init(grpc_call_combiner* call_combiner) { + gpr_mpscq_init(&call_combiner->queue); +} + +void grpc_call_combiner_destroy(grpc_call_combiner* call_combiner) { + gpr_mpscq_destroy(&call_combiner->queue); + GRPC_ERROR_UNREF(decode_cancel_state_error(call_combiner->cancel_state)); +} + +#ifndef NDEBUG +#define DEBUG_ARGS , const char *file, int line +#define DEBUG_FMT_STR "%s:%d: " +#define DEBUG_FMT_ARGS , file, line +#else +#define DEBUG_ARGS +#define DEBUG_FMT_STR +#define DEBUG_FMT_ARGS +#endif + +void grpc_call_combiner_start(grpc_exec_ctx* exec_ctx, + grpc_call_combiner* call_combiner, + grpc_closure* closure, + grpc_error* error DEBUG_ARGS, + const char* reason) { + GPR_TIMER_BEGIN("call_combiner_start", 0); + if (grpc_call_combiner_trace.enabled()) { + gpr_log(GPR_DEBUG, + "==> grpc_call_combiner_start() [%p] closure=%p [" DEBUG_FMT_STR + "%s] error=%s", + call_combiner, closure DEBUG_FMT_ARGS, reason, + grpc_error_string(error)); + } + size_t prev_size = + (size_t)gpr_atm_full_fetch_add(&call_combiner->size, (gpr_atm)1); + if (grpc_call_combiner_trace.enabled()) { + gpr_log(GPR_DEBUG, " size: %" PRIdPTR " -> %" PRIdPTR, prev_size, + prev_size + 1); + } + GRPC_STATS_INC_CALL_COMBINER_LOCKS_SCHEDULED_ITEMS(exec_ctx); + if (prev_size == 0) { + GRPC_STATS_INC_CALL_COMBINER_LOCKS_INITIATED(exec_ctx); + GPR_TIMER_MARK("call_combiner_initiate", 0); + if (grpc_call_combiner_trace.enabled()) { + gpr_log(GPR_DEBUG, " EXECUTING IMMEDIATELY"); + } + // Queue was empty, so execute this closure immediately. + GRPC_CLOSURE_SCHED(exec_ctx, closure, error); + } else { + if (grpc_call_combiner_trace.enabled()) { + gpr_log(GPR_INFO, " QUEUING"); + } + // Queue was not empty, so add closure to queue. + closure->error_data.error = error; + gpr_mpscq_push(&call_combiner->queue, (gpr_mpscq_node*)closure); + } + GPR_TIMER_END("call_combiner_start", 0); +} + +void grpc_call_combiner_stop(grpc_exec_ctx* exec_ctx, + grpc_call_combiner* call_combiner DEBUG_ARGS, + const char* reason) { + GPR_TIMER_BEGIN("call_combiner_stop", 0); + if (grpc_call_combiner_trace.enabled()) { + gpr_log(GPR_DEBUG, + "==> grpc_call_combiner_stop() [%p] [" DEBUG_FMT_STR "%s]", + call_combiner DEBUG_FMT_ARGS, reason); + } + size_t prev_size = + (size_t)gpr_atm_full_fetch_add(&call_combiner->size, (gpr_atm)-1); + if (grpc_call_combiner_trace.enabled()) { + gpr_log(GPR_DEBUG, " size: %" PRIdPTR " -> %" PRIdPTR, prev_size, + prev_size - 1); + } + GPR_ASSERT(prev_size >= 1); + if (prev_size > 1) { + while (true) { + if (grpc_call_combiner_trace.enabled()) { + gpr_log(GPR_DEBUG, " checking queue"); + } + bool empty; + grpc_closure* closure = (grpc_closure*)gpr_mpscq_pop_and_check_end( + &call_combiner->queue, &empty); + if (closure == nullptr) { + // This can happen either due to a race condition within the mpscq + // code or because of a race with grpc_call_combiner_start(). + if (grpc_call_combiner_trace.enabled()) { + gpr_log(GPR_DEBUG, " queue returned no result; checking again"); + } + continue; + } + if (grpc_call_combiner_trace.enabled()) { + gpr_log(GPR_DEBUG, " EXECUTING FROM QUEUE: closure=%p error=%s", + closure, grpc_error_string(closure->error_data.error)); + } + GRPC_CLOSURE_SCHED(exec_ctx, closure, closure->error_data.error); + break; + } + } else if (grpc_call_combiner_trace.enabled()) { + gpr_log(GPR_DEBUG, " queue empty"); + } + GPR_TIMER_END("call_combiner_stop", 0); +} + +void grpc_call_combiner_set_notify_on_cancel(grpc_exec_ctx* exec_ctx, + grpc_call_combiner* call_combiner, + grpc_closure* closure) { + GRPC_STATS_INC_CALL_COMBINER_SET_NOTIFY_ON_CANCEL(exec_ctx); + while (true) { + // Decode original state. + gpr_atm original_state = gpr_atm_acq_load(&call_combiner->cancel_state); + grpc_error* original_error = decode_cancel_state_error(original_state); + // If error is set, invoke the cancellation closure immediately. + // Otherwise, store the new closure. + if (original_error != GRPC_ERROR_NONE) { + if (grpc_call_combiner_trace.enabled()) { + gpr_log(GPR_DEBUG, + "call_combiner=%p: scheduling notify_on_cancel callback=%p " + "for pre-existing cancellation", + call_combiner, closure); + } + GRPC_CLOSURE_SCHED(exec_ctx, closure, GRPC_ERROR_REF(original_error)); + break; + } else { + if (gpr_atm_full_cas(&call_combiner->cancel_state, original_state, + (gpr_atm)closure)) { + if (grpc_call_combiner_trace.enabled()) { + gpr_log(GPR_DEBUG, "call_combiner=%p: setting notify_on_cancel=%p", + call_combiner, closure); + } + // If we replaced an earlier closure, invoke the original + // closure with GRPC_ERROR_NONE. This allows callers to clean + // up any resources they may be holding for the callback. + if (original_state != 0) { + closure = (grpc_closure*)original_state; + if (grpc_call_combiner_trace.enabled()) { + gpr_log(GPR_DEBUG, + "call_combiner=%p: scheduling old cancel callback=%p", + call_combiner, closure); + } + GRPC_CLOSURE_SCHED(exec_ctx, closure, GRPC_ERROR_NONE); + } + break; + } + } + // cas failed, try again. + } +} + +void grpc_call_combiner_cancel(grpc_exec_ctx* exec_ctx, + grpc_call_combiner* call_combiner, + grpc_error* error) { + GRPC_STATS_INC_CALL_COMBINER_CANCELLED(exec_ctx); + while (true) { + gpr_atm original_state = gpr_atm_acq_load(&call_combiner->cancel_state); + grpc_error* original_error = decode_cancel_state_error(original_state); + if (original_error != GRPC_ERROR_NONE) { + GRPC_ERROR_UNREF(error); + break; + } + if (gpr_atm_full_cas(&call_combiner->cancel_state, original_state, + encode_cancel_state_error(error))) { + if (original_state != 0) { + grpc_closure* notify_on_cancel = (grpc_closure*)original_state; + if (grpc_call_combiner_trace.enabled()) { + gpr_log(GPR_DEBUG, + "call_combiner=%p: scheduling notify_on_cancel callback=%p", + call_combiner, notify_on_cancel); + } + GRPC_CLOSURE_SCHED(exec_ctx, notify_on_cancel, GRPC_ERROR_REF(error)); + } + break; + } + // cas failed, try again. + } +} diff --git a/pool/shard010/C++/0111247_Settings.cpp b/pool/shard010/C++/0111247_Settings.cpp new file mode 100644 index 0000000000000000000000000000000000000000..591f289332d233cfcac26ab36955c0d0e7f8cb58 --- /dev/null +++ b/pool/shard010/C++/0111247_Settings.cpp @@ -0,0 +1,54 @@ +#include +#include + +#if defined(ESP8266) +#include +#endif + +#include "Settings.h" + +SettingsClass Settings; + +static const size_t EEPROM_SIZE = 512; + +void SettingsClass::begin() { +#if defined(ESP8266) + EEPROM.begin(EEPROM_SIZE); +#else + EEPROM.begin(); +#endif + EEPROM.get(0, *this); + + // Populate defaults if flash magic is unexpected + if (magic != FLASH_MAGIC) { + if (magic != FLASH_MAGIC_R2) { + if (magic != FLASH_MAGIC_R1) { + bzero(this, sizeof(*this)); +#if defined(ESP8266) + uint8_t mac[WL_MAC_ADDR_LENGTH]; + WiFi.macAddress(mac); + sprintf(hostname, "espclock%02x", mac[WL_MAC_ADDR_LENGTH-1]); +#else + strcpy(hostname, "espclock"); +#endif + strcpy(ntp_hostname, "us.pool.ntp.org"); + } + memset(preset_r, 0xff, sizeof(preset_r)); + memset(preset_g, 0xff, sizeof(preset_g)); + memset(preset_b, 0xff, sizeof(preset_b)); + memset(preset_w, 0xff, sizeof(preset_w)); + } + bzero(owm_apikey, sizeof(owm_apikey)); + + magic = FLASH_MAGIC; + save(); // Is this really necessary? + } +} + +void SettingsClass::save() { + EEPROM.put(0, *this); +#if defined(ESP8266) + EEPROM.commit(); +#endif +} + diff --git a/pool/shard010/C++/0111251_platform.cpp b/pool/shard010/C++/0111251_platform.cpp new file mode 100644 index 0000000000000000000000000000000000000000..027e2b0f39ff8533d867561154fac63b348eee14 --- /dev/null +++ b/pool/shard010/C++/0111251_platform.cpp @@ -0,0 +1,113 @@ +#include "platform.h" +#include +#include +#include + +Platform::Platform() +{ + collision_loop = false; + position.x = 0; + position.y = 0; +} + +void Platform::Draw(Vector2 camera, ALLEGRO_COLOR c) +{ + int np = collision_vertices.size(); + if(np == 0) + { + return; + } + Vector2 pn = collision_vertices[0]; + Vector2 ps, pe; + float angle = 0; + ps.x = cos(angle)*pn.x - sin(angle)*pn.y; + ps.y = sin(angle)*pn.x + cos(angle)*pn.y; + for(int i=1; i ((*i)-v).Length_squared() ) + { + r = *i; + index = n; + } + } + return index; +} + +Vertices& Platform::Get_vertices() +{ + return collision_vertices; +} diff --git a/pool/shard010/C++/0111256_main.cpp b/pool/shard010/C++/0111256_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..370eeb0925330a0eeff172290e03d95c2d231915 --- /dev/null +++ b/pool/shard010/C++/0111256_main.cpp @@ -0,0 +1,99 @@ +#include +#include +#include +#include +using namespace std; + +/* + * Approaches: + * + * 1) While we loop over the string, keep track of the starting and ending positions of groups of repeating characters. + * After we reach the end of the repeating group of characters, if the length is greater than or equal to the length + * which qualifies as a large group, then add the starting and ending indices to our result list (vector> result). + * Return our result list. + * + * Time complexity: O(n) [where n is the length of the input string, S] + * Space complexity: O(1) + * + * 2) Same logic as the first solution just using more explicit vector initialization when we are inserting our + * vectors containing the starting and ending indices of large group of repeating characters. + * + * Time complexity: O(n) [where n is the length of the input string, S] + * Space complexity: O(1) + */ + +vector> largeGroupPositions(string S) +{ + vector> result; + + if(S.empty()) + { + return result; + } + + int n=int(S.size()); + + int groupSize=3; + + for(int index=0;index startAndEnd(index, -1); + + while(S[index]==current) + { + startAndEnd.second=index; + + index++; + } + + if((startAndEnd.second - startAndEnd.first) + 1 >= groupSize) + { + result.push_back({{startAndEnd.first, startAndEnd.second}}); + } + } + + return result; +} + +vector> largeGroupPositions(string S) +{ + vector> result; + + if(S.empty()) + { + return result; + } + + int n=int(S.size()); + + int groupSize=3; + + for(int index=0;index startAndEnd(index, -1); + + while(S[index]==current) + { + startAndEnd.second=index; + + index++; + } + + if((startAndEnd.second - startAndEnd.first) + 1 >= groupSize) + { + vector v(2, 0); + + v[0]=startAndEnd.first; + + v[1]=startAndEnd.second; + + result.push_back(v); + } + } + + return result; +} \ No newline at end of file diff --git a/pool/shard010/C++/0111257_describelocalgatewayroutetablesresponse.cpp b/pool/shard010/C++/0111257_describelocalgatewayroutetablesresponse.cpp new file mode 100644 index 0000000000000000000000000000000000000000..55877eeba6a71bee2730664cfdf4e219a264e97a --- /dev/null +++ b/pool/shard010/C++/0111257_describelocalgatewayroutetablesresponse.cpp @@ -0,0 +1,132 @@ +/* + Copyright 2013-2021 Paul Colby + + This file is part of QtAws. + + QtAws 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. + + QtAws 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 QtAws. If not, see . +*/ + +#include "describelocalgatewayroutetablesresponse.h" +#include "describelocalgatewayroutetablesresponse_p.h" + +#include +#include +#include + +namespace QtAws { +namespace EC2 { + +/*! + * \class QtAws::EC2::DescribeLocalGatewayRouteTablesResponse + * \brief The DescribeLocalGatewayRouteTablesResponse class provides an interace for EC2 DescribeLocalGatewayRouteTables responses. + * + * \inmodule QtAwsEC2 + * + * Amazon Elastic Compute Cloud + * + * Amazon Elastic Compute Cloud (Amazon EC2) provides secure and resizable computing capacity in the AWS Cloud. Using + * Amazon EC2 eliminates the need to invest in hardware up front, so you can develop and deploy applications faster. Amazon + * Virtual Private Cloud (Amazon VPC) enables you to provision a logically isolated section of the AWS Cloud where you can + * launch AWS resources in a virtual network that you've defined. Amazon Elastic Block Store (Amazon EBS) provides block + * level storage volumes for use with EC2 instances. EBS volumes are highly available and reliable storage volumes that can + * be attached to any running instance and used like a hard + * + * drive> + * + * To learn more, see the following + * + * resources>
  • + * + * Amazon EC2: AmazonEC2 product page, Amazon EC2 documentation + * + *

  • + * + * Amazon EBS: Amazon EBS product page, Amazon EBS documentation + * + *

  • + * + * Amazon VPC: Amazon VPC product page, Amazon VPC documentation + * + *

  • + * + * AWS VPN: AWS VPN product page, AWS VPN documentation + * + * \sa Ec2Client::describeLocalGatewayRouteTables + */ + +/*! + * Constructs a DescribeLocalGatewayRouteTablesResponse object for \a reply to \a request, with parent \a parent. + */ +DescribeLocalGatewayRouteTablesResponse::DescribeLocalGatewayRouteTablesResponse( + const DescribeLocalGatewayRouteTablesRequest &request, + QNetworkReply * const reply, + QObject * const parent) + : Ec2Response(new DescribeLocalGatewayRouteTablesResponsePrivate(this), parent) +{ + setRequest(new DescribeLocalGatewayRouteTablesRequest(request)); + setReply(reply); +} + +/*! + * \reimp + */ +const DescribeLocalGatewayRouteTablesRequest * DescribeLocalGatewayRouteTablesResponse::request() const +{ + Q_D(const DescribeLocalGatewayRouteTablesResponse); + return static_cast(d->request); +} + +/*! + * \reimp + * Parses a successful EC2 DescribeLocalGatewayRouteTables \a response. + */ +void DescribeLocalGatewayRouteTablesResponse::parseSuccess(QIODevice &response) +{ + //Q_D(DescribeLocalGatewayRouteTablesResponse); + QXmlStreamReader xml(&response); + /// @todo +} + +/*! + * \class QtAws::EC2::DescribeLocalGatewayRouteTablesResponsePrivate + * \brief The DescribeLocalGatewayRouteTablesResponsePrivate class provides private implementation for DescribeLocalGatewayRouteTablesResponse. + * \internal + * + * \inmodule QtAwsEC2 + */ + +/*! + * Constructs a DescribeLocalGatewayRouteTablesResponsePrivate object with public implementation \a q. + */ +DescribeLocalGatewayRouteTablesResponsePrivate::DescribeLocalGatewayRouteTablesResponsePrivate( + DescribeLocalGatewayRouteTablesResponse * const q) : Ec2ResponsePrivate(q) +{ + +} + +/*! + * Parses a EC2 DescribeLocalGatewayRouteTables response element from \a xml. + */ +void DescribeLocalGatewayRouteTablesResponsePrivate::parseDescribeLocalGatewayRouteTablesResponse(QXmlStreamReader &xml) +{ + Q_ASSERT(xml.name() == QLatin1String("DescribeLocalGatewayRouteTablesResponse")); + Q_UNUSED(xml) ///< @todo +} + +} // namespace EC2 +} // namespace QtAws diff --git a/pool/shard010/C++/0111259_decode_svc_test.cc b/pool/shard010/C++/0111259_decode_svc_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..ec9935da795eadf8240bd97015124d8c8e5f9d08 --- /dev/null +++ b/pool/shard010/C++/0111259_decode_svc_test.cc @@ -0,0 +1,125 @@ +/* + * Copyright (c) 2016 The WebM 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 +#include + +#include "test/codec_factory.h" +#include "test/decode_test_driver.h" +#include "test/ivf_video_source.h" +#include "test/test_vectors.h" +#include "test/util.h" + +namespace { + +const unsigned int kNumFrames = 19; + +class DecodeSvcTest : public ::libvpx_test::DecoderTest, + public ::libvpx_test::CodecTestWithParam { + protected: + DecodeSvcTest() : DecoderTest(GET_PARAM(::libvpx_test::kCodecFactoryParam)) {} + virtual ~DecodeSvcTest() {} + + virtual void PreDecodeFrameHook( + const libvpx_test::CompressedVideoSource &video, + libvpx_test::Decoder *decoder) { + if (video.frame_number() == 0) + decoder->Control(VP9_DECODE_SVC_SPATIAL_LAYER, spatial_layer_); + } + + virtual void DecompressedFrameHook(const vpx_image_t &img, + const unsigned int frame_number) { + ASSERT_EQ(img.d_w, width_); + ASSERT_EQ(img.d_h, height_); + total_frames_ = frame_number; + } + + int spatial_layer_; + unsigned int width_; + unsigned int height_; + unsigned int total_frames_; +}; + +// SVC test vector is 1280x720, with 3 spatial layers, and 20 frames. + +// Decode the SVC test vector, which has 3 spatial layers, and decode up to +// spatial layer 0. Verify the resolution of each decoded frame and the total +// number of frames decoded. This results in 1/4x1/4 resolution (320x180). +TEST_P(DecodeSvcTest, DecodeSvcTestUpToSpatialLayer0) { + const std::string filename = GET_PARAM(1); + std::unique_ptr video; + video.reset(new libvpx_test::IVFVideoSource(filename)); + ASSERT_NE(video.get(), nullptr); + video->Init(); + total_frames_ = 0; + spatial_layer_ = 0; + width_ = 320; + height_ = 180; + ASSERT_NO_FATAL_FAILURE(RunLoop(video.get())); + ASSERT_EQ(total_frames_, kNumFrames); +} + +// Decode the SVC test vector, which has 3 spatial layers, and decode up to +// spatial layer 1. Verify the resolution of each decoded frame and the total +// number of frames decoded. This results in 1/2x1/2 resolution (640x360). +TEST_P(DecodeSvcTest, DecodeSvcTestUpToSpatialLayer1) { + const std::string filename = GET_PARAM(1); + std::unique_ptr video; + video.reset(new libvpx_test::IVFVideoSource(filename)); + ASSERT_NE(video.get(), nullptr); + video->Init(); + total_frames_ = 0; + spatial_layer_ = 1; + width_ = 640; + height_ = 360; + ASSERT_NO_FATAL_FAILURE(RunLoop(video.get())); + ASSERT_EQ(total_frames_, kNumFrames); +} + +// Decode the SVC test vector, which has 3 spatial layers, and decode up to +// spatial layer 2. Verify the resolution of each decoded frame and the total +// number of frames decoded. This results in the full resolution (1280x720). +TEST_P(DecodeSvcTest, DecodeSvcTestUpToSpatialLayer2) { + const std::string filename = GET_PARAM(1); + std::unique_ptr video; + video.reset(new libvpx_test::IVFVideoSource(filename)); + ASSERT_NE(video.get(), nullptr); + video->Init(); + total_frames_ = 0; + spatial_layer_ = 2; + width_ = 1280; + height_ = 720; + ASSERT_NO_FATAL_FAILURE(RunLoop(video.get())); + ASSERT_EQ(total_frames_, kNumFrames); +} + +// Decode the SVC test vector, which has 3 spatial layers, and decode up to +// spatial layer 10. Verify the resolution of each decoded frame and the total +// number of frames decoded. This is beyond the number of spatial layers, so +// the decoding should result in the full resolution (1280x720). +TEST_P(DecodeSvcTest, DecodeSvcTestUpToSpatialLayer10) { + const std::string filename = GET_PARAM(1); + std::unique_ptr video; + video.reset(new libvpx_test::IVFVideoSource(filename)); + ASSERT_NE(video.get(), nullptr); + video->Init(); + total_frames_ = 0; + spatial_layer_ = 10; + width_ = 1280; + height_ = 720; + ASSERT_NO_FATAL_FAILURE(RunLoop(video.get())); + ASSERT_EQ(total_frames_, kNumFrames); +} + +VP9_INSTANTIATE_TEST_SUITE( + DecodeSvcTest, ::testing::ValuesIn(libvpx_test::kVP9TestVectorsSvc, + libvpx_test::kVP9TestVectorsSvc + + libvpx_test::kNumVP9TestVectorsSvc)); +} // namespace diff --git a/pool/shard010/C++/0111260_bitcoin.cpp b/pool/shard010/C++/0111260_bitcoin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1166f4037f8058d4ff639530dde30ddf54cacdee --- /dev/null +++ b/pool/shard010/C++/0111260_bitcoin.cpp @@ -0,0 +1,297 @@ +/* + * W.J. van der Laan 2011-2012 + */ + +#include + +#include "bitcoingui.h" +#include "clientmodel.h" +#include "walletmodel.h" +#include "optionsmodel.h" +#include "guiutil.h" +#include "guiconstants.h" +#include "init.h" +#include "util.h" +#include "ui_interface.h" +#include "paymentserver.h" +#include "splashscreen.h" + +#include +#include +#include +#include +#include +#include + +#ifdef Q_OS_MAC +#include "macdockiconhandler.h" +#endif + +#if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED) +#define _BITCOIN_QT_PLUGINS_INCLUDED +#define __INSURE__ +#include +Q_IMPORT_PLUGIN(qcncodecs) +Q_IMPORT_PLUGIN(qjpcodecs) +Q_IMPORT_PLUGIN(qtwcodecs) +Q_IMPORT_PLUGIN(qkrcodecs) +Q_IMPORT_PLUGIN(qtaccessiblewidgets) +#endif + +// Declare meta types used for QMetaObject::invokeMethod +Q_DECLARE_METATYPE(bool*) + +// Need a global reference for the notifications to find the GUI +static BitcoinGUI *guiref; +static SplashScreen *splashref; + +static bool ThreadSafeMessageBox(const std::string& message, const std::string& caption, unsigned int style) +{ + // Message from network thread + if(guiref) + { + bool modal = (style & CClientUIInterface::MODAL); + bool ret = false; + // In case of modal message, use blocking connection to wait for user to click a button + QMetaObject::invokeMethod(guiref, "message", + modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection, + Q_ARG(QString, QString::fromStdString(caption)), + Q_ARG(QString, QString::fromStdString(message)), + Q_ARG(unsigned int, style), + Q_ARG(bool*, &ret)); + return ret; + } + else + { + printf("%s: %s\n", caption.c_str(), message.c_str()); + fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str()); + return false; + } +} + +static bool ThreadSafeAskFee(const mpq& nFeeRequired) +{ + if(!guiref) + return false; + if(nFeeRequired < CTransaction::nMinTxFee || nFeeRequired <= nTransactionFee || fDaemon) + return true; + + bool payFee = false; + + QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(), + Q_ARG(mpq, nFeeRequired), + Q_ARG(bool*, &payFee)); + + return payFee; +} + +static void InitMessage(const std::string &message) +{ + if(splashref) + { + splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(55,55,55)); + qApp->processEvents(); + } + printf("init message: %s\n", message.c_str()); +} + +/* + Translate string to current locale using Qt. + */ +static std::string Translate(const char* psz) +{ + return QCoreApplication::translate("bitcoin-core", psz).toStdString(); +} + +/* Handle runaway exceptions. Shows a message box with the problem and quits the program. + */ +static void handleRunawayException(std::exception *e) +{ + PrintExceptionContinue(e, "Runaway exception"); + QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. Scicoin can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning)); + exit(1); +} + +#ifndef BITCOIN_QT_TEST +int main(int argc, char *argv[]) +{ + // Command-line options take precedence: + ParseParameters(argc, argv); + + // Internal string conversion is all UTF-8 + QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); + QTextCodec::setCodecForCStrings(QTextCodec::codecForTr()); + + Q_INIT_RESOURCE(bitcoin); + QApplication app(argc, argv); + + // Register meta types used for QMetaObject::invokeMethod + qRegisterMetaType< bool* >(); + + // Do this early as we don't want to bother initializing if we are just calling IPC + // ... but do it after creating app, so QCoreApplication::arguments is initialized: + if (PaymentServer::ipcSendCommandLine()) + exit(0); + PaymentServer* paymentServer = new PaymentServer(&app); + + // Install global event filter that makes sure that long tooltips can be word-wrapped + app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app)); + + // ... then bitcoin.conf: + if (!boost::filesystem::is_directory(GetDataDir(false))) + { + // This message can not be translated, as translation is not initialized yet + // (which not yet possible because lang=XX can be overridden in bitcoin.conf in the data directory) + QMessageBox::critical(0, "Scicoin", + QString("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"]))); + return 1; + } + ReadConfigFile(mapArgs, mapMultiArgs); + + // Application identification (must be set before OptionsModel is initialized, + // as it is used to locate QSettings) + QApplication::setOrganizationName("Scicoin"); + QApplication::setOrganizationDomain("freico.in"); + if(GetBoolArg("-testnet")) // Separate UI settings for testnet + QApplication::setApplicationName("Scicoin-Qt-testnet"); + else + QApplication::setApplicationName("Scicoin-Qt"); + + // ... then GUI settings: + OptionsModel optionsModel; + + // Get desired locale (e.g. "de_DE") from command line or use system locale + QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString())); + QString lang = lang_territory; + // Convert to "de" only by truncating "_DE" + lang.truncate(lang_territory.lastIndexOf('_')); + + QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator; + // Load language files for configured locale: + // - First load the translator for the base language, without territory + // - Then load the more specific locale translator + + // Load e.g. qt_de.qm + if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) + app.installTranslator(&qtTranslatorBase); + + // Load e.g. qt_de_DE.qm + if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) + app.installTranslator(&qtTranslator); + + // Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc) + if (translatorBase.load(lang, ":/translations/")) + app.installTranslator(&translatorBase); + + // Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc) + if (translator.load(lang_territory, ":/translations/")) + app.installTranslator(&translator); + + // Subscribe to global signals from core + uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox); + uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee); + uiInterface.InitMessage.connect(InitMessage); + uiInterface.Translate.connect(Translate); + + // Show help message immediately after parsing command-line options (for "-lang") and setting locale, + // but before showing splash screen. + if (mapArgs.count("-?") || mapArgs.count("--help")) + { + GUIUtil::HelpMessageBox help; + help.showOrPrint(); + return 1; + } + +#ifdef Q_OS_MAC + // on mac, also change the icon now because it would look strange to have a testnet splash (green) and a std app icon (orange) + if(GetBoolArg("-testnet")) { + MacDockIconHandler::instance()->setIcon(QIcon(":icons/bitcoin_testnet")); + } +#endif + + SplashScreen splash(QPixmap(), 0); + if (GetBoolArg("-splash", true) && !GetBoolArg("-min")) + { + splash.show(); + splash.setAutoFillBackground(true); + splashref = &splash; + } + + app.processEvents(); + app.setQuitOnLastWindowClosed(false); + + try + { + // Regenerate startup link, to fix links to old versions + if (GUIUtil::GetStartOnSystemStartup()) + GUIUtil::SetStartOnSystemStartup(true); + + boost::thread_group threadGroup; + + BitcoinGUI window; + guiref = &window; + + QTimer* pollShutdownTimer = new QTimer(guiref); + QObject::connect(pollShutdownTimer, SIGNAL(timeout()), guiref, SLOT(detectShutdown())); + pollShutdownTimer->start(200); + + if(AppInit2(threadGroup)) + { + { + // Put this in a block, so that the Model objects are cleaned up before + // calling Shutdown(). + + optionsModel.Upgrade(); // Must be done after AppInit2 + + if (splashref) + splash.finish(&window); + + ClientModel clientModel(&optionsModel); + WalletModel walletModel(pwalletMain, &optionsModel); + + window.setClientModel(&clientModel); + window.addWallet("~Default", &walletModel); + window.setCurrentWallet("~Default"); + + // If -min option passed, start window minimized. + if(GetBoolArg("-min")) + { + window.showMinimized(); + } + else + { + window.show(); + } + + // Now that initialization/startup is done, process any command-line + // bitcoin: URIs + QObject::connect(paymentServer, SIGNAL(receivedURI(QString)), &window, SLOT(handleURI(QString))); + QTimer::singleShot(100, paymentServer, SLOT(uiReady())); + + app.exec(); + + window.hide(); + window.setClientModel(0); + window.removeAllWallets(); + guiref = 0; + } + // Shutdown the core and its threads, but don't exit Bitcoin-Qt here + threadGroup.interrupt_all(); + threadGroup.join_all(); + Shutdown(); + } + else + { + threadGroup.interrupt_all(); + threadGroup.join_all(); + Shutdown(); + return 1; + } + } catch (std::exception& e) { + handleRunawayException(&e); + } catch (...) { + handleRunawayException(NULL); + } + return 0; +} +#endif // BITCOIN_QT_TEST diff --git a/pool/shard010/C++/0111266_CryptoKeyReader.cc b/pool/shard010/C++/0111266_CryptoKeyReader.cc new file mode 100644 index 0000000000000000000000000000000000000000..1eb73e8fe9fe95ede43181a8072b66fae7569bb8 --- /dev/null +++ b/pool/shard010/C++/0111266_CryptoKeyReader.cc @@ -0,0 +1,80 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + +using namespace pulsar; + +CryptoKeyReader::CryptoKeyReader() {} +CryptoKeyReader::~CryptoKeyReader() {} + +Result CryptoKeyReader::getPublicKey(const std::string& keyName, std::map& metadata, + EncryptionKeyInfo& encKeyInfo) const { + return ResultInvalidConfiguration; +} + +Result CryptoKeyReader::getPrivateKey(const std::string& keyName, + std::map& metadata, + EncryptionKeyInfo& encKeyInfo) const { + return ResultInvalidConfiguration; +} + +DefaultCryptoKeyReader::DefaultCryptoKeyReader(const std::string& publicKeyPath, + const std::string& privateKeyPath) { + publicKeyPath_ = publicKeyPath; + privateKeyPath_ = privateKeyPath; +} + +DefaultCryptoKeyReader::~DefaultCryptoKeyReader() {} + +void DefaultCryptoKeyReader::readFile(std::string fileName, std::string& fileContents) const { + std::ifstream ifs(fileName); + std::stringstream fileStream; + fileStream << ifs.rdbuf(); + + fileContents = fileStream.str(); +} + +Result DefaultCryptoKeyReader::getPublicKey(const std::string& keyName, + std::map& metadata, + EncryptionKeyInfo& encKeyInfo) const { + std::string keyContents; + readFile(publicKeyPath_, keyContents); + + encKeyInfo.setKey(keyContents); + return ResultOk; +} + +Result DefaultCryptoKeyReader::getPrivateKey(const std::string& keyName, + std::map& metadata, + EncryptionKeyInfo& encKeyInfo) const { + std::string keyContents; + readFile(privateKeyPath_, keyContents); + + encKeyInfo.setKey(keyContents); + return ResultOk; +} + +CryptoKeyReaderPtr DefaultCryptoKeyReader::create(const std::string& publicKeyPath, + const std::string& privateKeyPath) { + return CryptoKeyReaderPtr(new DefaultCryptoKeyReader(publicKeyPath, privateKeyPath)); +} \ No newline at end of file diff --git a/pool/shard010/C++/0111268_Jit_Branch.cpp b/pool/shard010/C++/0111268_Jit_Branch.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2508fe1417f048f06c5b67cd87d888599a68888f --- /dev/null +++ b/pool/shard010/C++/0111268_Jit_Branch.cpp @@ -0,0 +1,251 @@ +// Copyright 2013 Dolphin Emulator Project +// Licensed under GPLv2 +// Refer to the license.txt file included. + +#include "Common/CommonTypes.h" + +#include "Core/PowerPC/Jit64/Jit.h" +#include "Core/PowerPC/Jit64/JitAsm.h" +#include "Core/PowerPC/Jit64/JitRegCache.h" + +// The branches are known good, or at least reasonably good. +// No need for a disable-mechanism. + +// If defined, clears CR0 at blr and bl-s. If the assumption that +// flags never carry over between functions holds, then the task for +// an optimizer becomes much easier. + +// #define ACID_TEST + +// Zelda and many more games seem to pass the Acid Test. + +using namespace Gen; + +void Jit64::sc(UGeckoInstruction inst) +{ + INSTRUCTION_START + JITDISABLE(bJITBranchOff); + + gpr.Flush(); + fpr.Flush(); + MOV(32, PPCSTATE(pc), Imm32(js.compilerPC + 4)); + LOCK(); + OR(32, PPCSTATE(Exceptions), Imm32(EXCEPTION_SYSCALL)); + WriteExceptionExit(); +} + +void Jit64::rfi(UGeckoInstruction inst) +{ + INSTRUCTION_START + JITDISABLE(bJITBranchOff); + + gpr.Flush(); + fpr.Flush(); + // See Interpreter rfi for details + const u32 mask = 0x87C0FFFF; + const u32 clearMSR13 = 0xFFFBFFFF; // Mask used to clear the bit MSR[13] + // MSR = ((MSR & ~mask) | (SRR1 & mask)) & clearMSR13; + AND(32, PPCSTATE(msr), Imm32((~mask) & clearMSR13)); + MOV(32, R(RSCRATCH), PPCSTATE_SRR1); + AND(32, R(RSCRATCH), Imm32(mask & clearMSR13)); + OR(32, PPCSTATE(msr), R(RSCRATCH)); + // NPC = SRR0; + MOV(32, R(RSCRATCH), PPCSTATE_SRR0); + WriteRfiExitDestInRSCRATCH(); +} + +void Jit64::bx(UGeckoInstruction inst) +{ + INSTRUCTION_START + JITDISABLE(bJITBranchOff); + + // We must always process the following sentence + // even if the blocks are merged by PPCAnalyst::Flatten(). + if (inst.LK) + MOV(32, PPCSTATE_LR, Imm32(js.compilerPC + 4)); + + // If this is not the last instruction of a block, + // we will skip the rest process. + // Because PPCAnalyst::Flatten() merged the blocks. + if (!js.isLastInstruction) + { + return; + } + + gpr.Flush(); + fpr.Flush(); + + u32 destination; + if (inst.AA) + destination = SignExt26(inst.LI << 2); + else + destination = js.compilerPC + SignExt26(inst.LI << 2); +#ifdef ACID_TEST + if (inst.LK) + AND(32, PPCSTATE(cr), Imm32(~(0xFF000000))); +#endif + if (destination == js.compilerPC) + { + //PanicAlert("Idle loop detected at %08x", destination); + // CALL(ProtectFunction(&CoreTiming::Idle, 0)); + // JMP(Asm::testExceptions, true); + // make idle loops go faster + js.downcountAmount += 8; + } + WriteExit(destination, inst.LK, js.compilerPC + 4); +} + +// TODO - optimize to hell and beyond +// TODO - make nice easy to optimize special cases for the most common +// variants of this instruction. +void Jit64::bcx(UGeckoInstruction inst) +{ + INSTRUCTION_START + JITDISABLE(bJITBranchOff); + + // USES_CR + + FixupBranch pCTRDontBranch; + if ((inst.BO & BO_DONT_DECREMENT_FLAG) == 0) // Decrement and test CTR + { + SUB(32, PPCSTATE_CTR, Imm8(1)); + if (inst.BO & BO_BRANCH_IF_CTR_0) + pCTRDontBranch = J_CC(CC_NZ, true); + else + pCTRDontBranch = J_CC(CC_Z, true); + } + + FixupBranch pConditionDontBranch; + if ((inst.BO & BO_DONT_CHECK_CONDITION) == 0) // Test a CR bit + { + pConditionDontBranch = JumpIfCRFieldBit(inst.BI >> 2, 3 - (inst.BI & 3), + !(inst.BO_2 & BO_BRANCH_IF_TRUE)); + } + + if (inst.LK) + MOV(32, PPCSTATE_LR, Imm32(js.compilerPC + 4)); + + u32 destination; + if (inst.AA) + destination = SignExt16(inst.BD << 2); + else + destination = js.compilerPC + SignExt16(inst.BD << 2); + + gpr.Flush(FLUSH_MAINTAIN_STATE); + fpr.Flush(FLUSH_MAINTAIN_STATE); + WriteExit(destination, inst.LK, js.compilerPC + 4); + + if ((inst.BO & BO_DONT_CHECK_CONDITION) == 0) + SetJumpTarget( pConditionDontBranch ); + if ((inst.BO & BO_DONT_DECREMENT_FLAG) == 0) + SetJumpTarget( pCTRDontBranch ); + + if (!analyzer.HasOption(PPCAnalyst::PPCAnalyzer::OPTION_CONDITIONAL_CONTINUE)) + { + gpr.Flush(); + fpr.Flush(); + WriteExit(js.compilerPC + 4); + } +} + +void Jit64::bcctrx(UGeckoInstruction inst) +{ + INSTRUCTION_START + JITDISABLE(bJITBranchOff); + + // bcctrx doesn't decrement and/or test CTR + _dbg_assert_msg_(POWERPC, inst.BO_2 & BO_DONT_DECREMENT_FLAG, "bcctrx with decrement and test CTR option is invalid!"); + + if (inst.BO_2 & BO_DONT_CHECK_CONDITION) + { + // BO_2 == 1z1zz -> b always + + //NPC = CTR & 0xfffffffc; + gpr.Flush(); + fpr.Flush(); + + MOV(32, R(RSCRATCH), PPCSTATE_CTR); + if (inst.LK_3) + MOV(32, PPCSTATE_LR, Imm32(js.compilerPC + 4)); // LR = PC + 4; + AND(32, R(RSCRATCH), Imm32(0xFFFFFFFC)); + WriteExitDestInRSCRATCH(inst.LK_3, js.compilerPC + 4); + } + else + { + // Rare condition seen in (just some versions of?) Nintendo's NES Emulator + + // BO_2 == 001zy -> b if false + // BO_2 == 011zy -> b if true + + FixupBranch b = JumpIfCRFieldBit(inst.BI >> 2, 3 - (inst.BI & 3), + !(inst.BO_2 & BO_BRANCH_IF_TRUE)); + MOV(32, R(RSCRATCH), PPCSTATE_CTR); + AND(32, R(RSCRATCH), Imm32(0xFFFFFFFC)); + //MOV(32, PPCSTATE(pc), R(RSCRATCH)); => Already done in WriteExitDestInRSCRATCH() + if (inst.LK_3) + MOV(32, PPCSTATE_LR, Imm32(js.compilerPC + 4)); // LR = PC + 4; + + gpr.Flush(FLUSH_MAINTAIN_STATE); + fpr.Flush(FLUSH_MAINTAIN_STATE); + WriteExitDestInRSCRATCH(inst.LK_3, js.compilerPC + 4); + // Would really like to continue the block here, but it ends. TODO. + SetJumpTarget(b); + + if (!analyzer.HasOption(PPCAnalyst::PPCAnalyzer::OPTION_CONDITIONAL_CONTINUE)) + { + gpr.Flush(); + fpr.Flush(); + WriteExit(js.compilerPC + 4); + } + } +} + +void Jit64::bclrx(UGeckoInstruction inst) +{ + INSTRUCTION_START + JITDISABLE(bJITBranchOff); + + FixupBranch pCTRDontBranch; + if ((inst.BO & BO_DONT_DECREMENT_FLAG) == 0) // Decrement and test CTR + { + SUB(32, PPCSTATE_CTR, Imm8(1)); + if (inst.BO & BO_BRANCH_IF_CTR_0) + pCTRDontBranch = J_CC(CC_NZ, true); + else + pCTRDontBranch = J_CC(CC_Z, true); + } + + FixupBranch pConditionDontBranch; + if ((inst.BO & BO_DONT_CHECK_CONDITION) == 0) // Test a CR bit + { + pConditionDontBranch = JumpIfCRFieldBit(inst.BI >> 2, 3 - (inst.BI & 3), + !(inst.BO_2 & BO_BRANCH_IF_TRUE)); + } + + // This below line can be used to prove that blr "eats flags" in practice. + // This observation could let us do some useful optimizations. +#ifdef ACID_TEST + AND(32, PPCSTATE(cr), Imm32(~(0xFF000000))); +#endif + + MOV(32, R(RSCRATCH), PPCSTATE_LR); + AND(32, R(RSCRATCH), Imm32(0xFFFFFFFC)); + if (inst.LK) + MOV(32, PPCSTATE_LR, Imm32(js.compilerPC + 4)); + + gpr.Flush(FLUSH_MAINTAIN_STATE); + fpr.Flush(FLUSH_MAINTAIN_STATE); + WriteBLRExit(); + + if ((inst.BO & BO_DONT_CHECK_CONDITION) == 0) + SetJumpTarget( pConditionDontBranch ); + if ((inst.BO & BO_DONT_DECREMENT_FLAG) == 0) + SetJumpTarget( pCTRDontBranch ); + + if (!analyzer.HasOption(PPCAnalyst::PPCAnalyzer::OPTION_CONDITIONAL_CONTINUE)) + { + gpr.Flush(); + fpr.Flush(); + WriteExit(js.compilerPC + 4); + } +} diff --git a/pool/shard010/C++/0111275_best_time_to_buy_and_sell_stock.cpp b/pool/shard010/C++/0111275_best_time_to_buy_and_sell_stock.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1a2bc7848ba95494ca063f725a71b07f367faf09 --- /dev/null +++ b/pool/shard010/C++/0111275_best_time_to_buy_and_sell_stock.cpp @@ -0,0 +1,31 @@ +#include +#include + +using std::cout; +using std::endl; +using std::vector; + +class Solution { +public: + typedef vector::size_type s_t; + int maxProfit(vector& prices) { + if (prices.size() < 2) + return 0; + vector dp(prices.size(), 0); + s_t min = 0; + for (s_t i = 1, iend = prices.size(); i < iend; ++i) { + int tmp = prices[i] - prices[min]; + min = prices[min] < prices[i] ? min : i; + dp[i] = dp[i-1] < tmp ? tmp : dp[i-1]; + } + return dp[prices.size()-1]; + } +}; + +int main(void) +{ + int array[] = {1, 2, 3, 4}; + vector vec(array, array+sizeof(array)/sizeof(array[0])); + cout << Solution().maxProfit(vec) << endl; + +} diff --git a/pool/shard010/C++/0111278_SetSelectionCommand.cpp b/pool/shard010/C++/0111278_SetSelectionCommand.cpp new file mode 100644 index 0000000000000000000000000000000000000000..00a4d561d2be6db9825a415dcf346c3f863b28e9 --- /dev/null +++ b/pool/shard010/C++/0111278_SetSelectionCommand.cpp @@ -0,0 +1,59 @@ +/* + * Copyright (C) 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 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. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. 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 "config.h" +#include "SetSelectionCommand.h" + +#include "Document.h" +#include "Frame.h" + +namespace WebCore { + +SetSelectionCommand::SetSelectionCommand(const VisibleSelection& selection, FrameSelection::SetSelectionOptions options) + : SimpleEditCommand(selection.base().anchorNode()->document()) + , m_options(options) + , m_selectionToSet(selection) +{ +} + +void SetSelectionCommand::doApply() +{ + FrameSelection& selection = frame().selection(); + + if (selection.shouldChangeSelection(m_selectionToSet) && !m_selectionToSet.isNoneOrOrphaned()) { + selection.setSelection(m_selectionToSet, m_options); + setEndingSelection(m_selectionToSet); + } +} + +void SetSelectionCommand::doUnapply() +{ + FrameSelection& selection = frame().selection(); + + if (selection.shouldChangeSelection(startingSelection()) && !startingSelection().isNoneOrOrphaned()) + selection.setSelection(startingSelection(), m_options); +} + +} // namespace WebCore diff --git a/pool/shard010/C++/0111279_unnamed_event.cc b/pool/shard010/C++/0111279_unnamed_event.cc new file mode 100644 index 0000000000000000000000000000000000000000..f52c79aac7c521ee03e523998f429d2e03385119 --- /dev/null +++ b/pool/shard010/C++/0111279_unnamed_event.cc @@ -0,0 +1,197 @@ +// Copyright 2010-2016, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. 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. + +#include "base/unnamed_event.h" + +#ifdef OS_WIN +#include +#else // OS_WIN +#include +#include +#include +#endif // OS_WIN + +#include "base/logging.h" +#include "base/port.h" + +namespace gbase { + +#ifdef OS_WIN +UnnamedEvent::UnnamedEvent() + : handle_(::CreateEvent(NULL, FALSE, FALSE, NULL)) { + // Use Auto reset mode of Win32 Event. (2nd arg of CreateEvent). + // pthread_cond_signal: auto reset mode. + // pthread_cond_broadcast: manual reset mode. + if (NULL == handle_.get()) { + LOG(ERROR) << "CreateEvent failed: " << ::GetLastError(); + } +} + +UnnamedEvent::~UnnamedEvent() {} + +bool UnnamedEvent::IsAvailable() const { + return (NULL != handle_.get()); +} + +bool UnnamedEvent::Notify() { + if (!IsAvailable()) { + LOG(WARNING) << "Event object is not available"; + return false; + } + + if (!::SetEvent(handle_.get())) { + LOG(ERROR) << "SetEvent failed: " << ::GetLastError(); + return false; + } + + return true; +} + +bool UnnamedEvent::Wait(int msec) { + if (!IsAvailable()) { + return true; // assume that it is already raised + } + + if (msec < 0) { + msec = INFINITE; + } + + return WAIT_TIMEOUT != + ::WaitForSingleObject(handle_.get(), msec); +} + +#else // OS_WIN + +namespace { +class ScopedPthreadMutexLock { + public: + explicit ScopedPthreadMutexLock(pthread_mutex_t *mutex) : mutex_(mutex) { + pthread_mutex_lock(mutex_); + } + ~ScopedPthreadMutexLock() { + pthread_mutex_unlock(mutex_); + } + + private: + pthread_mutex_t *mutex_; + DISALLOW_COPY_AND_ASSIGN(ScopedPthreadMutexLock); +}; +} // namespace + +UnnamedEvent::UnnamedEvent() : notified_(false) { + pthread_mutex_init(&mutex_, NULL); + pthread_cond_init(&cond_, NULL); +} + +// It is necessary to ensure that no threads wait for this event before the +// destruction. +UnnamedEvent::~UnnamedEvent() { + pthread_mutex_destroy(&mutex_); + pthread_cond_destroy(&cond_); +} + +bool UnnamedEvent::IsAvailable() const { + return true; +} + +bool UnnamedEvent::Notify() { + { + ScopedPthreadMutexLock lock(&mutex_); + notified_ = true; + } + + // Note: Need to awake all threads waiting for this event. Otherwise + // some thread would start to work incorrectly in some cases. + // An example error scenario is: + // - there are four threads, A, B, C and D. + // - A and B are producers. C and D are consumers. + // - C and D start to wait this event. + // - Then A notifies. + // - A takes the lock. + // - set notified_ true. + // - A releases the lock. + // - Then before A sends a signal to awake a thread (either C or D), + // B takes the lock. + // - A sends a signal, but both C and D are sleeping as the lock is + // still taken by B. + // - B releases the lock. So one of the thread (let's assume C for this + // example) starts to run, because it can take the lock. + // - B also sends a signal again. + // - C overrides notified_ to false, and releases the lock. + // - At last, D starts to run wrongly. + // The broadcast and while (in Wait) idiom is a popular way to fix such + // cases. + pthread_cond_broadcast(&cond_); + return true; +} + +bool UnnamedEvent::Wait(int msec) { + ScopedPthreadMutexLock lock(&mutex_); + if (!notified_) { + // Need to wait actually. + if (msec < 0) { + // Wait forever. + while (!notified_) { + pthread_cond_wait(&cond_, &mutex_); + } + } else { + // Wait with time out. + struct timeval tv; + if (gettimeofday(&tv, NULL) != 0) { + LOG(ERROR) << "Failed to take the current time: " << errno; + return false; + } + + struct timespec timeout; + timeout.tv_sec = tv.tv_sec + msec / 1000; + timeout.tv_nsec = 1000 * (tv.tv_usec + 1000 * (msec % 1000)); + + // if tv_nsec >= 10^9, pthread_cond_timedwait may return EINVAL + while (timeout.tv_nsec >= 1000000000) { + timeout.tv_sec++; + timeout.tv_nsec -= 1000000000; + } + + int result = 0; + while (!notified_ && result == 0) { + result = pthread_cond_timedwait(&cond_, &mutex_, &timeout); + } + + if (result != 0) { + // Time out. + return false; + } + } + } + DCHECK(notified_); + notified_ = false; + return true; +} +#endif // OS_WIN +} // namespace gbase diff --git a/pool/shard010/C++/0111283_connect_test.cpp b/pool/shard010/C++/0111283_connect_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2975a514d7c844f851dbd29a8dbb7af293b9d39a --- /dev/null +++ b/pool/shard010/C++/0111283_connect_test.cpp @@ -0,0 +1,222 @@ +/* + Copyright (C) Kai Blin 2007 + + 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 + + A client/server connect test for dplay. +*/ +#define INITGUID +#define _WIN32_DCOM +#include +#include +#include +#include + +// {EF016237-BEEE-402a-A2D6-A2694C109574} +DEFINE_GUID(CONNECT_TEST, +0xef016237, 0xbeee, 0x402a, 0xa2, 0xd6, 0xa2, 0x69, 0x4c, 0x10, 0x95, 0x74); + +typedef struct _dp_player_list { + DPID dpid; + char name[15]; + DWORD flags; + struct _dp_player_list *next; +} dp_player_list; + +//------------------------ Globals ---------------------- +IDirectPlay8Peer *pDP = NULL; +IDirectPlay8Address *pDP_addr = NULL; +BOOL is_server = FALSE; + +//------------------ Function prototypes ---------------- +DWORD handleArgs(int argc, char **argv); +HRESULT WINAPI dPlayMsgHandler(void * user_context, DWORD msg_id, void * msg_buff); +HRESULT initDPlay(); +void cleanupDPlay(); +HRESULT enumDPlaySP(); +HRESULT getDPlayAddr(); +HRESULT hostGame(); + +int main(int argc, char** argv) +{ + HRESULT hr; + DWORD dwresult; + MSG msg; + BOOL done = FALSE; + int i = 0; + + if((dwresult = handleArgs(argc, argv)) == -1) + { + return dwresult; + } + + if(FAILED(hr = CoInitialize(NULL))) + { + return -1; + } + + if(FAILED(hr = initDPlay())) + { + fprintf(stderr, "Failed to init dplay: 0x%08x\n", hr); + goto cleanup; + } + + if(FAILED(hr = enumDPlaySP())) + { + fprintf(stderr, "Failed enumerating service providers: 0x%08x\n", hr); + goto cleanup; + } + + if(FAILED(hr = getDPlayAddr())) + { + fprintf(stderr, "Failed to get IDirectPlay8Address com object: 0x%08x\n", hr); + goto cleanup; + } + + if(is_server) + { + printf("Selected server mode, hosting a game.\n"); + if(FAILED(hr = hostGame())) + { + fprintf(stderr, "Failed to host game: 0x%08x\n", hr); + goto cleanup; + } + } + else + { + printf("Selected client mode, enumerating games.\n"); + } + +#if 0 + while(!done) + { + if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) + { + TranslateMessage(&msg); + DispatchMessage(&msg); + } + else + { + // fake game loop + ++i; + if(is_server) + printf("S"); + else + printf("c"); + if(i > 25) + break; + } + } +#endif + puts("Press any key to exit."); + getchar(); + +cleanup: + cleanupDPlay(); + CoUninitialize(); +} + +DWORD handleArgs(int argc, char **argv) +{ + if(argc < 2) + { + is_server = FALSE; + return 0; + } + if(strcmp(argv[1], "server") == 0) + is_server = TRUE; + + return 0; +} + +HRESULT WINAPI dPlayMsgHandler(void * user_context, DWORD msg_id, void * msg_buff) +{ + return S_OK; +} + +HRESULT enumDPlaySP() +{ + HRESULT hr; + DWORD items = 0, size = 0, i; + DPN_SERVICE_PROVIDER_INFO *dp_sp_info, *dp_sp_item; + + hr = pDP->EnumServiceProviders(NULL, NULL, NULL, &size, &items, 0); + + if(hr != DPNERR_BUFFERTOOSMALL) + { + fprintf(stderr, "Failed to get the service provider array size: 0x%08x\n", hr); + return hr; + } + + dp_sp_info = static_cast(CoTaskMemAlloc(size)); + + if(FAILED(hr = pDP->EnumServiceProviders(NULL, NULL, dp_sp_info, &size, &items, 0))) + { + fprintf(stderr, "Failed to enumerate service providers: 0x%08x\n", hr); + return hr; + } + + dp_sp_item = dp_sp_info; + printf("Found %d providers:\n", items); + for(i = 0; i < items; ++i) + { + printf("Provider: %S\n", dp_sp_item->pwszName); + ++dp_sp_item; + } + + CoTaskMemFree(dp_sp_info); + return hr; +} + +HRESULT getDPlayAddr() +{ + HRESULT hr; + + if(FAILED(hr = CoCreateInstance(CLSID_DirectPlay8Address, NULL, CLSCTX_INPROC_SERVER, IID_IDirectPlay8Address, + (LPVOID *)&pDP_addr))) + { + fprintf(stderr, "Failed to create IDirectPlay8Address instance: 0x%08x\n", hr); + return hr; + } + + if(FAILED(pDP_addr->SetSP(&CLSID_DP8SP_TCPIP))) + { + fprintf(stderr, "Failed to set TCP/IP service provider: 0x%08x\n", hr); + return hr; + } + + printf("Loaded the TCP/IP service provider.\n"); + return hr; +} + +HRESULT hostGame() +{ + HRESULT hr; + DPN_APPLICATION_DESC app_desc; + + ZeroMemory(&app_desc, sizeof(DPN_APPLICATION_DESC)); + app_desc.dwSize = sizeof(DPN_APPLICATION_DESC); + app_desc.guidApplication = CONNECT_TEST; + + if(FAILED(hr = pDP->Host(&app_desc, &pDP_addr, 1, NULL, NULL, NULL, DPNHOST_OKTOQUERYFORADDRESSING))) + { + fprintf(stderr, "Failed to host a game: 0x%08x\n", hr); + return hr; + } + + printf("Hosted game.\n"); + + return hr; +} + diff --git a/pool/shard010/C++/0111284_main.cpp b/pool/shard010/C++/0111284_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..011ffdfd50111b145f2bb89ef7447d4be8b36c81 --- /dev/null +++ b/pool/shard010/C++/0111284_main.cpp @@ -0,0 +1,48 @@ +#include +#include +#include +#include +#include + +#include + +using namespace std; + + +int main(int argc, char **argv) { + if (argc < 2) { + cerr << "Usage: " << argv[0] << " [--wast]" << endl; + return 1; + } + + bool wast = false; + if (argc == 3) { + wast = (string(argv[2]) == "--wast"); + if (!wast) { + cerr << "Usage: " << argv[0] << " [--wast]" << endl; + return 1; + } + } + + ifstream input(argv[1]); + if (!input.is_open()) { + cerr << "File not found: " << argv[1] << endl; + return 1; + } + + string str( + (std::istreambuf_iterator(input)), + std::istreambuf_iterator() + ); + + // clean input of any whitespace (including space and new lines) + str.erase(remove_if(str.begin(), str.end(), [](unsigned char x){return std::isspace(x);}), str.end()); + + if (wast) { + cout << evm2wasm::evmhex2wast(str); + } else { + cout << evm2wasm::evmhex2wasm(str); + } + + return 0; +} diff --git a/pool/shard010/C++/0111285_speedwidget.cpp b/pool/shard010/C++/0111285_speedwidget.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6a321c2f865c15d2592dc49aa71f3fdf27cb5801 --- /dev/null +++ b/pool/shard010/C++/0111285_speedwidget.cpp @@ -0,0 +1,205 @@ +/* + * Bittorrent Client using Qt and libtorrent. + * Copyright (C) 2015 Anton Lashkov + * + * 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. + * + * In addition, as a special exception, the copyright holders give permission to + * link this program with the OpenSSL project's "OpenSSL" library (or with + * modified versions of it that use the same license as the "OpenSSL" library), + * and distribute the linked executables. You must obey the GNU General Public + * License in all respects for all of the code used other than "OpenSSL". If you + * modify file(s), you may extend this exception to your version of the file(s), + * but you are not obligated to do so. If you do not wish to do so, delete this + * exception statement from your version. + */ + +#include "speedwidget.h" + +#include +#include +#include +#include +#include + +#include + +#include "propertieswidget.h" +#include "base/bittorrent/session.h" +#include "base/bittorrent/sessionstatus.h" +#include "base/preferences.h" +#include "base/utils/misc.h" + +ComboBoxMenuButton::ComboBoxMenuButton(QWidget *parent, QMenu *menu) + : QComboBox(parent) + , m_menu(menu) +{ +} + +void ComboBoxMenuButton::showPopup() +{ + QPoint p = mapToGlobal(QPoint(0, height())); + m_menu->exec(p); + QComboBox::hidePopup(); +} + + +SpeedWidget::SpeedWidget(PropertiesWidget *parent) + : QWidget(parent) +{ + m_layout = new QVBoxLayout(this); + m_layout->setContentsMargins(0, 0, 0, 0); + + m_hlayout = new QHBoxLayout(); + m_hlayout->setContentsMargins(0, 0, 0, 0); + + m_periodLabel = new QLabel("" + tr("Period:") + ""); + + m_periodCombobox = new QComboBox(); + m_periodCombobox->addItem(tr("1 Minute")); + m_periodCombobox->addItem(tr("5 Minutes")); + m_periodCombobox->addItem(tr("30 Minutes")); + m_periodCombobox->addItem(tr("6 Hours")); + + connect(m_periodCombobox, SIGNAL(currentIndexChanged(int)), this, SLOT(onPeriodChange(int))); + + m_graphsMenu = new QMenu(); + m_graphsMenu->addAction(tr("Total Upload")); + m_graphsMenu->addAction(tr("Total Download")); + m_graphsMenu->addAction(tr("Payload Upload")); + m_graphsMenu->addAction(tr("Payload Download")); + m_graphsMenu->addAction(tr("Overhead Upload")); + m_graphsMenu->addAction(tr("Overhead Download")); + m_graphsMenu->addAction(tr("DHT Upload")); + m_graphsMenu->addAction(tr("DHT Download")); + m_graphsMenu->addAction(tr("Tracker Upload")); + m_graphsMenu->addAction(tr("Tracker Download")); + + m_graphsMenuActions = m_graphsMenu->actions(); + m_graphsSignalMapper = new QSignalMapper(); + + for (int id = SpeedPlotView::UP; id < SpeedPlotView::NB_GRAPHS; ++id) { + QAction *action = m_graphsMenuActions.at(id); + action->setCheckable(true); + action->setChecked(true); + connect(action, SIGNAL(changed()), m_graphsSignalMapper, SLOT(map())); + m_graphsSignalMapper->setMapping(action, id); + } + connect(m_graphsSignalMapper, SIGNAL(mapped(int)), this, SLOT(onGraphChange(int))); + + m_graphsButton = new ComboBoxMenuButton(this, m_graphsMenu); + m_graphsButton->addItem(tr("Select Graphs")); + + m_hlayout->addWidget(m_periodLabel); + m_hlayout->addWidget(m_periodCombobox); + m_hlayout->addStretch(); + m_hlayout->addWidget(m_graphsButton); + + m_plot = new SpeedPlotView(this); + + m_layout->addLayout(m_hlayout); + m_layout->addWidget(m_plot); + + loadSettings(); + + m_isUpdating = true; + m_updateFuture = QtConcurrent::run(this, &SpeedWidget::update); + + m_plot->show(); +} + +SpeedWidget::~SpeedWidget() +{ + qDebug("SpeedWidget::~SpeedWidget() ENTER"); + + m_isUpdating = false; + m_updateFuture.waitForFinished(); + + saveSettings(); + + qDebug("SpeedWidget::~SpeedWidget() EXIT"); +} + +void SpeedWidget::update() +{ + while (m_isUpdating) { + + BitTorrent::SessionStatus btStatus = BitTorrent::Session::instance()->status(); + + m_plot->pushXPoint(QDateTime::currentDateTime().toTime_t()); + m_plot->pushYPoint(SpeedPlotView::UP, btStatus.uploadRate()); + m_plot->pushYPoint(SpeedPlotView::DOWN, btStatus.downloadRate()); + m_plot->pushYPoint(SpeedPlotView::PAYLOAD_UP, btStatus.payloadUploadRate()); + m_plot->pushYPoint(SpeedPlotView::PAYLOAD_DOWN, btStatus.payloadDownloadRate()); + m_plot->pushYPoint(SpeedPlotView::OVERHEAD_UP, btStatus.ipOverheadUploadRate()); + m_plot->pushYPoint(SpeedPlotView::OVERHEAD_DOWN, btStatus.ipOverheadDownloadRate()); + m_plot->pushYPoint(SpeedPlotView::DHT_UP, btStatus.dhtUploadRate()); + m_plot->pushYPoint(SpeedPlotView::DHT_DOWN, btStatus.dhtDownloadRate()); + m_plot->pushYPoint(SpeedPlotView::TRACKER_UP, btStatus.trackerUploadRate()); + m_plot->pushYPoint(SpeedPlotView::TRACKER_DOWN, btStatus.trackerDownloadRate()); + + QMetaObject::invokeMethod(this, "graphUpdate", Qt::QueuedConnection); + Utils::Misc::msleep(1000); + } +} + +void SpeedWidget::graphUpdate() +{ + m_plot->replot(); +} + +void SpeedWidget::onPeriodChange(int period) +{ + m_plot->setViewableLastPoints(static_cast(period)); + graphUpdate(); +} + +void SpeedWidget::onGraphChange(int id) +{ + QAction *action = m_graphsMenuActions.at(id); + m_plot->setGraphEnable(static_cast(id), action->isChecked()); + + graphUpdate(); +} + +void SpeedWidget::loadSettings() +{ + Preferences *preferences = Preferences::instance(); + + int periodIndex = preferences->getSpeedWidgetPeriod(); + m_periodCombobox->setCurrentIndex(periodIndex); + onPeriodChange(static_cast(periodIndex)); + + for (int id = SpeedPlotView::UP; id < SpeedPlotView::NB_GRAPHS; ++id) { + QAction *action = m_graphsMenuActions.at(id); + bool enable = preferences->getSpeedWidgetGraphEnable(id); + + action->setChecked(enable); + m_plot->setGraphEnable(static_cast(id), enable); + } +} + +void SpeedWidget::saveSettings() const +{ + Preferences *preferences = Preferences::instance(); + + preferences->setSpeedWidgetPeriod(m_periodCombobox->currentIndex()); + + for (int id = SpeedPlotView::UP; id < SpeedPlotView::NB_GRAPHS; ++id) { + QAction *action = m_graphsMenuActions.at(id); + preferences->setSpeedWidgetGraphEnable(id, action->isChecked()); + } +} + diff --git a/pool/shard010/C++/0111286_camera_self_filter_server.cpp b/pool/shard010/C++/0111286_camera_self_filter_server.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e24edfbc353fc45e33bf3baee879801ed45bd4b4 --- /dev/null +++ b/pool/shard010/C++/0111286_camera_self_filter_server.cpp @@ -0,0 +1,186 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * Copyright (c) 2008, Robert Bosch LLC. + * 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 Robert Bosch 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. + * + *********************************************************************/ + +/* + * camera_self_filter.cpp + * + * Created on: Oct 6, 2010 + * Author: christian + */ + +#include + +#include +#include +#include +#include "cv_bridge/CvBridge.h" +#include "sensor_msgs/Image.h" +#include "sensor_msgs/CameraInfo.h" +#include "image_transport/image_transport.h" +#include + +#define GL_GLEXT_PROTOTYPES +#include +#include +#include + +#include "camera_self_filter/robotMeshModel.h" +#include "camera_self_filter/mask.h" + + +RobotMeshModel* robmod=NULL; +IplImage* ipl_maskBGRA = NULL; +IplImage* ipl_maskBW = NULL; + +bool inverted; +sensor_msgs::CvBridge bridge; + + +void initializeGL () +{ + glClearColor(0, 0, 0, 0); +// glEnable(GL_LIGHTING); +// glEnable(GL_LIGHT0); + glEnable(GL_NORMALIZE); + glEnable(GL_COLOR_MATERIAL); + glEnable(GL_CULL_FACE); + glEnable(GL_DEPTH_TEST); + glShadeModel(GL_SMOOTH); + glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, + GL_LINEAR_MIPMAP_LINEAR); +} + + + +//function that draws the robot at current state +void display() { + + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + + robmod->setCamera(); + robmod->setCameraPose(); + robmod->paintRobot(); + glReadPixels(0, 0, robmod->cam_info_->width, robmod->cam_info_->height , GL_BGRA, GL_UNSIGNED_BYTE, ipl_maskBGRA->imageData); + + glutSwapBuffers(); +} + + + +sensor_msgs::ImagePtr calc_and_publish_BWMask(const ros::Time time_stamp, const std::string frame_id ){ + robmod->updateRobotLinks(time_stamp); + glutPostRedisplay(); + glutMainLoopEvent(); + cvCvtColor(ipl_maskBGRA, ipl_maskBW, CV_BGRA2GRAY); + cvFlip(ipl_maskBW); + if (inverted) + cvNot(ipl_maskBW,ipl_maskBW); + + sensor_msgs::ImagePtr img_msg = sensor_msgs::CvBridge::cvToImgMsg(ipl_maskBW); + img_msg->header.frame_id = frame_id; + img_msg->header.stamp = time_stamp; + return img_msg; + + + +} + +bool calcMaskCB(camera_self_filter::maskRequest& req, camera_self_filter::maskResponse& res){ + sensor_msgs::ImagePtr img = calc_and_publish_BWMask(req.header.stamp, req.header.frame_id); + res.mask_image = *img; + return true; + +} + + +int main(int argc, char **argv) { + glutInit(&argc, argv); + ros::init(argc, argv, "robot_self_filter"); + + + //create selfilter service + ros::NodeHandle nh; + ros::NodeHandle nh_priv("~"); + + //set parameters + + + std::string camera_topic; + std::string camera_info_topic; + + nh_priv.param("inverted",inverted, false); + nh_priv.param("camera_topic", camera_topic, "/wide_stereo/right/image_rect_color" ); + nh_priv.param("camera_info_topic", camera_info_topic, "/wide_stereo/right/camera_info" ); + + ROS_INFO("camera topic %s", camera_topic.c_str()); + ROS_INFO("camera info %s", camera_info_topic.c_str()); + + //create robot model + robmod = new RobotMeshModel; + + //initialize glut + glutInitWindowSize (robmod->cam_info_->width, robmod->cam_info_->height); + glutInitDisplayMode ( GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH); + + + glutCreateWindow ("dummy"); + glutHideWindow(); + + initializeGL(); + // Register glut callbacks: + glutDisplayFunc (display); + + ipl_maskBGRA = cvCreateImage(cvSize( robmod->cam_info_->width, robmod->cam_info_->height), IPL_DEPTH_8U, 4); + ipl_maskBW = cvCreateImage(cvSize( robmod->cam_info_->width, robmod->cam_info_->height), IPL_DEPTH_8U, 1); + + + + + + ros::ServiceServer mask_service = nh.advertiseService("self_mask", calcMaskCB ); + + + ros::spin(); + + + //clean up + cvReleaseImage(&ipl_maskBGRA); + cvReleaseImage(&ipl_maskBW); + delete robmod; + return 0; +} + diff --git a/pool/shard010/C++/0111288_CAirbusStaticPort.cpp b/pool/shard010/C++/0111288_CAirbusStaticPort.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b7261ea2169a807b0e7e71b98c94ea6acf1927e9 --- /dev/null +++ b/pool/shard010/C++/0111288_CAirbusStaticPort.cpp @@ -0,0 +1,53 @@ + +// qt-plus +#include "CLogger.h" + +// Quick3D +#include "CConsoleBoard.h" +#include "C3DScene.h" +#include "CAtmosphere.h" +#include "CAircraft.h" + +// Application +#include "CAirbusStaticPort.h" + +using namespace Math; + +//------------------------------------------------------------------------------------------------- + +CComponent* CAirbusStaticPort::instantiator(C3DScene* pScene) +{ + return new CAirbusStaticPort(pScene); +} + +//------------------------------------------------------------------------------------------------- + +CAirbusStaticPort::CAirbusStaticPort(C3DScene* pScene) + : CComponent(pScene) +{ +} + +//------------------------------------------------------------------------------------------------- + +CAirbusStaticPort::~CAirbusStaticPort() +{ +} + +//------------------------------------------------------------------------------------------------- + +void CAirbusStaticPort::update(double dDeltaTime) +{ + QSP pAircraft = QSP_CAST(CAircraft, root()); + + if (pAircraft) + { + double dPressure = CAtmosphere::getInstance()->pressure_Nm2(pAircraft->geoloc().Altitude) * N_TO_KG; + + pushData(CAirbusData(m_sName, adStatic_Pressure_kgm2, dPressure)); + + LOG_VALUE(QString("%1 (PRS KGM2)").arg(m_sName), + QString("%1") + .arg(QString::number(dPressure, 'f', 4)) + ); + } +} diff --git a/pool/shard010/C++/0111293_MSOfficeTextStripper.cpp b/pool/shard010/C++/0111293_MSOfficeTextStripper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..841251312ff273aa2d897d7f4cde5801d31fa990 --- /dev/null +++ b/pool/shard010/C++/0111293_MSOfficeTextStripper.cpp @@ -0,0 +1,98 @@ +#include +#include +#include "MSOfficeTextStripper.h" + +#ifdef WIN32 +#include +#endif + +using namespace std; +FX_NS_DEF(plugin); + + +MSOfficeTextStripper::MSOfficeTextStripper(void) + : m_pTextBuffer(NULL) + , m_nTextPos(0) + , m_nTextSize(0) +{ + m_pAnalyze = new Analyze(this); +} + +MSOfficeTextStripper::~MSOfficeTextStripper(void) +{ + if (m_pTextBuffer) + { + delete m_pTextBuffer; + m_pTextBuffer = NULL; + } + m_nTextSize = 0; + m_nTextPos = 0; + delete m_pAnalyze; +} + +char* MSOfficeTextStripper::strip(const char* szFileName) +{ + m_nTextPos = 0; + + FILE* hFile = fopen(szFileName, "rb"); + if (!hFile) + return NULL; + + const char* p = szFileName; + while(*p) + p++; + p--; + if (*p == L't') + m_pAnalyze->parsePPT(hFile); + else if (*p == L's') + m_pAnalyze->parseXLS(hFile); + else + m_pAnalyze->parseDOC(hFile); + + fclose(hFile); + + if (m_nTextPos > 0 ) + return m_pTextBuffer; + return NULL; +} + +void MSOfficeTextStripper::output_paragraph(unsigned short int *buffer) +{ + size_t len = wcslen((const wchar_t*)buffer); + if (!m_pTextBuffer || (m_nTextSize - m_nTextPos < len) ) + growBuffer(0); +#ifdef WIN32 + int nRet = WideCharToMultiByte(CP_ACP, 0, (const wchar_t*)buffer, (int)len, + m_pTextBuffer + m_nTextPos, (int)m_nTextSize - m_nTextPos, NULL, NULL); + if (nRet > 0) + { + m_nTextPos += nRet; + } +#else + mbstate_t state; + memset( &state, 0, sizeof(state) ); + wchar_t const* tmp = (wchar_t const*)buffer; + size_t nRet = wcsrtombs(m_pTextBuffer + m_nTextPos,&tmp,m_nTextSize - m_nTextPos,&state); + if (nRet != (size_t)-1) + m_nTextPos += nRet; +#endif + if (m_nTextSize - m_nTextPos > 0) + m_pTextBuffer[m_nTextPos++] = ' '; +} + +void MSOfficeTextStripper::growBuffer(size_t nGrowLen) +{ + size_t nNewLen = m_nTextSize + nGrowLen; + if (nNewLen < (m_nTextSize << 1) ) + nNewLen = (m_nTextSize << 1); + if (nNewLen < (size_t)DEFAULT_TEXTBUF_SIZE) + nNewLen = DEFAULT_TEXTBUF_SIZE; + char* pBuf = new char[nNewLen]; + if (m_nTextPos > 0) + memcpy(pBuf,m_pTextBuffer,m_nTextPos); + delete[] m_pTextBuffer; + m_pTextBuffer = pBuf; + m_nTextSize = nNewLen; +} + +FX_NS_END diff --git a/pool/shard010/C++/0111295_dfsalgo.cpp b/pool/shard010/C++/0111295_dfsalgo.cpp new file mode 100644 index 0000000000000000000000000000000000000000..44ee30e8d3e20a190c372414a53fb8f386594a5e --- /dev/null +++ b/pool/shard010/C++/0111295_dfsalgo.cpp @@ -0,0 +1,107 @@ +/***************************************************************************** + * Copyright © 2016 Oakware - All Rights Reserved + * + * Github : + * Authors: Ivan Kondratuk + * + * This file is part of Graph Builder. + * + * Graph Builder 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. + * + * Graph Builder 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 Graph Builder. If not, see . + *****************************************************************************/ + +#include "dfsalgo.h" +#include "AlgoPlugins/graphreset.h" + +#define asleep() if(!sl->sleep(params.sleepTime)) return false; + +DfsAlgo::DfsAlgo(QObject *par): + QObject(par) +{ + sl = new Sleeper(this); +} + +bool DfsAlgo::run(AbstractGraph *gr, int sver){ + VectorListGS sgr = gr->getGraphModel().toVectorList(); // Return if + if(sgr.count() <= 1) return false; // no vertexes + + QBitArray vis(sgr.count()); // Variables + QStack st; + int conComp = 1; + + st << sver; vis[sver] = true; + resetGraph(gr, "#03A9F4", params.ri.color); + AG_CHANGE_VER_PARAM((*gr), sver, color, "#7E57C2") + + while(!st.empty()){ + asleep(); + + int i, v = st.top(); + for(i=0; iisOriented()){ + result += '\n'; + result += tr("Connected components count: ") + + QString::number(conComp); + } + return true; +} + +void DfsAlgo::stop(){ + sl->stop(); +} + +QString DfsAlgo::name(){ + return tr("DFS"); +} + +QString DfsAlgo::qmlDialog(){ + return "qrc:/DFS/ResDialog.qml"; +} + +QString DfsAlgo::getResult(){ + return result; +} + +void DfsAlgo::setParams(const plugParams &pp){ + params = pp; +} diff --git a/pool/shard010/C++/0111298_DeferredRenderPipeline.cpp b/pool/shard010/C++/0111298_DeferredRenderPipeline.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2590b5b99a43402401565cd4cc98ff2b1570dafd --- /dev/null +++ b/pool/shard010/C++/0111298_DeferredRenderPipeline.cpp @@ -0,0 +1,74 @@ +#include "DeferredRenderPipeline.h" +#include "SceneManager.h" +#include "MeshRendererComponent.h" +#include "Lighting.h" + +using namespace std; +using namespace AnEngine::Game; +using namespace AnEngine::RenderCore; + +namespace AnEngine::RenderCore +{ + void DeferredRenderPipeline::OnRender(std::mutex& sceneResMutex) + { + FenceContext::Instance()->WaitAllFence(); + + /* GBuffer阶段,渲染所有摄像机的 GBuffer、Depth、Normal */ + //lock_guard lock(sceneResMutex); + GBuffer(); + + /* 对于场景中的每一个光源,绘制其深度图,以生成阴影。 */ + //lock_guard lock(sceneResMutex); + DepthPreLight(); + + /* 阴影 */ + FenceContext::Instance()->WaitAllFence(); + Shadow(); + + /* 反射 */ + + /* 使用前向渲染处理半透明物体 */ + + /* 天空盒 */ + + /* 全屏后处理 */ + FenceContext::Instance()->WaitAllFence(); + PostProcess(); + + /* 绘制UI组件 */ + UI(); + } + + void DeferredRenderPipeline::GBuffer() + { + var scene = Game::SceneManager::ActiveScene(); + // 网格渲染器是 ECS 组织的 + var objs = scene->GetGroupOfType(); // 从场景中获取所有的 Mesh Renderer 组件进行渲染 + const auto& mrs = *objs; + var[list, allocator] = GraphicsContext::GetOne(); + var ilist = list->GetCommandList(); + var iallocator = allocator->GetAllocator(); + ThrowIfFailed(iallocator->Reset()); + + ThrowIfFailed(ilist->Close()); + GraphicsContext::Push(list, allocator); + } + + void DeferredRenderPipeline::DepthPreLight() + { + var scene = Game::SceneManager::ActiveScene(); + // 灯光是 Behaviour 组织的 + + } + + void DeferredRenderPipeline::Shadow() + { + } + + void DeferredRenderPipeline::UI() + { + } + void DeferredRenderPipeline::PostProcess() + { + } +} \ No newline at end of file diff --git a/pool/shard010/C++/0111302_QGis.cpp b/pool/shard010/C++/0111302_QGis.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2d0c126ec5caf824bc8d7210183a600287605daa --- /dev/null +++ b/pool/shard010/C++/0111302_QGis.cpp @@ -0,0 +1,78 @@ +/************************************************************************************ +TerraME - a software platform for multiple scale spatially-explicit dynamic modeling. +Copyright (C) 2001-2017 INPE and TerraLAB/UFOP -- www.terrame.org + +This code is part of the TerraME framework. +This framework 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. + +You should have received a copy of the GNU Lesser General Public +License along with this library. + +The authors reassure the license terms regarding the warranties. +They specifically disclaim any warranties, including, but not limited to, +the implied warranties of merchantability and fitness for a particular purpose. +The framework provided hereunder is on an "as is" basis, and the authors have no +obligation to provide maintenance, support, updates, enhancements, or modifications. +In no event shall INPE and TerraLAB / UFOP be held liable to any party for direct, +indirect, special, incidental, or consequential damages arising out of the use +of this software and its documentation. +*************************************************************************************/ + +#include "QGis.h" + +#include + +#include "QgsReader.h" +#include "QgsWriter.h" +#include "Utils.h" + +terrame::qgis::QGis& terrame::qgis::QGis::getInstance() +{ + static terrame::qgis::QGis instance; + return instance; +} + +terrame::qgis::QGisProject terrame::qgis::QGis::read(const std::string& qgsfile) +{ + QgsReader reader; + reader.setPostgisRole(user, password); + return reader.read(qgsfile); +} + +void terrame::qgis::QGis::write(const QGisProject& qgp) +{ + QgsWriter writer; + + if (boost::filesystem::exists(qgp.getFile())) + { + QGisProject fileQgp = getInstance().read(qgp.getFile()); + std::vector layersInFile = fileQgp.getLayers(); + std::vector layersParam = qgp.getLayers(); + std::vector layersToAdd = fileQgp.getLayersDiff(qgp); + std::vector layersToRemove = qgp.getLayersDiff(fileQgp); + + if(layersToAdd.size() > 0) + { + writer.addLayers(qgp, layersToAdd); + } + + if(layersToRemove.size() > 0) + { + writer.removeLayers(qgp, layersToRemove); + } + } + else + { + writer.create(qgp); + } +} + +void terrame::qgis::QGis::setPostgisRole(const std::string& user, + const std::string& password) +{ + this->user = user; + this->password = password; +} diff --git a/pool/shard010/C++/0111303_enumliterals.cpp b/pool/shard010/C++/0111303_enumliterals.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c17cb885b1e837cdcccbcc16e2d9196eba6bd25e --- /dev/null +++ b/pool/shard010/C++/0111303_enumliterals.cpp @@ -0,0 +1,26 @@ +#include "enumliterals.h" + +#include "dock/pages/model/enumliteralsmodel.h" + +EnumLiterals::EnumLiterals(QWidget* parent) : PageBase(parent),ui(new Ui_GenericTable()),m_pModel(0) +{ + ui->setupUi(this); +} + +EnumLiterals::~EnumLiterals() +{ + delete ui; +} + +void EnumLiterals::setCurrentObject(UMLObject* o) +{ + if (!m_pModel) { + m_pModel = new EnumLiteralsModel(this); + ui->m_pTable->setModel(m_pModel); + ui->m_pTable->horizontalHeader()->setResizeMode(0,QHeaderView::Stretch); + for (int i=1;icolumnCount();i++) { + ui->m_pTable->horizontalHeader()->setResizeMode(i,QHeaderView::ResizeToContents); + } + } + m_pModel->setCurrentObject(o); +} \ No newline at end of file diff --git a/pool/shard010/C++/0111308_playerwatcher.cpp b/pool/shard010/C++/0111308_playerwatcher.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a621b72a011001dde6374d7251c827553fe72c7e --- /dev/null +++ b/pool/shard010/C++/0111308_playerwatcher.cpp @@ -0,0 +1,153 @@ +#include "playerwatcher.h" + +#include "playerinterface.h" +#include "propertiesinterface.h" + +#include +#include + +#include + +using namespace std; +using namespace CppUtilities; + +namespace DBusSoundRecorder { + +inline ostream &operator<<(ostream &stream, const QString &str) +{ + return stream << str.toLocal8Bit().data(); +} + +PlayerWatcher::PlayerWatcher(const QString &appName, bool ignorePlaybackStatus, QObject *parent) + : QObject(parent) + , m_mediaPlayerInterfaceName(QStringLiteral("org.mpris.MediaPlayer2.%1").arg(appName)) + , m_mediaPlayerServiceWatcher( + new QDBusServiceWatcher(m_mediaPlayerInterfaceName, QDBusConnection::sessionBus(), QDBusServiceWatcher::WatchForOwnerChange, this)) + , m_propertiesInterface(new OrgFreedesktopDBusPropertiesInterface( + m_mediaPlayerInterfaceName, QStringLiteral("/org/mpris/MediaPlayer2"), QDBusConnection::sessionBus(), this)) + , m_playerInterface(new OrgMprisMediaPlayer2PlayerInterface( + m_mediaPlayerInterfaceName, QStringLiteral("/org/mpris/MediaPlayer2"), QDBusConnection::sessionBus(), this)) + , m_isPlaying(false) + , m_isAd(false) + , m_trackNumber(0) + , m_diskNumber(0) + , m_silent(false) + , m_ignorePlaybackStatus(ignorePlaybackStatus) +{ + if (!connect(m_mediaPlayerServiceWatcher, &QDBusServiceWatcher::serviceOwnerChanged, this, &PlayerWatcher::serviceOwnerChanged)) { + cout << "Warning: Unable to connect \"serviceOwnerChanged\" signal of service watcher." << endl; + } + // The code below might not work with some players: + //if(!connect(m_propertiesInterface, &OrgFreedesktopDBusPropertiesInterface::PropertiesChanged, this, &PlayerWatcher::propertiesChanged)) { + // cout << "Warning: Unable to connect \"PropertiesChanged\" signal of properties interface." << endl; + //} + // However, the following seems to work always: + if (!QDBusConnection::sessionBus().connect(m_mediaPlayerInterfaceName, QStringLiteral("/org/mpris/MediaPlayer2"), + QStringLiteral("org.freedesktop.DBus.Properties"), QStringLiteral("PropertiesChanged"), this, SLOT(propertiesChanged()))) { + cout << "Warning: Unable to connect \"PropertiesChanged\" signal of properties interface." << endl; + } + propertiesChanged(); +} + +void PlayerWatcher::play() +{ + m_playerInterface->Play(); +} + +void PlayerWatcher::stop() +{ + m_playerInterface->Stop(); +} + +void PlayerWatcher::pause() +{ + m_playerInterface->Pause(); +} + +void PlayerWatcher::playPause() +{ + m_playerInterface->PlayPause(); +} + +void PlayerWatcher::serviceOwnerChanged(const QString &service, const QString &oldOwner, const QString &newOwner) +{ + if (oldOwner.isEmpty()) { + cerr << "MPRIS service \"" << service << "\" is now online" << endl; + } + if (newOwner.isEmpty()) { + cerr << "MPRIS service \"" << service << "\" went offline" << endl; + } +} + +void PlayerWatcher::propertiesChanged() +{ + // get meta data + QVariantMap metadata = m_playerInterface->metadata(); + m_isAd = metadata.value(QStringLiteral("mpris:trackid")).toString().startsWith(QLatin1String("spotify:ad")); + QString title = metadata.value(QStringLiteral("xesam:title")).toString(); + QString album = metadata.value(QStringLiteral("xesam:album")).toString(); + QString artist = metadata.value(QStringLiteral("xesam:artist")).toString(); + bool isPlaying; + if (m_ignorePlaybackStatus) { + // determine playback status by checking whether there is a song title + isPlaying = !title.isEmpty(); + } else { + isPlaying = !m_playerInterface->playbackStatus().compare(QLatin1String("playing"), Qt::CaseInsensitive); + } + if (isPlaying) { + if (!m_isPlaying) { + cerr << "Playback started" << endl; + } + // use title, album and artist to identify song + if (m_title != title || m_album != album || m_artist != artist) { + // next song playing + m_title = title; + m_album = album; + m_artist = artist; + // read additional meta data + m_year = metadata.value(QStringLiteral("xesam:contentCreated")).toString(); + m_genre = metadata.value(QStringLiteral("xesam:genre")).toString(); + m_trackNumber = metadata.value(QStringLiteral("xesam:tracknumber")).toUInt(); + if (!m_trackNumber) { + m_trackNumber = metadata.value(QStringLiteral("xesam:trackNumber")).toUInt(); + } + m_diskNumber = metadata.value(QStringLiteral("xesam:discnumber")).toUInt(); + if (!m_diskNumber) { + m_diskNumber = metadata.value(QStringLiteral("xesam:discNumber")).toUInt(); + } + m_length = TimeSpan(metadata.value(QStringLiteral("mpris:length")).toULongLong() * 10); + // notify + cerr << "Next song: " << m_title << endl; + if (!m_isPlaying && !m_silent) { + m_isPlaying = true; + emit playbackStarted(); + } + if (!m_silent) { + m_isPlaying = true; + emit nextSong(); + } + } else if (!m_isPlaying) { + if (!m_silent) { + m_isPlaying = true; + emit playbackStarted(); + } + } + } else if (m_isPlaying) { + m_isPlaying = false; + cerr << "Playback stopped" << endl; + if (!m_silent) { + emit playbackStopped(); + } + } +} + +void PlayerWatcher::notificationReceived() +{ + cout << "It works!" << endl; +} + +void PlayerWatcher::seeked(qlonglong pos) +{ + cerr << "Seeked: " << pos << endl; +} +} // namespace DBusSoundRecorder diff --git a/pool/shard010/C++/0111312_MCASBench.cpp b/pool/shard010/C++/0111312_MCASBench.cpp new file mode 100644 index 0000000000000000000000000000000000000000..136c7070f70827a3c5fa764938ec81e45190e7f7 --- /dev/null +++ b/pool/shard010/C++/0111312_MCASBench.cpp @@ -0,0 +1,88 @@ +/** + * Copyright (C) 2011 + * University of Rochester Department of Computer Science + * and + * Lehigh University Department of Computer Science and Engineering + * + * License: Modified BSD + * Please see the file LICENSE.RSTM for licensing information + */ + +#if defined(STM_CPU_SPARC) +#include +#endif + +/** + * Step 1: + * Include the configuration code for the harness, and the API code. + */ +#include +#include +#include +#include "bmconfig.hpp" + +/** + * We provide the option to build the entire benchmark in a single + * source. The bmconfig.hpp include defines all of the important functions + * that are implemented in this file, and bmharness.cpp defines the + * execution infrastructure. + */ +#ifdef SINGLE_SOURCE_BUILD +#include "bmharness.cpp" +#endif + +/** + * Step 2: + * Declare the data type that will be stress tested via this benchmark. + * Also provide any functions that will be needed to manipulate the data + * type. Take care to avoid unnecessary indirection. + */ + +int* matrix; + +/** + * Step 3: + * Declare an instance of the data type, and provide init, test, and verify + * functions + */ + +/*** Initialize an array that we can use for our MCAS test */ +void bench_init() +{ + matrix = (int*)malloc(CFG.elements * sizeof(int)); +} + +/*** Run a bunch of random transactions */ +void bench_test(uintptr_t, uint32_t* seed) +{ + // cache the seed locally so we can restore it on abort + // + // NB: volatile needed because using a non-volatile local in conjunction + // with a setjmp-longjmp control transfer is undefined, and gcc won't + // allow it with -Wall -Werror. + volatile uint32_t local_seed = *seed; + + TM_BEGIN(atomic) { + for (uint32_t i = 0; i < CFG.ops; ++i) { + uint32_t loc = rand_r_32(&local_seed) % CFG.elements; + TM_WRITE(matrix[loc], 1 + TM_READ(matrix[loc])); + } + } TM_END; + *seed = local_seed; +} + +/*** Ensure the final state of the benchmark satisfies all invariants */ +bool bench_verify() { return true; } + +/** + * Step 4: + * Include the code that has the main() function, and the code for creating + * threads and calling the three above-named functions. Don't forget to + * provide an arg reparser. + */ + +/*** Deal with special names that map to different M values */ +void bench_reparse() +{ + if (CFG.bmname == "") CFG.bmname = "MCAS"; +} diff --git a/pool/shard010/C++/0111313_File.cpp b/pool/shard010/C++/0111313_File.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ea694e97b4e37b0741a16b29970fbd3ce7fcf787 --- /dev/null +++ b/pool/shard010/C++/0111313_File.cpp @@ -0,0 +1,92 @@ +#include "File.h" + +#include +#include + +#include + + +/** + * @class File + * A file can be filled by a downloader or read by an uploader. + * It has a fixed size. + * 'read' and 'write' are thread safe and a 'QReadWriteLock'. + */ + +/** + * Create a new empty file or open an existing one. + * If the file already exists the given size must match. + */ +File::File(const QString& name, quint64 size) throw(FileSizeDoesntMatchException) + : size(size) +{ + this->fileInWriteMode = new QFile(name); + if (this->fileInWriteMode->exists()) + { + if ((quint64)this->fileInWriteMode->size() != this->size) + throw FileSizeDoesntMatchException(); + } + this->fileInWriteMode->open(QIODevice::WriteOnly); + this->fileInWriteMode->resize(this->size); // Warning : can fail + + this->fileInReadMode = new QFile(name); + this->fileInReadMode->open(QIODevice::ReadOnly); + + quint64 offset = 0; + for (int chunkNum = 0; offset < size; offset += File::chunkSize, chunkNum++) + this->chunks.append(new Chunk(*this, chunkNum)); +} + +File::~File() +{ + this->fileInWriteMode->flush(); + + delete this->fileInWriteMode; + delete this->fileInReadMode; + foreach (Chunk* chunk, this->chunks) + delete chunk; +} + +/** + * Write some bytes to the file at the given offset. + * If the buffer exceed the file size then only the beginning of the buffer is + * used, the file is not resizing. + */ +bool File::write(const QByteArray& buffer, qint64 offset) +{ + if ((quint64)offset >= this->size) + return true; + + QMutexLocker locker(&this->writeLock); + + this->fileInWriteMode->seek(offset); + int maxSize = (this->size - offset); + qint64 n = this->fileInWriteMode->write(buffer.data(), buffer.size() > maxSize ? maxSize : buffer.size()); + + return offset + n >= (qint64)this->size || n == -1; +} + +/** + * Fill the buffer with the read bytes from the given offset. + * If the end of file is reached the buffer will be partialy filled. + */ +qint64 File::read(QByteArray& buffer, qint64 offset) +{ + if ((quint64)offset >= this->size) + return 0; + + QMutexLocker locker(&this->readLock); + + this->fileInReadMode->seek(offset); + qint64 bytesRead = this->fileInReadMode->read(buffer.data(), buffer.size()); + + return bytesRead; +} + +/** + * Return a collection of the file's chunks. + */ +const QList& File::getChunks() +{ + return this->chunks; +} diff --git a/pool/shard010/C++/0111318_PersonalizeErrors.cpp b/pool/shard010/C++/0111318_PersonalizeErrors.cpp new file mode 100644 index 0000000000000000000000000000000000000000..eeedf6c514c95aab847fd47c809856a0cc5b3dd9 --- /dev/null +++ b/pool/shard010/C++/0111318_PersonalizeErrors.cpp @@ -0,0 +1,57 @@ +/** + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0. + */ + +#include +#include +#include + +using namespace Aws::Client; +using namespace Aws::Utils; +using namespace Aws::Personalize; + +namespace Aws +{ +namespace Personalize +{ +namespace PersonalizeErrorMapper +{ + +static const int RESOURCE_ALREADY_EXISTS_HASH = HashingUtils::HashString("ResourceAlreadyExistsException"); +static const int LIMIT_EXCEEDED_HASH = HashingUtils::HashString("LimitExceededException"); +static const int INVALID_INPUT_HASH = HashingUtils::HashString("InvalidInputException"); +static const int RESOURCE_IN_USE_HASH = HashingUtils::HashString("ResourceInUseException"); +static const int INVALID_NEXT_TOKEN_HASH = HashingUtils::HashString("InvalidNextTokenException"); + + +AWSError GetErrorForName(const char* errorName) +{ + int hashCode = HashingUtils::HashString(errorName); + + if (hashCode == RESOURCE_ALREADY_EXISTS_HASH) + { + return AWSError(static_cast(PersonalizeErrors::RESOURCE_ALREADY_EXISTS), false); + } + else if (hashCode == LIMIT_EXCEEDED_HASH) + { + return AWSError(static_cast(PersonalizeErrors::LIMIT_EXCEEDED), true); + } + else if (hashCode == INVALID_INPUT_HASH) + { + return AWSError(static_cast(PersonalizeErrors::INVALID_INPUT), false); + } + else if (hashCode == RESOURCE_IN_USE_HASH) + { + return AWSError(static_cast(PersonalizeErrors::RESOURCE_IN_USE), false); + } + else if (hashCode == INVALID_NEXT_TOKEN_HASH) + { + return AWSError(static_cast(PersonalizeErrors::INVALID_NEXT_TOKEN), false); + } + return AWSError(CoreErrors::UNKNOWN, false); +} + +} // namespace PersonalizeErrorMapper +} // namespace Personalize +} // namespace Aws diff --git a/pool/shard010/C++/0111319_git.cpp b/pool/shard010/C++/0111319_git.cpp new file mode 100644 index 0000000000000000000000000000000000000000..03dc639d1944468ae6519a6a3ab52a99d9f30aac --- /dev/null +++ b/pool/shard010/C++/0111319_git.cpp @@ -0,0 +1,169 @@ +// Copyright 2015 Stefano Pogliani +#include + +#include "repositories/git/git.hpp" +#include "repositories/git/internal/error.hpp" +#include "repositories/git/internal/istream.hpp" + +using sf::exception::GitException; +using sf::exception::GitInvalidVersion; +using sf::exception::GitTypeError; + +using sf::repository::GitRepo; +using sf::repository::GitRepoVersion; +using sf::repository::RepositoryVersionRef; + +using sf::repository::internal::GitBlobStream; +using sf::repository::internal::GitBlobStreamBuf; +using sf::repository::internal::checkGitError; + + +void GitRepo::ensure_repo_is_open() { + // Return if repository is open valid. + if (this->repo) { + return; + } + + int error = git_repository_open(&this->repo, this->path.c_str()); + checkGitError(error); +} + +git_commit* GitRepo::resolveCommit(std::string revision) { + this->ensure_repo_is_open(); + + // Get object named by revision. + git_object* object = nullptr; + int error = git_revparse_single(&object, this->repo, revision.c_str()); + checkGitError(error); + + // Check type is commit. + if (git_object_type(object) != GIT_OBJ_COMMIT) { + git_object_free(object); + throw GitTypeError(GIT_OBJ_COMMIT, git_object_type(object)); + } + + return (git_commit*)object; +} + + +GitRepo::GitRepo(std::string path, std::string latest) { + this->latest_alias = latest; + this->path = path; + this->repo = nullptr; +} + +GitRepo::~GitRepo() { + if (this->repo) { + git_repository_free(this->repo); + } +} + +RepositoryVersionRef GitRepo::latest() { + return this->version(this->latest_alias); +} + +RepositoryVersionRef GitRepo::version(std::string revision) { + git_commit* commit = this->resolveCommit(revision); + git_tree* tree = nullptr; + + int error = git_commit_tree(&tree, commit); + git_commit_free(commit); + + checkGitError(error); + return RepositoryVersionRef(new GitRepoVersion(this, tree)); +} + +std::string GitRepo::resolveVersion( + sf::state::Context context, const std::string version +) { + this->verifyVersion(context, version); + git_commit* commit = nullptr; + + // Resolve special version. + if (version == "") { + commit = this->resolveCommit(this->latest_alias); + } else { + commit = this->resolveCommit(version); + } + + // Get commit ID. + char oidstr[GIT_OID_HEXSZ + 1]; + git_oid_tostr(oidstr, sizeof(oidstr), git_commit_id(commit)); + + git_commit_free(commit); + return std::string(oidstr); +} + +void GitRepo::verifyVersion( + sf::state::Context, const std::string version +) { + // Try to resolve the commit. + try { + // Resolve special version. + if (version == "") { + this->resolveCommit(this->latest_alias); + } else { + this->resolveCommit(version); + } + + } catch (GitTypeError&) { + throw GitInvalidVersion(version); + + } catch (GitException& exc) { + // If the version cannot be parsed or the commit + // cannot be found throw an exception. + int code = exc.gitCode(); + if (code == GIT_ENOTFOUND || code == GIT_EAMBIGUOUS) { + throw GitInvalidVersion(version); + } + + // Otherwise propagate the original exception. + throw; + } +} + + +GitRepoVersion::GitRepoVersion(GitRepo* repo, git_tree* tree) { + this->repo = repo; + this->tree = tree; +} + +GitRepoVersion::~GitRepoVersion() { + git_tree_free(this->tree); +} + +bool GitRepoVersion::exists(const std::string path) { + git_tree_entry* entry = nullptr; + int error = git_tree_entry_bypath(&entry, this->tree, path.c_str()); + if (error == GIT_ENOTFOUND) { + return false; + } + + checkGitError(error); + git_tree_entry_free(entry); + return true; +} + +std::istream* GitRepoVersion::streamFileRaw(const std::string path) { + // Get tree entry from path. + git_tree_entry* entry = nullptr; + int error = git_tree_entry_bypath(&entry, this->tree, path.c_str()); + checkGitError(error); + + // Check type is blob. + if (git_tree_entry_type(entry) != GIT_OBJ_BLOB) { + git_tree_entry_free(entry); + throw GitTypeError(GIT_OBJ_BLOB, git_tree_entry_type(entry)); + } + + // Convert to blob. + git_blob* blob = nullptr; + error = git_blob_lookup(&blob, this->repo->repo, git_tree_entry_id(entry)); + git_tree_entry_free(entry); + checkGitError(error); + + // Build stream and return. + GitBlobStreamBuf* buffer = new GitBlobStreamBuf(blob); + git_blob_free(blob); + return new GitBlobStream(buffer); +} diff --git a/pool/shard010/C++/0111322_net_converter.cc b/pool/shard010/C++/0111322_net_converter.cc new file mode 100644 index 0000000000000000000000000000000000000000..5223709ae585f128ab9933e1d2c80c7b5aaa3eb5 --- /dev/null +++ b/pool/shard010/C++/0111322_net_converter.cc @@ -0,0 +1,99 @@ +// Copyright (c) 2015 GitHub, Inc. +// Use of this source code is governed by the MIT license that can be +// found in the LICENSE file. + +#include "atom/common/native_mate_converters/net_converter.h" + +#include +#include + +#include "atom/common/node_includes.h" +#include "atom/common/native_mate_converters/gurl_converter.h" +#include "atom/common/native_mate_converters/value_converter.h" +#include "base/values.h" +#include "native_mate/dictionary.h" +#include "net/base/upload_bytes_element_reader.h" +#include "net/base/upload_data_stream.h" +#include "net/base/upload_element_reader.h" +#include "net/base/upload_file_element_reader.h" +#include "net/cert/x509_certificate.h" +#include "net/http/http_response_headers.h" +#include "net/url_request/url_request.h" + +namespace mate { + +// static +v8::Local Converter::ToV8( + v8::Isolate* isolate, const net::URLRequest* val) { + scoped_ptr dict(new base::DictionaryValue); + dict->SetString("method", val->method()); + std::string url; + if (!val->url_chain().empty()) url = val->url().spec(); + dict->SetStringWithoutPathExpansion("url", url); + dict->SetString("referrer", val->referrer()); + scoped_ptr list(new base::ListValue); + atom::GetUploadData(list.get(), val); + if (!list->empty()) + dict->Set("uploadData", std::move(list)); + return mate::ConvertToV8(isolate, *(dict.get())); +} + +// static +v8::Local Converter::ToV8( + v8::Isolate* isolate, const net::AuthChallengeInfo* val) { + mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate); + dict.Set("isProxy", val->is_proxy); + dict.Set("scheme", val->scheme); + dict.Set("host", val->challenger.host()); + dict.Set("port", static_cast(val->challenger.port())); + dict.Set("realm", val->realm); + return mate::ConvertToV8(isolate, dict); +} + +// static +v8::Local Converter>::ToV8( + v8::Isolate* isolate, const scoped_refptr& val) { + mate::Dictionary dict(isolate, v8::Object::New(isolate)); + std::string encoded_data; + net::X509Certificate::GetPEMEncoded( + val->os_cert_handle(), &encoded_data); + auto buffer = node::Buffer::Copy(isolate, + encoded_data.data(), + encoded_data.size()).ToLocalChecked(); + dict.Set("data", buffer); + dict.Set("issuerName", val->issuer().GetDisplayName()); + return dict.GetHandle(); +} + +} // namespace mate + +namespace atom { + +void GetUploadData(base::ListValue* upload_data_list, + const net::URLRequest* request) { + const net::UploadDataStream* upload_data = request->get_upload(); + if (!upload_data) + return; + const std::vector>* readers = + upload_data->GetElementReaders(); + for (const auto& reader : *readers) { + scoped_ptr upload_data_dict( + new base::DictionaryValue); + if (reader->AsBytesReader()) { + const net::UploadBytesElementReader* bytes_reader = + reader->AsBytesReader(); + scoped_ptr bytes( + base::BinaryValue::CreateWithCopiedBuffer(bytes_reader->bytes(), + bytes_reader->length())); + upload_data_dict->Set("bytes", std::move(bytes)); + } else if (reader->AsFileReader()) { + const net::UploadFileElementReader* file_reader = + reader->AsFileReader(); + auto file_path = file_reader->path().AsUTF8Unsafe(); + upload_data_dict->SetStringWithoutPathExpansion("file", file_path); + } + upload_data_list->Append(std::move(upload_data_dict)); + } +} + +} // namespace atom diff --git a/pool/shard010/C++/0111323_ecma-lcache.cpp b/pool/shard010/C++/0111323_ecma-lcache.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5ce4aca499507ce934f20e85f9ca7054c692a8b5 --- /dev/null +++ b/pool/shard010/C++/0111323_ecma-lcache.cpp @@ -0,0 +1,348 @@ +/* Copyright 2014-2015 Samsung Electronics Co., Ltd. + * + * 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 "ecma-gc.h" +#include "ecma-globals.h" +#include "ecma-helpers.h" +#include "ecma-lcache.h" +#include "jrt-libc-includes.h" + +/** \addtogroup ecma ECMA + * @{ + * + * \addtogroup ecmalcache Property lookup cache + * @{ + */ + +#ifndef CONFIG_ECMA_LCACHE_DISABLE +/** + * Entry of LCache hash table + */ +typedef struct +{ + /** Compressed pointer to object (ECMA_NULL_POINTER marks record empty) */ + mem_cpointer_t object_cp; + + /** Compressed pointer to property's name */ + mem_cpointer_t prop_name_cp; + + /** Compressed pointer to a property of the object */ + mem_cpointer_t prop_cp; + + /** Padding structure to 8 bytes size */ + uint16_t padding; +} ecma_lcache_hash_entry_t; + +JERRY_STATIC_ASSERT (sizeof (ecma_lcache_hash_entry_t) == sizeof (uint64_t)); + +/** + * LCache hash value length, in bits + */ +#define ECMA_LCACHE_HASH_BITS (sizeof (lit_string_hash_t) * JERRY_BITSINBYTE) + +/** + * Number of rows in LCache's hash table + */ +#define ECMA_LCACHE_HASH_ROWS_COUNT (1ull << ECMA_LCACHE_HASH_BITS) + +/** + * Number of entries in a row of LCache's hash table + */ +#define ECMA_LCACHE_HASH_ROW_LENGTH (2) + +/** + * LCache's hash table + */ +static ecma_lcache_hash_entry_t ecma_lcache_hash_table[ ECMA_LCACHE_HASH_ROWS_COUNT ][ ECMA_LCACHE_HASH_ROW_LENGTH ]; +#endif /* !CONFIG_ECMA_LCACHE_DISABLE */ + +/** + * Initialize LCache + */ +void +ecma_lcache_init (void) +{ +#ifndef CONFIG_ECMA_LCACHE_DISABLE + memset (ecma_lcache_hash_table, 0, sizeof (ecma_lcache_hash_table)); +#endif /* !CONFIG_ECMA_LCACHE_DISABLE */ +} /* ecma_lcache_init */ + +#ifndef CONFIG_ECMA_LCACHE_DISABLE +/** + * Invalidate specified LCache entry + */ +static void +ecma_lcache_invalidate_entry (ecma_lcache_hash_entry_t *entry_p) /**< entry to invalidate */ +{ + JERRY_ASSERT (entry_p != NULL); + JERRY_ASSERT (entry_p->object_cp != ECMA_NULL_POINTER); + + ecma_deref_object (ECMA_GET_NON_NULL_POINTER (ecma_object_t, + entry_p->object_cp)); + + entry_p->object_cp = ECMA_NULL_POINTER; + ecma_deref_ecma_string (ECMA_GET_NON_NULL_POINTER (ecma_string_t, + entry_p->prop_name_cp)); + + if (entry_p->prop_cp != ECMA_NULL_POINTER) + { + ecma_set_property_lcached (ECMA_GET_NON_NULL_POINTER (ecma_property_t, + entry_p->prop_cp), + false); + } +} /* ecma_lcache_invalidate_entry */ +#endif /* !CONFIG_ECMA_LCACHE_DISABLE */ + +/** + * Invalidate all entries in LCache + */ +void +ecma_lcache_invalidate_all (void) +{ +#ifndef CONFIG_ECMA_LCACHE_DISABLE + for (uint32_t row_index = 0; row_index < ECMA_LCACHE_HASH_ROWS_COUNT; row_index++) + { + for (uint32_t entry_index = 0; entry_index < ECMA_LCACHE_HASH_ROW_LENGTH; entry_index++) + { + if (ecma_lcache_hash_table[ row_index ][ entry_index ].object_cp != ECMA_NULL_POINTER) + { + ecma_lcache_invalidate_entry (&ecma_lcache_hash_table[ row_index ][ entry_index ]); + } + } + } +#endif /* !CONFIG_ECMA_LCACHE_DISABLE */ +} /* ecma_lcache_invalidate_all */ + +#ifndef CONFIG_ECMA_LCACHE_DISABLE +/** + * Invalidate entries of LCache's row that correspond to given (object, property) pair + */ +static void +ecma_lcache_invalidate_row_for_object_property_pair (uint32_t row_index, /**< index of the row */ + unsigned int object_cp, /**< compressed pointer + * to an object */ + unsigned property_cp) /**< compressed pointer + * to the object's + * property */ +{ + for (uint32_t entry_index = 0; entry_index < ECMA_LCACHE_HASH_ROW_LENGTH; entry_index++) + { + if (ecma_lcache_hash_table[ row_index ][ entry_index ].object_cp == object_cp + && ecma_lcache_hash_table[ row_index ][ entry_index ].prop_cp == property_cp) + { + ecma_lcache_invalidate_entry (&ecma_lcache_hash_table[ row_index ][ entry_index ]); + } + } +} /* ecma_lcache_invalidate_row_for_object_property_pair */ +#endif /* !CONFIG_ECMA_LCACHE_DISABLE */ + +/** + * Insert an entry into LCache + */ +void +ecma_lcache_insert (ecma_object_t *object_p, /**< object */ + ecma_string_t *prop_name_p, /**< property's name */ + ecma_property_t *prop_p) /**< pointer to associated property or NULL + * (NULL indicates that the object doesn't have property + * with the name specified) */ +{ + JERRY_ASSERT (object_p != NULL); + JERRY_ASSERT (prop_name_p != NULL); + +#ifndef CONFIG_ECMA_LCACHE_DISABLE + prop_name_p = ecma_copy_or_ref_ecma_string (prop_name_p); + + lit_string_hash_t hash_key = ecma_string_hash (prop_name_p); + + if (prop_p != NULL) + { + if (unlikely (ecma_is_property_lcached (prop_p))) + { + mem_cpointer_t prop_cp; + ECMA_SET_NON_NULL_POINTER (prop_cp, prop_p); + + int32_t entry_index; + for (entry_index = 0; entry_index < ECMA_LCACHE_HASH_ROW_LENGTH; entry_index++) + { + if (ecma_lcache_hash_table[hash_key][entry_index].object_cp != ECMA_NULL_POINTER + && ecma_lcache_hash_table[hash_key][entry_index].prop_cp == prop_cp) + { +#ifndef JERRY_NDEBUG + ecma_object_t* obj_in_entry_p; + obj_in_entry_p = ECMA_GET_NON_NULL_POINTER (ecma_object_t, + ecma_lcache_hash_table[hash_key][entry_index].object_cp); + JERRY_ASSERT (obj_in_entry_p == object_p); +#endif /* !JERRY_NDEBUG */ + break; + } + } + + JERRY_ASSERT (entry_index != ECMA_LCACHE_HASH_ROW_LENGTH); + ecma_lcache_invalidate_entry (&ecma_lcache_hash_table[hash_key][entry_index]); + } + + JERRY_ASSERT (!ecma_is_property_lcached (prop_p)); + ecma_set_property_lcached (prop_p, true); + } + + int32_t entry_index; + for (entry_index = 0; entry_index < ECMA_LCACHE_HASH_ROW_LENGTH; entry_index++) + { + if (ecma_lcache_hash_table[hash_key][entry_index].object_cp == ECMA_NULL_POINTER) + { + break; + } + } + + if (entry_index == ECMA_LCACHE_HASH_ROW_LENGTH) + { + /* No empty entry was found, invalidating the whole row */ + for (uint32_t i = 0; i < ECMA_LCACHE_HASH_ROW_LENGTH; i++) + { + ecma_lcache_invalidate_entry (&ecma_lcache_hash_table[hash_key][i]); + } + + entry_index = 0; + } + + ecma_ref_object (object_p); + ECMA_SET_NON_NULL_POINTER (ecma_lcache_hash_table[ hash_key ][ entry_index ].object_cp, object_p); + ECMA_SET_NON_NULL_POINTER (ecma_lcache_hash_table[ hash_key ][ entry_index ].prop_name_cp, prop_name_p); + ECMA_SET_POINTER (ecma_lcache_hash_table[ hash_key ][ entry_index ].prop_cp, prop_p); +#else /* CONFIG_ECMA_LCACHE_DISABLE */ + (void) prop_p; +#endif /* CONFIG_ECMA_LCACHE_DISABLE */ +} /* ecma_lcache_insert */ + +/** + * Lookup property in the LCache + * + * @return true - if (object, property name) pair is registered in LCache, + * false - probably, not registered. + */ +bool __attr_always_inline___ +ecma_lcache_lookup (ecma_object_t *object_p, /**< object */ + const ecma_string_t *prop_name_p, /**< property's name */ + ecma_property_t **prop_p_p) /**< out: if return value is true, + * then here will be pointer to property, + * if the object contains property with specified name, + * or, otherwise - NULL; + * if return value is false, + * then the output parameter is not set */ +{ +#ifndef CONFIG_ECMA_LCACHE_DISABLE + lit_string_hash_t hash_key = ecma_string_hash (prop_name_p); + + unsigned int object_cp; + ECMA_SET_NON_NULL_POINTER (object_cp, object_p); + + for (uint32_t i = 0; i < ECMA_LCACHE_HASH_ROW_LENGTH; i++) + { + if (ecma_lcache_hash_table[hash_key][i].object_cp == object_cp) + { + ecma_string_t *entry_prop_name_p = ECMA_GET_NON_NULL_POINTER (ecma_string_t, + ecma_lcache_hash_table[hash_key][i].prop_name_cp); + + if (ecma_compare_ecma_strings_equal_hashes (prop_name_p, entry_prop_name_p)) + { + ecma_property_t *prop_p = ECMA_GET_POINTER (ecma_property_t, ecma_lcache_hash_table[hash_key][i].prop_cp); + JERRY_ASSERT (prop_p == NULL || ecma_is_property_lcached (prop_p)); + + *prop_p_p = prop_p; + + return true; + } + else + { + /* may be equal but it is long to compare it here */ + } + } + } +#else /* CONFIG_ECMA_LCACHE_DISABLE */ + (void) object_p; + (void) prop_name_p; + (void) prop_p_p; +#endif /* CONFIG_ECMA_LCACHE_DISABLE */ + + return false; +} /* ecma_lcache_lookup */ + +/** + * Invalidate LCache entries associated with given object and property name / property + * + * Note: + * Either property name argument or property argument should be NULL, + * and another should be non-NULL. + * In case property name argument is NULL, property's name is taken + * from property's description. + */ +void +ecma_lcache_invalidate (ecma_object_t *object_p, /**< object */ + ecma_string_t *prop_name_arg_p, /**< property's name (See also: Note) */ + ecma_property_t *prop_p) /**< property (See also: Note) */ +{ + JERRY_ASSERT (object_p != NULL); + JERRY_ASSERT (prop_p != NULL || prop_name_arg_p != NULL); + +#ifndef CONFIG_ECMA_LCACHE_DISABLE + ecma_string_t *prop_name_p = NULL; + + if (prop_p != NULL) + { + JERRY_ASSERT (prop_p->type == ECMA_PROPERTY_NAMEDDATA + || prop_p->type == ECMA_PROPERTY_NAMEDACCESSOR); + + bool is_cached = ecma_is_property_lcached (prop_p); + + if (!is_cached) + { + return; + } + + ecma_set_property_lcached (prop_p, false); + + if (prop_p->type == ECMA_PROPERTY_NAMEDDATA) + { + prop_name_p = ECMA_GET_NON_NULL_POINTER (ecma_string_t, + prop_p->u.named_data_property.name_p); + } + else + { + prop_name_p = ECMA_GET_NON_NULL_POINTER (ecma_string_t, + prop_p->u.named_accessor_property.name_p); + } + } + else + { + prop_name_p = prop_name_arg_p; + } + + unsigned int object_cp, prop_cp; + ECMA_SET_NON_NULL_POINTER (object_cp, object_p); + ECMA_SET_POINTER (prop_cp, prop_p); + + lit_string_hash_t hash_key = ecma_string_hash (prop_name_p); + + /* Property's name has was computed. + * Given (object, property name) pair should be in the row corresponding to computed hash. + */ + ecma_lcache_invalidate_row_for_object_property_pair (hash_key, object_cp, prop_cp); +#endif /* !CONFIG_ECMA_LCACHE_DISABLE */ +} /* ecma_lcache_invalidate */ + +/** + * @} + * @} + */ diff --git a/pool/shard010/C++/0111328_vectorv.cc b/pool/shard010/C++/0111328_vectorv.cc new file mode 100644 index 0000000000000000000000000000000000000000..0efff4172e3e650604eb8f5d4aef78ff10f685f3 --- /dev/null +++ b/pool/shard010/C++/0111328_vectorv.cc @@ -0,0 +1,154 @@ +/* + * vectorv.cc -- template specialization for Vector + * Eddie Kohler + * + * Copyright (c) 1999-2000 Massachusetts Institute of Technology + * + * 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, subject to the conditions + * listed in the Click LICENSE file. These conditions include: you must + * preserve this copyright notice, and you cannot mention the copyright + * holders in advertising related to the Software without their permission. + * The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This + * notice is a summary of the Click LICENSE file; the license in that file is + * legally binding. + */ + +#include +#include +#include +CLICK_DECLS + +Vector::Vector(const Vector &x) + : _l(0), _n(0), _capacity(0) +{ + *this = x; +} + +Vector::~Vector() +{ + CLICK_LFREE(_l, sizeof(void *) * _capacity); +} + +Vector & +Vector::operator=(const Vector &o) +{ + if (&o != this) { +#ifdef VALGRIND_MAKE_MEM_NOACCESS + if (_l && _n) + VALGRIND_MAKE_MEM_NOACCESS(_l, _n * sizeof(void *)); +#endif + _n = 0; + if (reserve(o._n)) { + _n = o._n; +#ifdef VALGRIND_MAKE_MEM_UNDEFINED + if (_l && _n) + VALGRIND_MAKE_MEM_UNDEFINED(_l, _n * sizeof(void *)); +#endif + memcpy(_l, o._l, sizeof(void *) * _n); + } + } + return *this; +} + +Vector & +Vector::assign(size_type n, void* e) +{ +#ifdef VALGRIND_MAKE_MEM_NOACCESS + if (_l && _n) + VALGRIND_MAKE_MEM_NOACCESS(_l, _n * sizeof(void *)); +#endif + _n = 0; + resize(n, e); + return *this; +} + +Vector::iterator +Vector::insert(iterator i, void* e) +{ + assert(i >= begin() && i <= end()); + size_type pos = i - begin(); + if (_n < _capacity || reserve(RESERVE_GROW)) { +#ifdef VALGRIND_MAKE_MEM_UNDEFINED + VALGRIND_MAKE_MEM_UNDEFINED(_l + _n, sizeof(void*)); +#endif + i = begin() + pos; + memmove(i + 1, i, (end() - i) * sizeof(void*)); + *i = e; + _n++; + } + return i; +} + +Vector::iterator +Vector::erase(iterator a, iterator b) +{ + if (b > a) { + assert(a >= begin() && b <= end()); + memmove(a, b, (end() - b) * sizeof(void*)); + _n -= b - a; +#ifdef VALGRIND_MAKE_MEM_NOACCESS + VALGRIND_MAKE_MEM_NOACCESS(_l + _n, (b - a) * sizeof(void *)); +#endif + return a; + } else + return b; +} + +bool +Vector::reserve(size_type want) +{ + if (want < 0) + want = (_capacity > 0 ? _capacity * 2 : 4); + if (want <= _capacity) + return true; + + void** new_l = (void **) CLICK_LALLOC(sizeof(void *) * want); + if (!new_l) + return false; +#ifdef VALGRIND_MAKE_MEM_NOACCESS + VALGRIND_MAKE_MEM_NOACCESS(new_l + _n, (want - _n) * sizeof(void *)); +#endif + + memcpy(new_l, _l, sizeof(void*) * _n); + CLICK_LFREE(_l, sizeof(void *) * _capacity); + + _l = new_l; + _capacity = want; + return true; +} + +void +Vector::resize(size_type nn, void* e) +{ + if (nn <= _capacity || reserve(nn)) { +#ifdef VALGRIND_MAKE_MEM_NOACCESS + if (nn < _n) + VALGRIND_MAKE_MEM_NOACCESS(_l + nn, (_n - nn) * sizeof(void *)); + if (_n < nn) + VALGRIND_MAKE_MEM_UNDEFINED(_l + _n, (nn - _n) * sizeof(void *)); +#endif + for (size_type i = _n; i < nn; i++) + _l[i] = e; + _n = nn; + } +} + +void +Vector::swap(Vector &x) +{ + void **l = _l; + _l = x._l; + x._l = l; + + size_type n = _n; + _n = x._n; + x._n = n; + + size_type cap = _capacity; + _capacity = x._capacity; + x._capacity = cap; +} + +CLICK_ENDDECLS diff --git a/pool/shard010/C++/0111333_RotateTransformOperation.cpp b/pool/shard010/C++/0111333_RotateTransformOperation.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e64cd7d1e0846a0244d9453d5837ae585b115951 --- /dev/null +++ b/pool/shard010/C++/0111333_RotateTransformOperation.cpp @@ -0,0 +1,159 @@ +/* + * Copyright (C) 1999 Antti Koivisto (koivisto@kde.org) + * Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved. + * + * 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; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + * + */ + +#include "config.h" +#include "platform/transforms/RotateTransformOperation.h" + +#include "platform/animation/AnimationUtilities.h" +#include "platform/geometry/FloatPoint3D.h" +#include "wtf/MathExtras.h" +#include + +using namespace std; + +namespace blink { + +static const double angleEpsilon = 1e-4; + +FloatPoint3D RotateTransformOperation::axis() const +{ + return FloatPoint3D(x(), y(), z()); +} + +bool RotateTransformOperation::shareSameAxis(const RotateTransformOperation* from, const RotateTransformOperation* to, FloatPoint3D* axis, double* fromAngle, double* toAngle) +{ + *axis = FloatPoint3D(0, 0, 1); + *fromAngle = 0; + *toAngle = 0; + + if (!from && !to) + return true; + + bool fromZero = !from || from->axis().isZero(); + bool toZero = !to || to->axis().isZero(); + + if (fromZero && toZero) + return true; + + if (fromZero) { + *axis = to->axis(); + *toAngle = to->angle(); + return true; + } + + if (toZero) { + *axis = from->axis(); + *fromAngle = from->angle(); + return true; + } + + FloatPoint3D fromAxis = from->axis(); + FloatPoint3D toAxis = to->axis(); + + double fromSquared = fromAxis.lengthSquared(); + double toSquared = toAxis.lengthSquared(); + + double dot = fromAxis.dot(toAxis); + double error = std::abs(1 - (dot * dot) / (fromSquared * toSquared)); + + if (error > angleEpsilon) + return false; + *axis = from->axis(); + *fromAngle = from->angle(); + *toAngle = to->angle(); + return true; +} + +PassRefPtr RotateTransformOperation::blend(const TransformOperation* from, double progress, bool blendToIdentity) +{ + if (from && !from->isSameType(*this)) + return this; + + if (blendToIdentity) + return RotateTransformOperation::create(m_x, m_y, m_z, m_angle - m_angle * progress, m_type); + + const RotateTransformOperation* fromOp = static_cast(from); + + // Optimize for single axis rotation + if (!fromOp || (fromOp->m_x == 0 && fromOp->m_y == 0 && fromOp->m_z == 1) || + (fromOp->m_x == 0 && fromOp->m_y == 1 && fromOp->m_z == 0) || + (fromOp->m_x == 1 && fromOp->m_y == 0 && fromOp->m_z == 0)) { + double fromAngle = fromOp ? fromOp->m_angle : 0; + return RotateTransformOperation::create(fromOp ? fromOp->m_x : m_x, + fromOp ? fromOp->m_y : m_y, + fromOp ? fromOp->m_z : m_z, + blink::blend(fromAngle, m_angle, progress), m_type); + } + double fromAngle; + double toAngle; + FloatPoint3D axis; + + if (shareSameAxis(fromOp, this, &axis, &fromAngle, &toAngle)) + return RotateTransformOperation::create(axis.x(), axis.y(), axis.z(), blink::blend(fromAngle, toAngle, progress), m_type); + + const RotateTransformOperation* toOp = this; + + // Create the 2 rotation matrices + TransformationMatrix fromT; + TransformationMatrix toT; + fromT.rotate3d((fromOp ? fromOp->m_x : 0), + (fromOp ? fromOp->m_y : 0), + (fromOp ? fromOp->m_z : 1), + (fromOp ? fromOp->m_angle : 0)); + + toT.rotate3d((toOp ? toOp->m_x : 0), + (toOp ? toOp->m_y : 0), + (toOp ? toOp->m_z : 1), + (toOp ? toOp->m_angle : 0)); + + // Blend them + toT.blend(fromT, progress); + + // Extract the result as a quaternion + TransformationMatrix::DecomposedType decomp; + toT.decompose(decomp); + + // Convert that to Axis/Angle form + double x = -decomp.quaternionX; + double y = -decomp.quaternionY; + double z = -decomp.quaternionZ; + double length = sqrt(x * x + y * y + z * z); + double angle = 0; + + if (length > 0.00001) { + x /= length; + y /= length; + z /= length; + angle = rad2deg(acos(decomp.quaternionW) * 2); + } else { + x = 0; + y = 0; + z = 1; + } + return RotateTransformOperation::create(x, y, z, angle, Rotate3D); +} + +bool RotateTransformOperation::canBlendWith(const TransformOperation& other) const +{ + return other.isSameType(*this); +} + +} // namespace blink diff --git a/pool/shard010/C++/0111335_RetainedDOMInfo.cpp b/pool/shard010/C++/0111335_RetainedDOMInfo.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b12969fc73df789424b5bb2e3a81147f89ec3fd6 --- /dev/null +++ b/pool/shard010/C++/0111335_RetainedDOMInfo.cpp @@ -0,0 +1,90 @@ +/* + * Copyright (C) 2011 Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. 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. + */ + +#include "config.h" +#include "RetainedDOMInfo.h" + +#include "ContainerNode.h" + +namespace WebCore { + +RetainedDOMInfo::RetainedDOMInfo(Node* root) + : m_root(root) +{ + ASSERT(m_root); +} + +RetainedDOMInfo::~RetainedDOMInfo() +{ +} + +void RetainedDOMInfo::Dispose() +{ + delete this; +} + +bool RetainedDOMInfo::IsEquivalent(v8::RetainedObjectInfo* other) +{ + ASSERT(other); + return other == this || static_cast(other)->GetEquivalenceClass() == this->GetEquivalenceClass(); +} + +intptr_t RetainedDOMInfo::GetHash() +{ + return PtrHash::hash(m_root); +} + +const char* RetainedDOMInfo::GetGroupLabel() +{ + return m_root->inDocument() ? "(Document DOM trees)" : "(Detached DOM trees)"; +} + +const char* RetainedDOMInfo::GetLabel() +{ + return m_root->inDocument() ? "Document DOM tree" : "Detached DOM tree"; +} + +intptr_t RetainedDOMInfo::GetElementCount() +{ + intptr_t count = 1; + Node* current = m_root; + while (current) { + current = current->traverseNextNode(m_root); + ++count; + } + return count; +} + +intptr_t RetainedDOMInfo::GetEquivalenceClass() +{ + return reinterpret_cast(m_root); +} + +} // namespace WebCore diff --git a/pool/shard010/C++/0111336_matrix_exponential_op.cc b/pool/shard010/C++/0111336_matrix_exponential_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..4cc3f32f7e4a727fa2d9ec3c21a3750111f46392 --- /dev/null +++ b/pool/shard010/C++/0111336_matrix_exponential_op.cc @@ -0,0 +1,59 @@ +/* Copyright 2017 The TensorFlow Authors. 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. +==============================================================================*/ + +// See docs in ../ops/linalg_ops.cc. + +#include "third_party/eigen3/Eigen/Core" +#include "third_party/eigen3/unsupported/Eigen/MatrixFunctions" +#include "tensorflow/core/framework/kernel_def_builder.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/kernels/linalg_ops_common.h" +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/platform/logging.h" +#include "tensorflow/core/platform/macros.h" +#include "tensorflow/core/platform/types.h" + + +namespace tensorflow { + +template +class MatrixExponentialOp : public LinearAlgebraOp { + public: + INHERIT_LINALG_TYPEDEFS(Scalar); + + explicit MatrixExponentialOp(OpKernelConstruction* context) : Base(context) {} + + void ComputeMatrix(OpKernelContext* context, const ConstMatrixMaps& inputs, + MatrixMaps* outputs) final { + const ConstMatrixMap& input = inputs[0]; + if (input.rows() == 0) return; + using Matrix = Eigen::Matrix; + Matrix tmp = input; + outputs->at(0) = tmp.exp(); + } + + private: + TF_DISALLOW_COPY_AND_ASSIGN(MatrixExponentialOp); +}; + +REGISTER_LINALG_OP("MatrixExponential", (MatrixExponentialOp), float); +REGISTER_LINALG_OP("MatrixExponential", (MatrixExponentialOp), double); +REGISTER_LINALG_OP("MatrixExponential", + (MatrixExponentialOp), complex64); +REGISTER_LINALG_OP("MatrixExponential", + (MatrixExponentialOp), complex128); + +} // namespace tensorflow diff --git a/pool/shard010/C++/0111338_inireader.cpp b/pool/shard010/C++/0111338_inireader.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d9041fdf1f7f7ec810e4a289b92392331a70e38f --- /dev/null +++ b/pool/shard010/C++/0111338_inireader.cpp @@ -0,0 +1,47 @@ +#include "stdafx.h" +#include + +char Path[MAX_PATH]; +char iniFile[MAX_PATH]; +char Read[500]; +DWORD destsize = 500; +//"E:\\VehicleData.ini" +char* readIniString(char* Section, char* Key) { + GetPrivateProfileString(Section, Key, "NULL", Read, destsize, iniFile); + return Read; +} +DWORD readIniDWORD(char*Section, char* Key) { + DWORD ini = GetPrivateProfileInt(Section, Key, -1337, iniFile); + return ini; +} +void Init(HMODULE hModule) { + memset(Path, 0, sizeof(Path)); + + if (GetModuleFileNameA(hModule, Path, MAX_PATH) != 0) { + size_t slash = -1; + + for (size_t i = 0; i < strlen(Path); i++) { + if (Path[i] == '/' || Path[i] == '\\') { + slash = i; + } + } + + if (slash != -1) { + Path[slash + 1] = '\0'; + strcpy_s(iniFile, Path); + strcat_s(iniFile, "VehicleData.ini"); + + } + else { + // Shitty manual mapper detected. + MessageBoxA(NULL, "Unable to parse target module path", "ERROR", MB_OK); + ExitProcess(0); + } + } + else { + // Shitty manual mapper detected. + MessageBoxA(NULL, "GetModuleFileNameA failed", "ERROR", MB_OK); + ExitProcess(0); + } +} + diff --git a/pool/shard010/C++/0111339_BinaryNumber.cpp b/pool/shard010/C++/0111339_BinaryNumber.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6b5e8834830419f51746871767f2c5ef926c5c9d --- /dev/null +++ b/pool/shard010/C++/0111339_BinaryNumber.cpp @@ -0,0 +1,86 @@ +/*--------------------------------------------------------------------------* + + BinaryNumber.cpp + + See BinaryNumber.h for notes on this class. + + *--------------------------------------------------------------------------*/ +#include "BinaryNumber.h" + +#include // strlen +#include // ARRAYSIZE + +namespace ExampleLib +{ + BinaryNumber::BinaryNumber(const char* stringValue) + : + _numericValue(0) + { + size_t stringLength = strlen(stringValue); + if (stringLength > MaxStringValueLength) + { + throw BinaryNumber::InvalidInputException(); + } + + const char* cursor = stringValue + stringLength - 1; + unsigned int placeValue = 1; + while(cursor >= stringValue) + { + switch(*cursor) + { + case '1': + _numericValue += ( unsigned short ) placeValue; + break; + case '0': + break; + default: + throw BinaryNumber::InvalidInputException(); + } + placeValue *= 2; + cursor--; + } + + PopulateStringValue(_numericValue); + } + + BinaryNumber::BinaryNumber(unsigned short numericValue) + : + _numericValue(numericValue) + { + PopulateStringValue(numericValue); + } + + void BinaryNumber::PopulateStringValue(unsigned short numericValue) + { + unsigned short value = numericValue; + char* cursor = _stringValue + MaxStringValueLength; + *cursor-- = '\0'; + + while(value > 0 && cursor >= _stringValue) + { + *cursor-- = (value & 1) ? '1' : '0'; + value = value >> 1; + } + while(cursor >= _stringValue) + { + *cursor-- = '0'; + } + } + + BinaryNumber BinaryNumber::operator+(const BinaryNumber& rhs) + { + unsigned short sum = this->_numericValue + rhs._numericValue; + if (sum < this->_numericValue) + { + throw BinaryNumber::IntegerOverflowException(); + } + + return BinaryNumber(sum); + } + + bool BinaryNumber::operator==(const BinaryNumber& rhs) const + { + return ((this->_numericValue == rhs._numericValue) && + (strcmp(this->_stringValue, rhs._stringValue) == 0)); + } +} \ No newline at end of file diff --git a/pool/shard010/C++/0111341_qmllistselectionmodel.cpp b/pool/shard010/C++/0111341_qmllistselectionmodel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b1a5588ab4f233482b61c149790bd70efd32c51f --- /dev/null +++ b/pool/shard010/C++/0111341_qmllistselectionmodel.cpp @@ -0,0 +1,142 @@ +/* + Copyright (C) 2010 Klarälvdalens Datakonsult AB, + a KDAB Group company, info@kdab.net, + author Stephen Kelly + + 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; see the file COPYING.LIB. If not, write to the + Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301, USA. +*/ + +#include "qmllistselectionmodel.h" + +#include +#include + +QMLListSelectionModel::QMLListSelectionModel(QItemSelectionModel *selectionModel, QObject* parent) + : QObject(parent), m_selectionModel(selectionModel) +{ + connect(m_selectionModel, SIGNAL(selectionChanged(QItemSelection,QItemSelection)), SIGNAL(selectionChanged())); +} + +QMLListSelectionModel::QMLListSelectionModel(QAbstractItemModel* model, QObject* parent) + : QObject(parent), m_selectionModel(new QItemSelectionModel(model, this)) +{ + connect(m_selectionModel, SIGNAL(selectionChanged(QItemSelection,QItemSelection)), SIGNAL(selectionChanged())); +} + +QItemSelectionModel* QMLListSelectionModel::selectionModel() const +{ + return m_selectionModel; +} + +QList< int > QMLListSelectionModel::selection() const +{ + QList< int > list; + const QModelIndexList indexes = m_selectionModel->selectedRows(); + foreach (const QModelIndex &index, indexes) + list << index.row(); + return list; +} + +bool QMLListSelectionModel::hasSelection() const +{ + return m_selectionModel->hasSelection(); +} + +int QMLListSelectionModel::currentRow() const +{ + const QModelIndexList indexes = m_selectionModel->selectedRows(); + if (indexes.size() != 1) + return -1; + Q_ASSERT(indexes.first().isValid()); + return indexes.first().row(); +} + +void QMLListSelectionModel::setCurrentRow(int row) +{ + select(row, QItemSelectionModel::ClearAndSelect); +} + +qint64 QMLListSelectionModel::currentItemId() const +{ + const QModelIndexList indexes = m_selectionModel->selectedRows(); + if (indexes.size() != 1) + return -1; + Q_ASSERT(indexes.first().isValid()); + return indexes.first().data(Akonadi::EntityTreeModel::ItemIdRole).toLongLong(); +} + +void QMLListSelectionModel::setCurrentItemId(qint64 itemId) +{ + const QModelIndexList list = Akonadi::EntityTreeModel::modelIndexesForItem(m_selectionModel->model(), Akonadi::Item(itemId)); + if (list.size() == 1) { + const QModelIndex idx = list.first(); + m_selectionModel->select(QItemSelection(idx, idx), QItemSelectionModel::ClearAndSelect); + } +} + +void QMLListSelectionModel::select(int row, int command) +{ + if (row < 0) { + clearSelection(); + return; + } + static const int column = 0; + const QModelIndex idx = m_selectionModel->model()->index(row, column); + Q_ASSERT(idx.isValid()); + QItemSelection sel(idx, idx); + QItemSelectionModel::SelectionFlags flags = static_cast(command); + m_selectionModel->select(sel, flags); +} + +bool QMLListSelectionModel::requestNext() +{ + const QModelIndexList list = m_selectionModel->selectedRows(); + if (list.isEmpty() || list.size() != 1) + return false; + + const QModelIndex idx = list.first(); + Q_ASSERT(idx.isValid()); + const QModelIndex next = idx.sibling(idx.row() + 1, idx.column()); + if (!next.isValid()) + return false; + + m_selectionModel->select(QItemSelection(next, next), QItemSelectionModel::ClearAndSelect); + return true; +} + +bool QMLListSelectionModel::requestPrevious() +{ + const QModelIndexList list = m_selectionModel->selectedRows(); + if (list.isEmpty() || list.size() != 1) + return false; + + const QModelIndex idx = list.first(); + Q_ASSERT(idx.isValid()); + if (idx.row() == 0) + return false; + + const QModelIndex previous = idx.sibling(idx.row() - 1, idx.column()); + m_selectionModel->select(QItemSelection(previous, previous), QItemSelectionModel::ClearAndSelect); + return true; +} + +void QMLListSelectionModel::clearSelection() +{ + // Don't call QItemSelectionModel::clearSelection. It is non-virtual so + // item selection models in chains can't react to it properly. + m_selectionModel->select(QItemSelection(), QItemSelectionModel::Clear); +} + diff --git a/pool/shard010/C/0139063_fix-apple-kb.c b/pool/shard010/C/0139063_fix-apple-kb.c new file mode 100644 index 0000000000000000000000000000000000000000..f98f29bcb808b5fe80a3a0f9956f467f456a5371 --- /dev/null +++ b/pool/shard010/C/0139063_fix-apple-kb.c @@ -0,0 +1,85 @@ +// http://apple.stackexchange.com/a/199958 +#include +#include +#include +#include +#include + + +int main(int argc, char **argv) { + if (argc != 2 || strcmp(argv[1], "-h") == 0) { + printf("Pass a hidraw device as the first and only parameter!\n"); + printf("You may find the right device with:\n"); + printf(" dmesg | grep Apple | grep Keyboard | grep input0 | tail -1 | " + "sed -e 's/.hidraw\([[:digit:]]\+\)./\/dev\/hidraw\1/'\n"); + return 1; + } + int fd, i, res, desc_size = 0; + char buf[256]; + struct hidraw_devinfo info; + char *device = argv[1]; + fd = open(device, O_RDWR | O_NONBLOCK); + if (fd < 0) { + perror("Unable to open device"); + return 1; + } + memset(&info, 0, sizeof(info)); + memset(buf, 0, sizeof(buf)); + // Get Report Descriptor Size + res = ioctl(fd, HIDIOCGRDESCSIZE, &desc_size); + if (res < 0) { + perror("HIDIOCGRDESCSIZE"); + } +// if (desc_size != 75) { +// printf("Error: unexpected descriptor size %d; you've probably got " +// "the wrong hidraw device!\n", desc_size); +// return 1; +// } + // Get Raw Info + res = ioctl(fd, HIDIOCGRAWINFO, &info); + if (res < 0) { + perror("HIDIOCGRAWINFO"); + } else { + if (info.vendor != 0x05ac) { + printf("Error: Wrong vendor ID, make sure you got the right " + "hidraw device!\n"); + return 1; + } + if (info.product != 0x0250) { + printf("Warning: Unknown product ID 0x%x!\n", info.product); + } + } + // Get Feature + buf[0] = 0x09; // Report Number + res = ioctl(fd, HIDIOCGFEATURE(256), buf); + if (res < 0) { + perror("HIDIOCGFEATURE"); + } else { + printf("HID Feature Report (before change):\n\t"); + for (i = 0; i < res; i++) printf("%hhx ", buf[i]); + puts("\n"); + } + // Set Feature + buf[0] = 0x09; // Report Number + buf[1] = 0x00; // Report data + buf[2] = 0x00; // padding + buf[3] = 0x00; // padding + res = ioctl(fd, HIDIOCSFEATURE(4), buf); + if (res < 0) { + perror("HIDIOCSFEATURE"); + } else { + printf("Caps lock delay disabled.\n"); + } + // Get Feature + buf[0] = 0x09; // Report Number + res = ioctl(fd, HIDIOCGFEATURE(256), buf); + if (res < 0) { + perror("HIDIOCGFEATURE"); + } else { + printf("HID Feature Report (after change):\n\t"); + for (i = 0; i < res; i++) printf("%hhx ", buf[i]); + puts("\n"); + } + close(fd); + return 0; +} diff --git a/pool/shard010/C/0139064_btm_main.c b/pool/shard010/C/0139064_btm_main.c new file mode 100644 index 0000000000000000000000000000000000000000..043e7fd01d97deb5887068c4bde2b9d4e37d9765 --- /dev/null +++ b/pool/shard010/C/0139064_btm_main.c @@ -0,0 +1,97 @@ +/****************************************************************************** + * + * Copyright (C) 2002-2012 Broadcom Corporation + * + * 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. + * + ******************************************************************************/ + +/****************************************************************************** + * + * This file contains the definition of the btm control block when + * BTM_DYNAMIC_MEMORY is used. + * + ******************************************************************************/ + +#include "bt_types.h" +#include "bt_target.h" +#include +#include "btm_int.h" +#include "allocator.h" + +/* Global BTM control block structure +*/ +#if BTM_DYNAMIC_MEMORY == FALSE +tBTM_CB btm_cb; +#else +tBTM_CB *btm_cb_ptr; +#endif + +/******************************************************************************* +** +** Function btm_init +** +** Description This function is called at BTM startup to allocate the +** control block (if using dynamic memory), and initializes the +** tracing level. It then initializes the various components of +** btm. +** +** Returns void +** +*******************************************************************************/ +void btm_init (void) +{ +#if BTM_DYNAMIC_MEMORY + btm_cb_ptr = (tBTM_CB *)osi_malloc(sizeof(tBTM_CB)); +#endif /* #if BTM_DYNAMIC_MEMORY */ + /* All fields are cleared; nonzero fields are reinitialized in appropriate function */ + memset(&btm_cb, 0, sizeof(tBTM_CB)); + btm_cb.page_queue = fixed_queue_new(SIZE_MAX); + btm_cb.sec_pending_q = fixed_queue_new(SIZE_MAX); + +#if defined(BTM_INITIAL_TRACE_LEVEL) + btm_cb.trace_level = BTM_INITIAL_TRACE_LEVEL; +#else + btm_cb.trace_level = BT_TRACE_LEVEL_NONE; +#endif + /* Initialize BTM component structures */ + btm_inq_db_init(); /* Inquiry Database and Structures */ + btm_acl_init(); /* ACL Database and Structures */ +#if (SMP_INCLUDED == TRUE) + btm_sec_init(BTM_SEC_MODE_SP); /* Security Manager Database and Structures */ +#endif ///SMP_INCLUDED == TRUE +#if BTM_SCO_INCLUDED == TRUE + btm_sco_init(); /* SCO Database and Structures (If included) */ +#endif + + btm_dev_init(); /* Device Manager Structures & HCI_Reset */ +} + + +/******************************************************************************* +** +** Function btm_free +** +** Description This function is called at btu core free the fixed queue +** +** Returns void +** +*******************************************************************************/ +void btm_free(void) +{ + fixed_queue_free(btm_cb.page_queue, osi_free_func); + fixed_queue_free(btm_cb.sec_pending_q, osi_free_func); +#if BTM_DYNAMIC_MEMORY + FREE_AND_RESET(btm_cb_ptr); +#endif +} diff --git a/pool/shard010/C/0139065_omap4460plus_hwmon_temp_sensor.c b/pool/shard010/C/0139065_omap4460plus_hwmon_temp_sensor.c new file mode 100644 index 0000000000000000000000000000000000000000..aed431ecb4ac45540a92b24c37d6223b3822752d --- /dev/null +++ b/pool/shard010/C/0139065_omap4460plus_hwmon_temp_sensor.c @@ -0,0 +1,244 @@ +/* + * + * OMAP4460 Plus bandgap on die sensor hwmon driver. + * + * Copyright (C) 2011 Texas Instruments Incorporated - http://www.ti.com/ + * J Keerthy + * + * 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., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA + * + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static const char *names[3] = { "mpu", "gpu", "core"}; + +static ssize_t show_name(struct device *dev, + struct device_attribute *attr, char *buf) +{ + struct platform_device *pdev = container_of(dev, + struct platform_device, dev); + int id = pdev->id; + + return sprintf(buf, names[id]); +} + +static ssize_t show_temp_max(struct device *dev, + struct device_attribute *devattr, char *buf) +{ + struct temp_sensor_hwmon *tsh = dev_get_drvdata(dev); + struct platform_device *pdev = container_of(dev, + struct platform_device, dev); + int id = pdev->id; + int temp; + + temp = omap4460plus_scm_show_temp_max(tsh->scm_ptr, id); + + return sprintf(buf, "%d\n", temp); +} + +static ssize_t set_temp_max(struct device *dev, + struct device_attribute *devattr, + const char *buf, size_t count) +{ + struct temp_sensor_hwmon *tsh = dev_get_drvdata(dev); + struct platform_device *pdev = container_of(dev, + struct platform_device, dev); + int id = pdev->id, ret; + long val; + + if (strict_strtol(buf, 10, &val)) + return -EINVAL; + ret = omap4460plus_scm_set_temp_max(tsh->scm_ptr, id, val); + if (ret < 0) + return ret; + + return count; +} + +static ssize_t show_temp_max_hyst(struct device *dev, + struct device_attribute *devattr, char *buf) +{ + struct temp_sensor_hwmon *tsh = dev_get_drvdata(dev); + struct platform_device *pdev = container_of(dev, + struct platform_device, dev); + int id = pdev->id; + int temp; + + temp = omap4460plus_scm_show_temp_max_hyst(tsh->scm_ptr, id); + + return sprintf(buf, "%d\n", temp); +} + +static ssize_t set_temp_max_hyst(struct device *dev, + struct device_attribute *devattr, + const char *buf, size_t count) +{ + struct temp_sensor_hwmon *tsh = dev_get_drvdata(dev); + struct platform_device *pdev = container_of(dev, + struct platform_device, dev); + int id = pdev->id, ret; + long val; + + if (strict_strtol(buf, 10, &val)) + return -EINVAL; + ret = omap4460plus_scm_set_temp_max_hyst(tsh->scm_ptr, id, val); + if (ret < 0) + return ret; + + return count; +} + +static ssize_t show_update_interval(struct device *dev, + struct device_attribute *devattr, char *buf) +{ + int time = 0; + struct temp_sensor_hwmon *tsh = dev_get_drvdata(dev); + struct platform_device *pdev = container_of(dev, + struct platform_device, dev); + int id = pdev->id; + + time = omap4460plus_scm_show_update_interval(tsh->scm_ptr, id); + + return sprintf(buf, "%d\n", time); +} + +static ssize_t set_update_interval(struct device *dev, + struct device_attribute *devattr, + const char *buf, size_t count) +{ + struct temp_sensor_hwmon *tsh = dev_get_drvdata(dev); + struct platform_device *pdev = container_of(dev, + struct platform_device, dev); + int id = pdev->id; + unsigned long val; + + if (strict_strtoul(buf, 10, &val)) + return -EINVAL; + + omap4460plus_scm_set_update_interval(tsh->scm_ptr, val, id); + return count; +} + +static int read_temp(struct device *dev, + struct device_attribute *devattr, char *buf) +{ + struct temp_sensor_hwmon *tsh = dev_get_drvdata(dev); + struct platform_device *pdev = container_of(dev, + struct platform_device, dev); + int id = pdev->id; + int temp; + + temp = omap4460plus_scm_read_temp(tsh->scm_ptr, id); + + return sprintf(buf, "%d\n", temp); +} + +static DEVICE_ATTR(name, S_IRUGO, show_name, NULL); +static SENSOR_DEVICE_ATTR(temp1_input, S_IRUGO, read_temp, NULL, 0); +static SENSOR_DEVICE_ATTR(temp1_max, S_IWUSR | S_IRUGO, show_temp_max, + set_temp_max, 0); +static SENSOR_DEVICE_ATTR(temp1_max_hyst, S_IWUSR | S_IRUGO, show_temp_max_hyst, + set_temp_max_hyst, 0); +static SENSOR_DEVICE_ATTR(update_interval, S_IWUSR | S_IRUGO, + show_update_interval, set_update_interval, 0); + +static struct attribute *temp_sensor_attributes[] = { + &dev_attr_name.attr, + + &sensor_dev_attr_temp1_input.dev_attr.attr, + &sensor_dev_attr_temp1_max.dev_attr.attr, + &sensor_dev_attr_temp1_max_hyst.dev_attr.attr, + &sensor_dev_attr_update_interval.dev_attr.attr, + NULL +}; + +static const struct attribute_group temp_sensor_group = { + .attrs = temp_sensor_attributes, +}; + +static int __devinit omap4460plus_temp_sensor_probe(struct platform_device + *pdev) +{ + int ret; + struct device *hwmon; + + ret = sysfs_create_group(&pdev->dev.kobj, &temp_sensor_group); + if (ret) + goto err_sysfs; + hwmon = hwmon_device_register(&pdev->dev); + if (IS_ERR(hwmon)) { + dev_err(&pdev->dev, "hwmon_device_register failed.\n"); + ret = PTR_ERR(hwmon); + goto err_reg; + } + + return 0; + +err_reg: + sysfs_remove_group(&pdev->dev.kobj, &temp_sensor_group); +err_sysfs: + + return ret; +} + +static int __devexit omap4460plus_temp_sensor_remove(struct platform_device + *pdev) +{ + hwmon_device_unregister(&pdev->dev); + sysfs_remove_group(&pdev->dev.kobj, &temp_sensor_group); + + return 0; +} + +static struct platform_driver omap4460plus_temp_sensor_driver = { + .probe = omap4460plus_temp_sensor_probe, + .remove = omap4460plus_temp_sensor_remove, + .driver = { + .name = "temp_sensor_hwmon", + }, +}; + +static int __init omap4460plus_hwmon_temp_sensor_init(void) +{ + return platform_driver_register(&omap4460plus_temp_sensor_driver); +} + +module_init(omap4460plus_hwmon_temp_sensor_init); + +static void __exit omap4460plus_hwmon_temp_sensor_exit(void) +{ + platform_driver_unregister(&omap4460plus_temp_sensor_driver); +} + +module_exit(omap4460plus_hwmon_temp_sensor_exit); + +MODULE_DESCRIPTION("OMAP446X temperature sensor Hwmon Driver"); +MODULE_LICENSE("GPL"); +MODULE_ALIAS("platform:" DRIVER_NAME); +MODULE_AUTHOR("J Keerthy "); diff --git a/pool/shard010/C/0139066_gsfcid.c b/pool/shard010/C/0139066_gsfcid.c new file mode 100644 index 0000000000000000000000000000000000000000..fa5f12c458ce8e4de7b23890655d9ae445fab299 --- /dev/null +++ b/pool/shard010/C/0139066_gsfcid.c @@ -0,0 +1,209 @@ +/* Copyright (C) 2000 Aladdin Enterprises. All rights reserved. + + This software is provided AS-IS with no warranty, either express or + implied. + + This software is distributed under license and may not be copied, + modified or distributed except as expressly authorized under the terms + of the license contained in the file LICENSE in this distribution. + + For more information about licensing, please refer to + http://www.ghostscript.com/licensing/. For information on + commercial licensing, go to http://www.artifex.com/licensing/ or + contact Artifex Software, Inc., 101 Lucas Valley Road #110, + San Rafael, CA 94903, U.S.A., +1(415)492-9861. +*/ + +/* $Id: gsfcid.c,v 1.14 2005/01/13 16:58:07 igor Exp $ */ +/* Support for CID-keyed fonts */ +#include "memory_.h" +#include "gx.h" +#include "gsmatrix.h" /* for gsfont.h */ +#include "gsstruct.h" +#include "gxfcid.h" +#include "gserrors.h" + +/* CIDSystemInfo structure descriptors */ +public_st_cid_system_info(); +public_st_cid_system_info_element(); + +/* CID-keyed font structure descriptors */ +public_st_gs_font_cid_data(); +public_st_gs_font_cid0(); +private +ENUM_PTRS_WITH(font_cid0_enum_ptrs, gs_font_cid0 *pfcid0) +{ + index -= 2; + if (index < st_gs_font_cid_data_num_ptrs) + return ENUM_USING(st_gs_font_cid_data, &pfcid0->cidata.common, + sizeof(gs_font_cid_data), index); + ENUM_PREFIX(st_gs_font_base, st_gs_font_cid_data_num_ptrs); +} +ENUM_PTR(0, gs_font_cid0, cidata.FDArray); +ENUM_PTR(1, gs_font_cid0, cidata.proc_data); +ENUM_PTRS_END +private +RELOC_PTRS_WITH(font_cid0_reloc_ptrs, gs_font_cid0 *pfcid0); + RELOC_PREFIX(st_gs_font_base); + RELOC_USING(st_gs_font_cid_data, &pfcid0->cidata.common, + sizeof(st_gs_font_cid_data)); + RELOC_VAR(pfcid0->cidata.FDArray); + RELOC_VAR(pfcid0->cidata.proc_data); +RELOC_PTRS_END +public_st_gs_font_cid1(); +private +ENUM_PTRS_WITH(font_cid1_enum_ptrs, gs_font_cid1 *pfcid1) +{ + if (index < st_cid_system_info_num_ptrs) + return ENUM_USING(st_cid_system_info, &pfcid1->cidata.CIDSystemInfo, + sizeof(st_cid_system_info), index); + ENUM_PREFIX(st_gs_font_base, st_cid_system_info_num_ptrs); +} +ENUM_PTRS_END +private +RELOC_PTRS_WITH(font_cid1_reloc_ptrs, gs_font_cid1 *pfcid1); + RELOC_PREFIX(st_gs_font_base); + RELOC_USING(st_cid_system_info, &pfcid1->cidata.CIDSystemInfo, + sizeof(st_cid_system_info)); +RELOC_PTRS_END +public_st_gs_font_cid2(); +private +ENUM_PTRS_WITH(font_cid2_enum_ptrs, gs_font_cid2 *pfcid2) +{ + if (index < st_gs_font_cid_data_num_ptrs) + return ENUM_USING(st_gs_font_cid_data, &pfcid2->cidata.common, + sizeof(gs_font_cid_data), index); + ENUM_PREFIX(st_gs_font_type42, st_gs_font_cid_data_num_ptrs); +} +ENUM_PTRS_END +private +RELOC_PTRS_WITH(font_cid2_reloc_ptrs, gs_font_cid2 *pfcid2); + RELOC_PREFIX(st_gs_font_type42); + RELOC_USING(st_gs_font_cid_data, &pfcid2->cidata.common, + sizeof(st_gs_font_cid_data)); +RELOC_PTRS_END + +/* GC descriptor for allocating FDArray for CIDFontType 0 fonts. */ +gs_private_st_ptr(st_gs_font_type1_ptr, gs_font_type1 *, "gs_font_type1 *", + font1_ptr_enum_ptrs, font1_ptr_reloc_ptrs); +gs_public_st_element(st_gs_font_type1_ptr_element, gs_font_type1 *, + "gs_font_type1 *[]", font1_ptr_element_enum_ptrs, + font1_ptr_element_reloc_ptrs, st_gs_font_type1_ptr); + +/* + * The CIDSystemInfo of a CMap may be null. We represent this by setting + * Registry and Ordering to empty strings, and Supplement to 0. + */ +void +cid_system_info_set_null(gs_cid_system_info_t *pcidsi) +{ + memset(pcidsi, 0, sizeof(*pcidsi)); +} +bool +cid_system_info_is_null(const gs_cid_system_info_t *pcidsi) +{ + return (pcidsi->Registry.size == 0 && pcidsi->Ordering.size == 0 && + pcidsi->Supplement == 0); +} + +/* + * Get the CIDSystemInfo of a font. If the font is not a CIDFont, + * return NULL. + */ +const gs_cid_system_info_t * +gs_font_cid_system_info(const gs_font *pfont) +{ + switch (pfont->FontType) { + case ft_CID_encrypted: + return &((const gs_font_cid0 *)pfont)->cidata.common.CIDSystemInfo; + case ft_CID_user_defined: + return &((const gs_font_cid1 *)pfont)->cidata.CIDSystemInfo; + case ft_CID_TrueType: + return &((const gs_font_cid2 *)pfont)->cidata.common.CIDSystemInfo; + default: + return 0; + } +} + +/* + * Check CIDSystemInfo compatibility. + */ +bool +gs_is_CIDSystemInfo_compatible(const gs_cid_system_info_t *info0, + const gs_cid_system_info_t *info1) +{ + if (info0 == NULL || info1 == NULL) + return false; + if (info0->Registry.size != info1->Registry.size) + return false; + if (info0->Ordering.size != info1->Ordering.size) + return false; + if (memcmp(info0->Registry.data, info1->Registry.data, + info0->Registry.size)) + return false; + if (memcmp(info0->Ordering.data, info1->Ordering.data, + info0->Ordering.size)) + return false; + return true; +} + +/* + * Provide a default enumerate_glyph procedure for CIDFontType 0 fonts. + * Built for simplicity, not for speed. + */ +font_proc_enumerate_glyph(gs_font_cid0_enumerate_glyph); /* check prototype */ +int +gs_font_cid0_enumerate_glyph(gs_font *font, int *pindex, + gs_glyph_space_t ignore_glyph_space, + gs_glyph *pglyph) +{ + gs_font_cid0 *const pfont = (gs_font_cid0 *)font; + + while (*pindex < pfont->cidata.common.CIDCount) { + gs_glyph_data_t gdata; + int fidx; + gs_glyph glyph = (gs_glyph)(gs_min_cid_glyph + (*pindex)++); + int code; + + gdata.memory = pfont->memory; + code = pfont->cidata.glyph_data((gs_font_base *)pfont, glyph, + &gdata, &fidx); + if (code < 0 || gdata.bits.size == 0) + continue; + *pglyph = glyph; + gs_glyph_data_free(&gdata, "gs_font_cid0_enumerate_glyphs"); + return 0; + } + *pindex = 0; + return 0; +} + +/* Return the font from the FDArray at the given index */ +const gs_font * +gs_cid0_indexed_font(const gs_font *font, int fidx) +{ + gs_font_cid0 *const pfont = (gs_font_cid0 *)font; + + if (font->FontType != ft_CID_encrypted) { + eprintf1("Unexpected font type: %d\n", font->FontType); + return 0; + } + return (const gs_font*) (pfont->cidata.FDArray[fidx]); +} + +/* Check whether a CID font has a Type 2 subfont. */ +bool +gs_cid0_has_type2(const gs_font *font) +{ + gs_font_cid0 *const pfont = (gs_font_cid0 *)font; + int i; + + if (font->FontType != ft_CID_encrypted) { + eprintf1("Unexpected font type: %d\n", font->FontType); + return false; + } + for (i = 0; i < pfont->cidata.FDArray_size; i++) + if (((const gs_font *)pfont->cidata.FDArray[i])->FontType == ft_encrypted2) + return true; + return false; +} diff --git a/pool/shard010/C/0139067_main.c b/pool/shard010/C/0139067_main.c new file mode 100644 index 0000000000000000000000000000000000000000..8285d2082eebe8013bc871053296e1f240888d98 --- /dev/null +++ b/pool/shard010/C/0139067_main.c @@ -0,0 +1,81 @@ +/* + * main.c - main body of program + * + * (C) 2005 Attila Grosz ( gyros @ freemail . hu ) + * + * 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 "block.h" + +static void copyright() +{ + printf( "CMD2CAS 1.0 (C) 2005 by Attila Grosz\n"); +} + +static void usage() +{ + copyright(); + printf( "This program converts standard TRS-80/System-80 disk\n"); + printf( "(CMD) files to tape (CAS) images.\n"); + printf( "Syntax: cmd2cas \n"); +} + +int main(int argc, char *argv[]) +{ + FILE *inp, *outp; + unsigned char ck = 0; + + if ( argc == 3 ) { + + FILE *cmd, *cas; + int retval; + struct blockinfo_t block; + + copyright(); + + cmd = fopen( argv[1], "rb"); + if (!cmd) { + fprintf( stderr, "Error opening input file: %s.\n", argv[1]); + return 1; + } + cas = fopen( argv[2], "wb"); + if (!cas) { + fprintf( stderr, "Error opening output file: %s.\n", argv[2]); + return 2; + } + + cas_write_header( cas, argv[2]); + + do { + block.size = 0; + retval = parse_cmd( cmd, &block ); + if (retval) cas_write_block( cas, &block); + } while( retval > 0 ); + + fclose( cmd ); + + cas_write_eof( cas, block.address); + printf( "Conversion ready. CAS file size: %i bytes\n", ftell(cas)); + fclose( cas ); + + } else + usage(); + + return 0; +} diff --git a/pool/shard010/C/0139068_CWE325_Missing_Required_Cryptographic_Step__w32_CryptHashData_01.c b/pool/shard010/C/0139068_CWE325_Missing_Required_Cryptographic_Step__w32_CryptHashData_01.c new file mode 100644 index 0000000000000000000000000000000000000000..9c31ef89166ba645726da10cba0b452aa2c4491a --- /dev/null +++ b/pool/shard010/C/0139068_CWE325_Missing_Required_Cryptographic_Step__w32_CryptHashData_01.c @@ -0,0 +1,175 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE325_Missing_Required_Cryptographic_Step__w32_CryptHashData_01.c +Label Definition File: CWE325_Missing_Required_Cryptographic_Step__w32.label.xml +Template File: point-flaw-01.tmpl.c +*/ +/* + * @description + * CWE: 325 Missing Required Cryptographic Step + * Sinks: CryptHashData + * GoodSink: All required cryptographic steps are present + * BadSink : Missing call to CryptHashData() + * Flow Variant: 01 Baseline + * + * */ + +#include "std_testcase.h" + +#include + +#include + +#pragma comment(lib, "advapi32") + +#define HASH_INPUT "ABCDEFG123456" /* INCIDENTAL: Hardcoded crypto */ +#define PAYLOAD "plaintext" + +#ifndef OMITBAD + +void CWE325_Missing_Required_Cryptographic_Step__w32_CryptHashData_01_bad() +{ + { + BYTE payload[100]; + DWORD payloadLen = strlen(PAYLOAD); + HCRYPTPROV hCryptProv = (HCRYPTPROV)NULL; + HCRYPTHASH hHash = (HCRYPTHASH)NULL; + HCRYPTKEY hKey = (HCRYPTKEY)NULL; + char hashData[100] = HASH_INPUT; + do + { + /* Copy plaintext into payload buffer */ + memcpy(payload, PAYLOAD, payloadLen); + /* Aquire a Context */ + if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, 0)) + { + break; + } + /* Create hash handle */ + if(!CryptCreateHash(hCryptProv, CALG_SHA_256, 0, 0, &hHash)) + { + break; + } + /* FLAW: Missing required step (CryptHashData) does not use hash input when generating AES key */ + /* Derive an AES key from the hash */ + if(!CryptDeriveKey(hCryptProv, CALG_AES_256, hHash, 0, &hKey)) + { + break; + } + /* Encrypt the payload */ + if(!CryptEncrypt(hKey, 0, 1, 0, payload, &payloadLen, sizeof(payload))) + { + break; + } + } + while (0); + if (hKey) + { + CryptDestroyKey(hKey); + } + if (hHash) + { + CryptDestroyHash(hHash); + } + if (hCryptProv) + { + CryptReleaseContext(hCryptProv, 0); + } + /* Do something with the encrypted data */ + printBytesLine(payload, payloadLen); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +static void good1() +{ + { + BYTE payload[100]; + DWORD payloadLen = strlen(PAYLOAD); + HCRYPTPROV hCryptProv = (HCRYPTPROV)NULL; + HCRYPTHASH hHash = (HCRYPTHASH)NULL; + HCRYPTKEY hKey = (HCRYPTKEY)NULL; + char hashData[100] = HASH_INPUT; + do + { + /* Copy plaintext into payload buffer */ + memcpy(payload, PAYLOAD, payloadLen); + /* Aquire a Context */ + if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, 0)) + { + break; + } + /* Create hash handle */ + if(!CryptCreateHash(hCryptProv, CALG_SHA_256, 0, 0, &hHash)) + { + break; + } + /* FIX: All required steps are present */ + /* Hash the input string */ + if(!CryptHashData(hHash, (BYTE*)hashData, strlen(hashData), 0)) + { + break; + } + /* Derive an AES key from the hash */ + if(!CryptDeriveKey(hCryptProv, CALG_AES_256, hHash, 0, &hKey)) + { + break; + } + /* Encrypt the payload */ + if(!CryptEncrypt(hKey, 0, 1, 0, payload, &payloadLen, sizeof(payload))) + { + break; + } + } + while (0); + if (hKey) + { + CryptDestroyKey(hKey); + } + if (hHash) + { + CryptDestroyHash(hHash); + } + if (hCryptProv) + { + CryptReleaseContext(hCryptProv, 0); + } + /* Do something with the encrypted data */ + printBytesLine(payload, payloadLen); + } +} + +void CWE325_Missing_Required_Cryptographic_Step__w32_CryptHashData_01_good() +{ + good1(); +} + +#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()..."); + CWE325_Missing_Required_Cryptographic_Step__w32_CryptHashData_01_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE325_Missing_Required_Cryptographic_Step__w32_CryptHashData_01_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard010/C/0139069_lapacke_zunmql.c b/pool/shard010/C/0139069_lapacke_zunmql.c new file mode 100644 index 0000000000000000000000000000000000000000..b453cf1745eedbc610327635451566ff19f0d1df --- /dev/null +++ b/pool/shard010/C/0139069_lapacke_zunmql.c @@ -0,0 +1,88 @@ +/***************************************************************************** + Copyright (c) 2011, 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: + + * 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 Intel Corporation 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. +***************************************************************************** +* Contents: Native high-level C interface to LAPACK function zunmql +* Author: Intel Corporation +* Generated November, 2011 +*****************************************************************************/ + +#include "lapacke.h" +#include "lapacke_utils.h" + +lapack_int LAPACKE_zunmql( int matrix_order, char side, char trans, + lapack_int m, lapack_int n, lapack_int k, + const lapack_complex_double* a, lapack_int lda, + const lapack_complex_double* tau, + lapack_complex_double* c, lapack_int ldc ) +{ + lapack_int info = 0; + lapack_int lwork = -1; + lapack_complex_double* work = NULL; + lapack_complex_double work_query; + if( matrix_order != LAPACK_COL_MAJOR && matrix_order != LAPACK_ROW_MAJOR ) { + LAPACKE_xerbla( "LAPACKE_zunmql", -1 ); + return -1; + } +#ifndef LAPACK_DISABLE_NAN_CHECK + /* Optionally check input matrices for NaNs */ + lapack_int r = LAPACKE_lsame( side, 'l' ) ? m : n; + if( LAPACKE_zge_nancheck( matrix_order, r, k, a, lda ) ) { + return -7; + } + if( LAPACKE_zge_nancheck( matrix_order, m, n, c, ldc ) ) { + return -10; + } + if( LAPACKE_z_nancheck( k, tau, 1 ) ) { + return -9; + } +#endif + /* Query optimal working array(s) size */ + info = LAPACKE_zunmql_work( matrix_order, side, trans, m, n, k, a, lda, tau, + c, ldc, &work_query, lwork ); + if( info != 0 ) { + goto exit_level_0; + } + lwork = LAPACK_Z2INT( work_query ); + /* Allocate memory for work arrays */ + work = (lapack_complex_double*) + LAPACKE_malloc( sizeof(lapack_complex_double) * lwork ); + if( work == NULL ) { + info = LAPACK_WORK_MEMORY_ERROR; + goto exit_level_0; + } + /* Call middle-level interface */ + info = LAPACKE_zunmql_work( matrix_order, side, trans, m, n, k, a, lda, tau, + c, ldc, work, lwork ); + /* Release memory and exit */ + LAPACKE_free( work ); +exit_level_0: + if( info == LAPACK_WORK_MEMORY_ERROR ) { + LAPACKE_xerbla( "LAPACKE_zunmql", info ); + } + return info; +} diff --git a/pool/shard010/C/0139070_link.c b/pool/shard010/C/0139070_link.c new file mode 100644 index 0000000000000000000000000000000000000000..8458c6d97c0398ed6a8264fe732364163abb68a0 --- /dev/null +++ b/pool/shard010/C/0139070_link.c @@ -0,0 +1,86 @@ +/* + * Multi2Sim + * Copyright (C) 2012 Rafael Ubal (ubal@ece.neu.edu) + * + * 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 + + +struct net_link_t *net_link_create(struct net_t *net, + struct net_node_t *src_node, struct net_buffer_t *src_buffer, + struct net_node_t *dst_node, struct net_buffer_t *dst_buffer, + int bandwidth) +{ + struct net_link_t *link; + char name[MAX_STRING_SIZE]; + + /* Create */ + link = calloc(1, sizeof(struct net_link_t)); + if (!link) + fatal("%s: out of memory", __FUNCTION__); + + /* Fields */ + link->net = net; + link->src_node = src_node; + link->src_buffer = src_buffer; + link->dst_node = dst_node; + link->dst_buffer = dst_buffer; + link->bandwidth = bandwidth; + assert(src_buffer->node == src_node); + assert(dst_buffer->node == dst_node); + if (bandwidth < 1) + panic("%s: invalid bandwidth", __FUNCTION__); + + /* Connect buffers to link */ + assert(!src_buffer->link); + assert(!dst_buffer->link); + src_buffer->link = link; + dst_buffer->link = link; + + /* Name */ + snprintf(name, sizeof(name), "link_<%s.%s>_<%s.%s>", src_node->name, + src_buffer->name, dst_node->name, dst_buffer->name); + link->name = strdup(name); + + /* Return */ + return link; +} + + +void net_link_free(struct net_link_t *link) +{ + free(link->name); + free(link); +} + + +void net_link_dump_report(struct net_link_t *link, FILE *f) +{ + struct net_t *net = link->net; + + fprintf(f, "[ Network.%s.Link.%s ]\n", net->name, link->name); + fprintf(f, "Config.Bandwidth = %d\n", link->bandwidth); + fprintf(f, "TransferredMessages = %lld\n", link->transferred_msgs); + fprintf(f, "TransferredBytes = %lld\n", link->transferred_bytes); + fprintf(f, "BusyCycles = %lld\n", link->busy_cycles); + fprintf(f, "BytesPerCycle = %.4f\n", esim_cycle ? + (double) link->transferred_bytes / esim_cycle : 0.0); + fprintf(f, "Utilization = %.4f\n", esim_cycle ? + (double) link->transferred_bytes / (esim_cycle * link->bandwidth) : 0.0); + fprintf(f, "\n"); +} + diff --git a/pool/shard010/C/0139071_array-13.c b/pool/shard010/C/0139071_array-13.c new file mode 100644 index 0000000000000000000000000000000000000000..8335b7a186afe1e0de89676bb32e9f9177bb659e --- /dev/null +++ b/pool/shard010/C/0139071_array-13.c @@ -0,0 +1,28 @@ +/* { dg-do run } */ +/* { dg-options "" } */ + +/* Verify that GCC's initialized flexible array member extension + works properly. */ + +extern void abort(void); +extern void exit(int); + +typedef int T[]; +typedef int T0[0]; + +struct f { int w; T x; }; +struct g { int w; T0 x; }; + +static struct f f = { 4, { 0, 1, 2, 3 } }; +static int junk1[] = { -1, -1, -1, -1 }; +static struct g g = { 4, { 0, 1, 2, 3 } }; /* { dg-warning "(excess elements)|(near initialization)" "" } */ +static int junk2[] = { -1, -1, -1, -1 }; + +int main() +{ + int i; + for (i = 0; i < f.w; ++i) + if (f.x[i] != i) + abort (); + exit(0); +} diff --git a/pool/shard010/C/0139072_fat.c b/pool/shard010/C/0139072_fat.c new file mode 100644 index 0000000000000000000000000000000000000000..f343caf114a91346e61d0df497db6e891c4fe995 --- /dev/null +++ b/pool/shard010/C/0139072_fat.c @@ -0,0 +1,97 @@ +#include +#include +#include +#include +#include +#include + +/* Constants */ +#define SD_MOUNT "sd" + +/* Disc interfaces */ +extern const DISC_INTERFACE __io_wiisd; + + +s32 Fat_MountSD(void) +{ + s32 ret; + + /* Initialize SD interface */ + ret = __io_wiisd.startup(); + if (!ret) + return -1; + + /* Mount device */ + ret = fatMountSimple(SD_MOUNT, &__io_wiisd); + if (!ret) + return -2; + + return 0; +} + +s32 Fat_UnmountSD(void) +{ + s32 ret; + + /* Unmount device */ + fatUnmount(SD_MOUNT); + + /* Shutdown SD interface */ + ret = __io_wiisd.shutdown(); + if (!ret) + return -1; + + return 0; +} + +s32 Fat_ReadFile(const char *filepath, void **outbuf) +{ + FILE *fp = NULL; + void *buffer = NULL; + + struct stat filestat; + u32 filelen; + + s32 ret; + + /* Get filestats */ + stat(filepath, &filestat); + + /* Get filesize */ + filelen = filestat.st_size; + + /* Allocate memory */ + buffer = memalign(32, filelen); + if (!buffer) + goto err; + + /* Open file */ + fp = fopen(filepath, "rb"); + if (!fp) + goto err; + + /* Read file */ + ret = fread(buffer, 1, filelen, fp); + if (ret != filelen) + goto err; + + /* Set pointer */ + *outbuf = buffer; + + goto out; + +err: + /* Free memory */ + if (buffer) + free(buffer); + + /* Error code */ + ret = -1; + +out: + /* Close file */ + if (fp) + fclose(fp); + + return ret; +} diff --git a/pool/shard010/C/0139073_kalloc.c b/pool/shard010/C/0139073_kalloc.c new file mode 100644 index 0000000000000000000000000000000000000000..9356d408fe3b30ce19cdb1522fd71f0da9278108 --- /dev/null +++ b/pool/shard010/C/0139073_kalloc.c @@ -0,0 +1,214 @@ +#include +#include +#include +#include +#include "kalloc.h" + +/* The whole thing is: ("@" for the kheader_t of the block, "-" for free + * memory, and "+" for allocated memory. One char for one unit.) + * + * This region is core 1. This region is core 2. + * + * @-------@++++++@++++++++++++@------------ @----------@++++++++++++@+++++++@------------ + * | | | | + * p=p->ptr->ptr->ptr->ptr p->ptr p->ptr->ptr p->ptr->ptr->ptr + */ + +#define PTR(p) ((size_t*)((size_t*)p)[1]) + +typedef struct _allocated_t { + struct _allocated_t *next; + size_t *ptr; +} allocated_t; + +typedef struct { + size_t base[2], *loop_head; + allocated_t list_head, *list_tail; + size_t total_allocated; +} kmem_t; + +void *km_init() +{ + return calloc(1, sizeof(kmem_t)); +} + +static void kerror(const char *s) +{ + fprintf(stderr, "%s\n", s); + exit(1); +} + +static size_t *morecore(kmem_t *km, size_t nu) +{ + size_t rnu, *up; + + rnu = (nu + 0xfffff) & (~(size_t)0xfffff); + up = (size_t*)malloc(rnu * sizeof(size_t)); + if (!up) { /* fail to allocate memory */ + km_stat(km); + fprintf(stderr, "[morecore] %lu bytes requested but not available.\n", rnu * sizeof(size_t)); + exit(1); + } + /* put the pointer in km->list_head */ + if (km->list_tail == 0) km->list_tail = &km->list_head; + km->list_tail->ptr = up; + km->list_tail->next = (allocated_t*)calloc(1, sizeof(allocated_t)); + km->list_tail = km->list_tail->next; + + km->total_allocated += rnu * sizeof(size_t); + *up = rnu; /* the size of the current block, and in this case the block is the same as the new core */ + kfree(km, up + 1); /* initialize the new "core" */ + return km->loop_head; +} + +void km_destroy(void *_km) +{ + kmem_t *km = (kmem_t*)_km; + allocated_t *p, *q; + if (km == 0) return; + p = &km->list_head; + do { + q = p->next; + free(p->ptr); + if (p != &km->list_head) free(p); + p = q; + } while (p && p->next); + if (p != &km->list_head) free(p); + free(km); +} + +void kfree(void *_km, void *ap) +{ + size_t *p, *q; + kmem_t *km = (kmem_t*)_km; + + if (!ap) return; + if (km == 0) { + free(ap); + return; + } + p = (size_t*)ap - 1; /* *p is the size of the current block */ + /* Find the pointer that points to the block to be freed. The following loop can stop on two conditions: + * + * a) "p>q && pptr": @------@++++++++@+++++++@------- @---------------@+++++++@------- + * (can also be in | | | -> | | + * two cores) q p q->ptr q q->ptr + * + * @-------- @+++++++++@-------- @-------- @------------------ + * | | | -> | | + * q p q->ptr q q->ptr + * + * b) "q>=q->ptr && (p>q || pptr)": @-------@+++++ @--------@+++++++ @-------@+++++ @---------------- + * | | | -> | | + * q->ptr q p q->ptr q + * + * @+++++++@----- @++++++++@------- @------------- @++++++++@------- + * | | | -> | | + * p q->ptr q q->ptr q + */ + for (q = km->loop_head; !(p > q && p < PTR(q)); q = PTR(q)) + if (q >= PTR(q) && (p > q || p < PTR(q))) break; + if (p + (*p) == PTR(q)) { /* two adjacent blocks, merge p and q->ptr (the 2nd and 4th cases) */ + *p += *PTR(q); /* this is the new q->ptr size */ + p[1] = (size_t)PTR(PTR(q)); /* this is the new q->ptr->ptr */ + /* p is actually the new q->ptr. The actual change happens a few lines below. */ + } else if (p + (*p) > PTR(q) && PTR(q) >= p) { /* the end of the allocated block is in the next free block */ + kerror("[kfree] The end of the allocated block enters a free block."); + } else p[1] = (size_t)PTR(q); /* backup q->ptr */ + + if (q + (*q) == p) { /* two adjacent blocks, merge q and p (the other two cases) */ + *q += *p; + q[1] = (size_t)PTR(p); + km->loop_head = q; + } else if (q + (*q) > p && p >= q) { /* the end of a free block in the allocated block */ + kerror("[kfree] The end of a free block enters the allocated block."); + } else km->loop_head = p, q[1] = (size_t)p; /* in two cores, cannot be merged */ +} + +void *krealloc(void *_km, void *ap, size_t n_bytes) +{ + kmem_t *km = (kmem_t*)_km; + size_t n_units, *p, *q; + + if (n_bytes == 0) { + kfree(km, ap); return 0; + } + if (km == 0) return realloc(ap, n_bytes); + if (!ap) return kmalloc(km, n_bytes); + n_units = 1 + (n_bytes + sizeof(size_t) - 1) / sizeof(size_t); + p = (size_t*)ap - 1; + if (*p >= n_units) return ap; /* TODO: this prevents shrinking */ + q = (size_t*)kmalloc(km, n_bytes); + memcpy(q, ap, (*p - 1) * sizeof(size_t)); + kfree(km, ap); + return q; +} + +void *kmalloc(void *_km, size_t n_bytes) +{ + kmem_t *km = (kmem_t*)_km; + size_t n_units, *p, *q; + + if (n_bytes == 0) return 0; + if (km == 0) return malloc(n_bytes); + /* "n_units" means the number of units. The size of one unit equals to sizeof(kheader_t). + * "1" is the kheader_t of a block, which is always required. */ + n_units = 1 + (n_bytes + sizeof(size_t) - 1) / sizeof(size_t); + if (n_units&1) ++n_units; /* make n_units an even number, or it will segfault if only one unit remains */ + + if (!(q = km->loop_head)) { /* the first time when kmalloc() is called, intialization */ + km->base[1] = (size_t)(km->loop_head = q = km->base); *q = 0; + } + for (p = PTR(q);; q = p, p = PTR(p)) { /* search for a suitable block */ + if (*p >= n_units) { /* p->size if the size of current block. This line means the current block is large enough. */ + if (*p == n_units) q[1] = (size_t)PTR(p); /* no need to split the block */ + else { /* split the block */ + /* memory is allocated at the end of the block */ + *p -= n_units; /* reduce the size of the free block */ + p += *p; /* skip to the kheader_t of the allocated block */ + *p = n_units; /* set the size */ + } + km->loop_head = q; /* set the end of chain */ + return p + 1; /* skip the kheader_t */ + } + if (p == km->loop_head) { /* then ask for more "cores" */ + if ((p = morecore(km, n_units)) == 0) return 0; + } + } +} + +void *kcalloc(void *_km, size_t count, size_t size) +{ + kmem_t *km = (kmem_t*)_km; + void *p; + if (size == 0 || count == 0) return 0; + if (km == 0) return calloc(count, size); + p = kmalloc(km, count * size); + memset(p, 0, count * size); + return p; +} + +void km_stat(const void *_km) +{ + kmem_t *km = (kmem_t*)_km; + unsigned n_blocks, n_units; + size_t max_block = 0, *p, *q; + float frag; + + if (km == 0 || !(p = km->loop_head)) return; + n_blocks = n_units = 0; + do { + q = PTR(p); + if (*p > max_block) max_block = *p; + n_units += *p; + if (p + (*p) > q && q > p) + kerror("[kr_stat] The end of a free block enters another free block."); + p = q; + ++n_blocks; + } while (p != km->loop_head); + + --n_blocks; + frag = 1.0/1024.0 * n_units * sizeof(size_t) / n_blocks; + fprintf(stderr, "[kr_stat] tot=%lu, free=%lu, n_block=%u, max_block=%lu, frag_len=%.3fK\n", + km->total_allocated, n_units * sizeof(size_t), n_blocks, max_block * sizeof(size_t), frag); +} diff --git a/pool/shard010/C/0139074_SharedLock.c b/pool/shard010/C/0139074_SharedLock.c new file mode 100644 index 0000000000000000000000000000000000000000..e46b944af94dd7e5216a860e4ae8c1201c7a9935 --- /dev/null +++ b/pool/shard010/C/0139074_SharedLock.c @@ -0,0 +1,157 @@ +#define C_KINO_SHAREDLOCK +#include "KinoSearch/Util/ToolSet.h" + +#include +#include +#include + +#include "KinoSearch/Store/SharedLock.h" +#include "KinoSearch/Store/DirHandle.h" +#include "KinoSearch/Store/Folder.h" +#include "KinoSearch/Store/OutStream.h" + +SharedLock* +ShLock_new(Folder *folder, const CharBuf *name, const CharBuf *host, + int32_t timeout, int32_t interval) +{ + SharedLock *self = (SharedLock*)VTable_Make_Obj(SHAREDLOCK); + return ShLock_init(self, folder, name, host, timeout, interval); +} + +SharedLock* +ShLock_init(SharedLock *self, Folder *folder, const CharBuf *name, + const CharBuf *host, int32_t timeout, int32_t interval) +{ + LFLock_init((LockFileLock*)self, folder, name, host, timeout, interval); + + // Override. + DECREF(self->lock_path); + self->lock_path = (CharBuf*)INCREF(&EMPTY); + + return self; +} + +bool_t +ShLock_shared(SharedLock *self) { UNUSED_VAR(self); return true; } + +bool_t +ShLock_request(SharedLock *self) +{ + uint32_t i = 0; + ShLock_request_t super_request + = (ShLock_request_t)SUPER_METHOD(SHAREDLOCK, ShLock, Request); + + // EMPTY lock_path indicates whether this particular instance is locked. + if ( self->lock_path != (CharBuf*)&EMPTY + && Folder_Exists(self->folder, self->lock_path) + ) { + // Don't allow double obtain. + Err_set_error((Err*)LockErr_new(CB_newf( + "Lock already obtained via '%o'", self->lock_path))); + return false; + } + + DECREF(self->lock_path); + self->lock_path = CB_new(CB_Get_Size(self->name) + 10); + do { + CB_setf(self->lock_path, "locks/%o-%u32.lock", self->name, ++i); + } while ( Folder_Exists(self->folder, self->lock_path) ); + + bool_t success = super_request(self); + if (!success) { ERR_ADD_FRAME(Err_get_error()); } + return success; +} + +void +ShLock_release(SharedLock *self) +{ + if (self->lock_path != (CharBuf*)&EMPTY) { + ShLock_release_t super_release + = (ShLock_release_t)SUPER_METHOD(SHAREDLOCK, ShLock, Release); + super_release(self); + + // Empty out lock_path. + DECREF(self->lock_path); + self->lock_path = (CharBuf*)INCREF(&EMPTY); + } +} + + +void +ShLock_clear_stale(SharedLock *self) +{ + DirHandle *dh; + CharBuf *entry; + CharBuf *candidate = NULL; + CharBuf *lock_dir_name = (CharBuf*)ZCB_WRAP_STR("locks", 5); + + if (Folder_Find_Folder(self->folder, lock_dir_name)) { + dh = Folder_Open_Dir(self->folder, lock_dir_name); + if (!dh) { RETHROW(INCREF(Err_get_error())); } + entry = DH_Get_Entry(dh); + } + else { + return; + } + + // Take a stab at any file that begins with our lock name. + while (DH_Next(dh)) { + if ( CB_Starts_With(entry, self->name) + && CB_Ends_With_Str(entry, ".lock", 5) + ) { + candidate = candidate ? candidate : CB_new(0); + CB_setf(candidate, "%o/%o", lock_dir_name, entry); + ShLock_Maybe_Delete_File(self, candidate, false, true); + } + } + + DECREF(candidate); + DECREF(dh); +} + +bool_t +ShLock_is_locked(SharedLock *self) +{ + DirHandle *dh; + CharBuf *entry; + + CharBuf *lock_dir_name = (CharBuf*)ZCB_WRAP_STR("locks", 5); + if (Folder_Find_Folder(self->folder, lock_dir_name)) { + dh = Folder_Open_Dir(self->folder, lock_dir_name); + if (!dh) { RETHROW(INCREF(Err_get_error())); } + entry = DH_Get_Entry(dh); + } + else { + return false; + } + + while (DH_Next(dh)) { + // Translation: $locked = 1 if $entry =~ /^\Q$name-\d+\.lock$/ + if ( CB_Starts_With(entry, self->name) + && CB_Ends_With_Str(entry, ".lock", 5) + ) { + ZombieCharBuf *scratch = ZCB_WRAP(entry); + ZCB_Chop(scratch, sizeof(".lock") - 1); + while(isdigit(ZCB_Code_Point_From(scratch, 1))) { + ZCB_Chop(scratch, 1); + } + if (ZCB_Code_Point_From(scratch, 1) == '-') { + ZCB_Chop(scratch, 1); + if (ZCB_Equals(scratch, (Obj*)self->name)) { + DECREF(dh); + return true; + } + } + } + } + + DECREF(dh); + return false; +} + +/* Copyright 2007-2011 Marvin Humphrey + * + * This program is free software; you can redistribute it and/or modify + * under the same terms as Perl itself. + */ + diff --git a/pool/shard010/C/0139075_Utility_push_buffer.c b/pool/shard010/C/0139075_Utility_push_buffer.c new file mode 100644 index 0000000000000000000000000000000000000000..f5637cb88d19fe778de0c40ab25aa8aa4ae11371 --- /dev/null +++ b/pool/shard010/C/0139075_Utility_push_buffer.c @@ -0,0 +1,280 @@ +/* Version: MPL 1.1/GPL 2.0 + * + * The contents of this file are subject to the Mozilla Public License + * Version 1.1 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" + * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See + * the License for the specific language governing rights and + * limitations under the License. + * + * The Original Code is libUtility + * + * The Initial Developers of the Original Code are FumaSoftware Ltd, and Jamal Natour. + * Portions created before 1-Jan-2007 00:00:00 GMT by Jamal Natour, are Copyright + * (C) 2004-2007 Jamal Natour + * + * Portions created by Fumasoftware Ltd are Copyright (C) 2009-2010 FumaSoftware + * Ltd. + * + * Portions created by Jamal Natour are Copyright (C) 2009-2010 + * Fumasoftware Ltd and Jamal Natour. + * + * All Rights Reserved. + * + * Contributor(s): ______________________________________. + * + * Alternatively, the contents of this file may be used under the terms + * of the GNU General Public License Version 2 or later (the "GPL"), in + * which case the provisions of the GPL are applicable instead of those + * above. If you wish to allow use of your version of this file only + * under the terms of the GPL, and not to allow others to use your + * version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the + * notice and other provisions required by the GPL. If you do not + * delete the provisions above, a recipient may use your version of + * this file under the terms of any one of the MPL or the GPL. + * + */ +#if defined( __cplusplus) +extern "C" { +#endif + +#include "libUtility.h" + + +struct util_push_buf_tag +{ + FILE *fp; /* input stream */ + char *storage; /* underlying storage */ + const char *fname; /* filename for fopen/fdreopen */ + size_t len; /* maximum number of elements in buffer */ + size_t idx; /* read/write head */ +}; + +/* Allocate a new push back buffer + * + * Returns NULL on error setting errno + * Returns valid pointer on success + * + * EINVAL: invalid args passed + * function may fail and set errno for same reasons as malloc()*/ +util_push_buf_t * +utility_push_buf_alloc( + void + ) +{ +util_push_buf_t *push_buf; + + push_buf = malloc(sizeof(*push_buf)); + if(!push_buf) + return NULL; + + push_buf->fp = NULL; + push_buf->storage = NULL; + push_buf->fname = NULL; + push_buf->idx = 0; + push_buf->len = 0; + return push_buf; +} + +/* Release an existing push back buffer + * + * Returns NULL on error setting errno + * Returns valid pointer on success + * + * EINVAL: invalid args passed + * function may fail and set errno for same reasons as malloc()*/ + +void +utility_push_buf_release( + util_push_buf_t *push_buf + ) +{ + if(push_buf) + { + utility_push_buf_fclose(push_buf); + free(push_buf); + push_buf = NULL; + } +} + +/* Retrieve filename used to open underlying stream + + * Returns NULL on error setting errno + * Returns valid pointer on success + * + * EINVAL: invalid args passed + * function may fail and set errno for same reason + * utility_file_exists() + */ +const char * +utility_push_buf_fname( + util_push_buf_t *push_buf + ) +{ + errno = EINVAL; + return ( !push_buf || (1 > utility_file_exists(push_buf->fname))) ? NULL : push_buf->fname; +} + +/* Bind a file to the push back buffer + + * Returns NULL on error setting errno + * Returns valid pointer on success + * + * EINVAL: invalid args passed + * function may fail and set errno for same reasons as malloc()*/ +int +utility_push_buf_fopen( + util_push_buf_t *push_buf, + const char *fname + ) +{ + errno = EINVAL; + if((1 > utility_file_exists(fname)) || !push_buf) + return util_eError; + + push_buf->fp = utility_freopen(fname,"rb",push_buf->fp,1); + if(!push_buf->fp) + return util_eError; + + push_buf->fname = fname; + return util_eOk ; +} + +/* Unbind a file from the push back buffer + * + * Returns -1 on error setting errno + * Returns 0 on success + * + * EINVAL: invalid args passed*/ +int +utility_push_buf_fclose( + util_push_buf_t *push_buf + ) +{ + errno = EINVAL; + if(!push_buf) + return util_eError; + + if(push_buf->fp) + { + fclose(push_buf->fp); + push_buf->fp = NULL; + } + return util_eOk; +} + +/* Flush push back buffer + * + * Returns -1 on error setting errno + * Returns 0 on success + * + * EINVAL : push_buf is null + * Function may fail and set errno for same reasons + * */ +int +utility_push_buf_flush( + util_push_buf_t *push_buf + ) +{ + errno = EINVAL; + if(!push_buf || !push_buf->storage) + return util_eError; + + push_buf->idx = 0; + push_buf->storage[0] ='\0'; + return util_eOk; +} + + +/* Obtain byte from stream unless a previous pushed byte exists + * + * Returns EOF on failure setting errno + * Returns byte on success, EOF may be returned as a 'success' return when input stream is at end of file + * EINVAL: invalid args passed*/ +int +utility_push_buf_getc( + util_push_buf_t *push_buf + ) +{ + size_t nelem = 1; + errno = EINVAL; + if(!push_buf || !push_buf->storage || !push_buf->fp) + return EOF; + + if(push_buf->idx > 0) + return push_buf->storage[--push_buf->idx]; + + memset(push_buf->storage,'\0',push_buf->len); + nelem = fread(push_buf->storage,sizeof(uint8_t),push_buf->len-1,push_buf->fp); + /* short count is not always an error */ + if(nelem != push_buf->len) + { + if(ferror(push_buf->fp)) + return EOF; + + if(feof(push_buf->fp)) + return EOF; + } + + push_buf->idx = nelem; + utility_reverse(push_buf->storage,nelem); + return push_buf->storage[--push_buf->idx]; +} + +/* Store a byte for later use + * + * Returns EOF on failure setting errno + * Returns stored byte on success + * EINVAL: invalid args passed*/ +int +utility_push_buf_ungetc( + util_push_buf_t *push_buf, + int ch + ) +{ + errno = EINVAL; + if(!push_buf || !push_buf->storage || !(push_buf->idx < push_buf->len)) + return EOF; + + if(EOF != ch) + push_buf->storage[push_buf->idx++] = ch; + + return ch; +} + +/* set or retrive user data, + * calling with null data is a retrieve + * calling with non null data is a write + * + * + * EINVAL: parser ptr was null */ +const char * +utility_push_buf_storage( + util_push_buf_t *ptr, + char *buf, + size_t len + ) +{ + /* dodgy arguments so bail */ + errno = EINVAL; + if(!ptr) + return NULL; + + /* Read current value */ + if(!buf) + return ptr->storage; + + /* Overwrite current value, returning updated value */ + ptr->storage = buf; + ptr->len = len; + return buf; +} + + +#if defined( __cplusplus) + } +#endif diff --git a/pool/shard010/C/0139076_urandom.c b/pool/shard010/C/0139076_urandom.c new file mode 100644 index 0000000000000000000000000000000000000000..b7574ad10c5d198ab64369e694b04f52ba6814a4 --- /dev/null +++ b/pool/shard010/C/0139076_urandom.c @@ -0,0 +1,178 @@ +/* mpfr_urandom (rop, state, rnd_mode) -- Generate a uniform pseudorandom + real number between 0 and 1 (exclusive) and round it to the precision of rop + according to the given rounding mode. + +Copyright 2000-2004, 2006-2017 Free Software Foundation, Inc. +Contributed by the AriC and Caramba projects, INRIA. + +This file is part of the GNU MPFR Library. + +The GNU MPFR 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 3 of the License, or (at your +option) any later version. + +The GNU MPFR 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 MPFR Library; see the file COPYING.LESSER. If not, see +http://www.gnu.org/licenses/ or write to the Free Software Foundation, Inc., +51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. */ + + +#define MPFR_NEED_LONGLONG_H +#include "mpfr-impl.h" + + +/* generate one random bit */ +static int +random_rounding_bit (gmp_randstate_t rstate) +{ + mp_limb_t r; + + mpfr_rand_raw (&r, rstate, 1); + return r & MPFR_LIMB_ONE; +} + +/* FIXME: Generate exceptions (flags) when need be, as usual? The current + behavior is inconsistent as when reached, mpfr_check_range will detect + some exceptions and set the corresponding flag. */ + +int +mpfr_urandom (mpfr_ptr rop, gmp_randstate_t rstate, mpfr_rnd_t rnd_mode) +{ + mpfr_limb_ptr rp; + mpfr_prec_t nbits; + mp_size_t nlimbs; + mp_size_t n; + mpfr_exp_t exp; + mpfr_exp_t emin; + int cnt; + int inex; + + rp = MPFR_MANT (rop); + nbits = MPFR_PREC (rop); + + emin = mpfr_get_emin (); + + /* special code for nbits = 1 */ + if (nbits == 1) + { + exp = 0; + while (random_rounding_bit (rstate) == 0) + exp --; + + /* we assume the number is 0.000...0001xxx with e consecutive 0's after + the binary point */ + + MPFR_EXP (rop) = exp; /* may be outside the current exponent range */ + rp[0] = MPFR_LIMB_HIGHBIT; + goto rounding; + } + + nlimbs = MPFR_LIMB_SIZE (rop); + MPFR_SET_POS (rop); + exp = 0; + if (MPFR_UNLIKELY (emin > 0)) + { + if (rnd_mode == MPFR_RNDU || rnd_mode == MPFR_RNDA + || (emin == 1 && rnd_mode == MPFR_RNDN + && random_rounding_bit (rstate))) + { + mpfr_set_ui_2exp (rop, 1, emin - 1, rnd_mode); + return +1; + } + else + { + MPFR_SET_ZERO (rop); + return -1; + } + } + + /* Exponent */ +#define DRAW_BITS 8 /* we draw DRAW_BITS at a time */ + cnt = DRAW_BITS; + MPFR_STAT_STATIC_ASSERT (DRAW_BITS <= GMP_NUMB_BITS); + while (cnt == DRAW_BITS) + { + /* generate DRAW_BITS in rp[0] */ + mpfr_rand_raw (rp, rstate, DRAW_BITS); + if (MPFR_UNLIKELY (rp[0] == 0)) + cnt = DRAW_BITS; + else + { + count_leading_zeros (cnt, rp[0]); + cnt -= GMP_NUMB_BITS - DRAW_BITS; + } + exp -= cnt; /* no integer overflow */ + + if (MPFR_UNLIKELY (exp < emin)) + { + /* To get here, we have been drawing more than -emin zeros + in a row, then return 0 or the smallest representable + positive number. + + The rounding to nearest mode is subtle: + If exp == emin - 1, the rounding bit is set, except + if cnt == DRAW_BITS in which case the rounding bit is + outside rp[0] and must be generated. */ + if (rnd_mode == MPFR_RNDU || rnd_mode == MPFR_RNDA + || (rnd_mode == MPFR_RNDN && exp == emin - 1 + && (cnt != DRAW_BITS || random_rounding_bit (rstate)))) + { + mpfr_set_ui_2exp (rop, 1, emin - 1, rnd_mode); + return +1; + } + else + { + MPFR_SET_ZERO (rop); + return -1; + } + } + } + MPFR_EXP (rop) = exp; /* Warning: may be outside the current + exponent range */ + + /* Significand: we need generate only nbits-1 bits, since the most + significant is 1 */ + mpfr_rand_raw (rp, rstate, nbits - 1); + n = nlimbs * GMP_NUMB_BITS - nbits; + if (MPFR_LIKELY (n != 0)) /* this will put the low bits to zero */ + mpn_lshift (rp, rp, nlimbs, n); + + /* Set the msb to 1 since it was fixed by the exponent choice */ + rp[nlimbs - 1] |= MPFR_LIMB_HIGHBIT; + + rounding: + /* Rounding */ + if (rnd_mode == MPFR_RNDU || rnd_mode == MPFR_RNDA + || (rnd_mode == MPFR_RNDN && random_rounding_bit (rstate))) + { + /* Take care of the exponent range: it may have been reduced */ + if (exp < emin) + { + /* since we expect a number in [0,1], for RNDN when emin > 1 + we should return 0 */ + inex = mpfr_set_ui_2exp (rop, 1, ((emin > 1) ? 1 : emin) - 1, rnd_mode); + if (inex == 0) + inex = +1; + } + else if (exp > mpfr_get_emax ()) + { + mpfr_set_inf (rop, +1); /* overflow, flag set by mpfr_check_range */ + inex = +1; + } + else + { + mpfr_nextabove (rop); + inex = +1; + } + } + else + inex = -1; + + return mpfr_check_range (rop, inex, rnd_mode); +} diff --git a/pool/shard010/C/0139077_utlock.c b/pool/shard010/C/0139077_utlock.c new file mode 100644 index 0000000000000000000000000000000000000000..c356f62be8583dce27769745c6a6eebf7e8d3f8b --- /dev/null +++ b/pool/shard010/C/0139077_utlock.c @@ -0,0 +1,95 @@ + + + + +#include +#include "accommon.h" + +#define _COMPONENT ACPI_UTILITIES +ACPI_MODULE_NAME("utlock") + + +acpi_status acpi_ut_create_rw_lock(struct acpi_rw_lock *lock) +{ + acpi_status status; + + lock->num_readers = 0; + status = acpi_os_create_mutex(&lock->reader_mutex); + if (ACPI_FAILURE(status)) { + return status; + } + + status = acpi_os_create_mutex(&lock->writer_mutex); + return status; +} + +void acpi_ut_delete_rw_lock(struct acpi_rw_lock *lock) +{ + + acpi_os_delete_mutex(lock->reader_mutex); + acpi_os_delete_mutex(lock->writer_mutex); + + lock->num_readers = 0; + lock->reader_mutex = NULL; + lock->writer_mutex = NULL; +} + + + +acpi_status acpi_ut_acquire_read_lock(struct acpi_rw_lock *lock) +{ + acpi_status status; + + status = acpi_os_acquire_mutex(lock->reader_mutex, ACPI_WAIT_FOREVER); + if (ACPI_FAILURE(status)) { + return status; + } + + + + lock->num_readers++; + if (lock->num_readers == 1) { + status = + acpi_os_acquire_mutex(lock->writer_mutex, + ACPI_WAIT_FOREVER); + } + + acpi_os_release_mutex(lock->reader_mutex); + return status; +} + +acpi_status acpi_ut_release_read_lock(struct acpi_rw_lock *lock) +{ + acpi_status status; + + status = acpi_os_acquire_mutex(lock->reader_mutex, ACPI_WAIT_FOREVER); + if (ACPI_FAILURE(status)) { + return status; + } + + + + lock->num_readers--; + if (lock->num_readers == 0) { + acpi_os_release_mutex(lock->writer_mutex); + } + + acpi_os_release_mutex(lock->reader_mutex); + return status; +} + + + +acpi_status acpi_ut_acquire_write_lock(struct acpi_rw_lock *lock) +{ + acpi_status status; + + status = acpi_os_acquire_mutex(lock->writer_mutex, ACPI_WAIT_FOREVER); + return status; +} + +void acpi_ut_release_write_lock(struct acpi_rw_lock *lock) +{ + + acpi_os_release_mutex(lock->writer_mutex); +} diff --git a/pool/shard010/C/0139078_gm7121_cvbs.c b/pool/shard010/C/0139078_gm7121_cvbs.c new file mode 100644 index 0000000000000000000000000000000000000000..08c430e23ce09bb2a380d9f7b1003e4dad55371e --- /dev/null +++ b/pool/shard010/C/0139078_gm7121_cvbs.c @@ -0,0 +1,194 @@ +#include "panels.h" + +extern s32 gm7121_tv_power_on(u32 on_off); +extern s32 gm7121_tv_open(void); +extern s32 gm7121_tv_close(void); +extern s32 gm7121_tv_get_mode(void); +extern s32 gm7121_tv_set_mode(disp_tv_mode tv_mode); +extern s32 gm7121_tv_get_mode_support(disp_tv_mode tv_mode); + +static void LCD_power_on(u32 sel); +static void LCD_power_off(u32 sel); +static void LCD_bl_open(u32 sel); +static void LCD_bl_close(u32 sel); + +static void LCD_panel_init(u32 sel); +static void LCD_panel_exit(u32 sel); + +static void LCD_cfg_panel_info(panel_extend_para * info) +{ + u32 i = 0, j=0; + u32 items; + u8 lcd_gamma_tbl[][2] = + { + //{input value, corrected value} + {0, 0}, + {15, 15}, + {30, 30}, + {45, 45}, + {60, 60}, + {75, 75}, + {90, 90}, + {105, 105}, + {120, 120}, + {135, 135}, + {150, 150}, + {165, 165}, + {180, 180}, + {195, 195}, + {210, 210}, + {225, 225}, + {240, 240}, + {255, 255}, + }; + + u8 lcd_bright_curve_tbl[][2] = + { + //{input value, corrected value} + {0 ,0 },//0 + {15 ,3 },//0 + {30 ,6 },//0 + {45 ,9 },// 1 + {60 ,12 },// 2 + {75 ,16 },// 5 + {90 ,22 },//9 + {105 ,28 }, //15 + {120 ,36 },//23 + {135 ,44 },//33 + {150 ,54 }, + {165 ,67 }, + {180 ,84 }, + {195 ,108}, + {210 ,137}, + {225 ,171}, + {240 ,210}, + {255 ,255}, + }; + + u32 lcd_cmap_tbl[2][3][4] = { + { + {LCD_CMAP_G0,LCD_CMAP_B1,LCD_CMAP_G2,LCD_CMAP_B3}, + {LCD_CMAP_B0,LCD_CMAP_R1,LCD_CMAP_B2,LCD_CMAP_R3}, + {LCD_CMAP_R0,LCD_CMAP_G1,LCD_CMAP_R2,LCD_CMAP_G3}, + }, + { + {LCD_CMAP_B3,LCD_CMAP_G2,LCD_CMAP_B1,LCD_CMAP_G0}, + {LCD_CMAP_R3,LCD_CMAP_B2,LCD_CMAP_R1,LCD_CMAP_B0}, + {LCD_CMAP_G3,LCD_CMAP_R2,LCD_CMAP_G1,LCD_CMAP_R0}, + }, + }; + + memset(info,0,sizeof(panel_extend_para)); + + items = sizeof(lcd_gamma_tbl)/2; + for(i=0; ilcd_gamma_tbl[lcd_gamma_tbl[i][0] + j] = (value<<16) + (value<<8) + value; + } + } + info->lcd_gamma_tbl[255] = (lcd_gamma_tbl[items-1][1]<<16) + (lcd_gamma_tbl[items-1][1]<<8) + lcd_gamma_tbl[items-1][1]; + + items = sizeof(lcd_bright_curve_tbl)/2; + for(i=0; ilcd_bright_curve_tbl[lcd_bright_curve_tbl[i][0] + j] = value; + } + } + info->lcd_bright_curve_tbl[255] = lcd_bright_curve_tbl[items-1][1]; + + memcpy(info->lcd_cmap_tbl, lcd_cmap_tbl, sizeof(lcd_cmap_tbl)); + +} + +static s32 LCD_open_flow(u32 sel) +{ + LCD_OPEN_FUNC(sel, LCD_power_on, 200); + LCD_OPEN_FUNC(sel, LCD_panel_init, 100); + LCD_OPEN_FUNC(sel, sunxi_lcd_tcon_enable, 50); + LCD_OPEN_FUNC(sel, LCD_bl_open, 0); + return 0; +} + +static s32 LCD_close_flow(u32 sel) +{ + LCD_CLOSE_FUNC(sel, LCD_bl_close, 50); + LCD_CLOSE_FUNC(sel, sunxi_lcd_tcon_disable, 50); + LCD_CLOSE_FUNC(sel, LCD_panel_exit, 0); + LCD_CLOSE_FUNC(sel, LCD_power_off, 500); + return 0; +} + +static void LCD_power_on(u32 sel) +{ + sunxi_lcd_gpio_set_value(sel, 0, 0); + gm7121_tv_power_on(1); + sunxi_lcd_pin_cfg(sel, 1); +} + +static void LCD_power_off(u32 sel) +{ + gm7121_tv_power_on(0); +} + +static void LCD_bl_open(u32 sel) +{ + gm7121_tv_open(); +} + +static void LCD_bl_close(u32 sel) +{ + sunxi_lcd_gpio_set_value(sel, 0, 0); +} + +static void LCD_panel_init(u32 sel) +{ + sunxi_lcd_gpio_set_value(sel, 0, 1); + return; +} + +static void LCD_panel_exit(u32 sel) +{ + sunxi_lcd_pin_cfg(sel, 0); + return ; +} + +//sel: 0:lcd0; 1:lcd1 +static s32 LCD_user_defined_func(u32 sel, u32 para1, u32 para2, u32 para3) +{ + s32 ret = -1; + switch(para1){ + case 0: //tv_get_mode + ret = gm7121_tv_get_mode(); + break; + case 1: //tv_set_mode + ret = gm7121_tv_set_mode(para2); + break; + case 2: //tv_get_mode_support + ret = gm7121_tv_get_mode_support(para2); + break; + default: + break; + } + return ret; +} + +__lcd_panel_t gm7121_cvbs = { + /* panel driver name, must mach the name of lcd_drv_name in sys_config.fex */ + .name = "gm7121", + .func = { + .cfg_panel_info = LCD_cfg_panel_info, + .cfg_open_flow = LCD_open_flow, + .cfg_close_flow = LCD_close_flow, + .lcd_user_defined_func = LCD_user_defined_func, + }, +}; diff --git a/pool/shard010/C/0139079_demo_logger.c b/pool/shard010/C/0139079_demo_logger.c new file mode 100644 index 0000000000000000000000000000000000000000..c7b1543629f9f906cba10c8d5bad9e0d25a3de27 --- /dev/null +++ b/pool/shard010/C/0139079_demo_logger.c @@ -0,0 +1,75 @@ +/* + * test_logger.c + * + * Created on: Jul 2, 2013 + * Author: mgrosvenor + */ + +//Customize the logging build level - This is not necessary and can be omitted if you are happy with the default +//This MUST come before #include "../log/log.h"! +//************************************************************************************************************** +#include "../log/log_levels.h" +#define CH_LOG_BUILD_LVL CH_LOG_LVL_DEBUG3 +//************************************************************************************************************** + +//Pull in the logger +#include "../log/log.h" + +#include + +//Use it +// +USE_CH_LOGGER(CH_LOG_LVL_INFO,true,ch_log_tostdout,"NULL"); + +int main(int argc, char** argv) +{ + (void)argc; + (void)argv; + + int i = 0; + for(; i < 10; i++){ //Loop around a few times. Use valgrind to make sure that there are no memory leaks + + ch_log_settings.log_level = i; + printf("Log level = %i\n", i); + printf("--------------------------------------------\n"); + ch_log_error("Error text here - %u\n", i); + ch_log_warn("Warning text here - %u\n", i); + ch_log_debug1("Debug text here - %u\n", i); + ch_log_debug2("Debug 2 text here - %u\n", i); + ch_log_debug3("Debug 3 text here - %u\n", i); + printf("--------------------------------------------\n"); + + ch_log_settings.use_utc = i % 2; + ch_log_settings.incl_timezone = i % 3; + ch_log_settings.subsec_digits = 10 - i; + ch_log_info("Info text here - %u\n", i); + ch_log_settings.lvl_config[CH_LOG_LVL_INFO].source = !ch_log_settings.lvl_config[CH_LOG_LVL_INFO].source; + + } + + ch_log_settings_t new_settings = _ch_log_settings_default_min; + for(i=0; i < 10; i++){ //Loop around a few times. Use valgrind to make sure that there are no memory leaks + + new_settings.log_level = i; + printf("Log level = %i\n", i); + printf("--------------------------------------------\n"); + ch_elog_error(&new_settings,"Error text here - %u\n", i); + ch_elog_warn(&new_settings,"Warning text here - %u\n", i); + ch_elog_debug1(&new_settings,"Debug text here - %u\n", i); + ch_elog_debug2(&new_settings,"Debug 2 text here - %u\n", i); + ch_elog_debug3(&new_settings,"Debug 3 text here - %u\n", i); + printf("--------------------------------------------\n"); + + new_settings.use_utc = i % 2; + new_settings.incl_timezone = i % 3; + new_settings.subsec_digits = 10 - i; + ch_log_info("Info text here - %u\n", i); + new_settings.lvl_config[CH_LOG_LVL_INFO].source = !new_settings.lvl_config[CH_LOG_LVL_INFO].source; + + } + + //if we use the function, automated tests will detect a failure... + ch_log_fatal("Fatal error text here %u\n", i); + + return 0; +} diff --git a/pool/shard010/C/0139080_max1168_arch.c b/pool/shard010/C/0139080_max1168_arch.c new file mode 100644 index 0000000000000000000000000000000000000000..d696f74017b5947a7dd4141bbe05204840994783 --- /dev/null +++ b/pool/shard010/C/0139080_max1168_arch.c @@ -0,0 +1,63 @@ +/* + * Copyright (C) 2008-2009 Antoine Drouin + * Copyright (C) 2012 Gautier Hattenberger + * + * This file is part of paparazzi. + * + * paparazzi 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. + * + * paparazzi 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 paparazzi; see the file COPYING. If not, write to + * the Free Software Foundation, 59 Temple Place - Suite 330, + * Boston, MA 02111-1307, USA. + */ + +#include "peripherals/max1168.h" + +#include "LPC21xx.h" +#include "interrupt_hw.h" +#include BOARD_CONFIG + +static void EXTINT0_ISR(void) __attribute__((naked)); + +void max1168_arch_init(void) +{ + + /* connect P0.16 to extint0 (EOC) */ + MAX1168_EOC_PINSEL |= MAX1168_EOC_PINSEL_VAL << MAX1168_EOC_PINSEL_BIT; + /* extint0 is edge trigered */ + SetBit(EXTMODE, MAX1168_EOC_EINT); + /* extint0 is trigered on falling edge */ + ClearBit(EXTPOLAR, MAX1168_EOC_EINT); + /* clear pending extint0 before enabling interrupts */ + SetBit(EXTINT, MAX1168_EOC_EINT); + + /* initialize interrupt vector */ + VICIntSelect &= ~VIC_BIT(MAX1168_EOC_VIC_IT); // EXTINT0 selected as IRQ + VICIntEnable = VIC_BIT(MAX1168_EOC_VIC_IT); // EXTINT0 interrupt enabled + _VIC_CNTL(MAX1168_EOC_VIC_SLOT) = VIC_ENABLE | MAX1168_EOC_VIC_IT; + _VIC_ADDR(MAX1168_EOC_VIC_SLOT) = (uint32_t)EXTINT0_ISR; // address of the ISR +} + + +void EXTINT0_ISR(void) +{ + ISR_ENTRY(); + //ASSERT((max1168_status == MAX1168_SENDING_REQ), DEBUG_MAX_1168, MAX1168_ERR_SPURIOUS_EOC); + + max1168_status = MAX1168_GOT_EOC; + + //SetBit(EXTINT, MAX1168_EOC_EINT); /* clear extint0 */ + EXTINT = (1 << MAX1168_EOC_EINT); + VICVectAddr = 0x00000000; /* clear this interrupt from the VIC */ + + ISR_EXIT(); +} diff --git a/pool/shard010/C/0139081_serial_s5p.c b/pool/shard010/C/0139081_serial_s5p.c new file mode 100644 index 0000000000000000000000000000000000000000..8cb5e303d94fdaf4b17b511b399223283b32740e --- /dev/null +++ b/pool/shard010/C/0139081_serial_s5p.c @@ -0,0 +1,190 @@ +/* + * (C) Copyright 2009 SAMSUNG Electronics + * Minkyu Kang + * Heungjun Kim + * + * based on drivers/serial/s3c64xx.c + * + * SPDX-License-Identifier: GPL-2.0+ + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +DECLARE_GLOBAL_DATA_PTR; + +#define RX_FIFO_COUNT_SHIFT 0 +#define RX_FIFO_COUNT_MASK (0xff << RX_FIFO_COUNT_SHIFT) +#define RX_FIFO_FULL (1 << 8) +#define TX_FIFO_COUNT_SHIFT 16 +#define TX_FIFO_COUNT_MASK (0xff << TX_FIFO_COUNT_SHIFT) +#define TX_FIFO_FULL (1 << 24) + +/* Information about a serial port */ +struct s3c_serial_platdata { + struct s3c_uart *reg; /* address of registers in physical memory */ + u8 port_id; /* uart port number */ +}; + +/* + * The coefficient, used to calculate the baudrate on S5P UARTs is + * calculated as + * C = UBRDIV * 16 + number_of_set_bits_in_UDIVSLOT + * however, section 31.6.11 of the datasheet doesn't recomment using 1 for 1, + * 3 for 2, ... (2^n - 1) for n, instead, they suggest using these constants: + */ +static const int udivslot[] = { + 0, + 0x0080, + 0x0808, + 0x0888, + 0x2222, + 0x4924, + 0x4a52, + 0x54aa, + 0x5555, + 0xd555, + 0xd5d5, + 0xddd5, + 0xdddd, + 0xdfdd, + 0xdfdf, + 0xffdf, +}; + +int s5p_serial_setbrg(struct udevice *dev, int baudrate) +{ + struct s3c_serial_platdata *plat = dev->platdata; + struct s3c_uart *const uart = plat->reg; + u32 uclk = get_uclk(plat->port_id); + u32 val; + + val = uclk / baudrate; + + writel(val / 16 - 1, &uart->ubrdiv); + + if (s5p_uart_divslot()) + writew(udivslot[val % 16], &uart->rest.slot); + else + writeb(val % 16, &uart->rest.value); + + return 0; +} + +static int s5p_serial_probe(struct udevice *dev) +{ + struct s3c_serial_platdata *plat = dev->platdata; + struct s3c_uart *const uart = plat->reg; + + /* enable FIFOs, auto clear Rx FIFO */ + writel(0x3, &uart->ufcon); + writel(0, &uart->umcon); + /* 8N1 */ + writel(0x3, &uart->ulcon); + /* No interrupts, no DMA, pure polling */ + writel(0x245, &uart->ucon); + + return 0; +} + +static int serial_err_check(const struct s5p_uart *const uart, int op) +{ + unsigned int mask; + + /* + * UERSTAT + * Break Detect [3] + * Frame Err [2] : receive operation + * Parity Err [1] : receive operation + * Overrun Err [0] : receive operation + */ + if (op) + mask = 0x8; + else + mask = 0xf; + + return readl(&uart->uerstat) & mask; +} + +static int s5p_serial_getc(struct udevice *dev) +{ + struct s5p_serial_platdata *plat = dev->platdata; + struct s5p_uart *const uart = plat->reg; + + if (!(readl(&uart->ufstat) & RX_FIFO_COUNT_MASK)) + return -EAGAIN; + + serial_err_check(uart, 0); + return (int)(readb(&uart->urxh) & 0xff); +} + +static int s5p_serial_putc(struct udevice *dev, const char ch) +{ + struct s5p_serial_platdata *plat = dev->platdata; + struct s5p_uart *const uart = plat->reg; + + if (readl(&uart->ufstat) & TX_FIFO_FULL) + return -EAGAIN; + + writeb(ch, &uart->utxh); + serial_err_check(uart, 1); + + return 0; +} + +static int s5p_serial_pending(struct udevice *dev, bool input) +{ + struct s5p_serial_platdata *plat = dev->platdata; + struct s5p_uart *const uart = plat->reg; + uint32_t ufstat = readl(&uart->ufstat); + + if (input) + return (ufstat & RX_FIFO_COUNT_MASK) >> RX_FIFO_COUNT_SHIFT; + else + return (ufstat & TX_FIFO_COUNT_MASK) >> TX_FIFO_COUNT_SHIFT; +} + +static int s5p_serial_ofdata_to_platdata(struct udevice *dev) +{ + struct s5p_serial_platdata *plat = dev->platdata; + fdt_addr_t addr; + + addr = fdtdec_get_addr(gd->fdt_blob, dev->of_offset, "reg"); + if (addr == FDT_ADDR_T_NONE) + return -EINVAL; + + plat->reg = (struct s5p_uart *)addr; + plat->port_id = fdtdec_get_int(gd->fdt_blob, dev->of_offset, "id", -1); + + return 0; +} + +static const struct dm_serial_ops s5p_serial_ops = { + .putc = s5p_serial_putc, + .pending = s5p_serial_pending, + .getc = s5p_serial_getc, + .setbrg = s5p_serial_setbrg, +}; + +static const struct udevice_id s5p_serial_ids[] = { + { .compatible = "samsung,exynos4210-uart" }, + { } +}; + +U_BOOT_DRIVER(serial_s5p) = { + .name = "serial_s5p", + .id = UCLASS_SERIAL, + .of_match = s5p_serial_ids, + .ofdata_to_platdata = s5p_serial_ofdata_to_platdata, + .platdata_auto_alloc_size = sizeof(struct s5p_serial_platdata), + .probe = s5p_serial_probe, + .ops = &s5p_serial_ops, + .flags = DM_FLAG_PRE_RELOC, +}; diff --git a/pool/shard010/C/0139082_problem_28.c b/pool/shard010/C/0139082_problem_28.c new file mode 100644 index 0000000000000000000000000000000000000000..ddff7bbf9ed7a73df54920637d012e7e179c88e6 --- /dev/null +++ b/pool/shard010/C/0139082_problem_28.c @@ -0,0 +1,54 @@ +#include +#include +#include +#include +/** + * Problem 28 from Project Euler + * + * Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows: + * + * 21 22 23 24 25 + * 20 7 8 9 10 + * 19 6 1 2 11 + * 18 5 4 3 12 + * 17 16 15 14 13 + * + * It can be verified that the sum of the numbers on the diagonals is 101. + * + * What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way? + * + * @author Claudio Ludovico Panetta (@Ludo237) + * + * @version 1.0.0 + **/ +#define MAX 1001 +#define SPIRAL (MAX * MAX) + +int main(int argc, char *argv[]) +{ + // Benchmar variables + double start, end; + // Helper variable + unsigned int pivot = 0, total = 0; + // Algorithm starts + printf("Algorithm starts, please wait.\n"); + start = clock(); + // Iterating trough the spiral + for(unsigned int i = 1; i <= SPIRAL; i += pivot) + { + unsigned int pow = pivot + 1; + if( pow*pow == i) + { + // Since we cannot simply add i++ + // This is the only way to sum the diagonal numbers + pivot += 2; + } + // Our result + total += i; + } + // Finish + end = clock(); + printf("Algorithm end.\n"); + printf("Total time: %f\n", (end - start)/CLOCKS_PER_SEC); + return 0; +} diff --git a/pool/shard010/C/0139083_symtab.c b/pool/shard010/C/0139083_symtab.c new file mode 100644 index 0000000000000000000000000000000000000000..ffdbabbba953eb6e9bd6ae883eede4966824389d --- /dev/null +++ b/pool/shard010/C/0139083_symtab.c @@ -0,0 +1,146 @@ +/* scis - SCI assembler + * + * scis is the legal property of its developers, whose names are listed + * in the AUTHORS file. + * + * 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 +#include + +/* OPTIMIZE THIS! */ + +char *xstrdup(char *s) +{ + int sl = strlen(s) + 1; + char *m = malloc(sl); + memcpy(m, s, sl); + return m; +} + +typedef struct { + char *name; + int value; + char *file; + int line; + int type; +} symtab_entry_t; + +struct symtab_struct { + int dup; + int entries_used; + int table_size; + symtab_entry_t *table; +}; + +struct symtab_struct * +new_symtab(int dup) +{ + struct symtab_struct *st = malloc(sizeof(struct symtab_struct)); + st->dup = dup; + st->table_size = 64; + st->entries_used = 0; + st->table = malloc(sizeof(symtab_entry_t) * st->table_size); + + return st; +} + +void +free_symtab(struct symtab_struct *symtab) +{ + int i; + + for (i = 0; i < symtab->entries_used; i++) { + symtab_entry_t *e = (symtab->table) + i; + + free(e->name); + } + + free(symtab->table); + free(symtab); +} + +int +add_symbol(struct symtab_struct *symtab, char *symbol, int value, char *file, int line, int type) +{ + symtab_entry_t *e; + + if (!symtab->dup) + if (!read_symbol(symtab, symbol, NULL, NULL, NULL, NULL)) + return 1; /* Already defined */ + + if (symtab->entries_used + 1 == symtab->table_size) { + symtab->table_size <<= 1; + symtab->table = realloc(symtab->table, + sizeof(symtab_entry_t) * symtab->table_size); + } + + e = (symtab->table) + (symtab->entries_used)++; + + e->name = xstrdup(symbol); + e->file = file; + e->line = line; + e->value = value; + e->type = type; + return 0; +} + + +int +read_symbol(struct symtab_struct *symtab, char *symbol, int *value, char **file, int *line, int *type) +{ + int i; + + for (i = 0; i < symtab->entries_used; i++) + if (!strcmp(symtab->table[i].name, symbol)) { + symtab_entry_t *e = (symtab->table) + i; + if (value) + *value = e->value; + if (file) + *file = e->file; + if (line) + *line = e->line; + if (type) + *type = e->type; + return 0; + } + + return 1; /* failure */ +} + +int +pop_symbol(struct symtab_struct *symtab, char **symbol, int *value, char **file, int *line, int *type) +{ + if (symtab->entries_used <= 0) + return 1; + else { + symtab_entry_t *e = (symtab->table) + --(symtab->entries_used); + if (symbol) + *symbol = e->name; + else free(e->name); + + if (value) + *value = e->value; + if (file) + *file = e->file; + if (line) + *line = e->line; + if (type) + *type = e->type; + return 0; + } +} diff --git a/pool/shard010/C/0139084_exfat.c b/pool/shard010/C/0139084_exfat.c new file mode 100644 index 0000000000000000000000000000000000000000..dac6e743ea415b09b96511674fadefe44b8705a1 --- /dev/null +++ b/pool/shard010/C/0139084_exfat.c @@ -0,0 +1,115 @@ +/* + + File: exfat.c + + Copyright (C) 2009 Christophe GRENIER + + This software 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 the Free Software Foundation, Inc., 51 + Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + */ +#ifdef HAVE_CONFIG_H +#include +#endif + +#ifdef HAVE_STDLIB_H +#include +#endif +#ifdef HAVE_STRING_H +#include +#endif +#include +#include "types.h" +#include "common.h" +#include "exfat.h" +#include "log.h" + +extern const arch_fnct_t arch_none; + +uint64_t exfat_cluster_to_offset(const struct exfat_super_block *exfat_header, const unsigned int cluster) +{ + return ((uint64_t)(((cluster-2) << exfat_header->block_per_clus_bits) + le32(exfat_header->clus_blocknr))) << exfat_header->blocksize_bits; +} + +int exfat_read_cluster(disk_t *disk, const partition_t *partition, const struct exfat_super_block*exfat_header, void *buffer, const unsigned int cluster) +{ + return disk->pread(disk, + buffer, + 1 << (exfat_header->block_per_clus_bits + exfat_header->blocksize_bits), + partition->part_offset + exfat_cluster_to_offset(exfat_header, cluster)); +} + +static void set_exFAT_info(partition_t *partition, const struct exfat_super_block*exfat_header) +{ + partition->upart_type=UP_EXFAT; + partition->blocksize=1<<(exfat_header->block_per_clus_bits + exfat_header->blocksize_bits); + partition->fsname[0]='\0'; + if(partition->sb_offset==0) + snprintf(partition->info, sizeof(partition->info), "exFAT, blocksize=%u", partition->blocksize); + else + snprintf(partition->info, sizeof(partition->info), "exFAT found using backup sector, blocksize=%u", partition->blocksize); +} + +int check_exFAT(disk_t *disk, partition_t *partition) +{ + unsigned char *buffer=(unsigned char*)MALLOC(EXFAT_BS_SIZE); + if(disk->pread(disk, buffer, EXFAT_BS_SIZE, partition->part_offset) != EXFAT_BS_SIZE) + { + free(buffer); + return 1; + } + if(test_exFAT((struct exfat_super_block*)buffer)!=0) + { + free(buffer); + return 1; + } + set_exFAT_info(partition, (struct exfat_super_block*)buffer); + free(buffer); + return 0; +} + +int test_exFAT(const struct exfat_super_block *exfat_header) +{ + if(le16(exfat_header->signature)!=0xAA55) + return 1; + if(memcmp(exfat_header->oem_id, "EXFAT ", sizeof(exfat_header->oem_id))!=0) + return 1; + return 0; +} + +int recover_exFAT(const disk_t *disk, const struct exfat_super_block *exfat_header, partition_t *partition) +{ + if(test_exFAT(exfat_header)!=0) + return 1; + partition->sborg_offset=0; + partition->sb_size=12 << exfat_header->blocksize_bits; + partition->part_type_i386=P_EXFAT; + partition->part_type_gpt=GPT_ENT_TYPE_MS_BASIC_DATA; + partition->part_size=(uint64_t)le64(exfat_header->nr_sectors) * disk->sector_size; +#ifdef DEBUG_exFAT + log_info("recover_exFAT:\n"); + log_info("start_sector=%llu\n", (long long unsigned)le64(exfat_header->start_sector)); + log_info("blocksize=%u\n", (12<blocksize_bits)); + log_info("part_offset=%llu\n", partition->part_offset); +#endif + if((le64(exfat_header->start_sector) * disk ->sector_size + + (12 << exfat_header->blocksize_bits) == partition->part_offset) || + (disk->arch==&arch_none && ((uint64_t)12 << exfat_header->blocksize_bits) == partition->part_offset)) + { + partition->sb_offset=12 << exfat_header->blocksize_bits; + partition->part_offset-=partition->sb_offset; + } + set_exFAT_info(partition, exfat_header); + return 0; +} diff --git a/pool/shard010/C/0139085_dmx_error.c b/pool/shard010/C/0139085_dmx_error.c new file mode 100644 index 0000000000000000000000000000000000000000..b4997449ab51faef63fcd5074dc041e59ede5bcc --- /dev/null +++ b/pool/shard010/C/0139085_dmx_error.c @@ -0,0 +1,52 @@ +/* +$Id$ + + + DVBSNOOP + + a dvb sniffer and mpeg2 stream analyzer tool + http://dvbsnoop.sourceforge.net/ + + (c) 2001-2006 Rainer.Scherg@gmx.de (rasc) + + + -- simple error output for DMX & file I/O + +*/ + + +#include +#include +#include + + + +int IO_error (char *str) +{ + char *s; + int err; + + + s = (str) ? str : ""; + err = errno; + + switch (err) { + + case EOVERFLOW: + fprintf (stderr, + "Error(%d): %s: Buffer overflow, stream bandwidth to high\n", + err,s); + break; + + default: + fprintf (stderr,"Error(%d): ",err); + perror(s); + break; + + } + + return err; + +} + + diff --git a/pool/shard010/C/0139086_submission_72.c b/pool/shard010/C/0139086_submission_72.c new file mode 100644 index 0000000000000000000000000000000000000000..9a0bf1c7bb094354e68c295e4350454055fafce5 --- /dev/null +++ b/pool/shard010/C/0139086_submission_72.c @@ -0,0 +1,24 @@ + #include + int main() + { + int t,i,u[99],p=0; + char s[99]; + scanf("%d",&t); + for(i=0;i= 43) + { + continue; + } + else + p++; + } + if(p==0) + printf("YES"); + else + printf("NO"); + return 0; + } \ No newline at end of file diff --git a/pool/shard010/C/0139087_setup.c b/pool/shard010/C/0139087_setup.c new file mode 100644 index 0000000000000000000000000000000000000000..2734efc71a50cd0b98007300209c47bf55c05689 --- /dev/null +++ b/pool/shard010/C/0139087_setup.c @@ -0,0 +1,117 @@ +/* + * linux/arch/m32r/platforms/oaks32r/setup.c + * + * Setup routines for OAKS32R Board + * + * Copyright (c) 2002-2005 Hiroyuki Kondo, Hirokazu Takata, + * Hitoshi Yamamoto, Mamoru Sakugawa + */ + +#include +#include +#include + +#include +#include + +#define irq2port(x) (M32R_ICU_CR1_PORTL + ((x - 1) * sizeof(unsigned long))) + +icu_data_t icu_data[NR_IRQS]; + +static void disable_oaks32r_irq(unsigned int irq) +{ + unsigned long port, data; + + port = irq2port(irq); + data = icu_data[irq].icucr | M32R_ICUCR_ILEVEL7; + outl(data, port); +} + +static void enable_oaks32r_irq(unsigned int irq) +{ + unsigned long port, data; + + port = irq2port(irq); + data = icu_data[irq].icucr | M32R_ICUCR_IEN | M32R_ICUCR_ILEVEL6; + outl(data, port); +} + +static void mask_oaks32r(struct irq_data *data) +{ + disable_oaks32r_irq(data->irq); +} + +static void unmask_oaks32r(struct irq_data *data) +{ + enable_oaks32r_irq(data->irq); +} + +static void shutdown_oaks32r(struct irq_data *data) +{ + unsigned long port; + + port = irq2port(data->irq); + outl(M32R_ICUCR_ILEVEL7, port); +} + +static struct irq_chip oaks32r_irq_type = +{ + .name = "OAKS32R-IRQ", + .irq_shutdown = shutdown_oaks32r, + .irq_mask = mask_oaks32r, + .irq_unmask = unmask_oaks32r, +}; + +void __init init_IRQ(void) +{ + static int once = 0; + + if (once) + { + return; + } + else + { + once++; + } + +#ifdef CONFIG_NE2000 + /* INT3 : LAN controller (RTL8019AS) */ + irq_set_chip_and_handler(M32R_IRQ_INT3, &oaks32r_irq_type, + handle_level_irq); + icu_data[M32R_IRQ_INT3].icucr = M32R_ICUCR_IEN | M32R_ICUCR_ISMOD10; + disable_oaks32r_irq(M32R_IRQ_INT3); +#endif /* CONFIG_M32R_NE2000 */ + + /* MFT2 : system timer */ + irq_set_chip_and_handler(M32R_IRQ_MFT2, &oaks32r_irq_type, + handle_level_irq); + icu_data[M32R_IRQ_MFT2].icucr = M32R_ICUCR_IEN; + disable_oaks32r_irq(M32R_IRQ_MFT2); + +#ifdef CONFIG_SERIAL_M32R_SIO + /* SIO0_R : uart receive data */ + irq_set_chip_and_handler(M32R_IRQ_SIO0_R, &oaks32r_irq_type, + handle_level_irq); + icu_data[M32R_IRQ_SIO0_R].icucr = 0; + disable_oaks32r_irq(M32R_IRQ_SIO0_R); + + /* SIO0_S : uart send data */ + irq_set_chip_and_handler(M32R_IRQ_SIO0_S, &oaks32r_irq_type, + handle_level_irq); + icu_data[M32R_IRQ_SIO0_S].icucr = 0; + disable_oaks32r_irq(M32R_IRQ_SIO0_S); + + /* SIO1_R : uart receive data */ + irq_set_chip_and_handler(M32R_IRQ_SIO1_R, &oaks32r_irq_type, + handle_level_irq); + icu_data[M32R_IRQ_SIO1_R].icucr = 0; + disable_oaks32r_irq(M32R_IRQ_SIO1_R); + + /* SIO1_S : uart send data */ + irq_set_chip_and_handler(M32R_IRQ_SIO1_S, &oaks32r_irq_type, + handle_level_irq); + icu_data[M32R_IRQ_SIO1_S].icucr = 0; + disable_oaks32r_irq(M32R_IRQ_SIO1_S); +#endif /* CONFIG_SERIAL_M32R_SIO */ +} diff --git a/pool/shard010/C/0139088_futex_compat.c b/pool/shard010/C/0139088_futex_compat.c new file mode 100644 index 0000000000000000000000000000000000000000..3888617a1f9ef986a93db05975d33d88370196c1 --- /dev/null +++ b/pool/shard010/C/0139088_futex_compat.c @@ -0,0 +1,201 @@ +/* + * linux/kernel/futex_compat.c + * + * Futex compatibililty routines. + * + * Copyright 2006, Red Hat, Inc., Ingo Molnar + */ + +#include +#include +#include +#include +#include +#include + +#include + + +/* + * Fetch a robust-list pointer. Bit 0 signals PI futexes: + */ +static inline int +fetch_robust_entry(compat_uptr_t *uentry, struct robust_list __user **entry, + compat_uptr_t __user *head, unsigned int *pi) +{ + if (get_user(*uentry, head)) + return -EFAULT; + + *entry = compat_ptr((*uentry) & ~1); + *pi = (unsigned int)(*uentry) & 1; + + return 0; +} + +static void __user *futex_uaddr(struct robust_list __user *entry, + compat_long_t futex_offset) +{ + compat_uptr_t base = ptr_to_compat(entry); + void __user *uaddr = compat_ptr(base + futex_offset); + + return uaddr; +} + +/* + * Walk curr->robust_list (very carefully, it's a userspace list!) + * and mark any locks found there dead, and notify any waiters. + * + * We silently return on any sign of list-walking problem. + */ +void compat_exit_robust_list(struct task_struct *curr) +{ + struct compat_robust_list_head __user *head = curr->compat_robust_list; + struct robust_list __user *entry, *next_entry, *pending; + unsigned int limit = ROBUST_LIST_LIMIT, pi, pip; + unsigned int uninitialized_var(next_pi); + compat_uptr_t uentry, next_uentry, upending; + compat_long_t futex_offset; + int rc; + + if (!futex_cmpxchg_enabled) + return; + + /* + * Fetch the list head (which was registered earlier, via + * sys_set_robust_list()): + */ + if (fetch_robust_entry(&uentry, &entry, &head->list.next, &pi)) + return; + /* + * Fetch the relative futex offset: + */ + if (get_user(futex_offset, &head->futex_offset)) + return; + /* + * Fetch any possibly pending lock-add first, and handle it + * if it exists: + */ + if (fetch_robust_entry(&upending, &pending, + &head->list_op_pending, &pip)) + return; + + next_entry = NULL; /* avoid warning with gcc */ + while (entry != (struct robust_list __user *) &head->list) { + /* + * Fetch the next entry in the list before calling + * handle_futex_death: + */ + rc = fetch_robust_entry(&next_uentry, &next_entry, + (compat_uptr_t __user *)&entry->next, &next_pi); + /* + * A pending lock might already be on the list, so + * dont process it twice: + */ + if (entry != pending) { + void __user *uaddr = futex_uaddr(entry, futex_offset); + + if (handle_futex_death(uaddr, curr, pi)) + return; + } + if (rc) + return; + uentry = next_uentry; + entry = next_entry; + pi = next_pi; + /* + * Avoid excessively long or circular lists: + */ + if (!--limit) + break; + + cond_resched(); + } + if (pending) { + void __user *uaddr = futex_uaddr(pending, futex_offset); + + handle_futex_death(uaddr, curr, pip); + } +} + +COMPAT_SYSCALL_DEFINE2(set_robust_list, + struct compat_robust_list_head __user *, head, + compat_size_t, len) +{ + if (!futex_cmpxchg_enabled) + return -ENOSYS; + + if (unlikely(len != sizeof(*head))) + return -EINVAL; + + current->compat_robust_list = head; + + return 0; +} + +COMPAT_SYSCALL_DEFINE3(get_robust_list, int, pid, + compat_uptr_t __user *, head_ptr, + compat_size_t __user *, len_ptr) +{ + struct compat_robust_list_head __user *head; + unsigned long ret; + struct task_struct *p; + + if (!futex_cmpxchg_enabled) + return -ENOSYS; + + rcu_read_lock(); + + ret = -ESRCH; + if (!pid) + p = current; + else { + p = find_task_by_vpid(pid); + if (!p) + goto err_unlock; + } + + ret = -EPERM; + if (!ptrace_may_access(p, PTRACE_MODE_READ_REALCREDS)) + goto err_unlock; + + head = p->compat_robust_list; + rcu_read_unlock(); + + if (put_user(sizeof(*head), len_ptr)) + return -EFAULT; + return put_user(ptr_to_compat(head), head_ptr); + +err_unlock: + rcu_read_unlock(); + + return ret; +} + +COMPAT_SYSCALL_DEFINE6(futex, u32 __user *, uaddr, int, op, u32, val, + struct compat_timespec __user *, utime, u32 __user *, uaddr2, + u32, val3) +{ + struct timespec ts; + ktime_t t, *tp = NULL; + int val2 = 0; + int cmd = op & FUTEX_CMD_MASK; + + if (utime && (cmd == FUTEX_WAIT || cmd == FUTEX_LOCK_PI || + cmd == FUTEX_WAIT_BITSET || + cmd == FUTEX_WAIT_REQUEUE_PI)) { + if (get_compat_timespec(&ts, utime)) + return -EFAULT; + if (!timespec_valid(&ts)) + return -EINVAL; + + t = timespec_to_ktime(ts); + if (cmd == FUTEX_WAIT) + t = ktime_add_safe(ktime_get(), t); + tp = &t; + } + if (cmd == FUTEX_REQUEUE || cmd == FUTEX_CMP_REQUEUE || + cmd == FUTEX_CMP_REQUEUE_PI || cmd == FUTEX_WAKE_OP) + val2 = (int) (unsigned long) utime; + + return do_futex(uaddr, op, val, tp, uaddr2, val2, val3); +} diff --git a/pool/shard010/C/0139089_stacktrace.c b/pool/shard010/C/0139089_stacktrace.c new file mode 100644 index 0000000000000000000000000000000000000000..bcbc4e2ad4b1c14d3493a812f25bc39a8b00cfe2 --- /dev/null +++ b/pool/shard010/C/0139089_stacktrace.c @@ -0,0 +1,115 @@ +/* + * linux/arch/unicore32/kernel/stacktrace.c + * + * Code specific to PKUnity SoC and UniCore ISA + * + * Copyright (C) 2001-2010 GUAN Xue-tao + * + * 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 + +#if defined(CONFIG_FRAME_POINTER) +int notrace unwind_frame(struct stackframe *frame) +{ + unsigned long high, low; + unsigned long fp = frame->fp; + + + low = frame->sp; + high = ALIGN(low, THREAD_SIZE); + + + if (fp < (low + 12) || fp + 4 >= high) + return -EINVAL; + + + frame->fp = *(unsigned long *)(fp - 12); + frame->sp = *(unsigned long *)(fp - 8); + frame->pc = *(unsigned long *)(fp - 4); + + return 0; +} +#endif + +void notrace walk_stackframe(struct stackframe *frame, + int (*fn)(struct stackframe *, void *), void *data) +{ + while (1) { + int ret; + + if (fn(frame, data)) + break; + ret = unwind_frame(frame); + if (ret < 0) + break; + } +} +EXPORT_SYMBOL(walk_stackframe); + +#ifdef CONFIG_STACKTRACE +struct stack_trace_data { + struct stack_trace *trace; + unsigned int no_sched_functions; + unsigned int skip; +}; + +static int save_trace(struct stackframe *frame, void *d) +{ + struct stack_trace_data *data = d; + struct stack_trace *trace = data->trace; + unsigned long addr = frame->pc; + + if (data->no_sched_functions && in_sched_functions(addr)) + return 0; + if (data->skip) { + data->skip--; + return 0; + } + + trace->entries[trace->nr_entries++] = addr; + + return trace->nr_entries >= trace->max_entries; +} + +void save_stack_trace_tsk(struct task_struct *tsk, struct stack_trace *trace) +{ + struct stack_trace_data data; + struct stackframe frame; + + data.trace = trace; + data.skip = trace->skip; + + if (tsk != current) { + data.no_sched_functions = 1; + frame.fp = thread_saved_fp(tsk); + frame.sp = thread_saved_sp(tsk); + frame.lr = 0; + frame.pc = thread_saved_pc(tsk); + } else { + register unsigned long current_sp asm("sp"); + + data.no_sched_functions = 0; + frame.fp = (unsigned long)__builtin_frame_address(0); + frame.sp = current_sp; + frame.lr = (unsigned long)__builtin_return_address(0); + frame.pc = (unsigned long)save_stack_trace_tsk; + } + + walk_stackframe(&frame, save_trace, &data); + if (trace->nr_entries < trace->max_entries) + trace->entries[trace->nr_entries++] = ULONG_MAX; +} + +void save_stack_trace(struct stack_trace *trace) +{ + save_stack_trace_tsk(current, trace); +} +EXPORT_SYMBOL_GPL(save_stack_trace); +#endif diff --git a/pool/shard010/C/0139090_signalfd.c b/pool/shard010/C/0139090_signalfd.c new file mode 100644 index 0000000000000000000000000000000000000000..2f5db5879429e4aee276dca5b4027c786fcb3141 --- /dev/null +++ b/pool/shard010/C/0139090_signalfd.c @@ -0,0 +1,122 @@ +#include +#include +#include + +#include "common/compiler.h" +#include "signalfd.h" +#include "fdinfo.h" +#include "imgset.h" +#include "image.h" +#include "util.h" +#include "log.h" +#include "files.h" + +#include "protobuf.h" +#include "images/signalfd.pb-c.h" + +struct signalfd_info { + SignalfdEntry *sfe; + struct file_desc d; +}; + +int is_signalfd_link(char *link) +{ + return is_anon_link_type(link, "[signalfd]"); +} + +struct signalfd_dump_arg { + u32 id; + const struct fd_parms *p; + bool dumped; +}; + +static int dump_signalfd_entry(union fdinfo_entries *e, void *arg) +{ + struct signalfd_dump_arg *da = arg; + + if (da->dumped) { + pr_err("Several counters in a file?\n"); + return -1; + } + + da->dumped = true; + e->sfd.id = da->id; + e->sfd.flags = da->p->flags; + e->sfd.fown = (FownEntry *)&da->p->fown; + + return pb_write_one(img_from_set(glob_imgset, CR_FD_SIGNALFD), + &e->sfd, PB_SIGNALFD); +} + +static int dump_one_signalfd(int lfd, u32 id, const struct fd_parms *p) +{ + struct signalfd_dump_arg da = { .id = id, .p = p, }; + return parse_fdinfo(lfd, FD_TYPES__SIGNALFD, dump_signalfd_entry, &da); +} + +const struct fdtype_ops signalfd_dump_ops = { + .type = FD_TYPES__SIGNALFD, + .dump = dump_one_signalfd, +}; + +static void sigset_fill(sigset_t *to, unsigned long long from) +{ + int sig; + + pr_info("\tCalculating sigmask for %Lx\n", from); + sigemptyset(to); + for (sig = 1; sig < NSIG; sig++) + if (from & (1ULL << (sig - 1))) { + pr_debug("\t\tAdd %d signal to mask\n", sig); + sigaddset(to, sig); + } +} + +static int signalfd_open(struct file_desc *d) +{ + struct signalfd_info *info; + int tmp; + sigset_t mask; + + info = container_of(d, struct signalfd_info, d); + pr_info("Restoring signalfd %#x\n", info->sfe->id); + + sigset_fill(&mask, info->sfe->sigmask); + tmp = signalfd(-1, &mask, 0); + if (tmp < 0) { + pr_perror("Can't create signalfd %#08x", info->sfe->id); + return -1; + } + + if (rst_file_params(tmp, info->sfe->fown, info->sfe->flags)) { + pr_perror("Can't restore params on signalfd %#08x", + info->sfe->id); + goto err_close; + } + + return tmp; + +err_close: + close(tmp); + return -1; +} + +static struct file_desc_ops signalfd_desc_ops = { + .type = FD_TYPES__SIGNALFD, + .open = signalfd_open, +}; + +static int collect_one_sigfd(void *o, ProtobufCMessage *msg, struct cr_img *i) +{ + struct signalfd_info *info = o; + + info->sfe = pb_msg(msg, SignalfdEntry); + return file_desc_add(&info->d, info->sfe->id, &signalfd_desc_ops); +} + +struct collect_image_info signalfd_cinfo = { + .fd_type = CR_FD_SIGNALFD, + .pb_type = PB_SIGNALFD, + .priv_size = sizeof(struct signalfd_info), + .collect = collect_one_sigfd, +}; diff --git a/pool/shard010/C/0139091_senate_bus.c b/pool/shard010/C/0139091_senate_bus.c new file mode 100644 index 0000000000000000000000000000000000000000..622efa8e69c74bc12aed98a290b57e9e7a432ebc --- /dev/null +++ b/pool/shard010/C/0139091_senate_bus.c @@ -0,0 +1,76 @@ +#include +#include +#include +#include +#include + +#define MAX_RIDERS 100 + +pthread_mutex_t mutex; +sem_t riders_waiting; //multiplex +sem_t bus_arrival; //bus +sem_t bus_depart; //all_aboard +int waiting = 0; + + +/*void board(){ + sem_wait(&riders_waiting); + return; +}*/ + +void * rider(){ + while(1){ + sem_wait(&riders_waiting); + pthread_mutex_lock(&mutex); + waiting = waiting + 1; + printf("RIDERS: riders waiting = %d \n",waiting); + sleep(1); + pthread_mutex_unlock(&mutex); + sem_wait(&bus_arrival); + sem_post(&riders_waiting); + + //waiting--; + + printf("RIDER: bus is here. \n riders waiting: %d \n",waiting--); + sleep(1); + if(waiting ==0){ + sem_post(&bus_depart); + }else{ + sem_post(&bus_arrival); + } + } +} + +void * bus(){ + while(1){ + //sem_wait(&riders_waiting); + //printf("Bus arrived \t waiting: %d\n",waiting); + pthread_mutex_lock(&mutex); + if(waiting >0){ + sem_post(&bus_arrival); + sem_wait(&bus_depart); + } + printf("BUS: departing! \n riders waiting: %d \n",waiting); + pthread_mutex_unlock(&mutex); + sleep(1); + } +} + + +void main(int argc, char * argv[]){ + pthread_t riders [MAX_RIDERS]; + pthread_t b1; + pthread_mutex_init(&mutex,NULL); + sem_init(&riders_waiting,0,50); + sem_init(&bus_arrival,0,0); + sem_init(&bus_depart,0,0); + int t_id; + pthread_create(&b1,NULL,bus,NULL); + for(t_id=0; t_id< MAX_RIDERS ;t_id++){ + pthread_create(&riders[t_id],NULL,rider,NULL); + //sleep(1); + } + //pthread_create(&b1,NULL,bus,NULL); + //pthread_create(&t1,NULL,bus,(void*)&i); + pthread_join(b1,NULL); +} diff --git a/pool/shard010/C/0139092_dwarf.c b/pool/shard010/C/0139092_dwarf.c new file mode 100644 index 0000000000000000000000000000000000000000..afbb23bc0580f3c474738b233152def69667e286 --- /dev/null +++ b/pool/shard010/C/0139092_dwarf.c @@ -0,0 +1,83 @@ +/* dwarf.c + * Common DWARF parts + * + * Wireshark - Network traffic analyzer + * By Gerald Combs + * Copyright 1998 Gerald Combs + * + * 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 "config.h" + +#include + +#include "dwarf.h" + +gint +dissect_uleb128(tvbuff_t *tvb, gint offset, guint64 *value) +{ + guint start_offset = offset; + guint shift = 0; + guint8 byte; + + *value = 0; + + do { + byte = tvb_get_guint8(tvb, offset); + offset += 1; + + *value |= ((guint64)(byte & 0x7F) << shift); + shift += 7; + } while (byte & 0x80); + + return offset - start_offset; +} + +gint +dissect_leb128(tvbuff_t *tvb, gint offset, gint64 *value) +{ + guint start_offset = offset; + guint shift = 0; + guint8 byte; + + *value = 0; + + do { + byte = tvb_get_guint8(tvb, offset); + offset += 1; + + *value |= ((guint64)(byte & 0x7F) << shift); + shift += 7; + } while (byte & 0x80); + + if (shift < 64 && byte & 0x40) + *value |= - ((gint64)1 << shift); + + return offset - start_offset; +} + +/* + * Editor modelines - http://www.wireshark.org/tools/modelines.html + * + * Local variables: + * c-basic-offset: 4 + * tab-width: 8 + * indent-tabs-mode: nil + * End: + * + * vi: set shiftwidth=4 tabstop=8 expandtab: + * :indentSize=4:tabSize=8:noTabs=true: + */ diff --git a/pool/shard010/C/0139093_TestNOTQuery.c b/pool/shard010/C/0139093_TestNOTQuery.c new file mode 100644 index 0000000000000000000000000000000000000000..c81ec87edbe48eb54ef5e0795018b2fb3b06bf8c --- /dev/null +++ b/pool/shard010/C/0139093_TestNOTQuery.c @@ -0,0 +1,55 @@ +#define C_KINO_TESTNOTQUERY +#include "KinoSearch/Util/ToolSet.h" +#include + +#include "KinoSearch/Test.h" +#include "KinoSearch/Test/TestUtils.h" +#include "KinoSearch/Test/Search/TestNOTQuery.h" +#include "KinoSearch/Search/NOTQuery.h" +#include "KinoSearch/Search/LeafQuery.h" + +static void +test_Dump_Load_and_Equals(TestBatch *batch) +{ + Query *a_leaf = (Query*)TestUtils_make_leaf_query(NULL, "a"); + Query *b_leaf = (Query*)TestUtils_make_leaf_query(NULL, "b"); + NOTQuery *query = NOTQuery_new(a_leaf); + NOTQuery *kids_differ = NOTQuery_new(b_leaf); + NOTQuery *boost_differs = NOTQuery_new(a_leaf); + Obj *dump = (Obj*)NOTQuery_Dump(query); + NOTQuery *clone = (NOTQuery*)Obj_Load(dump, dump); + + TEST_FALSE(batch, NOTQuery_Equals(query, (Obj*)kids_differ), + "Different kids spoil Equals"); + TEST_TRUE(batch, NOTQuery_Equals(query, (Obj*)boost_differs), + "Equals with identical boosts"); + NOTQuery_Set_Boost(boost_differs, 1.5); + TEST_FALSE(batch, NOTQuery_Equals(query, (Obj*)boost_differs), + "Different boost spoils Equals"); + TEST_TRUE(batch, NOTQuery_Equals(query, (Obj*)clone), + "Dump => Load round trip"); + + DECREF(a_leaf); + DECREF(b_leaf); + DECREF(query); + DECREF(kids_differ); + DECREF(boost_differs); + DECREF(dump); + DECREF(clone); +} + +void +TestNOTQuery_run_tests() +{ + TestBatch *batch = TestBatch_new(4); + TestBatch_Plan(batch); + test_Dump_Load_and_Equals(batch); + DECREF(batch); +} + +/* Copyright 2005-2011 Marvin Humphrey + * + * This program is free software; you can redistribute it and/or modify + * under the same terms as Perl itself. + */ + diff --git a/pool/shard010/C/0139094_vocabularylist.c b/pool/shard010/C/0139094_vocabularylist.c new file mode 100644 index 0000000000000000000000000000000000000000..c7eb3dc6054a65255f7da68432b227d5451d3238 --- /dev/null +++ b/pool/shard010/C/0139094_vocabularylist.c @@ -0,0 +1,171 @@ +#include + + +gchar** +lw_vocabularylist_get_lists () +{ + //Declarations + GDir *dir; + gchar **atoms; + gchar *buffer; + const gchar *name; + guint chars; + gchar *uri; + + //Initializations + chars = 0; + buffer = NULL; + atoms = NULL; + + if ((uri = lw_util_build_filename (LW_PATH_VOCABULARY, NULL)) != NULL) + { + if ((dir = g_dir_open (uri, 0, NULL)) != NULL) + { + //Get the size needed for the buffer + while ((name = g_dir_read_name (dir)) != NULL) + { + chars += strlen(name) + 1; + } + + if ((buffer = g_new0 (gchar, chars + 1)) != NULL) + { + g_dir_rewind (dir); + + //Set the buffer + while ((name = g_dir_read_name (dir)) != NULL) + { + strcat(buffer, name); + strcat(buffer, ";"); + } + buffer[strlen(buffer) - 1] = '\0'; + + //Split it + atoms = g_strsplit (buffer, ";", -1); + + g_free (buffer); buffer = NULL; + } + g_dir_close (dir); dir = NULL; + } + g_free (uri); uri = NULL; + } + + return atoms; +} + +LwVocabularyList* +lw_vocabularylist_new (const gchar *NAME) +{ + g_assert (NAME != NULL && strlen (NAME) > 0); + + LwVocabularyList *list; + + list = g_new0 (LwVocabularyList, 1); + if (list != NULL) + { + list->name = g_strdup (NAME); + } + return list; +} + + +void +lw_vocabularylist_free (LwVocabularyList *list) +{ + if (list->name != NULL) g_free (list->name); + g_list_foreach (list->items, (GFunc) lw_vocabularyitem_free, NULL); + g_list_free (list->items); list->items = NULL; +} + + +void +lw_vocabularylist_load (LwVocabularyList *list, LwIoProgressCallback cb) +{ + LwVocabularyItem *item; + gchar *uri; + FILE *stream; + const gint MAX = 200; + gchar buffer[MAX + 1]; + + uri = lw_util_build_filename (LW_PATH_VOCABULARY, list->name); + stream = fopen (uri, "r"); + buffer[MAX] = '\0'; + + while (stream != NULL && feof(stream) == 0) + { + if (fgets (buffer, MAX, stream) != NULL) + { + item = lw_vocabularyitem_new_from_string (buffer); + if (item != NULL) + { + list->items = g_list_append (list->items, item); + } + } + } +} + +void +lw_vocabularylist_save (LwVocabularyList *list, LwIoProgressCallback cb) +{ + //Declarations + LwVocabularyItem *item; + GList *iter; + gint i; + gchar *uri; + FILE *stream; + + uri = lw_util_build_filename (LW_PATH_VOCABULARY, list->name); + stream = fopen (uri, "w"); + + for (iter = list->items; iter != NULL; iter = iter->next) + { + item = LW_VOCABULARYITEM (iter->data); + if (item != NULL) + { + for (i = 0; i < TOTAL_LW_VOCABULARYITEM_FIELDS - 1 && feof (stream) == 0; i++) + { + if (item->fields[i] != NULL) + { + fputs(item->fields[i], stream); + fputc(';', stream); + } + } + if (item->fields[i] != NULL) fputs(item->fields[i], stream); + fputc('\n', stream); + } + } + + fclose(stream); + g_free (uri); +} + +void +lw_vocabularylist_set_name (LwVocabularyList *list, const gchar *name) +{ + if (list->name != NULL) + g_free (list->name); + list->name = g_strdup (name); +} + +const gchar* +lw_vocabularylist_get_name (LwVocabularyList *list) +{ + return list->name; +} + +GList * +lw_vocabularylist_get_items (LwVocabularyList *list) +{ + return list->items; +} + +void +lw_vocabularylist_set_changed (LwVocabularyList *list, gboolean changed) +{ + list->changed = changed; +} + +gboolean +lw_vocabularylist_changed (LwVocabularyList *list) +{ + return list->changed; +} diff --git a/pool/shard010/C/0139095_ftruncate.c b/pool/shard010/C/0139095_ftruncate.c new file mode 100644 index 0000000000000000000000000000000000000000..39b4bda3dca748a514317ff6cc27073068f35ff0 --- /dev/null +++ b/pool/shard010/C/0139095_ftruncate.c @@ -0,0 +1,92 @@ +/* -*- buffer-read-only: t -*- vi: set ro: */ +/* DO NOT EDIT! GENERATED AUTOMATICALLY! */ +/* ftruncate emulations that work on some System V's. + This file is in the public domain. */ + +#include + +/* Specification. */ +#include + +#include +#include + +#ifdef F_CHSIZE + +int +ftruncate (int fd, off_t length) +{ + return fcntl (fd, F_CHSIZE, length); +} + +#else /* not F_CHSIZE */ +# ifdef F_FREESP + +/* By William Kucharski . */ + +# include +# include + +int +ftruncate (int fd, off_t length) +{ + struct flock fl; + struct stat filebuf; + + if (fstat (fd, &filebuf) < 0) + return -1; + + if (filebuf.st_size < length) + { + /* Extend file length. */ + if (lseek (fd, (length - 1), SEEK_SET) < 0) + return -1; + + /* Write a "0" byte. */ + if (write (fd, "", 1) != 1) + return -1; + } + else + { + + /* Truncate length. */ + + fl.l_whence = 0; + fl.l_len = 0; + fl.l_start = length; + fl.l_type = F_WRLCK; /* write lock on file space */ + + /* This relies on the *undocumented* F_FREESP argument to fcntl, + which truncates the file so that it ends at the position + indicated by fl.l_start. Will minor miracles never cease? */ + + if (fcntl (fd, F_FREESP, &fl) < 0) + return -1; + } + + return 0; +} + +# else /* not F_CHSIZE nor F_FREESP */ +# if HAVE_CHSIZE /* native Windows, e.g. mingw */ + +int +ftruncate (int fd, off_t length) +{ + return chsize (fd, length); +} + +# else /* not F_CHSIZE nor F_FREESP nor HAVE_CHSIZE */ + +# include + +int +ftruncate (int fd, off_t length) +{ + errno = EIO; + return -1; +} + +# endif /* not HAVE_CHSIZE */ +# endif /* not F_FREESP */ +#endif /* not F_CHSIZE */ diff --git a/pool/shard010/C/0139096_spl.c b/pool/shard010/C/0139096_spl.c new file mode 100644 index 0000000000000000000000000000000000000000..0e08f50e7618a7c310fd0eaf47fb89b133c5f20d --- /dev/null +++ b/pool/shard010/C/0139096_spl.c @@ -0,0 +1,230 @@ +/* + * (C) Copyright 2010 + * Texas Instruments, + * + * Aneesh V + * + * SPDX-License-Identifier: GPL-2.0+ + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +DECLARE_GLOBAL_DATA_PTR; + +#ifndef CONFIG_SYS_UBOOT_START +#define CONFIG_SYS_UBOOT_START CONFIG_SYS_TEXT_BASE +#endif +#ifndef CONFIG_SYS_MONITOR_LEN +#define CONFIG_SYS_MONITOR_LEN (200 * 1024) +#endif + +u32 *boot_params_ptr = NULL; +struct spl_image_info spl_image; + +/* Define board data structure */ +static bd_t bdata __attribute__ ((section(".data"))); + +/* + * Default function to determine if u-boot or the OS should + * be started. This implementation always returns 1. + * + * Please implement your own board specific funcion to do this. + * + * RETURN + * 0 to not start u-boot + * positive if u-boot should start + */ +#ifdef CONFIG_SPL_OS_BOOT +__weak int spl_start_uboot(void) +{ + puts("SPL: Please implement spl_start_uboot() for your board\n"); + puts("SPL: Direct Linux boot not active!\n"); + return 1; +} +#endif + +/* + * Weak default function for board specific cleanup/preparation before + * Linux boot. Some boards/platforms might not need it, so just provide + * an empty stub here. + */ +__weak void spl_board_prepare_for_linux(void) +{ + /* Nothing to do! */ +} + +void spl_parse_image_header(const struct image_header *header) +{ + u32 header_size = sizeof(struct image_header); + + if (image_get_magic(header) == IH_MAGIC) { + if (spl_image.flags & SPL_COPY_PAYLOAD_ONLY) { + /* + * On some system (e.g. powerpc), the load-address and + * entry-point is located at address 0. We can't load + * to 0-0x40. So skip header in this case. + */ + spl_image.load_addr = image_get_load(header); + spl_image.entry_point = image_get_ep(header); + spl_image.size = image_get_data_size(header); + } else { + spl_image.entry_point = image_get_load(header); + /* Load including the header */ + spl_image.load_addr = spl_image.entry_point - + header_size; + spl_image.size = image_get_data_size(header) + + header_size; + } + spl_image.os = image_get_os(header); + spl_image.name = image_get_name(header); + debug("spl: payload image: %.*s load addr: 0x%x size: %d\n", + (int)sizeof(spl_image.name), spl_image.name, + spl_image.load_addr, spl_image.size); + } else { + /* Signature not found - assume u-boot.bin */ + debug("mkimage signature not found - ih_magic = %x\n", + header->ih_magic); + /* Let's assume U-Boot will not be more than 200 KB */ + spl_image.size = CONFIG_SYS_MONITOR_LEN; + spl_image.entry_point = CONFIG_SYS_UBOOT_START; + spl_image.load_addr = CONFIG_SYS_TEXT_BASE; + spl_image.os = IH_OS_U_BOOT; + spl_image.name = "U-Boot"; + } +} + +__weak void __noreturn jump_to_image_no_args(struct spl_image_info *spl_image) +{ + typedef void __noreturn (*image_entry_noargs_t)(void); + + image_entry_noargs_t image_entry = + (image_entry_noargs_t) spl_image->entry_point; + + debug("image entry point: 0x%X\n", spl_image->entry_point); + image_entry(); +} + +#ifdef CONFIG_SPL_RAM_DEVICE +static void spl_ram_load_image(void) +{ + const struct image_header *header; + + /* + * Get the header. It will point to an address defined by handoff + * which will tell where the image located inside the flash. For + * now, it will temporary fixed to address pointed by U-Boot. + */ + header = (struct image_header *) + (CONFIG_SYS_TEXT_BASE - sizeof(struct image_header)); + + spl_parse_image_header(header); +} +#endif + +void board_init_r(gd_t *dummy1, ulong dummy2) +{ + u32 boot_device; + debug(">>spl:board_init_r()\n"); + +#ifdef CONFIG_SYS_SPL_MALLOC_START + mem_malloc_init(CONFIG_SYS_SPL_MALLOC_START, + CONFIG_SYS_SPL_MALLOC_SIZE); +#endif + + /* + * timer_init() does not exist on PPC systems. The timer is initialized + * and enabled (decrementer) in interrupt_init() here. + */ + timer_init(); + +#ifdef CONFIG_SPL_BOARD_INIT + spl_board_init(); +#endif + + boot_device = spl_boot_device(); + debug("boot device - %d\n", boot_device); + switch (boot_device) { +#ifdef CONFIG_SPL_MMC_SUPPORT + case BOOT_DEVICE_MMC1: + case BOOT_DEVICE_MMC2: + case BOOT_DEVICE_MMC2_2: + spl_mmc_load_image(); + break; +#endif +#ifdef CONFIG_SPL_YMODEM_SUPPORT + case BOOT_DEVICE_UART: + spl_ymodem_load_image(); + break; +#endif +#ifdef CONFIG_SPL_ETH_SUPPORT + case BOOT_DEVICE_CPGMAC: +#ifdef CONFIG_SPL_ETH_DEVICE + spl_net_load_image(CONFIG_SPL_ETH_DEVICE); +#else + spl_net_load_image(NULL); +#endif + break; +#endif +#ifdef CONFIG_SPL_USBETH_SUPPORT + case BOOT_DEVICE_USBETH: + spl_net_load_image("usb_ether"); + break; +#endif +#ifdef CONFIG_SPL_USB_SUPPORT + case BOOT_DEVICE_USB: + spl_usb_load_image(); + break; +#endif +#ifdef CONFIG_SPL_SATA_SUPPORT + case BOOT_DEVICE_SATA: + spl_sata_load_image(); + break; +#endif + default: + debug("SPL: Un-supported Boot Device\n"); + hang(); + } + + switch (spl_image.os) { + case IH_OS_U_BOOT: + debug("Jumping to U-Boot\n"); + break; +#ifdef CONFIG_SPL_OS_BOOT + case IH_OS_LINUX: + debug("Jumping to Linux\n"); + spl_board_prepare_for_linux(); + jump_to_image_linux((void *)CONFIG_SYS_SPL_ARGS_ADDR); +#endif + default: + debug("Unsupported OS image.. Jumping nevertheless..\n"); + } + jump_to_image_no_args(&spl_image); +} + +/* + * This requires UART clocks to be enabled. In order for this to work the + * caller must ensure that the gd pointer is valid. + */ +void preloader_console_init(void) +{ + gd->bd = &bdata; + gd->baudrate = CONFIG_BAUDRATE; + + serial_init(); /* serial communications setup */ + + gd->have_console = 1; + + puts("\nU-Boot SPL " PLAIN_VERSION " (" U_BOOT_DATE " - " \ + U_BOOT_TIME ")\n"); +#ifdef CONFIG_SPL_DISPLAY_PRINT + spl_display_print(); +#endif +} diff --git a/pool/shard010/C/0139097_garbage.c b/pool/shard010/C/0139097_garbage.c new file mode 100644 index 0000000000000000000000000000000000000000..cb72e91f14892180987dc59b66e4c248359c70b0 --- /dev/null +++ b/pool/shard010/C/0139097_garbage.c @@ -0,0 +1,396 @@ +/* + * NET3: Garbage Collector For AF_UNIX sockets + * + * Garbage Collector: + * Copyright (C) Barak A. Pearlmutter. + * Released under the GPL version 2 or later. + * + * Chopped about by Alan Cox 22/3/96 to make it fit the AF_UNIX socket problem. + * If it doesn't work blame me, it worked when Barak sent it. + * + * Assumptions: + * + * - object w/ a bit + * - free list + * + * Current optimizations: + * + * - explicit stack instead of recursion + * - tail recurse on first born instead of immediate push/pop + * - we gather the stuff that should not be killed into tree + * and stack is just a path from root to the current pointer. + * + * Future optimizations: + * + * - don't just push entire root set; process in place + * + * 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. + * + * Fixes: + * Alan Cox 07 Sept 1997 Vmalloc internal stack as needed. + * Cope with changing max_files. + * Al Viro 11 Oct 1998 + * Graph may have cycles. That is, we can send the descriptor + * of foo to bar and vice versa. Current code chokes on that. + * Fix: move SCM_RIGHTS ones into the separate list and then + * skb_free() them all instead of doing explicit fput's. + * Another problem: since fput() may block somebody may + * create a new unix_socket when we are in the middle of sweep + * phase. Fix: revert the logic wrt MARKED. Mark everything + * upon the beginning and unmark non-junk ones. + * + * [12 Oct 1998] AAARGH! New code purges all SCM_RIGHTS + * sent to connect()'ed but still not accept()'ed sockets. + * Fixed. Old code had slightly different problem here: + * extra fput() in situation when we passed the descriptor via + * such socket and closed it (descriptor). That would happen on + * each unix_gc() until the accept(). Since the struct file in + * question would go to the free list and might be reused... + * That might be the reason of random oopses on filp_close() + * in unrelated processes. + * + * AV 28 Feb 1999 + * Kill the explicit allocation of stack. Now we keep the tree + * with root in dummy + pointer (gc_current) to one of the nodes. + * Stack is represented as path from gc_current to dummy. Unmark + * now means "add to tree". Push == "make it a son of gc_current". + * Pop == "move gc_current to parent". We keep only pointers to + * parents (->gc_tree). + * AV 1 Mar 1999 + * Damn. Added missing check for ->dead in listen queues scanning. + * + * Miklos Szeredi 25 Jun 2007 + * Reimplement with a cycle collecting algorithm. This should + * solve several problems with the previous code, like being racy + * wrt receive and holding up unrelated socket operations. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +/* Internal data structures and random procedures: */ + +static LIST_HEAD(gc_inflight_list); +static LIST_HEAD(gc_candidates); +static DEFINE_SPINLOCK(unix_gc_lock); +static DECLARE_WAIT_QUEUE_HEAD(unix_gc_wait); + +unsigned int unix_tot_inflight; + + +struct sock *unix_get_socket(struct file *filp) +{ + struct sock *u_sock = NULL; + struct inode *inode = filp->f_path.dentry->d_inode; + + /* + * Socket ? + */ + if (S_ISSOCK(inode->i_mode)) { + struct socket *sock = SOCKET_I(inode); + struct sock *s = sock->sk; + + /* + * PF_UNIX ? + */ + if (s && sock->ops && sock->ops->family == PF_UNIX) + u_sock = s; + } + return u_sock; +} + +/* + * Keep the number of times in flight count for the file + * descriptor if it is for an AF_UNIX socket. + */ + +void unix_inflight(struct file *fp) +{ + struct sock *s = unix_get_socket(fp); + if (s) { + struct unix_sock *u = unix_sk(s); + spin_lock(&unix_gc_lock); + if (atomic_long_inc_return(&u->inflight) == 1) { + BUG_ON(!list_empty(&u->link)); + list_add_tail(&u->link, &gc_inflight_list); + } else { + BUG_ON(list_empty(&u->link)); + } + unix_tot_inflight++; + spin_unlock(&unix_gc_lock); + } +} + +void unix_notinflight(struct file *fp) +{ + struct sock *s = unix_get_socket(fp); + if (s) { + struct unix_sock *u = unix_sk(s); + spin_lock(&unix_gc_lock); + BUG_ON(list_empty(&u->link)); + if (atomic_long_dec_and_test(&u->inflight)) + list_del_init(&u->link); + unix_tot_inflight--; + spin_unlock(&unix_gc_lock); + } +} + +static inline struct sk_buff *sock_queue_head(struct sock *sk) +{ + return (struct sk_buff *)&sk->sk_receive_queue; +} + +#define receive_queue_for_each_skb(sk, next, skb) \ + for (skb = sock_queue_head(sk)->next, next = skb->next; \ + skb != sock_queue_head(sk); skb = next, next = skb->next) + +static void scan_inflight(struct sock *x, void (*func)(struct unix_sock *), + struct sk_buff_head *hitlist) +{ + struct sk_buff *skb; + struct sk_buff *next; + + spin_lock(&x->sk_receive_queue.lock); + receive_queue_for_each_skb(x, next, skb) { + /* + * Do we have file descriptors ? + */ + if (UNIXCB(skb).fp) { + bool hit = false; + /* + * Process the descriptors of this socket + */ + int nfd = UNIXCB(skb).fp->count; + struct file **fp = UNIXCB(skb).fp->fp; + while (nfd--) { + /* + * Get the socket the fd matches + * if it indeed does so + */ + struct sock *sk = unix_get_socket(*fp++); + if (sk) { + struct unix_sock *u = unix_sk(sk); + + /* + * Ignore non-candidates, they could + * have been added to the queues after + * starting the garbage collection + */ + if (u->gc_candidate) { + hit = true; + func(u); + } + } + } + if (hit && hitlist != NULL) { + __skb_unlink(skb, &x->sk_receive_queue); + __skb_queue_tail(hitlist, skb); + } + } + } + spin_unlock(&x->sk_receive_queue.lock); +} + +static void scan_children(struct sock *x, void (*func)(struct unix_sock *), + struct sk_buff_head *hitlist) +{ + if (x->sk_state != TCP_LISTEN) + scan_inflight(x, func, hitlist); + else { + struct sk_buff *skb; + struct sk_buff *next; + struct unix_sock *u; + LIST_HEAD(embryos); + + /* + * For a listening socket collect the queued embryos + * and perform a scan on them as well. + */ + spin_lock(&x->sk_receive_queue.lock); + receive_queue_for_each_skb(x, next, skb) { + u = unix_sk(skb->sk); + + /* + * An embryo cannot be in-flight, so it's safe + * to use the list link. + */ + BUG_ON(!list_empty(&u->link)); + list_add_tail(&u->link, &embryos); + } + spin_unlock(&x->sk_receive_queue.lock); + + while (!list_empty(&embryos)) { + u = list_entry(embryos.next, struct unix_sock, link); + scan_inflight(&u->sk, func, hitlist); + list_del_init(&u->link); + } + } +} + +static void dec_inflight(struct unix_sock *usk) +{ + atomic_long_dec(&usk->inflight); +} + +static void inc_inflight(struct unix_sock *usk) +{ + atomic_long_inc(&usk->inflight); +} + +static void inc_inflight_move_tail(struct unix_sock *u) +{ + atomic_long_inc(&u->inflight); + /* + * If this still might be part of a cycle, move it to the end + * of the list, so that it's checked even if it was already + * passed over + */ + if (u->gc_maybe_cycle) + list_move_tail(&u->link, &gc_candidates); +} + +static bool gc_in_progress = false; +#define UNIX_INFLIGHT_TRIGGER_GC 16000 + +void wait_for_unix_gc(void) +{ + /* + * If number of inflight sockets is insane, + * force a garbage collect right now. + */ + if (unix_tot_inflight > UNIX_INFLIGHT_TRIGGER_GC && !gc_in_progress) + unix_gc(); + wait_event(unix_gc_wait, gc_in_progress == false); +} + +/* The external entry point: unix_gc() */ +void unix_gc(void) +{ + struct unix_sock *u; + struct unix_sock *next; + struct sk_buff_head hitlist; + struct list_head cursor; + LIST_HEAD(not_cycle_list); + + spin_lock(&unix_gc_lock); + + /* Avoid a recursive GC. */ + if (gc_in_progress) + goto out; + + gc_in_progress = true; + /* + * First, select candidates for garbage collection. Only + * in-flight sockets are considered, and from those only ones + * which don't have any external reference. + * + * Holding unix_gc_lock will protect these candidates from + * being detached, and hence from gaining an external + * reference. Since there are no possible receivers, all + * buffers currently on the candidates' queues stay there + * during the garbage collection. + * + * We also know that no new candidate can be added onto the + * receive queues. Other, non candidate sockets _can_ be + * added to queue, so we must make sure only to touch + * candidates. + */ + list_for_each_entry_safe(u, next, &gc_inflight_list, link) { + long total_refs; + long inflight_refs; + + total_refs = file_count(u->sk.sk_socket->file); + inflight_refs = atomic_long_read(&u->inflight); + + BUG_ON(inflight_refs < 1); + BUG_ON(total_refs < inflight_refs); + if (total_refs == inflight_refs) { + list_move_tail(&u->link, &gc_candidates); + u->gc_candidate = 1; + u->gc_maybe_cycle = 1; + } + } + + /* + * Now remove all internal in-flight reference to children of + * the candidates. + */ + list_for_each_entry(u, &gc_candidates, link) + scan_children(&u->sk, dec_inflight, NULL); + + /* + * Restore the references for children of all candidates, + * which have remaining references. Do this recursively, so + * only those remain, which form cyclic references. + * + * Use a "cursor" link, to make the list traversal safe, even + * though elements might be moved about. + */ + list_add(&cursor, &gc_candidates); + while (cursor.next != &gc_candidates) { + u = list_entry(cursor.next, struct unix_sock, link); + + /* Move cursor to after the current position. */ + list_move(&cursor, &u->link); + + if (atomic_long_read(&u->inflight) > 0) { + list_move_tail(&u->link, ¬_cycle_list); + u->gc_maybe_cycle = 0; + scan_children(&u->sk, inc_inflight_move_tail, NULL); + } + } + list_del(&cursor); + + /* + * not_cycle_list contains those sockets which do not make up a + * cycle. Restore these to the inflight list. + */ + while (!list_empty(¬_cycle_list)) { + u = list_entry(not_cycle_list.next, struct unix_sock, link); + u->gc_candidate = 0; + list_move_tail(&u->link, &gc_inflight_list); + } + + /* + * Now gc_candidates contains only garbage. Restore original + * inflight counters for these as well, and remove the skbuffs + * which are creating the cycle(s). + */ + skb_queue_head_init(&hitlist); + list_for_each_entry(u, &gc_candidates, link) + scan_children(&u->sk, inc_inflight, &hitlist); + + spin_unlock(&unix_gc_lock); + + /* Here we are. Hitlist is filled. Die. */ + __skb_queue_purge(&hitlist); + + spin_lock(&unix_gc_lock); + + /* All candidates should have been detached by now. */ + BUG_ON(!list_empty(&gc_candidates)); + gc_in_progress = false; + wake_up(&unix_gc_wait); + + out: + spin_unlock(&unix_gc_lock); +} diff --git a/pool/shard010/C/0139098_audio_test.c b/pool/shard010/C/0139098_audio_test.c new file mode 100644 index 0000000000000000000000000000000000000000..6a805b3ba707ff506c8936c5dd39c23fe683e795 --- /dev/null +++ b/pool/shard010/C/0139098_audio_test.c @@ -0,0 +1,132 @@ +/**************************************************************************//** +* +* @copyright (C) 2019 Nuvoton Technology Corp. All rights reserved. +* +* SPDX-License-Identifier: Apache-2.0 +* +* Change Logs: +* Date Author Notes +* 2020-1-16 Wayne First version +* +******************************************************************************/ + +#include + +#if defined(PKG_USING_WAVPLAYER) + +#include "wavrecorder.h" +#include "wavplayer.h" +#include +#include +#include +#include +#include + +/* + The routine just for test automatically. + - For record function: Run it w/o parameter. + - For replay function: Run it with parameter. +*/ +static int audio_test(int argc, char **argv) +{ +#define DEF_MAX_ARGV_NUM 8 +#define DEF_MAX_TEST_SECOND 5 + + int smplrate[] = {8000, 16000, 44100, 48000}; + int smplbit[] = {16}; + int chnum[] = {1, 2}; + struct wavrecord_info info; + char strbuf[128]; + int i, j, k; + int bDoRecording = 1; + struct stat stat_buf; + + if (argc > 1) + bDoRecording = 0; + + for (i = 0; i < sizeof(smplrate) / sizeof(int); i++) + { + for (j = 0; j < sizeof(smplbit) / sizeof(int); j++) + { + for (k = 0; k < sizeof(chnum) / sizeof(int); k++) + { + snprintf(strbuf, sizeof(strbuf), "/mnt/sd0/%d_%d_%d.wav", smplrate[i], smplbit[j], chnum[k]); + + if (bDoRecording) + { + rt_kprintf("Recording file at %s\n", strbuf); + info.uri = strbuf; + info.samplerate = smplrate[i]; + info.samplebits = smplbit[j]; + info.channels = chnum[k]; + wavrecorder_start(&info); + rt_thread_mdelay(DEF_MAX_TEST_SECOND * 1000); + wavrecorder_stop(); + rt_thread_mdelay(DEF_MAX_TEST_SECOND * 1000); + } + else + { + if (stat((const char *)strbuf, &stat_buf) < 0) + { + rt_kprintf("%s non-exist.\n", strbuf); + continue; + } + + rt_kprintf("Replay file at %s\n", strbuf); + wavplayer_play(strbuf); + rt_thread_mdelay(DEF_MAX_TEST_SECOND * 1000); + wavplayer_stop(); + } + } // k + } // j + } // i + + return 0; +} + +#ifdef FINSH_USING_MSH + MSH_CMD_EXPORT(audio_test, Audio record / replay); +#endif + + +static int audio_overnight(int argc, char **argv) +{ +#define DEF_MAX_TEST_SECOND 5 + + struct wavrecord_info info; + char strbuf[128]; + struct stat stat_buf; + + snprintf(strbuf, sizeof(strbuf), "/test.wav"); + while (1) + { + rt_kprintf("Recording file at %s\n", strbuf); + info.uri = strbuf; + info.samplerate = 16000; + info.samplebits = 16; + info.channels = 2; + wavrecorder_start(&info); + rt_thread_mdelay(DEF_MAX_TEST_SECOND * 1000); + wavrecorder_stop(); + rt_thread_mdelay(1000); + + if (stat((const char *)strbuf, &stat_buf) < 0) + { + rt_kprintf("%s non-exist.\n", strbuf); + break; + } + + rt_kprintf("Replay file at %s\n", strbuf); + wavplayer_play(strbuf); + rt_thread_mdelay(DEF_MAX_TEST_SECOND * 1000); + wavplayer_stop(); + rt_thread_mdelay(1000); + } + return 0; +} + +#ifdef FINSH_USING_MSH + MSH_CMD_EXPORT(audio_overnight, auto test record / replay); +#endif + +#endif /* PKG_USING_WAVPLAYER */ diff --git a/pool/shard010/C/0139099_c.c b/pool/shard010/C/0139099_c.c new file mode 100644 index 0000000000000000000000000000000000000000..4e735deca63d72922157b362d0862bf09579e684 --- /dev/null +++ b/pool/shard010/C/0139099_c.c @@ -0,0 +1,17 @@ +#include +#include +void main() +{ + double x1,x2,x3,a; + printf("please input your number:"); + scanf("%lf",&a); + x2=a; + while(fabs(x1-x2)>1.0e-20) + { + x1=x2; + x2=2/3.0*x1+a/(3.0*pow(x1,2.0)); + } + printf("%.10lf\n",x2); + x3=pow(a,1.0/3); + printf("%.10lf\n",x3); +} \ No newline at end of file diff --git a/pool/shard010/C/0139100_netprio_cgroup.c b/pool/shard010/C/0139100_netprio_cgroup.c new file mode 100644 index 0000000000000000000000000000000000000000..2f385b9bccc0f3beae1fc3c7166f60310358ef54 --- /dev/null +++ b/pool/shard010/C/0139100_netprio_cgroup.c @@ -0,0 +1,288 @@ +/* + * net/core/netprio_cgroup.c Priority Control Group + * + * 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. + * + * Authors: Neil Horman + */ + +#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#define PRIOMAP_MIN_SZ 128 + +/* + * Extend @dev->priomap so that it's large enough to accommodate + * @target_idx. @dev->priomap.priomap_len > @target_idx after successful + * return. Must be called under rtnl lock. + */ +static int extend_netdev_table(struct net_device *dev, u32 target_idx) +{ + struct netprio_map *old, *new; + size_t new_sz, new_len; + + /* is the existing priomap large enough? */ + old = rtnl_dereference(dev->priomap); + if (old && old->priomap_len > target_idx) + return 0; + + /* + * Determine the new size. Let's keep it power-of-two. We start + * from PRIOMAP_MIN_SZ and double it until it's large enough to + * accommodate @target_idx. + */ + new_sz = PRIOMAP_MIN_SZ; + while (true) { + new_len = (new_sz - offsetof(struct netprio_map, priomap)) / + sizeof(new->priomap[0]); + if (new_len > target_idx) + break; + new_sz *= 2; + /* overflowed? */ + if (WARN_ON(new_sz < PRIOMAP_MIN_SZ)) + return -ENOSPC; + } + + /* allocate & copy */ + new = kzalloc(new_sz, GFP_KERNEL); + if (!new) + return -ENOMEM; + + if (old) + memcpy(new->priomap, old->priomap, + old->priomap_len * sizeof(old->priomap[0])); + + new->priomap_len = new_len; + + /* install the new priomap */ + rcu_assign_pointer(dev->priomap, new); + if (old) + kfree_rcu(old, rcu); + return 0; +} + +/** + * netprio_prio - return the effective netprio of a cgroup-net_device pair + * @css: css part of the target pair + * @dev: net_device part of the target pair + * + * Should be called under RCU read or rtnl lock. + */ +static u32 netprio_prio(struct cgroup_subsys_state *css, struct net_device *dev) +{ + struct netprio_map *map = rcu_dereference_rtnl(dev->priomap); + int id = css->cgroup->id; + + if (map && id < map->priomap_len) + return map->priomap[id]; + return 0; +} + +/** + * netprio_set_prio - set netprio on a cgroup-net_device pair + * @css: css part of the target pair + * @dev: net_device part of the target pair + * @prio: prio to set + * + * Set netprio to @prio on @css-@dev pair. Should be called under rtnl + * lock and may fail under memory pressure for non-zero @prio. + */ +static int netprio_set_prio(struct cgroup_subsys_state *css, + struct net_device *dev, u32 prio) +{ + struct netprio_map *map; + int id = css->cgroup->id; + int ret; + + /* avoid extending priomap for zero writes */ + map = rtnl_dereference(dev->priomap); + if (!prio && (!map || map->priomap_len <= id)) + return 0; + + ret = extend_netdev_table(dev, id); + if (ret) + return ret; + + map = rtnl_dereference(dev->priomap); + map->priomap[id] = prio; + return 0; +} + +static struct cgroup_subsys_state * +cgrp_css_alloc(struct cgroup_subsys_state *parent_css) +{ + struct cgroup_subsys_state *css; + + css = kzalloc(sizeof(*css), GFP_KERNEL); + if (!css) + return ERR_PTR(-ENOMEM); + + return css; +} + +static int cgrp_css_online(struct cgroup_subsys_state *css) +{ + struct cgroup_subsys_state *parent_css = css->parent; + struct net_device *dev; + int ret = 0; + + if (!parent_css) + return 0; + + rtnl_lock(); + /* + * Inherit prios from the parent. As all prios are set during + * onlining, there is no need to clear them on offline. + */ + for_each_netdev(&init_net, dev) { + u32 prio = netprio_prio(parent_css, dev); + + ret = netprio_set_prio(css, dev, prio); + if (ret) + break; + } + rtnl_unlock(); + return ret; +} + +static void cgrp_css_free(struct cgroup_subsys_state *css) +{ + kfree(css); +} + +static u64 read_prioidx(struct cgroup_subsys_state *css, struct cftype *cft) +{ + return css->cgroup->id; +} + +static int read_priomap(struct seq_file *sf, void *v) +{ + struct net_device *dev; + + rcu_read_lock(); + for_each_netdev_rcu(&init_net, dev) + seq_printf(sf, "%s %u\n", dev->name, + netprio_prio(seq_css(sf), dev)); + rcu_read_unlock(); + return 0; +} + +static ssize_t write_priomap(struct kernfs_open_file *of, + char *buf, size_t nbytes, loff_t off) +{ + char devname[IFNAMSIZ + 1]; + struct net_device *dev; + u32 prio; + int ret; + + if (sscanf(buf, "%"__stringify(IFNAMSIZ)"s %u", devname, &prio) != 2) + return -EINVAL; + + dev = dev_get_by_name(&init_net, devname); + if (!dev) + return -ENODEV; + + rtnl_lock(); + + ret = netprio_set_prio(of_css(of), dev, prio); + + rtnl_unlock(); + dev_put(dev); + return ret ?: nbytes; +} + +static int update_netprio(const void *v, struct file *file, unsigned n) +{ + int err; + struct socket *sock = sock_from_file(file, &err); + if (sock) + sock->sk->sk_cgrp_prioidx = (u32)(unsigned long)v; + return 0; +} + +static void net_prio_attach(struct cgroup_subsys_state *css, + struct cgroup_taskset *tset) +{ + struct task_struct *p; + void *v = (void *)(unsigned long)css->cgroup->id; + + cgroup_taskset_for_each(p, tset) { + task_lock(p); + iterate_fd(p->files, 0, update_netprio, v); + task_unlock(p); + } +} + +static struct cftype ss_files[] = { + { + .name = "prioidx", + .read_u64 = read_prioidx, + }, + { + .name = "ifpriomap", + .seq_show = read_priomap, + .write = write_priomap, + }, + { } /* terminate */ +}; + +struct cgroup_subsys net_prio_cgrp_subsys = { + .css_alloc = cgrp_css_alloc, + .css_online = cgrp_css_online, + .css_free = cgrp_css_free, + .attach = net_prio_attach, + .base_cftypes = ss_files, +}; + +static int netprio_device_event(struct notifier_block *unused, + unsigned long event, void *ptr) +{ + struct net_device *dev = netdev_notifier_info_to_dev(ptr); + struct netprio_map *old; + + /* + * Note this is called with rtnl_lock held so we have update side + * protection on our rcu assignments + */ + + switch (event) { + case NETDEV_UNREGISTER: + old = rtnl_dereference(dev->priomap); + RCU_INIT_POINTER(dev->priomap, NULL); + if (old) + kfree_rcu(old, rcu); + break; + } + return NOTIFY_DONE; +} + +static struct notifier_block netprio_device_notifier = { + .notifier_call = netprio_device_event +}; + +static int __init init_cgroup_netprio(void) +{ + register_netdevice_notifier(&netprio_device_notifier); + return 0; +} + +subsys_initcall(init_cgroup_netprio); +MODULE_LICENSE("GPL v2"); diff --git a/pool/shard010/C/0139101_init_32.c b/pool/shard010/C/0139101_init_32.c new file mode 100644 index 0000000000000000000000000000000000000000..b516cae185ee01291bc7e05f536179aae9c0905f --- /dev/null +++ b/pool/shard010/C/0139101_init_32.c @@ -0,0 +1,293 @@ +/* + * PowerPC version + * Copyright (C) 1995-1996 Gary Thomas (gdt@linuxppc.org) + * + * Modifications by Paul Mackerras (PowerMac) (paulus@cs.anu.edu.au) + * and Cort Dougan (PReP) (cort@cs.nmt.edu) + * Copyright (C) 1996 Paul Mackerras + * PPC44x/36-bit changes by Matt Porter (mporter@mvista.com) + * + * Derived from "arch/i386/mm/init.c" + * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds + * + * 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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "mmu_decl.h" + +#if defined(CONFIG_KERNEL_START_BOOL) || defined(CONFIG_LOWMEM_SIZE_BOOL) +/* The amount of lowmem must be within 0xF0000000 - KERNELBASE. */ +#if (CONFIG_LOWMEM_SIZE > (0xF0000000 - PAGE_OFFSET)) +#error "You must adjust CONFIG_LOWMEM_SIZE or CONFIG_START_KERNEL" +#endif +#endif +#define MAX_LOW_MEM CONFIG_LOWMEM_SIZE + +phys_addr_t total_memory; +phys_addr_t total_lowmem; + +phys_addr_t memstart_addr = (phys_addr_t)~0ull; +EXPORT_SYMBOL(memstart_addr); +phys_addr_t kernstart_addr; +EXPORT_SYMBOL(kernstart_addr); +phys_addr_t lowmem_end_addr; + +int boot_mapsize; +#ifdef CONFIG_PPC_PMAC +unsigned long agp_special_page; +EXPORT_SYMBOL(agp_special_page); +#endif + +void MMU_init(void); + +/* XXX should be in current.h -- paulus */ +extern struct task_struct *current_set[NR_CPUS]; + +/* + * this tells the system to map all of ram with the segregs + * (i.e. page tables) instead of the bats. + * -- Cort + */ +int __map_without_bats; +int __map_without_ltlbs; + +/* + * This tells the system to allow ioremapping memory marked as reserved. + */ +int __allow_ioremap_reserved; + +/* max amount of low RAM to map in */ +unsigned long __max_low_memory = MAX_LOW_MEM; + +/* +<<<<<<< HEAD +======= + * address of the limit of what is accessible with initial MMU setup - + * 256MB usually, but only 16MB on 601. + */ +phys_addr_t __initial_memory_limit_addr = (phys_addr_t)0x10000000; + +/* +>>>>>>> 296c66da8a02d52243f45b80521febece5ed498a + * Check for command-line options that affect what MMU_init will do. + */ +void MMU_setup(void) +{ + /* Check for nobats option (used in mapin_ram). */ + if (strstr(cmd_line, "nobats")) { + __map_without_bats = 1; + } + + if (strstr(cmd_line, "noltlbs")) { + __map_without_ltlbs = 1; + } +#ifdef CONFIG_DEBUG_PAGEALLOC + __map_without_bats = 1; + __map_without_ltlbs = 1; +#endif +} + +/* + * MMU_init sets up the basic memory mappings for the kernel, + * including both RAM and possibly some I/O regions, + * and sets up the page tables and the MMU hardware ready to go. + */ +void __init MMU_init(void) +{ + if (ppc_md.progress) + ppc_md.progress("MMU:enter", 0x111); + +<<<<<<< HEAD +======= + /* 601 can only access 16MB at the moment */ + if (PVR_VER(mfspr(SPRN_PVR)) == 1) + __initial_memory_limit_addr = 0x01000000; + /* 8xx can only access 8MB at the moment */ + if (PVR_VER(mfspr(SPRN_PVR)) == 0x50) + __initial_memory_limit_addr = 0x00800000; + +>>>>>>> 296c66da8a02d52243f45b80521febece5ed498a + /* parse args from command line */ + MMU_setup(); + + if (memblock.memory.cnt > 1) { +#ifndef CONFIG_WII + memblock.memory.cnt = 1; + memblock_analyze(); + printk(KERN_WARNING "Only using first contiguous memory region"); +#else + wii_memory_fixups(); +#endif + } + + total_lowmem = total_memory = memblock_end_of_DRAM() - memstart_addr; + lowmem_end_addr = memstart_addr + total_lowmem; + +#ifdef CONFIG_FSL_BOOKE + /* Freescale Book-E parts expect lowmem to be mapped by fixed TLB + * entries, so we need to adjust lowmem to match the amount we can map + * in the fixed entries */ + adjust_total_lowmem(); +#endif /* CONFIG_FSL_BOOKE */ + + if (total_lowmem > __max_low_memory) { + total_lowmem = __max_low_memory; + lowmem_end_addr = memstart_addr + total_lowmem; +#ifndef CONFIG_HIGHMEM + total_memory = total_lowmem; +<<<<<<< HEAD + memblock_enforce_memory_limit(total_lowmem); +======= + memblock_enforce_memory_limit(lowmem_end_addr); +>>>>>>> 296c66da8a02d52243f45b80521febece5ed498a + memblock_analyze(); +#endif /* CONFIG_HIGHMEM */ + } + + /* Initialize the MMU hardware */ + if (ppc_md.progress) + ppc_md.progress("MMU:hw init", 0x300); + MMU_init_hw(); + + /* Map in all of RAM starting at KERNELBASE */ + if (ppc_md.progress) + ppc_md.progress("MMU:mapin", 0x301); + mapin_ram(); + + /* Initialize early top-down ioremap allocator */ + ioremap_bot = IOREMAP_TOP; + + /* Map in I/O resources */ + if (ppc_md.progress) + ppc_md.progress("MMU:setio", 0x302); + + if (ppc_md.progress) + ppc_md.progress("MMU:exit", 0x211); + + /* From now on, btext is no longer BAT mapped if it was at all */ +#ifdef CONFIG_BOOTX_TEXT + btext_unmap(); +#endif +<<<<<<< HEAD + + /* Shortly after that, the entire linear mapping will be available */ + memblock_set_current_limit(lowmem_end_addr); +======= +>>>>>>> 296c66da8a02d52243f45b80521febece5ed498a +} + +/* This is only called until mem_init is done. */ +void __init *early_get_page(void) +{ +<<<<<<< HEAD + if (init_bootmem_done) + return alloc_bootmem_pages(PAGE_SIZE); + else + return __va(memblock_alloc(PAGE_SIZE, PAGE_SIZE)); +======= + void *p; + + if (init_bootmem_done) { + p = alloc_bootmem_pages(PAGE_SIZE); + } else { + p = __va(memblock_alloc_base(PAGE_SIZE, PAGE_SIZE, + __initial_memory_limit_addr)); + } + return p; +>>>>>>> 296c66da8a02d52243f45b80521febece5ed498a +} + +/* Free up now-unused memory */ +static void free_sec(unsigned long start, unsigned long end, const char *name) +{ + unsigned long cnt = 0; + + while (start < end) { + ClearPageReserved(virt_to_page(start)); + init_page_count(virt_to_page(start)); + free_page(start); + cnt++; + start += PAGE_SIZE; + } + if (cnt) { + printk(" %ldk %s", cnt << (PAGE_SHIFT - 10), name); + totalram_pages += cnt; + } +} + +void free_initmem(void) +{ +#define FREESEC(TYPE) \ + free_sec((unsigned long)(&__ ## TYPE ## _begin), \ + (unsigned long)(&__ ## TYPE ## _end), \ + #TYPE); + + printk ("Freeing unused kernel memory:"); + FREESEC(init); + printk("\n"); + ppc_md.progress = NULL; +#undef FREESEC +} + +<<<<<<< HEAD +#ifdef CONFIG_8xx /* No 8xx specific .c file to put that in ... */ +void setup_initial_memory_limit(phys_addr_t first_memblock_base, + phys_addr_t first_memblock_size) +{ + /* We don't currently support the first MEMBLOCK not mapping 0 + * physical on those processors + */ + BUG_ON(first_memblock_base != 0); + + /* 8xx can only access 8MB at the moment */ + memblock_set_current_limit(min_t(u64, first_memblock_size, 0x00800000)); +} +#endif /* CONFIG_8xx */ +======= +#ifdef CONFIG_BLK_DEV_INITRD +void free_initrd_mem(unsigned long start, unsigned long end) +{ + if (start < end) + printk ("Freeing initrd memory: %ldk freed\n", (end - start) >> 10); + for (; start < end; start += PAGE_SIZE) { + ClearPageReserved(virt_to_page(start)); + init_page_count(virt_to_page(start)); + free_page(start); + totalram_pages++; + } +} +#endif + +>>>>>>> 296c66da8a02d52243f45b80521febece5ed498a diff --git a/pool/shard010/C/0139102_test.c b/pool/shard010/C/0139102_test.c new file mode 100644 index 0000000000000000000000000000000000000000..e34c75180cd250b05dc7d9b0193bbc7174989841 --- /dev/null +++ b/pool/shard010/C/0139102_test.c @@ -0,0 +1,124 @@ +/* + * test.c + * + * Created on: Aug 10, 2014 + * Author: leeopop + */ + + +#include +#include +#include +#include +#include +#include + +#include "click_lex.h" +#include "click_yacc.h" +#include "click_parser.h" + +int main(int argc, char** argv) +{ + char* config_dir = 0; + while (1) { + int option_index = 0; + static struct option long_options[] = { + {"config-dir", required_argument, 0, 0}, + {0, 0, 0, 0} + }; + + int c = getopt_long(argc, argv, "", + long_options, &option_index); + if (c == -1) + break; + + switch (c) { + case 0: + switch(option_index) + { + case 0: + { + config_dir = optarg; + } + } + break; + + default: + printf("?? getopt returned character code 0%o ??\n", c); + } + } + + struct dirent *entry; + DIR *dir; + char filename[FILENAME_MAX+1]; + +#if 1 + { + + if ((dir = opendir(config_dir)) == NULL) + { + fprintf(stderr, "Can't open %s\n", config_dir); + return 0; + } + + while ((entry = readdir(dir)) != NULL) + { + if(entry->d_type == DT_REG) + { + snprintf(filename, sizeof(filename), "%s/%s", config_dir, entry->d_name); + + FILE* input = fopen(filename, "r"); + + yylex_destroy(); + yyset_in(input); + + printf("%s\n", filename); + while(1) + { + int ret = yylex(); + if(ret == 0) + break; + } + + fclose(input); + } + } + } +#endif + + +#if 1 + { + + if ((dir = opendir(config_dir)) == NULL) + { + fprintf(stderr, "Can't open %s\n", config_dir); + return 0; + } + + while ((entry = readdir(dir)) != NULL) + { + if(entry->d_type == DT_REG) + { + snprintf(filename, sizeof(filename), "%s/%s", config_dir, entry->d_name); + + FILE* input = fopen(filename, "r"); + + ParseInfo* info = click_parse_configuration(input, 0, 0, 0); + if(info == 0) + printf("ERROR: %s\n", filename); + else + { + printf("%s\n", filename); + + printf("%d module, %d root, %d leaf\n", click_num_module(info), click_num_root(info), click_num_leaf(info)); + } + click_destroy_configuration(info); + + fclose(input); + } + } + } +#endif + return 0; +} diff --git a/pool/shard010/C/0139103_unix-main.c b/pool/shard010/C/0139103_unix-main.c new file mode 100644 index 0000000000000000000000000000000000000000..ae008f3c3ca2e68ee07365698b361e20384800e8 --- /dev/null +++ b/pool/shard010/C/0139103_unix-main.c @@ -0,0 +1,91 @@ +/* +----------------------------------------------------------------------------- + $Id: unix-main.c,v 1.1 2009/11/20 16:53:30 jasminko Exp $ +----------------------------------------------------------------------------- +Copyright (c) 2001-2006 gogo6 Inc. All rights reserved. + + For license information refer to CLIENT-LICENSE.TXT + +----------------------------------------------------------------------------- +*/ + +#include "platform.h" +#include "gogoc_status.h" + +#include + +#include "tsp_client.h" +#include "hex_strings.h" +#include "log.h" +#include "os_uname.h" + +#ifdef HACCESS +#include "haccess.h" +#endif + +extern int indSigHUP; /* Declared in every unix platform tsp_local.c */ + + +/* -------------------------------------------------------------------------- +// Signal handler function. KEEP THIS FUNCTION AS SIMPLE AS POSSIBLE. +*/ +void signal_handler( int sigraised ) +{ + if( sigraised == SIGHUP ) + indSigHUP = 1; +} + + +// -------------------------------------------------------------------------- +// Retrieves OS information and puts it nicely in a string ready for display. +// +// Defined in tsp_client.h +// +void tspGetOSInfo( const size_t len, char* buf ) +{ + if( len > 0 && buf != NULL ) + { +#ifdef OS_UNAME_INFO + snprintf( buf, len, "Built on ///%s///", OS_UNAME_INFO ); +#else + snprintf( buf, len, "Built on ///unknown UNIX/BSD/Linux version///" ); +#endif + } +} + + +// -------------------------------------------------------------------------- +int main(int argc, char *argv[]) +{ + int rc; +#ifdef HACCESS + haccess_status status = HACCESS_STATUS_OK; +#endif + /* Install new signal handler for HUP signal. */ + signal( SIGHUP, &signal_handler ); + +#ifdef HACCESS + /* Initialize the HACCESS module. */ + status = haccess_initialize(); + + if (status != HACCESS_STATUS_OK) { + DirectErrorMessage(HACCESS_LOG_PREFIX_ERROR GOGO_STR_HACCESS_ERR_CANT_INIT_MODULE); + return ERR_HACCESS_INIT; + } +#endif + + /* entry point */ + rc = tspMain(argc, argv); + +#ifdef HACCESS + /* The HACCESS module destructs (deinitialization). */ + status = haccess_destruct(); + + if (status != HACCESS_STATUS_OK) + { + DirectErrorMessage(HACCESS_LOG_PREFIX_ERROR GOGO_STR_HACCESS_ERR_CANT_DO_SHUTDOWN); + } +#endif + + return rc; +} diff --git a/pool/shard010/C/0139104_vd_libdv.c b/pool/shard010/C/0139104_vd_libdv.c new file mode 100644 index 0000000000000000000000000000000000000000..137fa7bf606aac250d3b627d7f835047c8057d1c --- /dev/null +++ b/pool/shard010/C/0139104_vd_libdv.c @@ -0,0 +1,102 @@ +/* + * This file is part of MPlayer. + * + * MPlayer 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. + * + * MPlayer 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 MPlayer; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include +#include +#include +#include +#include +#include + +#include "config.h" + +#include "img_format.h" + +#include +#include + +#include "stream/stream.h" +#include "libmpdemux/demuxer.h" +#include "libmpdemux/stheader.h" + +#include "vd_internal.h" +#include "vd_libdv.h" + +static const vd_info_t info = +{ + "Raw DV Video Decoder", + "libdv", + "Alexander Neundorf ", + "http://libdv.sf.net", + "native codec" +}; + +LIBVD_EXTERN(libdv) + +// to set/get/query special features/parameters +static int control(sh_video_t *sh,int cmd,void* arg,...){ + return CONTROL_UNKNOWN; +} + +static dv_decoder_t* global_rawdv_decoder=NULL; + +dv_decoder_t* init_global_rawdv_decoder(void) +{ + if(!global_rawdv_decoder){ + global_rawdv_decoder=dv_decoder_new(TRUE,TRUE,FALSE); + global_rawdv_decoder->quality=DV_QUALITY_BEST; + global_rawdv_decoder->prev_frame_decoded = 0; + } + return global_rawdv_decoder; +} + +// init driver +static int init(sh_video_t *sh) +{ + sh->context = (void *)init_global_rawdv_decoder(); + return mpcodecs_config_vo(sh,sh->disp_w,sh->disp_h,IMGFMT_YUY2); +} + +// uninit driver +static void uninit(sh_video_t *sh){ +} + +// decode a frame +static mp_image_t* decode(sh_video_t *sh,void* data,int len,int flags) +{ + mp_image_t* mpi; + dv_decoder_t *decoder=sh->context; + + if(len<=0 || (flags&3)){ +// fprintf(stderr,"decode() (rawdv) SKIPPED\n"); + return NULL; // skipped frame + } + + dv_parse_header(decoder, data); + + mpi=mpcodecs_get_image(sh, MP_IMGTYPE_TEMP, MP_IMGFLAG_ACCEPT_STRIDE, sh->disp_w, sh->disp_h); + + if(!mpi){ // temporary! + fprintf(stderr,"couldn't allocate image for stderr codec\n"); + return NULL; + } + + dv_decode_full_frame(decoder, data, e_dv_color_yuv, mpi->planes, mpi->stride); + + return mpi; +} diff --git a/pool/shard010/C/0139105_dsa_backend.c b/pool/shard010/C/0139105_dsa_backend.c new file mode 100644 index 0000000000000000000000000000000000000000..5e3ff851544ec7f6fd567c8a2541e4c60b716626 --- /dev/null +++ b/pool/shard010/C/0139105_dsa_backend.c @@ -0,0 +1,189 @@ +/* + * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the Apache License 2.0 (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +/* + * DSA low level APIs are deprecated for public use, but still ok for + * internal use. + */ +#include "internal/deprecated.h" + +#include +#include +#ifndef FIPS_MODULE +# include +#endif +#include "crypto/dsa.h" +#include "dsa_local.h" + +/* + * The intention with the "backend" source file is to offer backend support + * for legacy backends (EVP_PKEY_ASN1_METHOD and EVP_PKEY_METHOD) and provider + * implementations alike. + */ + +int ossl_dsa_key_fromdata(DSA *dsa, const OSSL_PARAM params[]) +{ + const OSSL_PARAM *param_priv_key, *param_pub_key; + BIGNUM *priv_key = NULL, *pub_key = NULL; + + if (dsa == NULL) + return 0; + + param_priv_key = + OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_PRIV_KEY); + param_pub_key = + OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_PUB_KEY); + + /* It's ok if neither half is present */ + if (param_priv_key == NULL && param_pub_key == NULL) + return 1; + + if (param_pub_key != NULL && !OSSL_PARAM_get_BN(param_pub_key, &pub_key)) + goto err; + if (param_priv_key != NULL && !OSSL_PARAM_get_BN(param_priv_key, &priv_key)) + goto err; + + if (!DSA_set0_key(dsa, pub_key, priv_key)) + goto err; + + return 1; + + err: + BN_clear_free(priv_key); + BN_free(pub_key); + return 0; +} + +int ossl_dsa_is_foreign(const DSA *dsa) +{ +#ifndef FIPS_MODULE + if (dsa->engine != NULL || DSA_get_method((DSA *)dsa) != DSA_OpenSSL()) + return 1; +#endif + return 0; +} + +static ossl_inline int dsa_bn_dup_check(BIGNUM **out, const BIGNUM *f) +{ + if (f != NULL && (*out = BN_dup(f)) == NULL) + return 0; + return 1; +} + +DSA *ossl_dsa_dup(const DSA *dsa, int selection) +{ + DSA *dupkey = NULL; + + /* Do not try to duplicate foreign DSA keys */ + if (ossl_dsa_is_foreign(dsa)) + return NULL; + + if ((dupkey = ossl_dsa_new(dsa->libctx)) == NULL) + return NULL; + + if ((selection & OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) != 0 + && !ossl_ffc_params_copy(&dupkey->params, &dsa->params)) + goto err; + + dupkey->flags = dsa->flags; + + if ((selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0 + && ((selection & OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) == 0 + || !dsa_bn_dup_check(&dupkey->pub_key, dsa->pub_key))) + goto err; + + if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0 + && ((selection & OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) == 0 + || !dsa_bn_dup_check(&dupkey->priv_key, dsa->priv_key))) + goto err; + +#ifndef FIPS_MODULE + if (!CRYPTO_dup_ex_data(CRYPTO_EX_INDEX_DSA, + &dupkey->ex_data, &dsa->ex_data)) + goto err; +#endif + + return dupkey; + + err: + DSA_free(dupkey); + return NULL; +} + +#ifndef FIPS_MODULE +DSA *ossl_dsa_key_from_pkcs8(const PKCS8_PRIV_KEY_INFO *p8inf, + OSSL_LIB_CTX *libctx, const char *propq) +{ + const unsigned char *p, *pm; + int pklen, pmlen; + int ptype; + const void *pval; + const ASN1_STRING *pstr; + const X509_ALGOR *palg; + ASN1_INTEGER *privkey = NULL; + const BIGNUM *dsa_p, *dsa_g; + BIGNUM *dsa_pubkey = NULL, *dsa_privkey = NULL; + BN_CTX *ctx = NULL; + + DSA *dsa = NULL; + + if (!PKCS8_pkey_get0(NULL, &p, &pklen, &palg, p8inf)) + return 0; + X509_ALGOR_get0(NULL, &ptype, &pval, palg); + + if ((privkey = d2i_ASN1_INTEGER(NULL, &p, pklen)) == NULL) + goto decerr; + if (privkey->type == V_ASN1_NEG_INTEGER || ptype != V_ASN1_SEQUENCE) + goto decerr; + + pstr = pval; + pm = pstr->data; + pmlen = pstr->length; + if ((dsa = d2i_DSAparams(NULL, &pm, pmlen)) == NULL) + goto decerr; + /* We have parameters now set private key */ + if ((dsa_privkey = BN_secure_new()) == NULL + || !ASN1_INTEGER_to_BN(privkey, dsa_privkey)) { + ERR_raise(ERR_LIB_DSA, DSA_R_BN_ERROR); + goto dsaerr; + } + /* Calculate public key */ + if ((dsa_pubkey = BN_new()) == NULL) { + ERR_raise(ERR_LIB_DSA, ERR_R_MALLOC_FAILURE); + goto dsaerr; + } + if ((ctx = BN_CTX_new()) == NULL) { + ERR_raise(ERR_LIB_DSA, ERR_R_MALLOC_FAILURE); + goto dsaerr; + } + + dsa_p = DSA_get0_p(dsa); + dsa_g = DSA_get0_g(dsa); + BN_set_flags(dsa_privkey, BN_FLG_CONSTTIME); + if (!BN_mod_exp(dsa_pubkey, dsa_g, dsa_privkey, dsa_p, ctx)) { + ERR_raise(ERR_LIB_DSA, DSA_R_BN_ERROR); + goto dsaerr; + } + DSA_set0_key(dsa, dsa_pubkey, dsa_privkey); + + goto done; + + decerr: + ERR_raise(ERR_LIB_DSA, DSA_R_DECODE_ERROR); + dsaerr: + BN_free(dsa_privkey); + BN_free(dsa_pubkey); + DSA_free(dsa); + dsa = NULL; + done: + BN_CTX_free(ctx); + ASN1_STRING_clear_free(privkey); + return dsa; +} +#endif diff --git a/pool/shard010/C/0139106_sharelist.c b/pool/shard010/C/0139106_sharelist.c new file mode 100644 index 0000000000000000000000000000000000000000..7824fd94b798904330d595ae3ce656f8d084c671 --- /dev/null +++ b/pool/shard010/C/0139106_sharelist.c @@ -0,0 +1,239 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +MODULE_LICENSE("GPL"); + + +/** + * scheduled by kernel thread "keventd" in default workqueue + * + * test on linux-3.5.4 / linux-3.12 + */ + + +#define MAX_THREAD 100 +#define MAX_LIST_SIZE 800 +#define TIMEOUT 1 + + +typedef struct work_struct Work; +typedef struct mywork_struct MyWork; +typedef struct timer_list MyTimer; +typedef struct mylist_struct MyList; + + + +struct mywork_struct { + pid_t pid; /* current thread pid */ + spinlock_t spinlock; /* list spinlock */ + atomic_t counter; /* list counter */ + atomic_t list_size; /* list size */ + struct work_struct work; /* work_struct */ +}; + + +struct mylist_struct { + int id; /* id */ + struct list_head list; /* list_head */ +}; + + +static DEFINE_SEMAPHORE(sem); /* semaphore */ +static MyWork mywork; /* work queue*/ +static LIST_HEAD(mine); /* list head */ +static MyTimer mytimer; /* timmer */ + + +//########################################################// + +static void qt_task(unsigned long); +static void work_func(Work*); +static int sharelist(void*); +static void start_work(void); +static void share_init(void); +static void share_exit(void); + +//########################################################// + + +static __init +int startModule(void) { + + printk(KERN_INFO "start sharelist module!\n"); + share_init(); + start_work(); + return 0; +} + + +static __exit +void exitModule(void) { + + share_exit(); + printk(KERN_INFO "\nexit sharelist module!\n"); + +} + + +/* init func*/ +static +void share_init(void) { + + spin_lock_init(&(mywork.spinlock)); + atomic_set(&(mywork.counter),0); + atomic_set(&(mywork.list_size),0); + INIT_WORK(&(mywork.work), work_func); + setup_timer(&mytimer, qt_task, (unsigned long)&(mywork.work)); + add_timer(&mytimer); +} + +/* exit func*/ +static +void share_exit(void) { + + struct list_head *prev = NULL; + struct list_head *next = NULL; + MyList *p = NULL; + + printk(KERN_INFO "\n########## start to delete sharelist ##########\n\n"); + + del_timer(&mytimer); + spin_lock(&(mywork.spinlock)); + + list_for_each_safe(prev, next, &mine) { + p = list_entry(prev, typeof(*p), list); + if(p) { + list_del(prev); + printk(KERN_INFO "########## [share_exit] List Del :%d\n", p->id); + kfree(p); + } + + } + + spin_unlock(&(mywork.spinlock)); + printk(KERN_INFO "\n\nsharelist is empty now!\n"); + +} + + +/* work func */ +static +void work_func(Work *work) { + + struct task_struct *task = NULL; + + MyWork *mywork = container_of(work,typeof(*mywork),work); + + /* create a thread to operate list by kerner_thread*/ + // kernel_thread(sharelist,NULL,CLONE_KERNEL | SIGCHLD); + task = kthread_run(sharelist,(void*)work,"sharelist-thread"); + if( !task) { + printk(KERN_ERR "kernel_thread error!\n"); + return; + } + + mywork->pid = task->pid; + + //printk(KERN_INFO "********** create thread --> pid = %d\n",task->pid); + up(&sem); + +} + + +/* schedule work by keventd*/ +static +void start_work(void) { + + int i; + if(&(mywork.work)) { + for(i = 0; ispinlock)); + + if(atomic_read(&(mywork->list_size)) <= MAX_LIST_SIZE) { + + if(NULL == (p = kmalloc(sizeof(MyList), GFP_KERNEL))) { + printk(KERN_ERR "kmalloc failed!\n"); + return -ENOMEM; + } + p->id = atomic_read(&(mywork->counter)); + list_add(&(p->list),&mine); /* add to mine list*/ + atomic_inc(&(mywork->counter)); + atomic_inc(&(mywork->list_size)); + printk(KERN_INFO "$$$$$$$$$$ [sharelist thread] pid = %d List Add :%d\n",mywork->pid, p->id); + + }else { + + p = list_entry(mine.prev, typeof(*p), list); + if(p) { + list_del(mine.prev); + atomic_dec(&(mywork->list_size)); + printk(KERN_INFO "[sharelist thread] pid = %d List Del :%d\n",mywork->pid, p->id); + kfree(p); + } + } + + spin_unlock(&(mywork->spinlock)); + + return 0; +} + +/* timmer func*/ +static +void qt_task(unsigned long data) { + + + MyWork *mywork = container_of((Work*)data,typeof(*mywork),work); + MyList *p; + spin_lock(&(mywork->spinlock)); + if(!list_empty(&mine)) { + p = list_entry(mine.next, typeof(*p), list); + if(p) { + list_del(mine.next); + atomic_dec(&(mywork->list_size)); + printk(KERN_INFO "@@@@@@@@@@ [qt_task] List Del :%d \n", p->id); + kfree(p); + } + } + spin_unlock(&(mywork->spinlock)); + mod_timer(&mytimer,jiffies+1); +} + +module_init(startModule); +module_exit(exitModule); + diff --git a/pool/shard010/C/0139107_crosswind_curvature.c b/pool/shard010/C/0139107_crosswind_curvature.c new file mode 100644 index 0000000000000000000000000000000000000000..bbbceeb08c6a13df2a15394ac7abc475855ee03b --- /dev/null +++ b/pool/shard010/C/0139107_crosswind_curvature.c @@ -0,0 +1,283 @@ +/* + * Copyright 2020 Makani Technologies LLC + * + * 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 "control/crosswind/crosswind_curvature.h" + +#include +#include +#include +#include + +#include "common/c_math/filter.h" +#include "common/c_math/util.h" +#include "common/c_math/vec3.h" +#include "control/control_params.h" +#include "control/crosswind/crosswind_types.h" +#include "control/crosswind/crosswind_util.h" +#include "control/simple_aero.h" +#include "control/system_params.h" +#include "control/system_types.h" + +void CrosswindCurvatureInit(double tension, double alpha, double beta, + const CrosswindCurvatureParams *params, + CrosswindCurvatureState *state) { + memset(state, 0, sizeof(*state)); + state->tension_hpf_z1 = 0.0; + state->tension_z1 = tension; + state->alpha_cmd_z1 = + Saturate(alpha, params->alpha_cmd_min, params->alpha_cmd_max); + state->beta_cmd_z1 = + Saturate(beta, params->beta_cmd_min, params->beta_cmd_max); + state->transout_flare_time = 0.0; +} + +// Finds a tether roll, alpha, beta command that will meet the +// curvature command. Trade-offs are made between these commands to +// limit tensions, improve curvature response, limit maximum AoA, +// sideslip, and tether roll, etc. The equation which describes the +// trade-offs is in the comment to the CurvatureToTetherRoll equation +// above. +// +// Note: We have strict limits on maximum tether roll command at low +// tensions. Here we are actually using tether tension as a proxy for +// situations where the tether pitch angle is negative (e.g. after +// trans-in before the tether becomes taught). Under these +// situations, rolling the wing causes an adverse yaw moment from the +// tether and can lead to large sideslips. +// +// TODO: We use tension (rather than tether pitch) to +// limit the roll command here because W7 was not designed for a +// tether pitch measurement; however, we may want to reconsider this +// for the M600. +// +// TODO: Try a complementary fast/slow response approach. +// Use predominately CL and CY for the high-pass-filtered k_aero_cmd, +// and use predominately tether_roll for the low-pass-filtered +// k_aero_cmd. +// +// NOTE: Previous versions of the controller contained a +// trick that used pitch-down and side-slip to increase turning +// authority when large tether roll angles were commanded. This trick +// was used often with W7, but its efficacy on the M600 was +// questionable, so we pulled it out. The idea behind this trick is +// that large rolls are an indication of poor turning which is often +// caused by negative sideslip, and moving the bridle point forward in +// body coordinates should help reduce the adverse yaw moment when the +// bridle point is behind the center-of-mass. We should put this +// trick on a firmer analytical footing and consider revisiting it in +// the future. +// +// Args: +// k_aero_cmd: Aerodynamic curvature command. +// tension: Tether tension. +// airspeed: Measured airspeed. +// flags: Flags are used to change behavior based on sensor faults +// or extreme wind conditions. +// params: Curvature loop parameters. +// state: Curvature loop state. +// flaring: True if the vehicle is latched in the final trans-out flare. +// alpha_cmd: Output for the angle-of-attack set-point. +// dCL_cmd: Output command for a change in lift coefficient from the +// center flaps. This is used to quickly change CL without +// changing the angle-of-attack. +// beta_cmd: Output for the sideslip set-point. +// tether_roll_cmd: Output for the tether roll set-point. +static void SetAngles(double k_aero_cmd, double tension, double airspeed, + double alpha_nom, double beta_nom, double loop_angle, + CrosswindPathType path_type, + const FlightStatus *flight_status, + const CrosswindFlags *flags, + const CrosswindCurvatureParams *params, + CrosswindCurvatureState *state, bool *flaring, + double *alpha_cmd, double *dCL_cmd, double *beta_cmd, + double *tether_roll_cmd) { + // Validate parameters. + assert(params->alpha_cmd_rate_min <= params->alpha_cmd_rate_max); + assert(params->alpha_cmd_rate_min <= 0.0); + assert(params->alpha_cmd_rate_max >= 0.0); + assert(params->beta_cmd_rate_min <= params->beta_cmd_rate_max); + assert(params->beta_cmd_rate_min <= 0.0); + assert(params->beta_cmd_rate_max >= 0.0); + assert(params->dalpha_dairspeed < 0.0); + + assert(params->preptransout_alpha_rate >= 0.0); + assert(params->transout_flare_alpha_rate >= 0.0); + + // Adjust angle-of-attack to limit tension. We use airspeed, rather + // than tension, as the independent variable because it is difficult + // to control the tension loop while maintaining a reasonable + // bandwidth. + double alpha_nom_airspeed = + params->alpha_min_airspeed - + (params->alpha_min - alpha_nom) / params->dalpha_dairspeed; + *alpha_cmd = Crossfade(alpha_nom, params->alpha_min, airspeed, + alpha_nom_airspeed, params->alpha_min_airspeed); + *beta_cmd = beta_nom; + + // Trans-out flare state machine. + *flaring = (flight_status->flight_mode == kFlightModeCrosswindPrepTransOut && + path_type == kCrosswindPathPrepareTransitionOut && + (airspeed < params->transout_flare_airspeed || + state->transout_flare_time > 0.0)); + if (*flaring) { + state->transout_flare_time += *g_sys.ts; + } else { + state->transout_flare_time = 0.0; + } + + // Calculate rate limits. + double alpha_cmd_rate_min = params->alpha_cmd_rate_min; + double alpha_cmd_rate_max = params->alpha_cmd_rate_max; + double beta_cmd_rate_min = params->beta_cmd_rate_min; + double beta_cmd_rate_max = params->beta_cmd_rate_max; + + if (flight_status->flight_mode == kFlightModeCrosswindPrepTransOut && + !*flaring) { + // We're in PrepTransOut but not yet flaring. Move to lower angle + // of attack to dump lift before slowing down. + *alpha_cmd = params->preptransout_alpha_cmd; + alpha_cmd_rate_min = -params->preptransout_alpha_rate; + alpha_cmd_rate_max = params->preptransout_alpha_rate; + + } else if (*flaring) { + // Flare. + *alpha_cmd = params->transout_flare_alpha_cmd; + *beta_cmd = params->transout_flare_beta_cmd; + + // Impose alpha and beta limits as a proxy for body rotation rate limits. + alpha_cmd_rate_min = -params->transout_flare_alpha_rate; + alpha_cmd_rate_max = params->transout_flare_alpha_rate; + beta_cmd_rate_min = -params->transout_flare_beta_rate; + beta_cmd_rate_max = params->transout_flare_beta_rate; + } + + // Apply rate limits. + *alpha_cmd = RateLimit(*alpha_cmd, alpha_cmd_rate_min, alpha_cmd_rate_max, + *g_sys.ts, &state->alpha_cmd_z1); + + *beta_cmd = RateLimit(*beta_cmd, beta_cmd_rate_min, beta_cmd_rate_max, + *g_sys.ts, &state->beta_cmd_z1); + + // Remove high frequency tension noise with the flaps. High pass + // filter the tension and produce an appropriate change-in-CL + // command (dCL_cmd). Turn this feature off if there is any + // indication of a fault in the tension measurement. We currently + // set the gain on this to 0 because the exact amount to use this + // feature depends on unknown details of servo wear, etc... + if (!flags->loadcell_fault) { + double tension_hpf = Hpf(tension, params->fc_tension, *g_sys.ts, + &state->tension_hpf_z1, &state->tension_z1); + *dCL_cmd = + params->kp_tension_hf * -tension_hpf / + fmax(0.5 * g_sys.phys->rho * g_sys.wing->A * airspeed * airspeed, 1.0); + } else { + *dCL_cmd = 0.0; + } + + // Convert a curvature command to a tether roll command based on the + // curvature equation in the function comment above. + *tether_roll_cmd = CurvatureToTetherRoll( + k_aero_cmd, AlphaToCL(*alpha_cmd, g_cont.simple_aero_model) + *dCL_cmd, + BetaToCY(*beta_cmd, g_cont.simple_aero_model)); + + // Add the feedforward tether roll command. + *tether_roll_cmd += params->tether_roll_ff_amplitude * + cos(loop_angle + params->tether_roll_ff_phase); + + // Fade in tether roll command following transition-in. This + // greatly reduces the transients. + if (flight_status->last_flight_mode == kFlightModeTransIn) { + *tether_roll_cmd = Crossfade(0.0, *tether_roll_cmd, + flight_status->flight_mode_time, 0.0, 2.0); + } + + // Determine maximum tether roll angle excursion. If any of the + // loadcells have failed, do not trust the tension measurement and + // default to the safer high roll angle case. + double tether_roll_max_excursion; + if (flags->loadcell_fault) { + tether_roll_max_excursion = params->tether_roll_max_excursion_high; + } else { + tether_roll_max_excursion = Crossfade( + params->tether_roll_max_excursion_low, + params->tether_roll_max_excursion_high, tension, + params->tether_roll_tension_low, params->tether_roll_tension_high); + } + + // Saturate commands within reasonable limits. + double alpha_cmd_max = + *flaring ? params->alpha_cmd_max_flare : params->alpha_cmd_max; + *alpha_cmd = Saturate(*alpha_cmd, params->alpha_cmd_min, alpha_cmd_max); + *dCL_cmd = Saturate(*dCL_cmd, -params->dCL_cmd_max, params->dCL_cmd_max); + *beta_cmd = Saturate(*beta_cmd, -params->beta_cmd_max, params->beta_cmd_max); + *tether_roll_cmd = Saturate( + *tether_roll_cmd, params->tether_roll_nom - tether_roll_max_excursion, + params->tether_roll_nom + tether_roll_max_excursion); +} + +double CrosswindCurvatureFlareTimer(const CrosswindCurvatureState *state) { + return state->transout_flare_time; +} + +// Finds the angular rate (in body coordinates) expected for a given +// curvature, tether roll, and speed. The magnitude of the expected +// angular rate is: |pqr| = curvature / velocity. The direction of +// the expected angular rate is perpendicular to the crosswind flight +// plane, so we need to know the pitch and roll angle of the wing +// relative to the flight plane. Currently, we assume the pitch is +// small and the roll angle is given by: +// +// body_roll_cmd = -tether_roll_cmd - (half cone angle) +// +// where the "half cone angle" for a circle radius R is defined by: +// +// (half cone angle) = asin(R / tether_len) +// +// TODO: This does not take into account natural changes +// in the angular rate due to wind asymmetries. +static const Vec3 *SetRates(double k_geom_cmd, double tether_roll_cmd, + const Vec3 *Vg, Vec3 *pqr_cmd) { + if (fabs(k_geom_cmd) < DBL_TOL) { + *pqr_cmd = kVec3Zero; + } else { + double pqr_norm = k_geom_cmd * Vec3Norm(Vg); + double body_roll_cmd = + -Asin(1.0 / (k_geom_cmd * g_sys.tether->length)) - tether_roll_cmd; + pqr_cmd->x = 0.0; + pqr_cmd->y = pqr_norm * sin(body_roll_cmd); + pqr_cmd->z = pqr_norm * cos(body_roll_cmd); + } + return pqr_cmd; +} + +void CrosswindCurvatureStep(double k_aero_cmd, double k_geom_cmd, + double tension, double airspeed, double alpha_nom, + double beta_nom, double loop_angle, + CrosswindPathType path_type, const Vec3 *Vg, + const FlightStatus *flight_status, + const CrosswindFlags *flags, + const CrosswindCurvatureParams *params, + CrosswindCurvatureState *state, Vec3 *pqr_cmd, + bool *flaring, double *alpha_cmd, double *dCL_cmd, + double *beta_cmd, double *tether_roll_cmd) { + assert(Vg != NULL && flags != NULL && params != NULL && state != NULL && + pqr_cmd != NULL && alpha_cmd != NULL && dCL_cmd != NULL && + beta_cmd != NULL && tether_roll_cmd != NULL); + SetAngles(k_aero_cmd, tension, airspeed, alpha_nom, beta_nom, loop_angle, + path_type, flight_status, flags, params, state, flaring, alpha_cmd, + dCL_cmd, beta_cmd, tether_roll_cmd); + SetRates(k_geom_cmd, *tether_roll_cmd, Vg, pqr_cmd); +} diff --git a/pool/shard010/C/0139108_cp.c b/pool/shard010/C/0139108_cp.c new file mode 100644 index 0000000000000000000000000000000000000000..e48e21c9708c60d7762808d7b8e52737f07baf08 --- /dev/null +++ b/pool/shard010/C/0139108_cp.c @@ -0,0 +1,208 @@ +/* vi: set sw=4 ts=4: */ +/* + * Mini cp implementation for busybox + * + * Copyright (C) 2000 by Matt Kraai + * SELinux support by Yuichi Nakamura + * + * Licensed under GPLv2 or later, see file LICENSE in this source tree. + */ + +/* http://www.opengroup.org/onlinepubs/007904975/utilities/cp.html */ + +/* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org) + * + * Size reduction. + */ + +//usage:#define cp_trivial_usage +//usage: "[OPTIONS] SOURCE DEST" +//usage:#define cp_full_usage "\n\n" +//usage: "Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY\n" +//usage: "\n -a Same as -dpR" +//usage: IF_SELINUX( +//usage: "\n -c Preserve security context" +//usage: ) +//usage: "\n -R,-r Recurse" +//usage: "\n -d,-P Preserve symlinks (default if -R)" +//usage: "\n -L Follow all symlinks" +//usage: "\n -H Follow symlinks on command line" +//usage: "\n -p Preserve file attributes if possible" +//usage: "\n -f Overwrite" +//usage: "\n -i Prompt before overwrite" +//usage: "\n -l,-s Create (sym)links" + +#include "libbb.h" +#include "libcoreutils/coreutils.h" + +/* This is a NOEXEC applet. Be very careful! */ + +int cp_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE; +int cp_main(int argc, char **argv) +{ + struct stat source_stat; + struct stat dest_stat; + const char *last; + const char *dest; + int s_flags; + int d_flags; + int flags; + int status; + enum { + OPT_a = 1 << (sizeof(FILEUTILS_CP_OPTSTR)-1), + OPT_r = 1 << (sizeof(FILEUTILS_CP_OPTSTR)), + OPT_P = 1 << (sizeof(FILEUTILS_CP_OPTSTR)+1), + OPT_v = 1 << (sizeof(FILEUTILS_CP_OPTSTR)+2), +#if ENABLE_FEATURE_CP_LONG_OPTIONS + OPT_parents = 1 << (sizeof(FILEUTILS_CP_OPTSTR)+3), +#endif + }; + + // Need at least two arguments + // Soft- and hardlinking doesn't mix + // -P and -d are the same (-P is POSIX, -d is GNU) + // -r and -R are the same + // -R (and therefore -r) turns on -d (coreutils does this) + // -a = -pdR + opt_complementary = "-2:l--s:s--l:Pd:rRd:Rd:apdR"; +#if ENABLE_FEATURE_CP_LONG_OPTIONS + applet_long_options = + "archive\0" No_argument "a" + "force\0" No_argument "f" + "interactive\0" No_argument "i" + "link\0" No_argument "l" + "dereference\0" No_argument "L" + "no-dereference\0" No_argument "P" + "recursive\0" No_argument "R" + "symbolic-link\0" No_argument "s" + "verbose\0" No_argument "v" + "parents\0" No_argument "\xff" + ; +#endif + // -v (--verbose) is ignored + flags = getopt32(argv, FILEUTILS_CP_OPTSTR "arPv"); + /* Options of cp from GNU coreutils 6.10: + * -a, --archive + * -f, --force + * -i, --interactive + * -l, --link + * -L, --dereference + * -P, --no-dereference + * -R, -r, --recursive + * -s, --symbolic-link + * -v, --verbose + * -H follow command-line symbolic links in SOURCE + * -d same as --no-dereference --preserve=links + * -p same as --preserve=mode,ownership,timestamps + * -c same as --preserve=context + * --parents + * use full source file name under DIRECTORY + * NOT SUPPORTED IN BBOX: + * --backup[=CONTROL] + * make a backup of each existing destination file + * -b like --backup but does not accept an argument + * --copy-contents + * copy contents of special files when recursive + * --preserve[=ATTR_LIST] + * preserve attributes (default: mode,ownership,timestamps), + * if possible additional attributes: security context,links,all + * --no-preserve=ATTR_LIST + * --remove-destination + * remove each existing destination file before attempting to open + * --sparse=WHEN + * control creation of sparse files + * --strip-trailing-slashes + * remove any trailing slashes from each SOURCE argument + * -S, --suffix=SUFFIX + * override the usual backup suffix + * -t, --target-directory=DIRECTORY + * copy all SOURCE arguments into DIRECTORY + * -T, --no-target-directory + * treat DEST as a normal file + * -u, --update + * copy only when the SOURCE file is newer than the destination + * file or when the destination file is missing + * -x, --one-file-system + * stay on this file system + * -Z, --context=CONTEXT + * (SELinux) set SELinux security context of copy to CONTEXT + */ + argc -= optind; + argv += optind; + /* Reverse this bit. If there is -d, bit is not set: */ + flags ^= FILEUTILS_DEREFERENCE; + /* coreutils 6.9 compat: + * by default, "cp" derefs symlinks (creates regular dest files), + * but "cp -R" does not. We switch off deref if -r or -R (see above). + * However, "cp -RL" must still deref symlinks: */ + if (flags & FILEUTILS_DEREF_SOFTLINK) /* -L */ + flags |= FILEUTILS_DEREFERENCE; + +#if ENABLE_SELINUX + if (flags & FILEUTILS_PRESERVE_SECURITY_CONTEXT) { + selinux_or_die(); + } +#endif + + status = EXIT_SUCCESS; + last = argv[argc - 1]; + /* If there are only two arguments and... */ + if (argc == 2) { + s_flags = cp_mv_stat2(*argv, &source_stat, + (flags & FILEUTILS_DEREFERENCE) ? stat : lstat); + if (s_flags < 0) + return EXIT_FAILURE; + d_flags = cp_mv_stat(last, &dest_stat); + if (d_flags < 0) + return EXIT_FAILURE; + +#if ENABLE_FEATURE_CP_LONG_OPTIONS + if (flags & OPT_parents) { + if (!(d_flags & 2)) { + bb_error_msg_and_die("with --parents, the destination must be a directory"); + } + } +#endif + + /* ...if neither is a directory... */ + if (!((s_flags | d_flags) & 2) + /* ...or: recursing, the 1st is a directory, and the 2nd doesn't exist... */ + || ((flags & FILEUTILS_RECUR) && (s_flags & 2) && !d_flags) + ) { + /* Do a simple copy */ + dest = last; + goto DO_COPY; /* NB: argc==2 -> *++argv==last */ + } + } + + while (1) { +#if ENABLE_FEATURE_CP_LONG_OPTIONS + if (flags & OPT_parents) { + char *dest_dup; + char *dest_dir; + dest = concat_path_file(last, *argv); + dest_dup = xstrdup(dest); + dest_dir = dirname(dest_dup); + if (bb_make_directory(dest_dir, -1, FILEUTILS_RECUR)) { + return EXIT_FAILURE; + } + free(dest_dup); + goto DO_COPY; + } +#endif + dest = concat_path_file(last, bb_get_last_path_component_strip(*argv)); + DO_COPY: + if (copy_file(*argv, dest, flags) < 0) { + status = EXIT_FAILURE; + } + if (*++argv == last) { + /* possibly leaking dest... */ + break; + } + /* don't move up: dest may be == last and not malloced! */ + free((void*)dest); + } + + /* Exit. We are NOEXEC, not NOFORK. We do exit at the end of main() */ + return status; +} diff --git a/pool/shard010/C/0139109_idprom.c b/pool/shard010/C/0139109_idprom.c new file mode 100644 index 0000000000000000000000000000000000000000..72934b37ac28d6893d2858088110bef0112be30f --- /dev/null +++ b/pool/shard010/C/0139109_idprom.c @@ -0,0 +1,95 @@ + + +#include +#include +#include +#include + +#include +#include + +struct idprom *idprom; +EXPORT_SYMBOL(idprom); + +static struct idprom idprom_buffer; + +#ifdef CONFIG_SPARC32 +#include /* Fun with Sun released architectures. */ + +static struct Sun_Machine_Models Sun_Machines[NUM_SUN_MACHINES] = { +/* First, Sun4's */ +{ .name = "Sun 4/100 Series", .id_machtype = (SM_SUN4 | SM_4_110) }, +{ .name = "Sun 4/200 Series", .id_machtype = (SM_SUN4 | SM_4_260) }, +{ .name = "Sun 4/300 Series", .id_machtype = (SM_SUN4 | SM_4_330) }, +{ .name = "Sun 4/400 Series", .id_machtype = (SM_SUN4 | SM_4_470) }, +/* Now Leon */ +{ .name = "Leon3 System-on-a-Chip", .id_machtype = (M_LEON | M_LEON3_SOC) }, +/* Now, Sun4c's */ +{ .name = "Sun4c SparcStation 1", .id_machtype = (SM_SUN4C | SM_4C_SS1) }, +{ .name = "Sun4c SparcStation IPC", .id_machtype = (SM_SUN4C | SM_4C_IPC) }, +{ .name = "Sun4c SparcStation 1+", .id_machtype = (SM_SUN4C | SM_4C_SS1PLUS) }, +{ .name = "Sun4c SparcStation SLC", .id_machtype = (SM_SUN4C | SM_4C_SLC) }, +{ .name = "Sun4c SparcStation 2", .id_machtype = (SM_SUN4C | SM_4C_SS2) }, +{ .name = "Sun4c SparcStation ELC", .id_machtype = (SM_SUN4C | SM_4C_ELC) }, +{ .name = "Sun4c SparcStation IPX", .id_machtype = (SM_SUN4C | SM_4C_IPX) }, +/* Finally, early Sun4m's */ +{ .name = "Sun4m SparcSystem600", .id_machtype = (SM_SUN4M | SM_4M_SS60) }, +{ .name = "Sun4m SparcStation10/20", .id_machtype = (SM_SUN4M | SM_4M_SS50) }, +{ .name = "Sun4m SparcStation5", .id_machtype = (SM_SUN4M | SM_4M_SS40) }, +/* One entry for the OBP arch's which are sun4d, sun4e, and newer sun4m's */ +{ .name = "Sun4M OBP based system", .id_machtype = (SM_SUN4M_OBP | 0x0) } }; + +static void __init display_system_type(unsigned char machtype) +{ + char sysname[128]; + register int i; + + for (i = 0; i < NUM_SUN_MACHINES; i++) { + if (Sun_Machines[i].id_machtype == machtype) { + if (machtype != (SM_SUN4M_OBP | 0x00) || + prom_getproperty(prom_root_node, "banner-name", + sysname, sizeof(sysname)) <= 0) + printk(KERN_WARNING "TYPE: %s\n", + Sun_Machines[i].name); + else + printk(KERN_WARNING "TYPE: %s\n", sysname); + return; + } + } + + prom_printf("IDPROM: Warning, bogus id_machtype value, 0x%x\n", machtype); +} +#else +static void __init display_system_type(unsigned char machtype) +{ +} +#endif +/* Calculate the IDPROM checksum (xor of the data bytes). */ +static unsigned char __init calc_idprom_cksum(struct idprom *idprom) +{ + unsigned char cksum, i, *ptr = (unsigned char *)idprom; + + for (i = cksum = 0; i <= 0x0E; i++) + cksum ^= *ptr++; + + return cksum; +} + +/* Create a local IDPROM copy, verify integrity, and display information. */ +void __init idprom_init(void) +{ + prom_get_idprom((char *) &idprom_buffer, sizeof(idprom_buffer)); + + idprom = &idprom_buffer; + + if (idprom->id_format != 0x01) + prom_printf("IDPROM: Warning, unknown format type!\n"); + + if (idprom->id_cksum != calc_idprom_cksum(idprom)) + prom_printf("IDPROM: Warning, checksum failure (nvram=%x, calc=%x)!\n", + idprom->id_cksum, calc_idprom_cksum(idprom)); + + display_system_type(idprom->id_machtype); + + printk(KERN_WARNING "Ethernet address: %pM\n", idprom->id_ethaddr); +} diff --git a/pool/shard010/C/0139110_gps_demo.c b/pool/shard010/C/0139110_gps_demo.c new file mode 100644 index 0000000000000000000000000000000000000000..9bdcd18ebdd9d9e9f091f21e9c974d1beab1c67c --- /dev/null +++ b/pool/shard010/C/0139110_gps_demo.c @@ -0,0 +1,29 @@ +#include +#include + +#include "gps_demo.h" +#include +#include + +/* creates random GPSSamp data for simulation. + directly sets samp value rather than generate a cusom NMEA sentence + ** for that see RPiGPSDemo +*/ +int getGPSSample_DEMO(FullGPSData* samp, bool passToLog, void* userData){ + //TODO: introduce some randomizing factor + samp->spdKph = 1.34f; + samp->course = 50.0f; + + samp->longitude = 6.7f; + samp->latitude += 0.5f; + //samp->latitude = samp->latitude + samp->spdKph * sin(samp->course * PI/180); + //samp->longitude = samp->latitude + samp->spdKph * cos(samp->course * PI/180); + samp->altitude = 280.0f; + + char logStr[120]; + sprintf(logStr, "DEMO: lat: %f, lon: %f, alt: %f, crs: %f, spd(kph): %f |", samp->latitude, samp->longitude, + samp->altitude, samp->course, samp->spdKph); + + logEvent(logStr, LOG4C_PRIORITY_INFO, INFO, &logMaster); + return FULL_SAMPLE; +} diff --git a/pool/shard010/C/0139111_zlauu2.c b/pool/shard010/C/0139111_zlauu2.c new file mode 100644 index 0000000000000000000000000000000000000000..d462bd768d02cbb72a17dbc4424fbb3f319df8ba --- /dev/null +++ b/pool/shard010/C/0139111_zlauu2.c @@ -0,0 +1,112 @@ +/*********************************************************************/ +/* */ +/* Optimized BLAS libraries */ +/* By Kazushige Goto */ +/* */ +/* Copyright (c) The University of Texas, 2009. All rights reserved. */ +/* UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING */ +/* THIS SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR ANY PARTICULAR PURPOSE, */ +/* NON-INFRINGEMENT AND WARRANTIES OF PERFORMANCE, AND ANY WARRANTY */ +/* THAT MIGHT OTHERWISE ARISE FROM COURSE OF DEALING OR USAGE OF */ +/* TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH RESPECT TO */ +/* THE USE OF THE SOFTWARE OR DOCUMENTATION. */ +/* Under no circumstances shall University be liable for incidental, */ +/* special, indirect, direct or consequential damages or loss of */ +/* profits, interruption of business, or related expenses which may */ +/* arise from use of Software or Documentation, including but not */ +/* limited to those resulting from defects in Software and/or */ +/* Documentation, or loss or inaccuracy of data of any kind. */ +/*********************************************************************/ + +#include +#include "common.h" +#ifdef FUNCTION_PROFILE +#include "functable.h" +#endif + +#ifdef XDOUBLE +#define ERROR_NAME "QLAUU2" +#elif defined(DOUBLE) +#define ERROR_NAME "ZLAUU2" +#else +#define ERROR_NAME "CLAUU2" +#endif + +static blasint (*lauu2[])(blas_arg_t *, BLASLONG *, BLASLONG *, FLOAT *, FLOAT *, BLASLONG) = { + +#ifdef XDOUBLE + xlauu2_U, xlauu2_L, +#elif defined(DOUBLE) + zlauu2_U, zlauu2_L, +#else + clauu2_U, clauu2_L, +#endif + }; + +int NAME(char *UPLO, blasint *N, FLOAT *a, blasint *ldA, blasint *Info){ + + blas_arg_t args; + + blasint uplo_arg = *UPLO; + blasint uplo; + blasint info; + FLOAT *buffer; +#ifdef PPC440 + extern +#endif + FLOAT *sa, *sb; + + PRINT_DEBUG_NAME; + + args.n = *N; + args.a = (void *)a; + args.lda = *ldA; + + TOUPPER(uplo_arg); + + uplo = -1; + if (uplo_arg == 'U') uplo = 0; + if (uplo_arg == 'L') uplo = 1; + + info = 0; + if (args.lda < MAX(1,args.n)) info = 4; + if (args.n < 0) info = 2; + if (uplo < 0) info = 1; + if (info) { + BLASFUNC(xerbla)(ERROR_NAME, &info, sizeof(ERROR_NAME)); + *Info = - info; + return 0; + } + + *Info = 0; + + if (args.n <= 0) return 0; + + IDEBUG_START; + + FUNCTION_PROFILE_START(); + +#ifndef PPC440 + buffer = (FLOAT *)blas_memory_alloc(1); + + sa = (FLOAT *)((BLASLONG)buffer + GEMM_OFFSET_A); + sb = (FLOAT *)(((BLASLONG)sa + ((GEMM_P * GEMM_Q * COMPSIZE * SIZE + GEMM_ALIGN) & ~GEMM_ALIGN)) + GEMM_OFFSET_B); +#endif + + info = (lauu2[uplo])(&args, NULL, NULL, sa, sb, 0); + + *Info = info; + +#ifndef PPC440 + blas_memory_free(buffer); +#endif + + FUNCTION_PROFILE_END(1, .5 * args.n * args.n, + 2. * args.n * (1./3. + args.n * ( 1./2. + args.n * 1./6.)) + + 6. * 1./6. * args.n * (args.n * args.n - 1)); + + IDEBUG_END; + + return 0; +} diff --git a/pool/shard010/C/0139112_IDL2W_EngTrans.c b/pool/shard010/C/0139112_IDL2W_EngTrans.c new file mode 100644 index 0000000000000000000000000000000000000000..b1ce1b3fbaa42c25ac5c8c54bcfa8c92118f688b --- /dev/null +++ b/pool/shard010/C/0139112_IDL2W_EngTrans.c @@ -0,0 +1,45 @@ +#include "GlobalDef.h" +#include "Input.h" +#include "IDL2W_EngTrans.h" + +// Specific protocol driver library +#include "iDatalink.h" + +volatile Uint8 EngineTransmissionSupported; // This variable is used to store YES if Engine and Transmission Info is supported and No if not +volatile Uint8 EngineType; +volatile Uint8 EngineCylinder; +volatile Uint8 TransmissionType; + +/*******************************************************************************************/ +/* Uint8 IDL2W_SendEngTrans(Uint8 Repeat) */ +/* */ +/* Parameter : Repeat = number of time the message will be sent on the idl2w bus. */ +/* Return value : None */ +/* */ +/* This function sends current engine and transmission info. */ +/*******************************************************************************************/ +void IDL2W_SendEngTrans(Uint8 Repeat) +{ + #if !defined(INCLUDE_RS_INTERFACE) + Uint8 *data; + + // Do not send if not supported + if(EngineTransmissionSupported == NO) + return; + + // Get idatalink buffer for data + data=IDL2W_TX_GetNextBufferPtr(); + + // If fifo is full, return! + if(data == 0) + return; + + data[0]=Repeat; + data[1]=IDL2W_DL_ADDR; + data[2]=IDL2W_ALL_NODES; + data[3]=IDL2W_ENG_TRANS_CODE; + data[4]=1; + data[5]=((EngineType|EngineCylinder)|TransmissionType); + #endif +} + diff --git a/pool/shard010/C/0139113_elanfreq.c b/pool/shard010/C/0139113_elanfreq.c new file mode 100644 index 0000000000000000000000000000000000000000..de08acff5101dd64b93a913905a8961bfd08c69f --- /dev/null +++ b/pool/shard010/C/0139113_elanfreq.c @@ -0,0 +1,234 @@ +/* + * elanfreq: cpufreq driver for the AMD ELAN family + * + * (c) Copyright 2002 Robert Schwebel + * + * Parts of this code are (c) Sven Geggus + * + * All Rights Reserved. + * + * 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. + * + * 2002-02-13: - initial revision for 2.4.18-pre9 by Robert Schwebel + * + */ + +#include +#include +#include + +#include +#include + +#include +#include +#include +#include + +#define REG_CSCIR 0x22 /* Chip Setup and Control Index Register */ +#define REG_CSCDR 0x23 /* Chip Setup and Control Data Register */ + +/* Module parameter */ +static int max_freq; + +struct s_elan_multiplier { + int clock; /* frequency in kHz */ + int val40h; /* PMU Force Mode register */ + int val80h; /* CPU Clock Speed Register */ +}; + +/* + * It is important that the frequencies + * are listed in ascending order here! + */ +static struct s_elan_multiplier elan_multiplier[] = { + {1000, 0x02, 0x18}, + {2000, 0x02, 0x10}, + {4000, 0x02, 0x08}, + {8000, 0x00, 0x00}, + {16000, 0x00, 0x02}, + {33000, 0x00, 0x04}, + {66000, 0x01, 0x04}, + {99000, 0x01, 0x05} +}; + +static struct cpufreq_frequency_table elanfreq_table[] = { + {0, 1000}, + {1, 2000}, + {2, 4000}, + {3, 8000}, + {4, 16000}, + {5, 33000}, + {6, 66000}, + {7, 99000}, + {0, CPUFREQ_TABLE_END}, +}; + + +/** + * elanfreq_get_cpu_frequency: determine current cpu speed + * + * Finds out at which frequency the CPU of the Elan SOC runs + * at the moment. Frequencies from 1 to 33 MHz are generated + * the normal way, 66 and 99 MHz are called "Hyperspeed Mode" + * and have the rest of the chip running with 33 MHz. + */ + +static unsigned int elanfreq_get_cpu_frequency(unsigned int cpu) +{ + u8 clockspeed_reg; /* Clock Speed Register */ + + local_irq_disable(); + outb_p(0x80, REG_CSCIR); + clockspeed_reg = inb_p(REG_CSCDR); + local_irq_enable(); + + if ((clockspeed_reg & 0xE0) == 0xE0) + return 0; + + /* Are we in CPU clock multiplied mode (66/99 MHz)? */ + if ((clockspeed_reg & 0xE0) == 0xC0) { + if ((clockspeed_reg & 0x01) == 0) + return 66000; + else + return 99000; + } + + /* 33 MHz is not 32 MHz... */ + if ((clockspeed_reg & 0xE0) == 0xA0) + return 33000; + + return (1<<((clockspeed_reg & 0xE0) >> 5)) * 1000; +} + + +static int elanfreq_target(struct cpufreq_policy *policy, + unsigned int state) +{ + /* + * Access to the Elan's internal registers is indexed via + * 0x22: Chip Setup & Control Register Index Register (CSCI) + * 0x23: Chip Setup & Control Register Data Register (CSCD) + * + */ + + /* + * 0x40 is the Power Management Unit's Force Mode Register. + * Bit 6 enables Hyperspeed Mode (66/100 MHz core frequency) + */ + + local_irq_disable(); + outb_p(0x40, REG_CSCIR); /* Disable hyperspeed mode */ + outb_p(0x00, REG_CSCDR); + local_irq_enable(); /* wait till internal pipelines and */ + udelay(1000); /* buffers have cleaned up */ + + local_irq_disable(); + + /* now, set the CPU clock speed register (0x80) */ + outb_p(0x80, REG_CSCIR); + outb_p(elan_multiplier[state].val80h, REG_CSCDR); + + /* now, the hyperspeed bit in PMU Force Mode Register (0x40) */ + outb_p(0x40, REG_CSCIR); + outb_p(elan_multiplier[state].val40h, REG_CSCDR); + udelay(10000); + local_irq_enable(); + + return 0; +} +/* + * Module init and exit code + */ + +static int elanfreq_cpu_init(struct cpufreq_policy *policy) +{ + struct cpuinfo_x86 *c = &cpu_data(0); + unsigned int i; + + /* capability check */ + if ((c->x86_vendor != X86_VENDOR_AMD) || + (c->x86 != 4) || (c->x86_model != 10)) + return -ENODEV; + + /* max freq */ + if (!max_freq) + max_freq = elanfreq_get_cpu_frequency(0); + + /* table init */ + for (i = 0; (elanfreq_table[i].frequency != CPUFREQ_TABLE_END); i++) { + if (elanfreq_table[i].frequency > max_freq) + elanfreq_table[i].frequency = CPUFREQ_ENTRY_INVALID; + } + + /* cpuinfo and default policy values */ + policy->cpuinfo.transition_latency = CPUFREQ_ETERNAL; + + return cpufreq_table_validate_and_show(policy, elanfreq_table); +} + + +#ifndef MODULE +/** + * elanfreq_setup - elanfreq command line parameter parsing + * + * elanfreq command line parameter. Use: + * elanfreq=66000 + * to set the maximum CPU frequency to 66 MHz. Note that in + * case you do not give this boot parameter, the maximum + * frequency will fall back to _current_ CPU frequency which + * might be lower. If you build this as a module, use the + * max_freq module parameter instead. + */ +static int __init elanfreq_setup(char *str) +{ + max_freq = simple_strtoul(str, &str, 0); + printk(KERN_WARNING "You're using the deprecated elanfreq command line option. Use elanfreq.max_freq instead, please!\n"); + return 1; +} +__setup("elanfreq=", elanfreq_setup); +#endif + + +static struct cpufreq_driver elanfreq_driver = { + .get = elanfreq_get_cpu_frequency, + .verify = cpufreq_generic_frequency_table_verify, + .target_index = elanfreq_target, + .init = elanfreq_cpu_init, + .exit = cpufreq_generic_exit, + .name = "elanfreq", + .attr = cpufreq_generic_attr, +}; + +static const struct x86_cpu_id elan_id[] = { + { X86_VENDOR_AMD, 4, 10, }, + {} +}; +MODULE_DEVICE_TABLE(x86cpu, elan_id); + +static int __init elanfreq_init(void) +{ + if (!x86_match_cpu(elan_id)) + return -ENODEV; + return cpufreq_register_driver(&elanfreq_driver); +} + + +static void __exit elanfreq_exit(void) +{ + cpufreq_unregister_driver(&elanfreq_driver); +} + + +module_param(max_freq, int, 0444); + +MODULE_LICENSE("GPL"); +MODULE_AUTHOR("Robert Schwebel , " + "Sven Geggus "); +MODULE_DESCRIPTION("cpufreq driver for AMD's Elan CPUs"); + +module_init(elanfreq_init); +module_exit(elanfreq_exit); diff --git a/pool/shard010/C/0139114_mi-cmd-info.c b/pool/shard010/C/0139114_mi-cmd-info.c new file mode 100644 index 0000000000000000000000000000000000000000..aa4d210ed7672557e266226d5da9105812a6a31f --- /dev/null +++ b/pool/shard010/C/0139114_mi-cmd-info.c @@ -0,0 +1,89 @@ +/* MI Command Set - information commands. + Copyright (C) 2011-2013 Free Software Foundation, Inc. + + This file is part of GDB. + + 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 "defs.h" +#include "osdata.h" +#include "mi-cmds.h" +#include "ada-lang.h" +#include "arch-utils.h" + +/* Implement the "-info-ada-exceptions" GDB/MI command. */ + +void +mi_cmd_info_ada_exceptions (char *command, char **argv, int argc) +{ + struct ui_out *uiout = current_uiout; + struct gdbarch *gdbarch = get_current_arch (); + char *regexp; + struct cleanup *old_chain; + VEC(ada_exc_info) *exceptions; + int ix; + struct ada_exc_info *info; + + switch (argc) + { + case 0: + regexp = NULL; + break; + case 1: + regexp = argv[0]; + break; + default: + error (_("Usage: -info-ada-exceptions [REGEXP]")); + break; + } + + exceptions = ada_exceptions_list (regexp); + old_chain = make_cleanup (VEC_cleanup (ada_exc_info), &exceptions); + + make_cleanup_ui_out_table_begin_end + (uiout, 2, VEC_length (ada_exc_info, exceptions), "ada-exceptions"); + ui_out_table_header (uiout, 1, ui_left, "name", "Name"); + ui_out_table_header (uiout, 1, ui_left, "address", "Address"); + ui_out_table_body (uiout); + + for (ix = 0; VEC_iterate(ada_exc_info, exceptions, ix, info); ix++) + { + struct cleanup *sub_chain; + + sub_chain = make_cleanup_ui_out_tuple_begin_end (uiout, NULL); + ui_out_field_string (uiout, "name", info->name); + ui_out_field_core_addr (uiout, "address", gdbarch, info->addr); + + do_cleanups (sub_chain); + } + + do_cleanups (old_chain); +} + +void +mi_cmd_info_os (char *command, char **argv, int argc) +{ + switch (argc) + { + case 0: + info_osdata_command ("", 0); + break; + case 1: + info_osdata_command (argv[0], 0); + break; + default: + error (_("Usage: -info-os [INFOTYPE]")); + break; + } +} diff --git a/pool/shard010/C/0139115_test_Ttmm.c b/pool/shard010/C/0139115_test_Ttmm.c new file mode 100644 index 0000000000000000000000000000000000000000..a5d2d979ee429b56e64656462f504b7ded061750 --- /dev/null +++ b/pool/shard010/C/0139115_test_Ttmm.c @@ -0,0 +1,183 @@ +/* + + Copyright (C) 2014, The University of Texas at Austin + + This file is part of libflame and is available under the 3-Clause + BSD license, which can be found in the LICENSE file at the top-level + directory, or at http://opensource.org/licenses/BSD-3-Clause + +*/ + +#include "FLAME.h" + +#define N_PARAM_COMBOS 2 + +#define FLA_ALG_REFERENCE 0 +#define FLA_ALG_FRONT 1 + +char* pc_str[N_PARAM_COMBOS] = { "l", "u" }; + +void time_Ttmm( + int param_combo, int type, int n_repeats, int m, FLA_Uplo uplo, + FLA_Obj A, FLA_Obj x, FLA_Obj b, FLA_Obj norm, + double *dtime, double *diff, double *gflops ); + + +int main(int argc, char *argv[]) +{ + int + datatype, + m_input, + m, + p_first, p_last, p_inc, + p, + n_repeats, + param_combo, + i, + n_param_combos = N_PARAM_COMBOS; + + FLA_Uplo uplo; + + char *colors = "brkgmcbrkg"; + char *ticks = "o+*xso+*xs"; + char m_dim_desc[14]; + char m_dim_tag[10]; + + double max_gflops=6.0; + + double + dtime, + gflops, + diff; + + FLA_Obj + A, x, b, norm; + + + FLA_Init(); + + + fprintf( stdout, "%c number of repeats:", '%' ); + scanf( "%d", &n_repeats ); + fprintf( stdout, "%c %d\n", '%', n_repeats ); + + fprintf( stdout, "%c enter problem size first, last, inc:", '%' ); + scanf( "%d%d%d", &p_first, &p_last, &p_inc ); + fprintf( stdout, "%c %d %d %d\n", '%', p_first, p_last, p_inc ); + + fprintf( stdout, "%c enter m (-1 means bind to problem size): ", '%' ); + scanf( "%d", &m_input ); + fprintf( stdout, "%c %d\n", '%', m_input ); + + + fprintf( stdout, "\nclear all;\n\n" ); + + + if ( m_input > 0 ) { + sprintf( m_dim_desc, "m = %d", m_input ); + sprintf( m_dim_tag, "m%dc", m_input); + } + else if( m_input < -1 ) { + sprintf( m_dim_desc, "m = p/%d", -m_input ); + sprintf( m_dim_tag, "m%dp", -m_input ); + } + else if( m_input == -1 ) { + sprintf( m_dim_desc, "m = p" ); + sprintf( m_dim_tag, "m%dp", 1 ); + } + + //datatype = FLA_FLOAT; + //datatype = FLA_DOUBLE; + //datatype = FLA_COMPLEX; + datatype = FLA_DOUBLE_COMPLEX; + + for ( p = p_first, i = 1; p <= p_last; p += p_inc, i += 1 ) + { + m = m_input; + + if( m < 0 ) m = p / abs(m_input); + + for ( param_combo = 0; param_combo < n_param_combos; param_combo++ ){ + + FLA_Obj_create( datatype, m, m, 0, 0, &A ); + FLA_Obj_create( datatype, m, 1, 0, 0, &x ); + FLA_Obj_create( datatype, m, 1, 0, 0, &b ); + +/* + FLA_Obj_create( datatype, m, m, m, 1, &A ); + FLA_Obj_create( datatype, m, 1, 1, 1, &x ); + FLA_Obj_create( datatype, m, 1, 1, 1, &b ); +*/ + + if ( FLA_Obj_is_single_precision( A ) ) + FLA_Obj_create( FLA_FLOAT, 1, 1, 0, 0, &norm ); + else + FLA_Obj_create( FLA_DOUBLE, 1, 1, 0, 0, &norm ); + + FLA_Param_map_netlib_to_flame_uplo( &pc_str[param_combo][0], &uplo ); + + FLA_Random_spd_matrix( uplo, A ); + FLA_Random_matrix( b ); + + fprintf( stdout, "data_ttmm_%s( %d, 1:5 ) = [ %d ", pc_str[param_combo], i, p ); + fflush( stdout ); + +/* + time_Ttmm( param_combo, FLA_ALG_REFERENCE, n_repeats, m, uplo, + A, x, b, norm, &dtime, &diff, &gflops ); + + fprintf( stdout, "%6.3lf %6.2le ", gflops, diff ); + fflush( stdout ); +*/ + + time_Ttmm( param_combo, FLA_ALG_FRONT, n_repeats, m, uplo, + A, x, b, norm, &dtime, &diff, &gflops ); + + fprintf( stdout, "%6.3lf %6.2le ", gflops, diff ); + fflush( stdout ); + + fprintf( stdout, " ]; \n" ); + fflush( stdout ); + + FLA_Obj_free( &A ); + FLA_Obj_free( &x ); + FLA_Obj_free( &b ); + FLA_Obj_free( &norm ); + } + + fprintf( stdout, "\n" ); + } + +/* + fprintf( stdout, "figure;\n" ); + + fprintf( stdout, "hold on;\n" ); + + for ( i = 0; i < n_param_combos; i++ ) { + fprintf( stdout, "plot( data_ttmm_%s( :,1 ), data_ttmm_%s( :, 2 ), '%c:%c' ); \n", + pc_str[i], pc_str[i], colors[ i ], ticks[ i ] ); + fprintf( stdout, "plot( data_ttmm_%s( :,1 ), data_ttmm_%s( :, 4 ), '%c-.%c' ); \n", + pc_str[i], pc_str[i], colors[ i ], ticks[ i ] ); + } + + fprintf( stdout, "legend( ... \n" ); + + for ( i = 0; i < n_param_combos; i++ ) + fprintf( stdout, "'ref\\_ttmm\\_%s', 'fla\\_ttmm\\_%s', ... \n", pc_str[i], pc_str[i] ); + + fprintf( stdout, "'Location', 'SouthWest' ); \n" ); + + fprintf( stdout, "xlabel( 'problem size p' );\n" ); + fprintf( stdout, "ylabel( 'GFLOPS/sec.' );\n" ); + fprintf( stdout, "axis( [ 0 %d 0 %.2f ] ); \n", p_last, max_gflops ); + fprintf( stdout, "title( 'FLAME ttmm front-end performance (%s)' );\n", m_dim_desc ); + fprintf( stdout, "print -depsc ttmm_front_%s.eps\n", m_dim_tag ); + fprintf( stdout, "hold off;\n"); + fflush( stdout ); +*/ + + FLA_Finalize( ); + + return 0; +} + diff --git a/pool/shard010/C/0139116_26.c b/pool/shard010/C/0139116_26.c new file mode 100644 index 0000000000000000000000000000000000000000..dd2978a57d90faf26ee3c1de552b7e030096d49c --- /dev/null +++ b/pool/shard010/C/0139116_26.c @@ -0,0 +1,19 @@ +#include + +int main() +{ + char string_array[1024] ="123fdd"; + int i,count_number = 0,count_char = 0; + + for( i = 0; string_array[i] != '\0' ; i++) + { + char e = string_array[i]; + if( (e>='a' && e<='z') || (e>='A' && e<='Z')) + count_char += 1; + if( e>='0' && e<='9') + count_number += 1; + printf("%c",e); + } + printf("\nchar counts:%d\tnunber counts:%d",count_number,count_char); + return 0; +} diff --git a/pool/shard010/C/0139117_rx_buffers_append.c b/pool/shard010/C/0139117_rx_buffers_append.c new file mode 100644 index 0000000000000000000000000000000000000000..ce8fa5e0671aa9708a05592a5b2cf5b4df94b10b --- /dev/null +++ b/pool/shard010/C/0139117_rx_buffers_append.c @@ -0,0 +1,107 @@ +#include "_eth_include.h" + + +#ifdef _ETH // the Ethernet device is present + +/**************************************************************************** + * Function: EthRxBuffersAppend + * + * PreCondition: EthInit, EthAddDescriptors, EthRxSetBufferSize should have been called. + * each buffer supplied should be >= EthRxSetBufferSize(). + * + * Input: ppBuff - pointer to an array of buffers (could be NULL terminated) to be appended to the receiving process + * nBuffs - number of buffers supplied (or 0 if ppBuff is NULL terminated) + * rxFlags - flags applied to all RX buffers passed + * + * Output: ETH_RES_OK for success, + * an error code otherwise + * + * Side Effects: None + * + * Overview: This function supplies buffers to the receiving process and enables the receiving part of the controller. + * As soon as the controller starts receiving data packets these will be stored into memory + * at the addresses specified by these buffers. + * A received packet can consist of multiple buffers, split across buffers with the SAME size, as specified in the EthRxSetBufferSize(). + * Each buffer needs an associated receive descriptor. Therefore, the number of needed + * receive descriptors should be available for this function to succeed. + * Once a receive operation is scheduled, EthRxPacket() can be called to get the received packet. + * + * Note: - Not multithreaded safe. Don't call from from both ISR -non ISR code or multiple ISR's! + * - This function enables the Ethernet receiving. + * - When a packet is split into multiple buffers, all buffers have the same size, set by the EthRxSetBufferSize(). + * - The append process continues until a NULL buffer pointer is retrieved or nBuffs buffers are appended. + * - Only RX eEthBuffFlags are relevant for this function + *****************************************************************************/ +eEthRes EthRxBuffersAppend(void* ppBuff[], int nBuffs, eEthBuffFlags rxFlags) +{ + void* pBuff; + sEthDNode *pEDcpt; + eEthRes res=ETH_RES_OK; + sEthDcptList newList={0, 0}; + + if(nBuffs==0) + { + nBuffs=0x7fffffff; + } + + for(pBuff=*ppBuff; pBuff!=0 && nBuffs; pBuff=*(++ppBuff), nBuffs--) + { + pEDcpt=SlRemoveHead(&_EthRxFreeList); + if(!pEDcpt) + { // we've run out of descriptors... + res=ETH_RES_NO_DESCRIPTORS; + break; + } + // ok valid descriptor + // pas it to hw, always use linked descriptors + pEDcpt->hwDcpt.pEDBuff=(unsigned char*)KVA_TO_PA(pBuff); + + pEDcpt->hwDcpt.hdr.w=_SDCPT_HDR_NPV_MASK_|_SDCPT_HDR_EOWN_MASK_; // hw owned + + if(rxFlagsÐ_BUFF_FLAG_RX_STICKY) + { + pEDcpt->hwDcpt.hdr.sticky=1; + } + + if(rxFlagsÐ_BUFF_FLAG_RX_UNACK) + { + pEDcpt->hwDcpt.hdr.rx_nack=1; + } + + if(IS_KVA0(pBuff)) + { + pEDcpt->hwDcpt.hdr.kv0=1; + } + else if(!IS_KVA(pBuff)) + { + res=ETH_RES_USPACE_ERR; + break; + } + + SlAddTail(&newList, pEDcpt); + } + + if(pBuff && nBuffs) + { // failed, still buffers in the descriptors, put back the removed nodes + SlAppendTail(&_EthRxFreeList, &newList); + return res; + } + + // all's well + if(!SlIsEmpty(&newList)) + { + _EthAppendBusyList(&_EthRxBusyList, &newList, 1); + + if(ETHRXST==0) + { // 1st time reception! + ETHRXST=KVA_TO_PA(&_EthRxBusyList.head->hwDcpt); + } + ETHCON1SET=_ETHCON1_RXEN_MASK; // and we're running! + } + + return ETH_RES_OK; + +} + + +#endif // _ETH diff --git a/pool/shard010/C/0139118_test-ext-handle-scope-root.c b/pool/shard010/C/0139118_test-ext-handle-scope-root.c new file mode 100644 index 0000000000000000000000000000000000000000..a3c2a3da5fec727da81e1f2da2741921e9cd6130 --- /dev/null +++ b/pool/shard010/C/0139118_test-ext-handle-scope-root.c @@ -0,0 +1,74 @@ +/* Copyright JS Foundation and other contributors, http://js.foundation + * + * 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. + */ + +/** + * Unit test for jerry-ext/handle-scope. + */ + +#include "jerryscript.h" +#include "jerryscript-ext/handle-scope.h" +#include "test-common.h" + +static int native_free_cb_call_count; +static int reusing_times = 10; + +static void +native_free_cb (void *native_p) +{ + ++native_free_cb_call_count; + (void) native_p; +} /* native_free_cb */ + +static const jerry_object_native_info_t native_info = +{ + .free_cb = native_free_cb, +}; + +static jerry_value_t +create_object (void) +{ + jerry_value_t obj = jerry_create_object (); + jerry_set_object_native_pointer (obj, NULL, &native_info); + return obj; +} /* create_object */ + +static void +test_handle_scope_val (void) +{ + jerryx_escapable_handle_scope root = jerryx_handle_scope_get_root (); + // root handle scope should always be reusable after close + for (int i = 0; i < reusing_times; ++i) + { + jerry_value_t obj = jerryx_create_handle (create_object ()); + (void) obj; + jerryx_close_handle_scope (root); + jerry_gc (JERRY_GC_PRESSURE_LOW); + TEST_ASSERT (native_free_cb_call_count == (i + 1)); + } +} /* test_handle_scope_val */ + +int +main (void) +{ + jerry_init (JERRY_INIT_EMPTY); + + native_free_cb_call_count = 0; + test_handle_scope_val (); + + jerry_gc (JERRY_GC_PRESSURE_LOW); + TEST_ASSERT (native_free_cb_call_count == reusing_times); + + jerry_cleanup (); +} /* main */ diff --git a/pool/shard010/C/0139119_DeltaACK-r11.c b/pool/shard010/C/0139119_DeltaACK-r11.c new file mode 100644 index 0000000000000000000000000000000000000000..b604514836e2a6be82512c651a1feec1854fece6 --- /dev/null +++ b/pool/shard010/C/0139119_DeltaACK-r11.c @@ -0,0 +1,146 @@ +/* + * Generated by asn1c-0.9.24 (http://lionet.info/asn1c) + * From ASN.1 module "InformationElements" + * found in "../asn/InformationElements.asn" + * `asn1c -fcompound-names -fnative-types` + */ + +#include "DeltaACK-r11.h" + +int +DeltaACK_r11_constraint(asn_TYPE_descriptor_t *td, const void *sptr, + asn_app_constraint_failed_f *ctfailcb, void *app_key) { + long value; + + if(!sptr) { + _ASN_CTFAIL(app_key, td, sptr, + "%s: value not given (%s:%d)", + td->name, __FILE__, __LINE__); + return -1; + } + + value = *(const long *)sptr; + + if((value >= 0 && value <= 10)) { + /* Constraint check succeeded */ + return 0; + } else { + _ASN_CTFAIL(app_key, td, sptr, + "%s: constraint failed (%s:%d)", + td->name, __FILE__, __LINE__); + return -1; + } +} + +/* + * This type is implemented using NativeInteger, + * so here we adjust the DEF accordingly. + */ +static void +DeltaACK_r11_1_inherit_TYPE_descriptor(asn_TYPE_descriptor_t *td) { + td->free_struct = asn_DEF_NativeInteger.free_struct; + td->print_struct = asn_DEF_NativeInteger.print_struct; + td->ber_decoder = asn_DEF_NativeInteger.ber_decoder; + td->der_encoder = asn_DEF_NativeInteger.der_encoder; + td->xer_decoder = asn_DEF_NativeInteger.xer_decoder; + td->xer_encoder = asn_DEF_NativeInteger.xer_encoder; + td->uper_decoder = asn_DEF_NativeInteger.uper_decoder; + td->uper_encoder = asn_DEF_NativeInteger.uper_encoder; + if(!td->per_constraints) + td->per_constraints = asn_DEF_NativeInteger.per_constraints; + td->elements = asn_DEF_NativeInteger.elements; + td->elements_count = asn_DEF_NativeInteger.elements_count; + td->specifics = asn_DEF_NativeInteger.specifics; +} + +void +DeltaACK_r11_free(asn_TYPE_descriptor_t *td, + void *struct_ptr, int contents_only) { + DeltaACK_r11_1_inherit_TYPE_descriptor(td); + td->free_struct(td, struct_ptr, contents_only); +} + +int +DeltaACK_r11_print(asn_TYPE_descriptor_t *td, const void *struct_ptr, + int ilevel, asn_app_consume_bytes_f *cb, void *app_key) { + DeltaACK_r11_1_inherit_TYPE_descriptor(td); + return td->print_struct(td, struct_ptr, ilevel, cb, app_key); +} + +asn_dec_rval_t +DeltaACK_r11_decode_ber(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td, + void **structure, const void *bufptr, size_t size, int tag_mode) { + DeltaACK_r11_1_inherit_TYPE_descriptor(td); + return td->ber_decoder(opt_codec_ctx, td, structure, bufptr, size, tag_mode); +} + +asn_enc_rval_t +DeltaACK_r11_encode_der(asn_TYPE_descriptor_t *td, + void *structure, int tag_mode, ber_tlv_tag_t tag, + asn_app_consume_bytes_f *cb, void *app_key) { + DeltaACK_r11_1_inherit_TYPE_descriptor(td); + return td->der_encoder(td, structure, tag_mode, tag, cb, app_key); +} + +asn_dec_rval_t +DeltaACK_r11_decode_xer(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td, + void **structure, const char *opt_mname, const void *bufptr, size_t size) { + DeltaACK_r11_1_inherit_TYPE_descriptor(td); + return td->xer_decoder(opt_codec_ctx, td, structure, opt_mname, bufptr, size); +} + +asn_enc_rval_t +DeltaACK_r11_encode_xer(asn_TYPE_descriptor_t *td, void *structure, + int ilevel, enum xer_encoder_flags_e flags, + asn_app_consume_bytes_f *cb, void *app_key) { + DeltaACK_r11_1_inherit_TYPE_descriptor(td); + return td->xer_encoder(td, structure, ilevel, flags, cb, app_key); +} + +asn_dec_rval_t +DeltaACK_r11_decode_uper(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td, + asn_per_constraints_t *constraints, void **structure, asn_per_data_t *per_data) { + DeltaACK_r11_1_inherit_TYPE_descriptor(td); + return td->uper_decoder(opt_codec_ctx, td, constraints, structure, per_data); +} + +asn_enc_rval_t +DeltaACK_r11_encode_uper(asn_TYPE_descriptor_t *td, + asn_per_constraints_t *constraints, + void *structure, asn_per_outp_t *per_out) { + DeltaACK_r11_1_inherit_TYPE_descriptor(td); + return td->uper_encoder(td, constraints, structure, per_out); +} + +static asn_per_constraints_t asn_PER_type_DeltaACK_r11_constr_1 = { + { APC_CONSTRAINED, 4, 4, 0, 10 } /* (0..10) */, + { APC_UNCONSTRAINED, -1, -1, 0, 0 }, + 0, 0 /* No PER value map */ +}; +static ber_tlv_tag_t asn_DEF_DeltaACK_r11_tags_1[] = { + (ASN_TAG_CLASS_UNIVERSAL | (2 << 2)) +}; +asn_TYPE_descriptor_t asn_DEF_DeltaACK_r11 = { + "DeltaACK-r11", + "DeltaACK-r11", + DeltaACK_r11_free, + DeltaACK_r11_print, + DeltaACK_r11_constraint, + DeltaACK_r11_decode_ber, + DeltaACK_r11_encode_der, + DeltaACK_r11_decode_xer, + DeltaACK_r11_encode_xer, + DeltaACK_r11_decode_uper, + DeltaACK_r11_encode_uper, + 0, /* Use generic outmost tag fetcher */ + asn_DEF_DeltaACK_r11_tags_1, + sizeof(asn_DEF_DeltaACK_r11_tags_1) + /sizeof(asn_DEF_DeltaACK_r11_tags_1[0]), /* 1 */ + asn_DEF_DeltaACK_r11_tags_1, /* Same as above */ + sizeof(asn_DEF_DeltaACK_r11_tags_1) + /sizeof(asn_DEF_DeltaACK_r11_tags_1[0]), /* 1 */ + &asn_PER_type_DeltaACK_r11_constr_1, + 0, 0, /* No members */ + 0 /* No specifics */ +}; + diff --git a/pool/shard010/C/0139120_ofdt.c b/pool/shard010/C/0139120_ofdt.c new file mode 100644 index 0000000000000000000000000000000000000000..fd61de537c8a3b395195c01510ac9975d8ab6075 --- /dev/null +++ b/pool/shard010/C/0139120_ofdt.c @@ -0,0 +1,147 @@ +/** + * @file ofdt.c + * + * Copyright (C) 2005 IBM Corporation + * Common Public License Version 1.0 (see COPYRIGHT) + * + * @author John Rose + */ + +#include +#include +#include +#include +#include +#include "librtas.h" +#include "common.h" + +static const char *ofdt_rtas_path = "/proc/device-tree/rtas"; + +/** + * open_prop_file + * @brief Open the property name located at the specified property path + * + * @param prop_path path to the property name + * @param prop_name property name + * @param fd reference to file descriptor + * @return 0 on success, -1 on failure + */ +static int open_prop_file(const char *prop_path, const char *prop_name, int *fd) +{ + char *path; + int len; + + /* allocate enough for two string, a slash and trailing NULL */ + len = strlen(prop_path) + strlen(prop_name) + 1 + 1; + path = malloc(len); + if (path == NULL) { + errno = ENOMEM; + return -1; + } + + snprintf(path, len, "%s/%s", prop_path, prop_name); + + *fd = open(path, O_RDONLY); + free(path); + if (*fd < 0) { + errno = ENOSYS; + return -1; + } + + return 0; +} + +/** + * get_property + * @brief Open a property file and read in its contents + * + * @param prop_path path to the property file + * @param prop_name propery name + * @param prop_val + * @param prop_len + * @return 0 on success, !0 otherwise + */ +static int +get_property(const char *prop_path, const char *prop_name, char **prop_val, + size_t * prop_len) +{ + int fd; + int rc; + + rc = open_prop_file(prop_path, prop_name, &fd); + if (rc) + return rc; + + rc = read_entire_file(fd, prop_val, prop_len); + close(fd); + + return rc; +} + +/** + * rtas_token + * @brief Retrive a rtas token for a given name + * + * @param call_name rtas name to retrieve token for + * @return 0 on success, !0 otherwise + */ +int rtas_token(const char *call_name) +{ + char *prop_buf = NULL; + size_t len; + int rc; + + rc = get_property(ofdt_rtas_path, call_name, &prop_buf, &len); + if (rc < 0) + return RTAS_UNKNOWN_OP; + + rc = *(int *)prop_buf; + free(prop_buf); + + return rc; +} + +#define BLOCK_SIZE 4096 + +/** + * read_entire_file + * @brief Read in an entire file into the supplied buffer + * + * @param fd opened file descriptor for file to read + * @param buf buffer to read file into + * @param len variable to return amount read into buffer + * @return 0 on success, !0 otherwise + */ +int read_entire_file(int fd, char **buf, size_t * len) +{ + size_t buf_size = 0; + size_t off = 0; + int rc; + + *buf = NULL; + do { + buf_size += BLOCK_SIZE; + if (*buf == NULL) + *buf = malloc(buf_size); + else + *buf = realloc(*buf, buf_size); + + if (*buf == NULL) { + errno = ENOMEM; + return -1; + } + + rc = read(fd, *buf + off, BLOCK_SIZE); + if (rc < 0) { + dbg1("read failed\n"); + errno = EIO; + return -1; + } + off += rc; + } while (rc == BLOCK_SIZE); + + if (len) + *len = off; + + return 0; +} diff --git a/pool/shard010/C/0139121_isp_k_fetch.c b/pool/shard010/C/0139121_isp_k_fetch.c new file mode 100644 index 0000000000000000000000000000000000000000..3784c03833acebc62ae85ee204d9297552bd5564 --- /dev/null +++ b/pool/shard010/C/0139121_isp_k_fetch.c @@ -0,0 +1,133 @@ +/* + * Copyright (C) 2012 Spreadtrum Communications Inc. + * + * This software is licensed under the terms of the GNU General Public + * License version 2, as published by the Free Software Foundation, and + * may be copied, distributed, and modified under those terms. + * + * 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. + */ +#include +#include +#include