diff --git a/pool/shard000/C++/0000002_gen_menge_grid.cpp b/pool/shard000/C++/0000002_gen_menge_grid.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f4d601ef1d2d390bf207c25781f9f52c92fca597 --- /dev/null +++ b/pool/shard000/C++/0000002_gen_menge_grid.cpp @@ -0,0 +1,64 @@ +#include + +#include +#include +#include + +#define GLM_FORCE_RADIANS +#include + +enum { + TOTAL_ITERATIONS = 3 +}; + +bool is_in_sierpinski_carpet(unsigned int i, unsigned int j) +{ + while (i != 0 && j != 0) { + if (i % 3 == 1 && j % 3 == 1) { + return false; + } + i /= 3; + j /= 3; + } + return true; +} + +bool is_in_menge_sponge(unsigned int i, unsigned int j, unsigned int k) +{ + if (!is_in_sierpinski_carpet(i, j)) { + return false; + } + if (!is_in_sierpinski_carpet(j, k)) { + return false; + } + if (!is_in_sierpinski_carpet(k, i)) { + return false; + } + return true; +} + +int main() +{ + const int grid_side_len = pow(3, TOTAL_ITERATIONS); + const int grid_size = (int)pow(grid_side_len, 2); + int grid[grid_side_len][grid_side_len]; + std::vector instance_displacements; + + for (unsigned int i = 0; i < grid_side_len; i++){ + for (unsigned int j = 0; j < grid_side_len; j++) { + for (unsigned int k = 0; k < grid_side_len; k++) { + if (is_in_menge_sponge(i, j, k)) { + instance_displacements.push_back( + glm::vec3(i * 2.0f,j * 2.0f,k * -2.0f)); + } + } + } + } + + fprintf(stdout, "%lu \n", instance_displacements.size()); + fwrite( + &instance_displacements[0], + sizeof(instance_displacements[0]), + instance_displacements.size(), + stdout); +} diff --git a/pool/shard000/C++/0000009_fp_FieldTOCNum.cpp b/pool/shard000/C++/0000009_fp_FieldTOCNum.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8d3bacd09cad615f740860ca9648d9f76ca35396 --- /dev/null +++ b/pool/shard000/C++/0000009_fp_FieldTOCNum.cpp @@ -0,0 +1,214 @@ +/* AbiWord + * Copyright (C) 1998 AbiSource, Inc. + * BIDI Copyright (c) 2001,2002 Tomas Frydrych + * (C) Martin Sevior 2004, , + * + * 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 "fp_FieldTOCNum.h" +#include "fl_BlockLayout.h" +#include "pt_Types.h" +#include "pd_Document.h" +#include "fl_DocLayout.h" +#include "fp_Line.h" +#include "ut_debugmsg.h" +#include "fl_TOCLayout.h" +#include + +fp_FieldTOCNumRun::fp_FieldTOCNumRun(fl_BlockLayout* pBL,UT_uint32 iOffsetFirst, UT_uint32 iLen) : fp_FieldRun(pBL,iOffsetFirst, iLen) +{ + UT_ASSERT(pBL); + _setDirection(pBL->getDominantDirection()); +} + +bool fp_FieldTOCNumRun::calculateValue(void) +{ + UT_UCSChar sz_ucs_FieldValue[FPFIELD_MAX_LENGTH + 1]; +// +// First Find page number. +// + PL_StruxDocHandle sdh = getBlock()->getStruxDocHandle(); + PD_Document * pDoc = getBlock()->getDocument(); + PT_DocPosition pos = pDoc->getStruxPosition(sdh)+1; + FL_DocLayout * pLayout = getBlock()->getDocLayout(); + fl_BlockLayout * pBlockInDoc = pLayout->findBlockAtPosition(pos); + if(pBlockInDoc == NULL) + { + sz_ucs_FieldValue[0] = static_cast(' '); + sz_ucs_FieldValue[1] = 0; + return _setValue(sz_ucs_FieldValue); + } + fp_Line * pLine = static_cast(pBlockInDoc->getFirstContainer()); + if(pLine == NULL) + { + sz_ucs_FieldValue[0] = static_cast(' '); + sz_ucs_FieldValue[1] = 0; + return _setValue(sz_ucs_FieldValue); + } + fp_Page * pPage = pLine->getPage(); + UT_sint32 iPage = pLayout->findPage(pPage); + if( iPage < 0) + { + sz_ucs_FieldValue[0] = static_cast(' '); + sz_ucs_FieldValue[1] = 0; + return _setValue(sz_ucs_FieldValue); + } + iPage++; // Start from Page 1. + UT_String sVal(""); + FootnoteType iType = getBlock()->getTOCNumType(); + pLayout->getStringFromFootnoteVal(sVal,iPage,iType); + const char * psz = sVal.c_str(); + bool bStop = false; + UT_sint32 i = 0; + sz_ucs_FieldValue[0] = static_cast(' '); + for(i=1; (i(*psz); + if(*psz == 0) + { + bStop = true; + } + else + { + psz++; + } + } + return _setValue(sz_ucs_FieldValue); +} + +void fp_FieldTOCNumRun::_draw(dg_DrawArgs* pDA) +{ + _defaultDraw(pDA); +} + +void fp_FieldTOCNumRun::_lookupProperties(const PP_AttrProp * pSpanAP, + const PP_AttrProp * pBlockAP, + const PP_AttrProp * pSectionAP, + GR_Graphics * pG) +{ + fp_FieldRun::_lookupProperties (pSpanAP, pBlockAP, pSectionAP,pG) ; +} + +///////////////////////////////////////////////////////////////////////////// + + +fp_FieldTOCListLabelRun::fp_FieldTOCListLabelRun(fl_BlockLayout* pBL,UT_uint32 iOffsetFirst, UT_uint32 iLen) : fp_FieldRun(pBL,iOffsetFirst, iLen) +{ + UT_ASSERT(pBL); + _setDirection(pBL->getDominantDirection()); + _setLength(0); +} + +bool fp_FieldTOCListLabelRun::calculateValue(void) +{ + UT_UCSChar sz_ucs_FieldValue[FPFIELD_MAX_LENGTH + 1]; +// +// First get owning TOC. +// + UT_ASSERT(getLength() == 0); + fl_TOCLayout * pTOCL = static_cast(getBlock()->myContainingLayout()); + UT_ASSERT(pTOCL->getContainerType() == FL_CONTAINER_TOC); + UT_String str = pTOCL->getTOCListLabel(getBlock()).utf8_str(); + if(str.size() == 0) + { + sz_ucs_FieldValue[0] = 0; + return _setValue(sz_ucs_FieldValue); + } + UT_sint32 i = 0; + bool bStop = false; + for(i=0; (i(str[i]); + if(str[i] == 0) + { + bStop = true; + } + } + return _setValue(sz_ucs_FieldValue); +} + +void fp_FieldTOCListLabelRun::_draw(dg_DrawArgs* pDA) +{ + _defaultDraw(pDA); +} + +void fp_FieldTOCListLabelRun::_lookupProperties(const PP_AttrProp * pSpanAP, + const PP_AttrProp * pBlockAP, + const PP_AttrProp * pSectionAP, + GR_Graphics * pG) +{ + fp_FieldRun::_lookupProperties (pSpanAP, pBlockAP, pSectionAP,pG) ; + _setLength(0); +} + +//////////////////////////////////////////////////////////////////////////// + + +fp_FieldTOCHeadingRun::fp_FieldTOCHeadingRun(fl_BlockLayout* pBL,UT_uint32 iOffsetFirst, UT_uint32 iLen) : fp_FieldRun(pBL,iOffsetFirst, iLen) +{ + UT_ASSERT(pBL); + _setDirection(pBL->getDominantDirection()); + _setLength(0); +} + +bool fp_FieldTOCHeadingRun::calculateValue(void) +{ + UT_UCSChar sz_ucs_FieldValue[FPFIELD_MAX_LENGTH + 1]; +// +// First get owning TOC. +// + UT_ASSERT(getLength() == 0); + fl_TOCLayout * pTOCL = static_cast(getBlock()->myContainingLayout()); + UT_ASSERT(pTOCL->getContainerType() == FL_CONTAINER_TOC); + UT_UCS4String str = pTOCL->getTOCHeading().ucs4_str(); + if(str.size() == 0) + { + sz_ucs_FieldValue[0] = 0; + return _setValue(sz_ucs_FieldValue); + } + UT_sint32 i = 0; + bool bStop = false; + + for(i=0; (i(str[i]); + if(str[i] == 0) + { + bStop = true; + } + } + return _setValue(sz_ucs_FieldValue); +} + +void fp_FieldTOCHeadingRun::_draw(dg_DrawArgs* pDA) +{ + _defaultDraw(pDA); +} + +void fp_FieldTOCHeadingRun::_lookupProperties(const PP_AttrProp * pSpanAP, + const PP_AttrProp * pBlockAP, + const PP_AttrProp * pSectionAP, + GR_Graphics * pG) +{ + fp_FieldRun::_lookupProperties (pSpanAP, pBlockAP, pSectionAP,pG) ; + _setLength(0); +} + + + + diff --git a/pool/shard000/C++/0000012_android_cache_database_unittest.cc b/pool/shard000/C++/0000012_android_cache_database_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..8d51ffa8b9f25dc48b23189b730b6145aca264cc --- /dev/null +++ b/pool/shard000/C++/0000012_android_cache_database_unittest.cc @@ -0,0 +1,115 @@ +// 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 "components/history/core/browser/android/android_cache_database.h" + +#include "base/files/file_path.h" +#include "base/files/scoped_temp_dir.h" +#include "base/strings/utf_string_conversions.h" +#include "chrome/test/base/testing_profile.h" +#include "components/history/core/browser/android/android_time.h" +#include "components/history/core/browser/history_database.h" +#include "components/history/core/test/test_history_database.h" +#include "testing/gtest/include/gtest/gtest.h" + +using base::Time; +using base::TimeDelta; + +namespace history { + +class AndroidCacheDatabaseTest : public testing::Test { + public: + AndroidCacheDatabaseTest() {} + ~AndroidCacheDatabaseTest() override {} + + protected: + void SetUp() override { + // Get a temporary directory for the test DB files. + ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); + base::FilePath history_db_name_ = + temp_dir_.path().AppendASCII("history.db"); + android_cache_db_name_ = temp_dir_.path().AppendASCII( + "TestAndroidCache.db"); + ASSERT_EQ(sql::INIT_OK, history_db_.Init(history_db_name_)); + ASSERT_EQ(sql::INIT_OK, + history_db_.InitAndroidCacheDatabase(android_cache_db_name_)); + } + + base::ScopedTempDir temp_dir_; + base::FilePath android_cache_db_name_; + TestHistoryDatabase history_db_; +}; + +TEST(AndroidCacheDatabaseAttachTest, AttachDatabaseInTransactionNesting) { + base::ScopedTempDir temp_dir; + base::FilePath android_cache_db_name; + TestHistoryDatabase history_db; + ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); + base::FilePath history_db_name = temp_dir.path().AppendASCII("history.db"); + android_cache_db_name = temp_dir.path().AppendASCII( + "TestAndroidCache.db"); + ASSERT_EQ(sql::INIT_OK, history_db.Init(history_db_name)); + // Create nested transactions. + history_db.BeginTransaction(); + history_db.BeginTransaction(); + history_db.BeginTransaction(); + int transaction_nesting = history_db.transaction_nesting(); + ASSERT_EQ(sql::INIT_OK, + history_db.InitAndroidCacheDatabase(android_cache_db_name)); + // The count of nested transaction is still same. + EXPECT_EQ(transaction_nesting, history_db.transaction_nesting()); +} + +TEST_F(AndroidCacheDatabaseTest, InitAndroidCacheDatabase) { + // Try to run a sql against the table to verify them exist. + AndroidCacheDatabase* cache_db = + static_cast(&history_db_); + EXPECT_TRUE(cache_db->GetDB().Execute( + "DELETE FROM android_cache_db.bookmark_cache")); + EXPECT_TRUE(cache_db->GetDB().Execute( + "DELETE FROM android_cache_db.search_terms")); +} + +TEST_F(AndroidCacheDatabaseTest, SearchTermsTable) { + // Test AddSearchTerm. + Time search_time1 = Time::Now() - TimeDelta::FromDays(1); + base::string16 search_term1(base::UTF8ToUTF16("search term 1")); + SearchTermID id1 = history_db_.AddSearchTerm(search_term1, search_time1); + ASSERT_TRUE(id1); + SearchTermRow row1; + ASSERT_EQ(id1, history_db_.GetSearchTerm(search_term1, &row1)); + EXPECT_EQ(search_term1, row1.term); + EXPECT_EQ(ToDatabaseTime(search_time1), + ToDatabaseTime(row1.last_visit_time)); + EXPECT_EQ(id1, row1.id); + + // Test UpdateSearchTerm. + SearchTermRow update_row1; + update_row1.term = (base::UTF8ToUTF16("update search term1")); + update_row1.last_visit_time = Time::Now(); + ASSERT_TRUE(history_db_.UpdateSearchTerm(id1, update_row1)); + EXPECT_EQ(id1, history_db_.GetSearchTerm(update_row1.term, &row1)); + EXPECT_EQ(update_row1.term, row1.term); + EXPECT_EQ(ToDatabaseTime(update_row1.last_visit_time), + ToDatabaseTime(row1.last_visit_time)); + EXPECT_EQ(id1, row1.id); + + Time search_time2 = Time::Now() - TimeDelta::FromHours(1); + base::string16 search_term2(base::UTF8ToUTF16("search term 2")); + SearchTermID id2 = history_db_.AddSearchTerm(search_term2, search_time2); + ASSERT_TRUE(id2); + ASSERT_TRUE(history_db_.SetKeywordSearchTermsForURL(1, 1, search_term2)); + ASSERT_TRUE(history_db_.DeleteUnusedSearchTerms()); + + // The search_term1 was removed. + EXPECT_FALSE(history_db_.GetSearchTerm(update_row1.term, NULL)); + // The search_term2 should still in the table. + ASSERT_EQ(id2, history_db_.GetSearchTerm(search_term2, &row1)); + EXPECT_EQ(id2, row1.id); + EXPECT_EQ(ToDatabaseTime(search_time2), + ToDatabaseTime(row1.last_visit_time)); + EXPECT_EQ(search_term2, row1.term); +} + +} // namespace history diff --git a/pool/shard000/C++/0000019_fcitx-formatted-preedit.cpp b/pool/shard000/C++/0000019_fcitx-formatted-preedit.cpp new file mode 100644 index 0000000000000000000000000000000000000000..badaa761fc775644beff5d097d71213744412a3b --- /dev/null +++ b/pool/shard000/C++/0000019_fcitx-formatted-preedit.cpp @@ -0,0 +1,73 @@ +/*************************************************************************** + * Copyright (C) 2012~2012 by CSSlayer * + * * + * 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 St, Fifth Floor, Boston, MA 02110-1301, USA. * + ***************************************************************************/ + +#include + +#include "fcitx-formatted-preedit.h" + + +void FcitxFormattedPreedit::registerMetaType() +{ + qRegisterMetaType("FcitxFormattedPreedit"); + qDBusRegisterMetaType(); + qRegisterMetaType("FcitxFormattedPreeditList"); + qDBusRegisterMetaType(); +} + +qint32 FcitxFormattedPreedit::format() const +{ + return m_format; +} + +const QString& FcitxFormattedPreedit::string() const +{ + return m_string; +} + +void FcitxFormattedPreedit::setFormat(qint32 format) +{ + m_format = format; +} + +void FcitxFormattedPreedit::setString(const QString& str) +{ + m_string = str; +} + + +QDBusArgument& operator<<(QDBusArgument& argument, const FcitxFormattedPreedit& im) +{ + argument.beginStructure(); + argument << im.string(); + argument << im.format(); + argument.endStructure(); + return argument; +} + +const QDBusArgument& operator>>(const QDBusArgument& argument, FcitxFormattedPreedit& preedit) +{ + QString str; + qint32 format; + argument.beginStructure(); + argument >> str >> format; + argument.endStructure(); + preedit.setString(str); + preedit.setFormat(format); + return argument; +} diff --git a/pool/shard000/C++/0000025_WindowsUpdater.cpp b/pool/shard000/C++/0000025_WindowsUpdater.cpp new file mode 100644 index 0000000000000000000000000000000000000000..31fc2d5efd54622fa4ad3c236880391ddd1ab17e --- /dev/null +++ b/pool/shard000/C++/0000025_WindowsUpdater.cpp @@ -0,0 +1,53 @@ +#include +#include +#include +#include +#include + +using namespace MellowPlayer::Infrastructure; + +WindowsUpdater::WindowsUpdater(IFileDownloader& fileDownloader) : AbstractPlatformUpdater(fileDownloader) +{ +} + +bool WindowsUpdater::canInstall() const +{ + return asset_.isValid() && asset_.isWindowsInstaller(); +} + +void WindowsUpdater::doInstall(const QString& assetLocalPath) +{ + installerPath_ = assetLocalPath; + // no installation here, we'll start the installer when user clicked on restart + emit installFinished(QFile::exists(installerPath_)); +} + +QString WindowsUpdater::assetUrl() const +{ + return asset_.url(); +} + +QString WindowsUpdater::assetFileName() const +{ + return asset_.name(); +} + +void WindowsUpdater::setRelease(const Release* release) +{ + AbstractPlatformUpdater::setRelease(release); + + if (release_ != nullptr) { + for (auto& asset : release_->assets()) { + if (asset.isWindowsInstaller()) { + asset_ = asset; + break; + } + } + } +} + +void WindowsUpdater::restart() +{ + QProcess::startDetached(installerPath_); + qApp->quit(); +} diff --git a/pool/shard000/C++/0000029_P1MeterSerial.cpp b/pool/shard000/C++/0000029_P1MeterSerial.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9a3447d1d5ead666b77de2772376558df5304a74 --- /dev/null +++ b/pool/shard000/C++/0000029_P1MeterSerial.cpp @@ -0,0 +1,167 @@ +#include "stdafx.h" +#include "P1MeterSerial.h" +#include "../main/Logger.h" +#include "../main/localtime_r.h" +#include "../main/Helper.h" + +//NOTE!!!, this code is partly based on the great work of RHekkers: +//https://github.com/rhekkers + +#include +#include +#include +#include + +#include + +// +//Class P1MeterSerial +// +P1MeterSerial::P1MeterSerial(const int ID, const std::string& devname, unsigned int baud_rate): +m_szSerialPort(devname) +{ + m_HwdID=ID; + m_iBaudRate=baud_rate; + m_stoprequested = false; +} + +P1MeterSerial::P1MeterSerial(const std::string& devname, + unsigned int baud_rate, + boost::asio::serial_port_base::parity opt_parity, + boost::asio::serial_port_base::character_size opt_csize, + boost::asio::serial_port_base::flow_control opt_flow, + boost::asio::serial_port_base::stop_bits opt_stop) + :AsyncSerial(devname,baud_rate,opt_parity,opt_csize,opt_flow,opt_stop), + m_iBaudRate(baud_rate) +{ + m_stoprequested = false; +} + +P1MeterSerial::~P1MeterSerial() +{ + clearReadCallback(); +} + +//#define DEBUG_FROM_FILE + +bool P1MeterSerial::StartHardware() +{ +#ifdef DEBUG_FROM_FILE + FILE *fIn=fopen("E:\\meter.txt","rb+"); + BYTE buffer[1000]; + int ret=fread((BYTE*)&buffer,1,sizeof(buffer),fIn); + fclose(fIn); + ParseData((const BYTE*)&buffer,ret); +#endif + m_stoprequested = false; + m_thread = boost::shared_ptr(new boost::thread(boost::bind(&P1MeterSerial::Do_Work, this))); + + //Try to open the Serial Port + try + { + _log.Log(LOG_STATUS,"P1 Smart Meter: Using serial port: %s", m_szSerialPort.c_str()); + if (m_iBaudRate==9600) + { + open( + m_szSerialPort, + m_iBaudRate, + boost::asio::serial_port_base::parity( + boost::asio::serial_port_base::parity::even), + boost::asio::serial_port_base::character_size(7) + ); + } + else + { + //DSMRv4 + open( + m_szSerialPort, + m_iBaudRate, + boost::asio::serial_port_base::parity( + boost::asio::serial_port_base::parity::none), + boost::asio::serial_port_base::character_size(8) + ); + } + } + catch (boost::exception & e) + { + _log.Log(LOG_ERROR,"P1 Smart Meter: Error opening serial port!"); +#ifdef _DEBUG + _log.Log(LOG_ERROR,"-----------------\n%s\n-----------------",boost::diagnostic_information(e).c_str()); +#endif + return false; + } + catch ( ... ) + { + _log.Log(LOG_ERROR,"P1 Smart Meter: Error opening serial port!!!"); + return false; + } + m_bIsStarted=true; + m_linecount=0; + m_exclmarkfound=0; + setReadCallback(boost::bind(&P1MeterSerial::readCallback, this, _1, _2)); + sOnConnected(this); + return true; +} + +bool P1MeterSerial::StopHardware() +{ + if (isOpen()) + { + try { + clearReadCallback(); + close(); + doClose(); + setErrorStatus(true); + } catch(...) + { + //Don't throw from a Stop command + } + } + m_stoprequested = true; + if (m_thread) + { + m_thread->join(); + // Wait a while. The read thread might be reading. Adding this prevents a pointer error in the async serial class. + sleep_milliseconds(10); + } + m_bIsStarted = false; + return true; +} + + +void P1MeterSerial::readCallback(const char *data, size_t len) +{ + boost::lock_guard l(readQueueMutex); + + if (!m_bEnableReceive) + return; //receiving not enabled + + ParseData((const unsigned char*)data, static_cast(len)); +} + +bool P1MeterSerial::WriteToHardware(const char *pdata, const unsigned char length) +{ + return false; +} + +void P1MeterSerial::Do_Work() +{ + int sec_counter = 0; + int msec_counter = 0; + while (!m_stoprequested) + { + sleep_milliseconds(200); + if (m_stoprequested) + break; + msec_counter++; + if (msec_counter == 5) + { + msec_counter = 0; + + sec_counter++; + if (sec_counter % 12 == 0) { + m_LastHeartbeat=mytime(NULL); + } + } + } +} diff --git a/pool/shard000/C++/0000030_ReaderBinding.cpp b/pool/shard000/C++/0000030_ReaderBinding.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fcb039dac616ea41cca5043dd14a3d0697ebeeca --- /dev/null +++ b/pool/shard000/C++/0000030_ReaderBinding.cpp @@ -0,0 +1,147 @@ +////////////////////////////////////////////////////////////////////////// +// +// Copyright (c) 2007-2010, Image Engine Design 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 Image Engine Design nor the names of any +// other contributors to this software 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 "boost/python.hpp" + +#include "IECorePython/ReaderBinding.h" + +#include "IECorePython/OpBinding.h" +#include "IECorePython/ScopedGILLock.h" +#include "IECorePython/ScopedGILRelease.h" + +#include "IECore/FileNameParameter.h" +#include "IECore/Object.h" +#include "IECore/Reader.h" + +using std::string; +using namespace boost; +using namespace boost::python; +using namespace IECore; +using namespace IECorePython; + +namespace +{ + +static list supportedExtensions() +{ + list result; + std::vector e; + Reader::supportedExtensions( e ); + for( unsigned int i=0; i e; + Reader::supportedExtensions( typeId, e ); + for( unsigned int i=0; i( m_fn( fileName ) ); + return result; + } + + private : + + object m_fn; + +}; + +struct ReaderCanRead +{ + + ReaderCanRead( object fn ) + : m_fn( fn ) + { + } + + bool operator()( const std::string &fileName ) + { + ScopedGILLock gilLock; + bool result = m_fn( fileName ); + return result; + } + + private : + + object m_fn; + +}; + +static void registerReader( const std::string &extensions, object &canRead, object &creator, TypeId typeId ) +{ + Reader::registerReader( extensions, ReaderCanRead( canRead ), ReaderCreator( creator ), typeId ); +} + +} // namespace + +namespace IECorePython +{ + +void bindReader() +{ + using boost::python::arg; + + ReaderClass >() + .def( init< const std::string &>( ( arg( "description" ) ) ) ) + .def( "create", &Reader::create ).staticmethod( "create" ) + .def( "supportedExtensions", ( list(*)( ) ) &supportedExtensions ) + .def( "supportedExtensions", ( list(*)( IECore::TypeId ) ) &supportedExtensions ) + .staticmethod( "supportedExtensions" ) + .def( "registerReader", ®isterReader ) + .staticmethod( "registerReader" ) + ; +} + +} // namespace IECorePython diff --git a/pool/shard000/C++/0000031_testcli.cpp b/pool/shard000/C++/0000031_testcli.cpp new file mode 100644 index 0000000000000000000000000000000000000000..588f31797faaf27a3f97de8e59a4b0aa5b1c1635 --- /dev/null +++ b/pool/shard000/C++/0000031_testcli.cpp @@ -0,0 +1,150 @@ +/* + * Copyright 2009 Stephen Liu + * For license terms, see the file COPYING along with this library. + */ + +#include +#include +#include +#include +#include +#include + +#include "spnetkit/spnksocket.hpp" +#include "spnetkit/spnklog.hpp" +#include "spnetkit/spnkgetopt.h" +#include "spnetkit/spnklist.hpp" + +#include "sphivedbcli.hpp" +#include "sphivemsg.hpp" +#include "sphivejson.hpp" + +void showUsage( const char * program ) +{ + printf( "\n\n%s [-h host] [-p port] [-t type]\n", program ); + printf( "\t[-i dbfile] [-u user] [-n dbname] [-s sql] [-o] [-v]\n\n" ); + + printf( "\t-h http host\n" ); + printf( "\t-p http port\n" ); + printf( "\t-t rpc type, json/protobuf\n" ); + printf( "\t-i dbfile\n" ); + printf( "\t-u user\n" ); + printf( "\t-n dbname\n" ); + printf( "\t-s sql script\n" ); + printf( "\t-o log socket io\n" ); + printf( "\t-v show this usage\n" ); + printf( "\n\n" ); + + exit( 0 ); +} + +void printResultSet( SP_HiveResultSet * rs ) +{ + printf( "row.count %d\n", rs->getRowCount() ); + + int column = rs->getColumnCount(); + + for( int i = 0; i < column; i++ ) { + printf( "\t%s(%s)", rs->getName(i), rs->getType(i) ); + } + + printf( "\n" ); + + for( int i = 0; i < rs->getRowCount(); i++ ) { + rs->moveTo( i ); + for( int j = 0; j < column; j++ ) { + char tmp[ 32 ] = { 0 }; + const char * val = rs->getAsString( j, tmp, sizeof( tmp ) ); + + printf( "\t[%s]", val ); + } + + printf( "\n" ); + } +} + +int main( int argc, char * argv[] ) +{ + SP_NKLog::init4test( "testcli" ); + SP_NKLog::setLogLevel( LOG_DEBUG ); + + char * host = NULL, * port = NULL, * type = NULL; + char * dbfile = NULL, * user = NULL, * dbname = NULL, * sql = NULL; + + extern char *optarg ; + int c ; + + while( ( c = getopt( argc, argv, "h:p:t:i:u:n:s:ov" ) ) != EOF ) { + switch ( c ) { + case 'h' : host = optarg; break; + case 'p' : port = optarg; break; + case 't' : type = optarg; break; + case 'i' : dbfile = optarg; break; + case 'u' : user = optarg; break; + case 'n' : dbname = optarg; break; + case 's' : sql = optarg; break; + case 'o' : SP_NKSocket::setLogSocketDefault( 1 ); break; + case 'v' : + default: showUsage( argv[ 0 ] ); break; + } + } + + if( NULL == host || NULL == host || NULL == dbfile + || NULL == user || NULL == dbname || NULL == sql ) { + showUsage( argv[ 0 ] ); + } + + SP_NKStringList sqlList; + { + sql = strdup( sql ); + + for( char * pos = sql; NULL != pos && '\0' != *pos; ) { + char * next = strchr( pos, ';' ); + if( NULL != next ) *next = '\0'; + + for( ; isspace( *pos ); ) pos++; + + if( '\0' != *pos ) sqlList.append( pos ); + + pos = next ? next + 1 : NULL; + } + + free( sql ); + } + + int rpcType = SP_HiveDBClientConfig::eJsonRpc; + + if( NULL != type && 0 == strcasecmp( type, "protobuf" ) ) { + rpcType = SP_HiveDBClientConfig::eProtoBufRpc; + } + + SP_NKTcpSocket socket( host, atoi( port ) ); + + SP_HiveDBProtocol protocol( &socket, 0, rpcType ); + + SP_HiveRespObject * resp = protocol.execute( atoi( dbfile ), user, dbname, &sqlList ); + + if( NULL != resp ) { + if( 0 == resp->getErrorCode() ) { + printf( "result.count %d\n", resp->getResultCount() ); + + for( int i = 0; i < resp->getResultCount(); i++ ) { + SP_HiveResultSet * rs = resp->getResultSet( i ); + + printResultSet( rs ); + + delete rs; + } + } else { + printf( "execute fail, errcode %d, %s\n", + resp->getErrdataCode(), resp->getErrdataMsg() ); + } + + delete resp; + } else { + printf( "socket error\n" ); + } + + return 0; +} + diff --git a/pool/shard000/C++/0000036_main.cpp b/pool/shard000/C++/0000036_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..97d7611de6f4fb419b62ef99141ebdb867e77b99 --- /dev/null +++ b/pool/shard000/C++/0000036_main.cpp @@ -0,0 +1,106 @@ +#include "mainwindow.h" +#if SINGLE_APP +#include "singleapplication.h" +#endif + +#include +#include +#include + +/*! \mainpage QtPass + * + * \section intro_sec Introduction + * + * QtPass is a multi-platform GUI for pass, the standard unix password manager. + * + * https://qtpass.org/ + * + * \section install_sec Installation + * + * \subsection dependencies Dependencies + * + * - QtPass requires Qt 5.2 or later. + * - The Linguist package is required to compile the translations. + * - For use of the fallback icons the SVG library is required. + * + * At runtime the only real dependency is gpg2 but to make the most of it, + * you'll need git and pass too. + * + * \subsection source From source + * + * On most *nix systems all you need is: + * + * `qmake && make && make install` + */ + +/** + * @brief main + * @param argc + * @param argv + * @return + */ +int main(int argc, char *argv[]) { +#if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0) + QApplication::setAttribute(Qt::AA_EnableHighDpiScaling); +#endif + QString text = ""; + for (int i = 1; i < argc; ++i) { + if (i > 1) + text += " "; + text += argv[i]; + } + + if ((text.indexOf("-psn_") == 0) || (text.indexOf("-session") == 0)) { + text.clear(); + } + +#if SINGLE_APP + QString name = qgetenv("USER"); + if (name.isEmpty()) + name = qgetenv("USERNAME"); + SingleApplication app(argc, argv, name + "QtPass"); + if (app.isRunning()) { + if (text.length() > 0) + app.sendMessage(text); + return 0; + } +#else + QApplication app(argc, argv); +#endif + + Q_INIT_RESOURCE(resources); + Q_INIT_RESOURCE(qmake_qmake_qm_files); // qmake names the file + + QCoreApplication::setOrganizationName("IJHack"); + QCoreApplication::setOrganizationDomain("ijhack.org"); + QCoreApplication::setApplicationName("QtPass"); + QCoreApplication::setApplicationVersion(VERSION); + + // Setup and load translator for localization + QTranslator translator; + QString locale = QLocale::system().name(); + // locale = "nl_NL"; + // locale = "he_IL"; + // locale = "ar_MA"; + translator.load(QString(":localization/localization_%1.qm").arg(locale)); + SingleApplication::installTranslator(&translator); + SingleApplication::setLayoutDirection( + QObject::tr("LTR") == "RTL" ? Qt::RightToLeft : Qt::LeftToRight); + MainWindow w(text); + + SingleApplication::setActiveWindow(&w); + SingleApplication::setWindowIcon(QIcon(":artwork/icon.png")); + +#if SINGLE_APP + QObject::connect(&app, &SingleApplication::messageAvailable, &w, + &MainWindow::messageAvailable); +#endif + +#if (QT_VERSION >= QT_VERSION_CHECK(5, 7, 0)) + QGuiApplication::setDesktopFileName("qtpass.desktop"); +#endif + + w.show(); + + return SingleApplication::exec(); +} diff --git a/pool/shard000/C++/0000043_Syntax.cpp b/pool/shard000/C++/0000043_Syntax.cpp new file mode 100644 index 0000000000000000000000000000000000000000..850fb9ecbf082737a8210a5743dea7b6bb9666f3 --- /dev/null +++ b/pool/shard000/C++/0000043_Syntax.cpp @@ -0,0 +1,111 @@ +//===--- Syntax.cpp - Swift Syntax Implementation -------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +#include "swift/Syntax/Syntax.h" +#include "swift/Syntax/SyntaxData.h" +#include "swift/Syntax/SyntaxVisitor.h" +#include "swift/Syntax/TokenSyntax.h" + +using namespace swift; +using namespace swift::syntax; + +const RC &Syntax::getRaw() const { + return Data->getRaw(); +} + +SyntaxKind Syntax::getKind() const { + return getRaw()->getKind(); +} + +void Syntax::print(llvm::raw_ostream &OS, SyntaxPrintOptions Opts) const { + if (auto Raw = getRaw()) + Raw->print(OS, Opts); +} + +void Syntax::dump() const { + getRaw()->dump(); +} + +void Syntax::dump(llvm::raw_ostream &OS, unsigned Indent) const { + getRaw()->dump(OS, 0); +} + +bool Syntax::isType() const { + return Data->isType(); +} + +bool Syntax::isDecl() const { + return Data->isDecl(); +} + +bool Syntax::isStmt() const { + return Data->isStmt(); +} + +bool Syntax::isExpr() const { + return Data->isExpr(); +} + +bool Syntax::isToken() const { + return getRaw()->isToken(); +} + +bool Syntax::isPattern() const { + return Data->isPattern(); +} + +bool Syntax::isUnknown() const { + return Data->isUnknown(); +} + +bool Syntax::isPresent() const { + return getRaw()->isPresent(); +} + +bool Syntax::isMissing() const { + return getRaw()->isMissing(); +} + +llvm::Optional Syntax::getParent() const { + auto ParentData = getData().getParent(); + if (!ParentData) return llvm::None; + return llvm::Optional { + Syntax { Root, ParentData } + }; +} + +Syntax Syntax::getRoot() const { + return { Root, Root.get() }; +} + +size_t Syntax::getNumChildren() const { + return Data->getNumChildren(); +} + +llvm::Optional Syntax::getChild(const size_t N) const { + auto ChildData = Data->getChild(N); + if (!ChildData) + return llvm::None; + return Syntax {Root, ChildData.get()}; +} + +Optional Syntax::getFirstToken() const { + if (auto tok = getData().getFirstToken()) + return TokenSyntax(Root, tok.get()); + return None; +} + +Optional Syntax::getLastToken() const { + if (auto tok = getData().getLastToken()) + return TokenSyntax(Root, tok.get()); + return None; +} diff --git a/pool/shard000/C++/0000053_random_sample.cpp b/pool/shard000/C++/0000053_random_sample.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2f6fe9077007b98703292116d0e4672f771a2366 --- /dev/null +++ b/pool/shard000/C++/0000053_random_sample.cpp @@ -0,0 +1,40 @@ +#include +#include +using namespace std; + +//given an array of numbers, produce a sample of size K of them. +//algorithm: swap(array[i++],array[random]) k times -> so that the first k elements are the random sample + +void swap(int array[],int a,int b){ + if(a!=b){ + array[a]^=array[b]; + array[b]^=array[a]; + array[a]^=array[b]; + } +} + +int main(){ + + int numbers[]={1,2,3,4,5,6,7,8,9,10}; + int n=sizeof(numbers)/sizeof(int); + + random_device rd; + default_random_engine gen(rd()); + + int sampleSize=4; + + for(int i=0;i dis(i,n-1); + swap(numbers,i,dis(gen)); + } + + //print random sample of size sampleSize + for(int i=0;i +#include +#include + +int main(int argc, char *argv[]) +{ + QApplication a(argc, argv); + MainWindow w; + + QDesktopWidget dw; + int x=dw.width()*0.7; + int y=dw.height()*0.7; + //w.setFixedSize(x,y); + //QRect rect(0, 0, 240, 320); + //frame->setFrameShape(QFrame::Box); + //frame->setLineWidth(3); + //frame->setFrameShadow(QFrame::Plain); + //frame->setGeometry(rect); + + //adjustSize(); + + //void createHorizontalGroupBox(); + + //QPalette pal = palette(); + //pal.setColor(QPalette::Background, Qt::black); + //w.setAutoFillBackground(true); + //w.setPalette(pal); + + // QPushButton hello( "Hello world!", 0 ); + // hello.resize( 100, 30 ); + // a.setMainWidget( &hello ); + // hello.show(); + + w.show(); + + return a.exec(); +} diff --git a/pool/shard000/C++/0000061_CElmPhotocam.cc b/pool/shard000/C++/0000061_CElmPhotocam.cc new file mode 100644 index 0000000000000000000000000000000000000000..e3f5a6213c3ec06d773c99b361acc11da68d31b3 --- /dev/null +++ b/pool/shard000/C++/0000061_CElmPhotocam.cc @@ -0,0 +1,184 @@ +#include "elm.h" +#include "CElmPhotocam.h" + +namespace elm { + +using namespace v8; + +GENERATE_PROPERTY_CALLBACKS(CElmPhotocam, file); +GENERATE_PROPERTY_CALLBACKS(CElmPhotocam, zoom); +GENERATE_PROPERTY_CALLBACKS(CElmPhotocam, zoom_mode); +GENERATE_PROPERTY_CALLBACKS(CElmPhotocam, paused); +GENERATE_PROPERTY_CALLBACKS(CElmPhotocam, gesture_enabled); +GENERATE_RO_PROPERTY_CALLBACKS(CElmPhotocam, image_size); +GENERATE_RO_PROPERTY_CALLBACKS(CElmPhotocam, image_region); +GENERATE_METHOD_CALLBACKS(CElmPhotocam, image_region_show); +GENERATE_METHOD_CALLBACKS(CElmPhotocam, image_region_bring_in); + +GENERATE_TEMPLATE_FULL(CElmObject, CElmPhotocam, + PROPERTY(file), + PROPERTY(zoom), + PROPERTY(zoom_mode), + PROPERTY(paused), + PROPERTY(gesture_enabled), + PROPERTY_RO(image_size), + PROPERTY_RO(image_region), + METHOD(image_region_show), + METHOD(image_region_bring_in)); + +CElmPhotocam::CElmPhotocam(Local _jsObject, CElmObject *parent) + : CElmObject(_jsObject, elm_photocam_add(elm_object_top_widget_get(parent->GetEvasObject()))) +{ +} + +void CElmPhotocam::Initialize(Handle target) +{ + target->Set(String::NewSymbol("Photocam"), GetTemplate()->GetFunction()); +} + +void CElmPhotocam::file_set(Handle val) +{ + if (!val->IsString()) + return; + + String::Utf8Value str(val); + if (!access(*str, R_OK)) + { + elm_photocam_file_set(eo, *str); + return; + } + + ELM_ERR("warning: can't read image file %s", *str); +} + +Handle CElmPhotocam::file_get(void) const +{ + const char *file = elm_photocam_file_get(eo); + return file ? String::New(file) : Null(); +} + +Handle CElmPhotocam::zoom_get() const +{ + return Number::New(elm_photocam_zoom_get(eo)); +} + +void CElmPhotocam::zoom_set(Handle value) +{ + if (value->IsNumber()) + elm_photocam_zoom_set(eo, value->NumberValue()); +} + +Handle CElmPhotocam::zoom_mode_get() const +{ + switch (elm_photocam_zoom_mode_get(eo)) { + case ELM_PHOTOCAM_ZOOM_MODE_MANUAL: + return String::NewSymbol("manual"); + case ELM_PHOTOCAM_ZOOM_MODE_AUTO_FIT: + return String::NewSymbol("auto-fit"); + case ELM_PHOTOCAM_ZOOM_MODE_AUTO_FILL: + return String::NewSymbol("auto-fill"); + default: + return String::NewSymbol("auto-fit-in"); + } +} + +void CElmPhotocam::zoom_mode_set(Handle value) +{ + Elm_Photocam_Zoom_Mode new_mode; + + if (value->IsNumber()) + new_mode = (Elm_Photocam_Zoom_Mode)value->NumberValue(); + else if (value->IsString()) + { + String::Utf8Value mode(value->ToString()); + if (!strcmp(*mode, "manual")) + new_mode = ELM_PHOTOCAM_ZOOM_MODE_MANUAL; + else if (!strcmp(*mode, "auto-fit")) + new_mode = ELM_PHOTOCAM_ZOOM_MODE_AUTO_FIT; + else if (!strcmp(*mode, "auto-fill")) + new_mode = ELM_PHOTOCAM_ZOOM_MODE_AUTO_FILL; + else + new_mode = ELM_PHOTOCAM_ZOOM_MODE_AUTO_FIT_IN; + } + else + new_mode = ELM_PHOTOCAM_ZOOM_MODE_MANUAL; + + elm_photocam_zoom_mode_set(eo, new_mode); +} + +void CElmPhotocam::paused_set(Handle val) +{ + elm_photocam_paused_set(eo, val->BooleanValue()); +} + +Handle CElmPhotocam::paused_get() const +{ + return Boolean::New(elm_photocam_paused_get(eo)); +} + +void CElmPhotocam::gesture_enabled_set(Handle val) +{ + elm_photocam_gesture_enabled_set(eo, val->BooleanValue()); +} + +Handle CElmPhotocam::gesture_enabled_get() const +{ + return Boolean::New(elm_photocam_gesture_enabled_get(eo)); +} + +Handle CElmPhotocam::image_region_get() const +{ + HandleScope scope; + + int x, y, w, h; + elm_photocam_image_region_get(eo, &x, &y, &w, &h); + + Local obj = Object::New(); + obj->Set(String::NewSymbol("x"), Number::New(x)); + obj->Set(String::NewSymbol("y"), Number::New(y)); + obj->Set(String::NewSymbol("width"), Number::New(w)); + obj->Set(String::NewSymbol("height"), Number::New(h)); + + return scope.Close(obj); +} + +Handle CElmPhotocam::image_size_get() const +{ + HandleScope scope; + + int w, h; + elm_photocam_image_size_get(eo, &w, &h); + + Local obj = Object::New(); + obj->Set(String::NewSymbol("width"), Number::New(w)); + obj->Set(String::NewSymbol("height"), Number::New(h)); + + return scope.Close(obj); +} + +Handle CElmPhotocam::image_region_show(const Arguments &args) +{ + for (int i = 0; i < 4; i++) + if (!args[i]->IsNumber()) + return Undefined(); + + elm_photocam_image_region_show(eo, args[0]->ToInt32()->Value(), args[1]->ToInt32()->Value(), + args[2]->ToInt32()->Value(), args[3]->ToInt32()->Value()); + + return Undefined(); + +} + +Handle CElmPhotocam::image_region_bring_in(const Arguments &args) +{ + for (int i = 0; i < 4; i++) + if (!args[i]->IsNumber()) + return Undefined(); + + elm_photocam_image_region_bring_in(eo, args[0]->ToInt32()->Value(), args[1]->ToInt32()->Value(), + args[2]->ToInt32()->Value(), args[3]->ToInt32()->Value()); + + return Undefined(); +} + +} diff --git a/pool/shard000/C++/0000065_modelprinter.cpp b/pool/shard000/C++/0000065_modelprinter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..600ed89e9b6c4ef8825edc61eb239e457db4fdca --- /dev/null +++ b/pool/shard000/C++/0000065_modelprinter.cpp @@ -0,0 +1,152 @@ +/* + * Copyright 2013 Canonical Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation; version 3. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + * + * Authors: + * Nick Dedekind + */ + +// self +#include "modelprinter.h" + +#include + +// Qt +#include + +ModelPrinter::ModelPrinter(QObject *parent) + : QObject(parent) + , m_model(nullptr) +{ +} + +void ModelPrinter::setSourceModel(UnityMenuModel * sourceModel) +{ + if (m_model != nullptr) { + disconnect(m_model); + } + if (m_model != sourceModel) { + m_model = sourceModel; + Q_EMIT modelChanged(); + Q_EMIT textChanged(); + } + if (m_model != nullptr) { + connect(m_model, &UnityMenuModel::rowsInserted, this, &ModelPrinter::textChanged); + connect(m_model, &UnityMenuModel::rowsRemoved, this, &ModelPrinter::textChanged); + connect(m_model, &UnityMenuModel::dataChanged, this, &ModelPrinter::textChanged); + } +} + +UnityMenuModel* ModelPrinter::sourceModel() const +{ + return m_model; +} + +QString ModelPrinter::text() +{ + return getModelDataString(m_model, 0); +} + +QString tabify(int level) { QString str; + for (int i = 0; i < level; i++) { + str += QLatin1String(" "); + } + return str; +} + +QString ModelPrinter::getModelDataString(UnityMenuModel* sourceModel, int level) +{ + if (!sourceModel) + return QLatin1String(""); + + QString str; + QTextStream stream(&str); + + int rowCount = sourceModel->rowCount(); + for (int row = 0; row < rowCount; row++) { + + stream << getRowSring(sourceModel, row, level) << endl; + + UnityMenuModel* childMenuModel = qobject_cast(sourceModel->submenu(row)); + if (childMenuModel) { + + if (!m_children.contains(childMenuModel)) { + m_children << childMenuModel; + connect(childMenuModel, &UnityMenuModel::rowsInserted, this, &ModelPrinter::textChanged); + connect(childMenuModel, &UnityMenuModel::rowsRemoved, this, &ModelPrinter::textChanged); + connect(childMenuModel, &UnityMenuModel::dataChanged, this, &ModelPrinter::textChanged); + } + stream << getModelDataString(childMenuModel, level+1); + } + } + return str; +} + +QString ModelPrinter::getRowSring(UnityMenuModel* sourceModel, int row, int depth) const +{ + QString str; + QTextStream stream(&str); + + // Print out this row + QHash roleNames = sourceModel->roleNames(); + QList roles = roleNames.keys(); + qSort(roles); + + Q_FOREACH(int role, roles) { + const QByteArray& roleName = roleNames[role]; + stream << getVariantString(roleName, sourceModel->get(row, roleName), depth); + } + return str; +} + +QString ModelPrinter::getVariantString(const QVariant& vData) const +{ + if (vData.type() == QVariant::List) { + QStringList strList; + for (const auto& v : vData.toList()) + strList.append(getVariantString(v)); + + return '[' + strList.join(", ") + ']'; + } + + return vData.toString(); +} + +QString ModelPrinter::getVariantString(const QString& roleName, const QVariant &vData, int depth) const +{ + QString str; + QTextStream stream(&str); + + if (vData.canConvert(QMetaType::QVariantMap)) { + QMapIterator iter(vData.toMap()); + while (iter.hasNext()) { + iter.next(); + stream << tabify(depth); + stream << roleName + << "." + << iter.key() + << ": " + << getVariantString(iter.value()) + << endl; + } + } + else { + stream << tabify(depth); + stream << roleName + << ": " + << getVariantString(vData) + << endl; + } + return str; +} diff --git a/pool/shard000/C++/0000067_main.cpp b/pool/shard000/C++/0000067_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..330e7ef2fe2cb0e8444b22178a1089a831bb112a --- /dev/null +++ b/pool/shard000/C++/0000067_main.cpp @@ -0,0 +1,112 @@ +// Copyright (c) 2012-2013 The Cryptonote developers +// Distributed under the MIT/X11 software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include + +#include "include_base_utils.h" +using namespace epee; + +#include "common/command_line.h" +#include "transactions_flow_test.h" + +namespace po = boost::program_options; + +namespace +{ + const command_line::arg_descriptor arg_test_transactions_flow = {"test_transactions_flow", ""}; + + const command_line::arg_descriptor arg_working_folder = {"working-folder", "", "."}; + const command_line::arg_descriptor arg_source_wallet = {"source-wallet", "", "", true}; + const command_line::arg_descriptor arg_dest_wallet = {"dest-wallet", "", "", true}; + const command_line::arg_descriptor arg_daemon_addr_a = {"daemon-addr-a", "", "127.0.0.1:8080"}; + const command_line::arg_descriptor arg_daemon_addr_b = {"daemon-addr-b", "", "127.0.0.1:8082"}; + + const command_line::arg_descriptor arg_transfer_amount = {"transfer_amount", "", 60000000000000}; + const command_line::arg_descriptor arg_mix_in_factor = {"mix-in-factor", "", 10}; + const command_line::arg_descriptor arg_tx_count = {"tx-count", "", 100}; + const command_line::arg_descriptor arg_tx_per_second = {"tx-per-second", "", 20}; + const command_line::arg_descriptor arg_test_repeat_count = {"test_repeat_count", "", 1}; +} + +int main(int argc, char* argv[]) +{ + TRY_ENTRY(); + string_tools::set_module_name_and_folder(argv[0]); + + //set up logging options + log_space::get_set_log_detalisation_level(true, LOG_LEVEL_3); + log_space::log_singletone::add_logger(LOGGER_CONSOLE, NULL, NULL, LOG_LEVEL_2); + log_space::log_singletone::add_logger(LOGGER_FILE, + log_space::log_singletone::get_default_log_file().c_str(), + log_space::log_singletone::get_default_log_folder().c_str()); + + po::options_description desc_options("Allowed options"); + command_line::add_arg(desc_options, command_line::arg_help); + + command_line::add_arg(desc_options, arg_test_transactions_flow); + + command_line::add_arg(desc_options, arg_working_folder); + command_line::add_arg(desc_options, arg_source_wallet); + command_line::add_arg(desc_options, arg_dest_wallet); + command_line::add_arg(desc_options, arg_daemon_addr_a); + command_line::add_arg(desc_options, arg_daemon_addr_b); + + command_line::add_arg(desc_options, arg_transfer_amount); + command_line::add_arg(desc_options, arg_mix_in_factor); + command_line::add_arg(desc_options, arg_tx_count); + command_line::add_arg(desc_options, arg_tx_per_second); + command_line::add_arg(desc_options, arg_test_repeat_count); + + po::variables_map vm; + bool r = command_line::handle_error_helper(desc_options, [&]() + { + po::store(po::parse_command_line(argc, argv, desc_options), vm); + po::notify(vm); + return true; + }); + if (!r) + return 1; + + if (command_line::get_arg(vm, command_line::arg_help)) + { + std::cout << desc_options << std::endl; + return 0; + } + + if (command_line::get_arg(vm, arg_test_transactions_flow)) + { + std::string working_folder = command_line::get_arg(vm, arg_working_folder); + std::string path_source_wallet, path_target_wallet; + if(command_line::has_arg(vm, arg_source_wallet)) + path_source_wallet = command_line::get_arg(vm, arg_source_wallet); + if(command_line::has_arg(vm, arg_dest_wallet)) + path_target_wallet = command_line::get_arg(vm, arg_dest_wallet); + + std::string daemon_addr_a = command_line::get_arg(vm, arg_daemon_addr_a); + std::string daemon_addr_b = command_line::get_arg(vm, arg_daemon_addr_b); + uint64_t amount_to_transfer = command_line::get_arg(vm, arg_transfer_amount); + size_t mix_in_factor = command_line::get_arg(vm, arg_mix_in_factor); + size_t transactions_count = command_line::get_arg(vm, arg_tx_count); + size_t transactions_per_second = command_line::get_arg(vm, arg_tx_per_second); + size_t repeat_count = command_line::get_arg(vm, arg_test_repeat_count); + + for(size_t i = 0; i != repeat_count; i++) + if(!transactions_flow_test(working_folder, path_source_wallet, path_target_wallet, daemon_addr_a, daemon_addr_b, amount_to_transfer, mix_in_factor, transactions_count, transactions_per_second)) + break; + + std::string s; + std::cin >> s; + + return 1; + } + else + { + std::cout << desc_options << std::endl; + return 1; + } + + CATCH_ENTRY_L0("main", 1); + + return 0; +} diff --git a/pool/shard000/C++/0000069_mpmat_test.cpp b/pool/shard000/C++/0000069_mpmat_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ef35e7ba0939aadad2f498417558beb244656e9f --- /dev/null +++ b/pool/shard000/C++/0000069_mpmat_test.cpp @@ -0,0 +1,68 @@ +#include "../../src/SDPSolver.h" +#include "../../src/Timers.h" +#include "../../src/parse.h" + +// FIXME: This should not be a global +Timers timers; + +int main() { + + mp_bitcnt_t precision(512); + mpf_set_default_prec(precision); + + Real residue("10e-" + std::to_string(std::floor(precision/(log(10)/log(2))))); + Real sqrt_residue(sqrt(residue)); + + const size_t Nx(9224), Ny(368); + Matrix matrix(Nx, Ny), square_gmp(Ny, Ny); + for (size_t i = 0; i < Nx; ++i) + for (size_t j = 0; j < Ny; ++j) { + Real ri(i + 1), rj(j+1); + matrix.elt(i, j) = ri + rj*rj - sqrt_residue; + } + + matrixSquareIntoBlock(matrix, square_gmp, 0, 0); + + mpmat workspace(1); + mpf_set_default_prec(mpf_get_default_prec() + 256); + Matrix square_mpmat(Ny, Ny); + mpf_set_default_prec(mpf_get_default_prec() - 256); + + matrixSquareIntoBlockMpmat(workspace, matrix, square_mpmat, 0, 0); + + bool passed (true); + std::cout.precision(static_cast(precision * 0.31 + 5)); + for (size_t i = 0; i < Ny; ++i) { + for (size_t j = 0; j < Ny; ++j) { + if (abs((square_gmp.elt(i, j) - square_mpmat.elt(i, j)) / + (square_gmp.elt(i, j) + square_mpmat.elt(i, j))) > residue) + { + passed=false; + std::cout << i << " " << j << "\n\t" + << "square_gmp: " << square_gmp.elt(i, j) << "\n\t" + << "square_mpmat: " << square_mpmat.elt(i, j) << "\n\t" + << "target residue: " << residue << "\n\t" + << "measured residue: " + << (square_gmp.elt(i, j) - square_mpmat.elt(i, j)) << "\n"; + } + } + } + if(passed) + { std::cout << "PASS: sqrt(1-epsilon)^2\n"; } + else + { std::cout << "FAIL: sqrt(1-epsilon)^2\n"; } + + // SDPSolverParameters parameters; + // parameters.precision = 2048; + // parameters.resetPrecision(); + // parameters.maxThreads = 1; + // // parameters.maxThreads=128; + + // omp_set_num_threads(parameters.maxThreads); + + // SDPSolver solver(readBootstrapSDP(std::vector( + // // {"../inputs/TTTTtestsmall.xml"})), + // {"test/mpmat/input.xml"})), + // parameters); + // solver.testMultiplication(1, 1, 5); +} diff --git a/pool/shard000/C++/0000081_B._Volcanoes.cpp b/pool/shard000/C++/0000081_B._Volcanoes.cpp new file mode 100644 index 0000000000000000000000000000000000000000..16d25f121efe68fd4a30e57c0016b14ff343c505 --- /dev/null +++ b/pool/shard000/C++/0000081_B._Volcanoes.cpp @@ -0,0 +1,57 @@ +#include +#include +#define MAX 1000000005//too long +using namespace std; +bool visited [MAX][MAX]; +bool planet [MAX][MAX]; +int n; +bool valid (int i, int j) +{ + return i>=0 && j>=0 && i>n>>m; + memset(visited,false, n+5); + memset(planet,true,n+5); + bool flag=true; + for(int i=0;i>x>>y; + if(x==n && y==n) + { + flag=false; + break; + } + planet [x-1][y-1]=false; + } + if(!flag) + cout<<-1< +#include + +using namespace std; + +int N; +long long map[100001]; +long long solve(int left, int right); +int main() +{ + scanf("%d", &N); + for(int i=0; i. + */ + +#include +#include +#include +#include + +using namespace shogun; +using namespace internal; +using namespace mmd; + +UnbiasedIncomplete::UnbiasedIncomplete(index_t _n) : n(_n) +{ +} + +float64_t UnbiasedIncomplete::operator()(SGMatrix km) +{ + using MatrixXt = const Eigen::MatrixXd; + using Block = const Eigen::Block>; + + Eigen::Map map(km.matrix, km.num_rows, km.num_cols); + + Block& b_x = map.block(0, 0, n, n); + auto term_1 = b_x.sum() - b_x.diagonal().sum(); + + Block& b_y = map.block(n, n, n, n); + auto term_2 = b_y.sum() - b_y.diagonal().sum(); + + Block& b_xy = map.block(n, 0, n, n); + auto term_3 = b_xy.sum() - b_xy.diagonal().sum(); + + auto statistic = term_1/n/(n-1) + term_2/n/(n-1) - 2*term_3/n/n; + + return statistic; + +} diff --git a/pool/shard000/C++/0000091_updateoriginendpointresponse.cpp b/pool/shard000/C++/0000091_updateoriginendpointresponse.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2b34e3b42bf61abb4ed00089976784d4f3040ef0 --- /dev/null +++ b/pool/shard000/C++/0000091_updateoriginendpointresponse.cpp @@ -0,0 +1,100 @@ +/* + 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 "updateoriginendpointresponse.h" +#include "updateoriginendpointresponse_p.h" + +#include +#include +#include + +namespace QtAws { +namespace MediaPackage { + +/*! + * \class QtAws::MediaPackage::UpdateOriginEndpointResponse + * \brief The UpdateOriginEndpointResponse class provides an interace for MediaPackage UpdateOriginEndpoint responses. + * + * \inmodule QtAwsMediaPackage + * + * + * \sa MediaPackageClient::updateOriginEndpoint + */ + +/*! + * Constructs a UpdateOriginEndpointResponse object for \a reply to \a request, with parent \a parent. + */ +UpdateOriginEndpointResponse::UpdateOriginEndpointResponse( + const UpdateOriginEndpointRequest &request, + QNetworkReply * const reply, + QObject * const parent) + : MediaPackageResponse(new UpdateOriginEndpointResponsePrivate(this), parent) +{ + setRequest(new UpdateOriginEndpointRequest(request)); + setReply(reply); +} + +/*! + * \reimp + */ +const UpdateOriginEndpointRequest * UpdateOriginEndpointResponse::request() const +{ + Q_D(const UpdateOriginEndpointResponse); + return static_cast(d->request); +} + +/*! + * \reimp + * Parses a successful MediaPackage UpdateOriginEndpoint \a response. + */ +void UpdateOriginEndpointResponse::parseSuccess(QIODevice &response) +{ + //Q_D(UpdateOriginEndpointResponse); + QXmlStreamReader xml(&response); + /// @todo +} + +/*! + * \class QtAws::MediaPackage::UpdateOriginEndpointResponsePrivate + * \brief The UpdateOriginEndpointResponsePrivate class provides private implementation for UpdateOriginEndpointResponse. + * \internal + * + * \inmodule QtAwsMediaPackage + */ + +/*! + * Constructs a UpdateOriginEndpointResponsePrivate object with public implementation \a q. + */ +UpdateOriginEndpointResponsePrivate::UpdateOriginEndpointResponsePrivate( + UpdateOriginEndpointResponse * const q) : MediaPackageResponsePrivate(q) +{ + +} + +/*! + * Parses a MediaPackage UpdateOriginEndpoint response element from \a xml. + */ +void UpdateOriginEndpointResponsePrivate::parseUpdateOriginEndpointResponse(QXmlStreamReader &xml) +{ + Q_ASSERT(xml.name() == QLatin1String("UpdateOriginEndpointResponse")); + Q_UNUSED(xml) ///< @todo +} + +} // namespace MediaPackage +} // namespace QtAws diff --git a/pool/shard000/C++/0000092_asset_texture.cpp b/pool/shard000/C++/0000092_asset_texture.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f913728be9f062373a0801685feba8afd2fc23df --- /dev/null +++ b/pool/shard000/C++/0000092_asset_texture.cpp @@ -0,0 +1,139 @@ +/* +The MIT License (MIT) +Copyright (c) 2016 Alexey Yegorov + +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 "asset_texture.h" +#include "io/utils/file_guard.h" +#include +#include +#include +#include + +namespace eps { + +static void read_png_data_callback(png_structp png_ptr, + png_byte * raw_data, + png_size_t read_length) +{ + io::file * stream = static_cast(png_get_io_ptr(png_ptr)); + stream->read(raw_data, 1, read_length); +} + +asset_texture::asset_texture() + : data_(nullptr, ::free) +{} + +asset_texture::asset_texture(const std::string & resource) + : asset(resource) + , data_(nullptr, ::free) +{} + +bool asset_texture::load(utils::link fs, const std::string & resource) +{ + io::file_guard stream(fs, resource); + if(!stream.valid()) + return false; + + png_byte header[8]; + if(stream.read(header, 1, 8) != 8) + return false; + + if(png_sig_cmp(header, 0, 8) != 0) + return false; + + png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr); + if(png_ptr == nullptr) + return false; + + png_infop info_ptr = png_create_info_struct(png_ptr); + if(info_ptr == nullptr) + { + png_destroy_read_struct(&png_ptr, &info_ptr, nullptr); + return false; + } + + png_set_read_fn(png_ptr, stream.get(), read_png_data_callback); + + if(setjmp(png_jmpbuf(png_ptr))) + { + png_destroy_read_struct(&png_ptr, &info_ptr, nullptr); + return false; + } + + png_uint_32 width, height; + int bit_depth, color_type; + + png_set_sig_bytes(png_ptr, 8); + png_read_info(png_ptr, info_ptr); + png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, + nullptr, nullptr, nullptr); + + // convert transparency to full alpha + if(png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) + png_set_tRNS_to_alpha(png_ptr); + + // convert grayscale, if needed. + if(color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) + png_set_expand_gray_1_2_4_to_8(png_ptr); + + // convert paletted images, if needed. + if(color_type == PNG_COLOR_TYPE_PALETTE) + png_set_palette_to_rgb(png_ptr); + + // add alpha channel, if there is none. + // rationale: GL_RGBA is faster than GL_RGB on many GPUs + if(color_type == PNG_COLOR_TYPE_PALETTE || color_type == PNG_COLOR_TYPE_RGB) + png_set_add_alpha(png_ptr, 0xFF, PNG_FILLER_AFTER); + + // ensure 8-bit packing + if(bit_depth < 8) + png_set_packing(png_ptr); + else if (bit_depth == 16) + png_set_scale_16(png_ptr); + + png_read_update_info(png_ptr, info_ptr); + + // read the new color type after updates have been made. + color_type = png_get_color_type(png_ptr, info_ptr); + + png_size_t row_size = png_get_rowbytes(png_ptr, info_ptr); + assert(row_size > 0); + + png_byte * raw_image = static_cast(malloc(row_size * height)); + assert(raw_image != nullptr); + + std::vector row_ptrs(height); + + for(png_uint_32 i = 0; i < height; ++i) + row_ptrs[i] = raw_image + i * row_size; + + png_read_image(png_ptr, &row_ptrs[0]); + png_destroy_read_struct(&png_ptr, &info_ptr, nullptr); + + data_ = utils::unique(raw_image, ::free); + size_.x = width; + size_.y = height; + + return true; +} + +} /* eps */ diff --git a/pool/shard000/C++/0000094_test_201_300.cpp b/pool/shard000/C++/0000094_test_201_300.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e1281b6c6f4ffdfe25dcd3f6fcdac4ef293cd2df --- /dev/null +++ b/pool/shard000/C++/0000094_test_201_300.cpp @@ -0,0 +1,82 @@ +#include +#include + +#include "linked_list.hpp" +#include "binary_tree.hpp" + +#include "234.hpp" +#include "237.hpp" +#include "268.hpp" +#include "283.hpp" + +using ::testing::UnorderedElementsAre; +using ::testing::ElementsAre; + + +TEST(Test234, GeneralTest) { + using List = LinkedList; + + List l0; + EXPECT_TRUE(isPalindromeStack(l0.head())); + EXPECT_TRUE(isPalindrome(l0.head())); + + List l1 {1, 2}; + EXPECT_FALSE(isPalindromeStack(l1.head())); + EXPECT_FALSE(isPalindrome(l1.head())); + // Test that the linked list has been recovered after reverse. + EXPECT_THAT(l1.toVector(), ElementsAre(1, 2)); + + List l2 {1, 2, 3, 2, 1}; + EXPECT_TRUE(isPalindromeStack(l2.head())); + EXPECT_TRUE(isPalindrome(l2.head())); + EXPECT_THAT(l2.toVector(), ElementsAre(1, 2, 3, 2, 1)); + + List l3 {1, 2, 2, 1}; + EXPECT_TRUE(isPalindromeStack(l3.head())); + EXPECT_TRUE(isPalindrome(l3.head())); + EXPECT_THAT(l3.toVector(), ElementsAre(1, 2, 2, 1)); +} + +TEST(Test237, GeneralTest) { + using List = LinkedList; + + List l0 {0, 1, 2}; + deleteNode(l0.nthNode(1)); + EXPECT_THAT(l0.toVector(), ElementsAre(0, 2)); + + List l1 {0, 1, 2}; + deleteNode(l1.nthNode(0)); + EXPECT_THAT(l1.toVector(), ElementsAre(1, 2)); +} + +TEST(Test268, GeneralTest) { + std::vector nums0 {3, 0, 1}; + EXPECT_EQ(missingNumber(nums0), 2); + + std::vector nums1 {1}; + EXPECT_EQ(missingNumber(nums1), 0); + + std::vector nums2 {9, 6, 4, 2, 3, 5, 7, 0, 1}; + EXPECT_EQ(missingNumber(nums2), 8); +} + +TEST(Test283, GeneralTest) { + std::vector nums0 {0, 1, 0, 3, 12}; + moveZeroes(nums0); + EXPECT_THAT(nums0, ElementsAre(1, 3, 12, 0, 0)); + + std::vector nums1 {0}; + moveZeroes(nums1); + EXPECT_THAT(nums1, ElementsAre(0)); + + std::vector nums2 {1, 2}; + moveZeroes(nums2); + EXPECT_THAT(nums2, ElementsAre(1, 2)); +} + + +int main(int argc, char **argv) { + ::testing::InitGoogleTest(&argc, argv); + + return RUN_ALL_TESTS(); +} \ No newline at end of file diff --git a/pool/shard000/C++/0000097_strlen_of_shadow.cc b/pool/shard000/C++/0000097_strlen_of_shadow.cc new file mode 100644 index 0000000000000000000000000000000000000000..3066dd5b61ae92fbd52bce81f104643e65de9b5c --- /dev/null +++ b/pool/shard000/C++/0000097_strlen_of_shadow.cc @@ -0,0 +1,36 @@ +// RUN: %clangxx_msan -O0 %s -o %t && %run %t + +// Check that strlen() and similar intercepted functions can be called on shadow +// memory. + +#include +#include +#include +#include +#include +#include "test.h" + +const char *mem_to_shadow(const char *p) { +#if defined(__x86_64__) + return (char *)((uintptr_t)p ^ 0x500000000000ULL); +#elif defined (__mips64) + return (char *)((uintptr_t)p & ~0x4000000000ULL); +#elif defined(__powerpc64__) +#define LINEARIZE_MEM(mem) \ + (((uintptr_t)(mem) & ~0x200000000000ULL) ^ 0x100000000000ULL) + return (char *)(LINEARIZE_MEM(p) + 0x080000000000ULL); +#elif defined(__aarch64__) + return (char *)((uintptr_t)p ^ 0x6000000000ULL); +#endif +} + +int main(void) { + const char *s = "abcdef"; + assert(strlen(s) == 6); + assert(strlen(mem_to_shadow(s)) == 0); + + char *t = new char[42]; + t[41] = 0; + assert(strlen(mem_to_shadow(t)) == 41); + return 0; +} diff --git a/pool/shard000/C++/0000112_check_nan.cc b/pool/shard000/C++/0000112_check_nan.cc new file mode 100644 index 0000000000000000000000000000000000000000..ec916ff8cfe616c7e7bc065ce1c7a1a0de7907f1 --- /dev/null +++ b/pool/shard000/C++/0000112_check_nan.cc @@ -0,0 +1,59 @@ +// { dg-do run { target c++11 } } +// { dg-require-c-std "" } +// { dg-add-options ieee } +// { dg-options "-D__STDCPP_WANT_MATH_SPEC_FUNCS__" } + +// Copyright (C) 2016 Free Software Foundation, Inc. +// +// This file is part of the GNU ISO C++ Library. This library is free +// software; you can redistribute it and/or modify it under the +// terms of the GNU General Public License as published by the +// Free Software Foundation; either version 3, or (at your option) +// any later version. +// +// This 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 General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this library; see the file COPYING3. If not see +// . + +// 8.1.2 assoc_legendre + +#include +#include + +void +test01() +{ + float xf = std::numeric_limits::quiet_NaN(); + double xd = std::numeric_limits::quiet_NaN(); + long double xl = std::numeric_limits::quiet_NaN(); + + unsigned int l = 2, m = 1; + + float a = std::assoc_legendre(l, m, xf); + float b = std::assoc_legendref(l, m, xf); + double c = std::assoc_legendre(l, m, xd); + long double d = std::assoc_legendre(l, m, xl); + long double e = std::assoc_legendrel(l, m, xl); + + bool test [[gnu::unused]] = true; + VERIFY(std::isnan(a)); + VERIFY(std::isnan(b)); + VERIFY(std::isnan(c)); + VERIFY(std::isnan(d)); + VERIFY(std::isnan(e)); + + return; +} + +int +main() +{ + test01(); + return 0; +} + diff --git a/pool/shard000/C++/0000122_decoder_engine.cc b/pool/shard000/C++/0000122_decoder_engine.cc new file mode 100644 index 0000000000000000000000000000000000000000..11f959fa15341f5dc9454300dffcb3d2e0783448 --- /dev/null +++ b/pool/shard000/C++/0000122_decoder_engine.cc @@ -0,0 +1,117 @@ +// Copyright 2018 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 "chromeos/services/ime/decoder/decoder_engine.h" + +#include "base/callback_helpers.h" +#include "base/files/file_path.h" +#include "base/files/file_util.h" +#include "chromeos/services/ime/constants.h" + +namespace chromeos { +namespace ime { + +namespace { + +// A client delegate passed to the shared library in order for the +// shared library to send replies back to the engine. +class ClientDelegate : public ImeClientDelegate { + public: + // All replies from the shared library will be sent to both |remote| and + // |callback|. + ClientDelegate(const std::string& ime_spec, + mojo::PendingRemote remote) + : ime_spec_(ime_spec), client_remote_(std::move(remote)) { + client_remote_.set_disconnect_handler(base::BindOnce( + &ClientDelegate::OnDisconnected, base::Unretained(this))); + } + + ~ClientDelegate() override {} + + const char* ImeSpec() override { return ime_spec_.c_str(); } + + void Process(const uint8_t* data, size_t size) override { + if (client_remote_ && client_remote_.is_bound()) { + std::vector msg(data, data + size); + client_remote_->ProcessMessage(msg, base::DoNothing()); + } + } + + void Destroy() override {} + + private: + void OnDisconnected() { + client_remote_.reset(); + LOG(ERROR) << "Client remote is disconnected." << ime_spec_; + } + + // The ime specification which is unique in the scope of engine. + std::string ime_spec_; + + // The InputChannel remote used to talk to the client. + mojo::Remote client_remote_; +}; + +} // namespace + +DecoderEngine::DecoderEngine(ImeCrosPlatform* platform) : platform_(platform) { + if (!TryLoadDecoder()) { + LOG(WARNING) << "DecoderEngine INIT INCOMPLETED."; + } +} + +DecoderEngine::~DecoderEngine() {} + +bool DecoderEngine::TryLoadDecoder() { + auto* decoder = ImeDecoder::GetInstance(); + if (decoder->GetStatus() == ImeDecoder::Status::kSuccess && + decoder->GetEntryPoints().is_ready) { + decoder_entry_points_ = decoder->GetEntryPoints(); + decoder_entry_points_->init_once(platform_); + return true; + } + return false; +} + +bool DecoderEngine::BindRequest( + const std::string& ime_spec, + mojo::PendingReceiver receiver, + mojo::PendingRemote remote, + const std::vector& extra) { + if (IsImeSupportedByDecoder(ime_spec)) { + // Activates an IME engine via the shared library. Passing a + // |ClientDelegate| for engine instance created by the shared library to + // make safe calls on the client. + if (decoder_entry_points_->activate_ime( + ime_spec.c_str(), + new ClientDelegate(ime_spec, std::move(remote)))) { + decoder_channel_receivers_.Add(this, std::move(receiver)); + // TODO(https://crbug.com/837156): Registry connection error handler. + return true; + } + return false; + } + return false; +} + +bool DecoderEngine::IsImeSupportedByDecoder(const std::string& ime_spec) { + return decoder_entry_points_ && + decoder_entry_points_->supports(ime_spec.c_str()); +} + +void DecoderEngine::ProcessMessage(const std::vector& message, + ProcessMessageCallback callback) { + // TODO(https://crbug.com/837156): Set a default protobuf message. + std::vector result; + + // Handle message via corresponding functions of loaded decoder. + if (decoder_entry_points_) { + decoder_entry_points_->process(message.data(), message.size()); + } + + std::move(callback).Run(result); +} + +} // namespace ime +} // namespace chromeos diff --git a/pool/shard000/C++/0000127_time_conversion_unittest.cc b/pool/shard000/C++/0000127_time_conversion_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..4d8c77ea6ee8a1b0fa57b96f83b76d7054be1441 --- /dev/null +++ b/pool/shard000/C++/0000127_time_conversion_unittest.cc @@ -0,0 +1,57 @@ +// 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 +#include + +#include "ppapi/shared_impl/time_conversion.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace ppapi { + +// Slop we'll allow in two Time "internal values" to consider them equal. +// Double conversion can introduce rounding errors. The internal values are in +// microseconds, so an error here is very small. +static const int kTimeInternalValueSlop = 2; + +// Same as above in double-precision seconds units. +static const double kTimeSecondsSlop = + static_cast(kTimeInternalValueSlop) / + base::Time::kMicrosecondsPerSecond; + +TEST(TimeConversion, Time) { + // Should be able to round-trip. + base::Time now = base::Time::Now(); + base::Time converted = ppapi::PPTimeToTime(TimeToPPTime(now)); + EXPECT_GE(kTimeInternalValueSlop, + abs(static_cast((converted - now).ToInternalValue()))); + + // Units should be in seconds. + base::Time one_second_from_now = now + base::TimeDelta::FromSeconds(1); + double converted_one_second_from_now = + ppapi::TimeToPPTime(one_second_from_now) - ppapi::TimeToPPTime(now); + EXPECT_GE(kTimeSecondsSlop, fabs(converted_one_second_from_now - 1)); +} + +TEST(TimeConversion, EpochTime) { + // Should be able to round-trip from epoch time. + base::Time epoch = base::Time::UnixEpoch(); + base::Time converted = ppapi::PPTimeToTime(TimeToPPTime(epoch)); + EXPECT_GE(kTimeInternalValueSlop, + abs(static_cast((converted - epoch).ToInternalValue()))); + + // Units should be in seconds. + base::Time one_second_from_epoch = epoch + base::TimeDelta::FromSeconds(1); + double converted_one_second_from_epoch = + ppapi::TimeToPPTime(one_second_from_epoch) - ppapi::TimeToPPTime(epoch); + EXPECT_GE(kTimeSecondsSlop, fabs(converted_one_second_from_epoch - 1)); + + // Epoch time should be equal to a PP_Time of 0.0. + EXPECT_GE(kTimeSecondsSlop, fabs(ppapi::TimeToPPTime(epoch) - 0.0)); + EXPECT_GE(kTimeInternalValueSlop, + abs(static_cast( + (ppapi::PPTimeToTime(0.0) - epoch).ToInternalValue()))); +} + +} // namespace ppapi diff --git a/pool/shard000/C++/0000141_potential_file_reader.cpp b/pool/shard000/C++/0000141_potential_file_reader.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3d357771c7d2187a164866361f17259c60bb4d1f --- /dev/null +++ b/pool/shard000/C++/0000141_potential_file_reader.cpp @@ -0,0 +1,283 @@ +/* -*- c++ -*- ---------------------------------------------------------- + LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator + https://lammps.sandia.gov/, Sandia National Laboratories + Steve Plimpton, sjplimp@sandia.gov + + Copyright (2003) Sandia Corporation. Under the terms of Contract + DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains + certain rights in this software. This software is distributed under + the GNU General Public License. + + See the README file in the top-level LAMMPS directory. +------------------------------------------------------------------------- */ + +/* ---------------------------------------------------------------------- + Contributing authors: Richard Berger (Temple U) +------------------------------------------------------------------------- */ + +#include "potential_file_reader.h" + +#include "comm.h" +#include "error.h" +#include "text_file_reader.h" +#include "tokenizer.h" +#include "update.h" + +using namespace LAMMPS_NS; + +/** Class for reading and parsing LAMMPS potential files + * + * The value of the class member variable *ignore_comments* controls + * whether any text following the pound sign (#) should be ignored (true) + * or not (false). Default: true, i.e. ignore. +\verbatim embed:rst + +*See also* + :cpp:class:`TextFileReader` + +\endverbatim + * + * \param lmp Pointer to LAMMPS instance + * \param filename Name of file to be read + * \param potential_name Name of potential style for error messages + * \param name_suffix Suffix added to potential name in error messages + * \param auto_convert Bitmask of supported unit conversions + */ + +PotentialFileReader::PotentialFileReader(LAMMPS *lmp, + const std::string &filename, + const std::string &potential_name, + const std::string &name_suffix, + const int auto_convert) : + Pointers(lmp), + reader(nullptr), + filename(filename), + filetype(potential_name + name_suffix), + unit_convert(auto_convert) +{ + if (comm->me != 0) { + error->one(FLERR, "FileReader should only be called by proc 0!"); + } + + try { + reader = open_potential(filename); + if (!reader) { + error->one(FLERR, "cannot open {} potential file {}: {}", + potential_name, filename, utils::getsyserror()); + } + } catch (FileReaderException &e) { + error->one(FLERR, e.what()); + } +} + +/* + * \param lmp Pointer to LAMMPS instance + * \param filename Name of file to be read + * \param potential_name Name of potential style for error messages + * \param auto_convert Bitmask of supported unit conversions + */ +PotentialFileReader::PotentialFileReader(LAMMPS *lmp, + const std::string &filename, + const std::string &potential_name, + const int auto_convert) : + PotentialFileReader(lmp, filename, potential_name, " potential", auto_convert) +{ +} + +/** Closes the file */ + +PotentialFileReader::~PotentialFileReader() { + delete reader; +} + +/** Set comment (= text after '#') handling preference for the file to be read + * + * \param value Comment text is ignored if true, or not if false */ +void PotentialFileReader::ignore_comments(bool value) { + reader->ignore_comments = value; +} + +/** Read a line but ignore its content */ + +void PotentialFileReader::skip_line() { + try { + reader->skip_line(); + } catch (FileReaderException &e) { + error->one(FLERR, e.what()); + } +} + +/** Read the next line(s) until *nparams* words have been read. + * + * This reads a line and counts the words in it, if the number + * is less than the requested number, it will read the next + * line, as well. Output will be a string with all read lines + * combined. The purpose is to somewhat replicate the reading + * behavior of formatted files in Fortran. + * + * \param nparams Number of words that must be read. Default: 0 + * \return String with the concatenated text */ + +char *PotentialFileReader::next_line(int nparams) { + try { + return reader->next_line(nparams); + } catch (FileReaderException &e) { + error->one(FLERR, e.what()); + } + return nullptr; +} + +/** Read lines until *n* doubles have been read and stored in array *list* + * + * This reads lines from the file using the next_line() function, + * and splits them into floating-point numbers using the + * ValueTokenizer class and stores the number is the provided list. + * + * \param list Pointer to array with suitable storage for *n* doubles + * \param n Number of doubles to be read */ + +void PotentialFileReader::next_dvector(double * list, int n) { + try { + return reader->next_dvector(list, n); + } catch (FileReaderException &e) { + error->one(FLERR, e.what()); + } +} + +/** Read text until *nparams* words are read and passed to a tokenizer object for custom parsing. + * + * This reads lines from the file using the next_line() function, + * and splits them into floating-point numbers using the + * ValueTokenizer class and stores the number is the provided list. + * + * \param nparams Number of words to be read + * \param separators String with list of separators. + * \return ValueTokenizer object for read in text */ + +ValueTokenizer PotentialFileReader::next_values(int nparams, const std::string &separators) { + try { + return reader->next_values(nparams, separators); + } catch (FileReaderException &e) { + error->one(FLERR, e.what()); + } + return ValueTokenizer(""); +} + +/** Read next line and convert first word to a double + * + * \return Value of first word in line as double */ + +double PotentialFileReader::next_double() { + try { + char * line = reader->next_line(1); + return ValueTokenizer(line).next_double(); + } catch (FileReaderException &e) { + error->one(FLERR, e.what()); + } + return 0.0; +} + +/** Read next line and convert first word to an int + * + * \return Value of first word in line as int */ + +int PotentialFileReader::next_int() { + try { + char * line = reader->next_line(1); + return ValueTokenizer(line).next_int(); + } catch (FileReaderException &e) { + error->one(FLERR, e.what()); + } + return 0; +} + +/** Read next line and convert first word to a tagint + * + * \return Value of first word in line as tagint */ + +tagint PotentialFileReader::next_tagint() { + try { + char * line = reader->next_line(1); + return ValueTokenizer(line).next_tagint(); + } catch (FileReaderException &e) { + error->one(FLERR, e.what()); + } + return 0; +} + +/** Read next line and convert first word to a bigint + * + * \return Value of first word in line as bigint */ + +bigint PotentialFileReader::next_bigint() { + try { + char * line = reader->next_line(1); + return ValueTokenizer(line).next_bigint(); + } catch (FileReaderException &e) { + error->one(FLERR, e.what()); + } + return 0; +} + +/** Read next line and return first word + * + * \return First word of read in line */ + +std::string PotentialFileReader::next_string() { + try { + char * line = reader->next_line(1); + return ValueTokenizer(line).next_string(); + } catch (FileReaderException &e) { + error->one(FLERR, e.what()); + } + return ""; +} + +/** Look up and open the potential file + * +\verbatim embed:rst + +*See also* + :cpp:func:`utils::open_potential`, + :cpp:class:`TextFileReader` + +\endverbatim + * \param path Path of the potential file to open + * \return Pointer to TextFileReader object created */ + +TextFileReader *PotentialFileReader::open_potential(const std::string &path) { + std::string filepath = utils::get_potential_file_path(path); + + if (!filepath.empty()) { + std::string unit_style = lmp->update->unit_style; + std::string date = utils::get_potential_date(filepath, filetype); + std::string units = utils::get_potential_units(filepath, filetype); + + if (!date.empty()) + utils::logmesg(lmp,"Reading {} file {} with DATE: {}\n", + filetype, filename, date); + + if (units.empty()) { + unit_convert = utils::NOCONVERT; + } else { + if (units == unit_style) { + unit_convert = utils::NOCONVERT; + } else { + if ((units == "metal") && (unit_style == "real") && (unit_convert & utils::METAL2REAL)) { + unit_convert = utils::METAL2REAL; + } else if ((units == "real") && (unit_style == "metal") && (unit_convert & utils::REAL2METAL)) { + unit_convert = utils::REAL2METAL; + } else { + lmp->error->one(FLERR, "{} file {} requires {} units " + "but {} units are in use", filetype, + filename, units, unit_style); + } + } + } + if (unit_convert != utils::NOCONVERT) + lmp->error->warning(FLERR, fmt::format("Converting {} in {} units to {} " + "units", filetype, units, unit_style)); + return new TextFileReader(filepath, filetype); + } + return nullptr; +} diff --git a/pool/shard000/C++/0000144_testArrayBuffer.cpp b/pool/shard000/C++/0000144_testArrayBuffer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ed00f09755a68cb7f2e8555823f438488d92e994 --- /dev/null +++ b/pool/shard000/C++/0000144_testArrayBuffer.cpp @@ -0,0 +1,227 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * vim: set ts=8 sts=4 et sw=4 tw=99: + */ + +#include "jsfriendapi.h" + +#include "jsapi-tests/tests.h" + +BEGIN_TEST(testArrayBuffer_bug720949_steal) +{ + static const unsigned NUM_TEST_BUFFERS = 2; + static const unsigned MAGIC_VALUE_1 = 3; + static const unsigned MAGIC_VALUE_2 = 17; + + JS::RootedObject buf_len1(cx), buf_len200(cx); + JS::RootedObject tarray_len1(cx), tarray_len200(cx); + + uint32_t sizes[NUM_TEST_BUFFERS] = { sizeof(uint32_t), 200 * sizeof(uint32_t) }; + JS::HandleObject testBuf[NUM_TEST_BUFFERS] = { buf_len1, buf_len200 }; + JS::HandleObject testArray[NUM_TEST_BUFFERS] = { tarray_len1, tarray_len200 }; + + // Single-element ArrayBuffer (uses fixed slots for storage) + CHECK(buf_len1 = JS_NewArrayBuffer(cx, sizes[0])); + CHECK(tarray_len1 = JS_NewInt32ArrayWithBuffer(cx, testBuf[0], 0, -1)); + + CHECK(JS_SetElement(cx, testArray[0], 0, MAGIC_VALUE_1)); + + // Many-element ArrayBuffer (uses dynamic storage) + CHECK(buf_len200 = JS_NewArrayBuffer(cx, 200 * sizeof(uint32_t))); + CHECK(tarray_len200 = JS_NewInt32ArrayWithBuffer(cx, testBuf[1], 0, -1)); + + for (unsigned i = 0; i < NUM_TEST_BUFFERS; i++) { + JS::HandleObject obj = testBuf[i]; + JS::HandleObject view = testArray[i]; + uint32_t size = sizes[i]; + JS::RootedValue v(cx); + + // Byte lengths should all agree + CHECK(JS_IsArrayBufferObject(obj)); + CHECK_EQUAL(JS_GetArrayBufferByteLength(obj), size); + CHECK(JS_GetProperty(cx, obj, "byteLength", &v)); + CHECK(v.isInt32(size)); + CHECK(JS_GetProperty(cx, view, "byteLength", &v)); + CHECK(v.isInt32(size)); + + // Modifying the underlying data should update the value returned through the view + { + JS::AutoCheckCannotGC nogc; + bool sharedDummy; + uint8_t* data = JS_GetArrayBufferData(obj, &sharedDummy, nogc); + CHECK(data != nullptr); + *reinterpret_cast(data) = MAGIC_VALUE_2; + } + CHECK(JS_GetElement(cx, view, 0, &v)); + CHECK(v.isInt32(MAGIC_VALUE_2)); + + // Steal the contents + void* contents = JS_StealArrayBufferContents(cx, obj); + CHECK(contents != nullptr); + + CHECK(JS_IsDetachedArrayBufferObject(obj)); + + // Transfer to a new ArrayBuffer + JS::RootedObject dst(cx, JS_NewArrayBufferWithContents(cx, size, contents)); + CHECK(JS_IsArrayBufferObject(dst)); + { + JS::AutoCheckCannotGC nogc; + bool sharedDummy; + (void) JS_GetArrayBufferData(obj, &sharedDummy, nogc); + } + + JS::RootedObject dstview(cx, JS_NewInt32ArrayWithBuffer(cx, dst, 0, -1)); + CHECK(dstview != nullptr); + + CHECK_EQUAL(JS_GetArrayBufferByteLength(dst), size); + { + JS::AutoCheckCannotGC nogc; + bool sharedDummy; + uint8_t* data = JS_GetArrayBufferData(dst, &sharedDummy, nogc); + CHECK(data != nullptr); + CHECK_EQUAL(*reinterpret_cast(data), MAGIC_VALUE_2); + } + CHECK(JS_GetElement(cx, dstview, 0, &v)); + CHECK(v.isInt32(MAGIC_VALUE_2)); + } + + return true; +} +END_TEST(testArrayBuffer_bug720949_steal) + +// Varying number of views of a buffer, to test the detachment weak pointers +BEGIN_TEST(testArrayBuffer_bug720949_viewList) +{ + JS::RootedObject buffer(cx); + + // No views + buffer = JS_NewArrayBuffer(cx, 2000); + buffer = nullptr; + GC(cx); + + // One view. + { + buffer = JS_NewArrayBuffer(cx, 2000); + JS::RootedObject view(cx, JS_NewUint8ArrayWithBuffer(cx, buffer, 0, -1)); + void* contents = JS_StealArrayBufferContents(cx, buffer); + CHECK(contents != nullptr); + JS_free(nullptr, contents); + GC(cx); + CHECK(hasDetachedBuffer(view)); + CHECK(JS_IsDetachedArrayBufferObject(buffer)); + view = nullptr; + GC(cx); + buffer = nullptr; + GC(cx); + } + + // Two views + { + buffer = JS_NewArrayBuffer(cx, 2000); + + JS::RootedObject view1(cx, JS_NewUint8ArrayWithBuffer(cx, buffer, 0, -1)); + JS::RootedObject view2(cx, JS_NewUint8ArrayWithBuffer(cx, buffer, 1, 200)); + + // Remove, re-add a view + view2 = nullptr; + GC(cx); + view2 = JS_NewUint8ArrayWithBuffer(cx, buffer, 1, 200); + + // Detach + void* contents = JS_StealArrayBufferContents(cx, buffer); + CHECK(contents != nullptr); + JS_free(nullptr, contents); + + CHECK(hasDetachedBuffer(view1)); + CHECK(hasDetachedBuffer(view2)); + CHECK(JS_IsDetachedArrayBufferObject(buffer)); + + view1 = nullptr; + GC(cx); + view2 = nullptr; + GC(cx); + buffer = nullptr; + GC(cx); + } + + return true; +} + +static void GC(JSContext* cx) +{ + JS_GC(cx); + JS_GC(cx); // Trigger another to wait for background finalization to end +} + +bool hasDetachedBuffer(JS::HandleObject obj) { + JS::RootedValue v(cx); + return JS_GetProperty(cx, obj, "byteLength", &v) && v.toInt32() == 0; +} + +END_TEST(testArrayBuffer_bug720949_viewList) + +BEGIN_TEST(testArrayBuffer_externalize) +{ + if (!testWithSize(cx, 2)) // ArrayBuffer data stored inline in the object. + return false; + if (!testWithSize(cx, 2000)) // ArrayBuffer data stored out-of-line in a separate heap allocation. + return false; + + return true; +} + +bool testWithSize(JSContext* cx, size_t n) +{ + JS::RootedObject buffer(cx, JS_NewArrayBuffer(cx, n)); + CHECK(buffer != nullptr); + + JS::RootedObject view(cx, JS_NewUint8ArrayWithBuffer(cx, buffer, 0, -1)); + CHECK(view != nullptr); + + void* contents = JS_ExternalizeArrayBufferContents(cx, buffer); + CHECK(contents != nullptr); + uint32_t actualLength; + CHECK(hasExpectedLength(cx, view, &actualLength)); + CHECK(actualLength == n); + CHECK(!JS_IsDetachedArrayBufferObject(buffer)); + CHECK(JS_GetArrayBufferByteLength(buffer) == uint32_t(n)); + + uint8_t* uint8Contents = static_cast(contents); + CHECK(*uint8Contents == 0); + uint8_t randomByte(rand() % UINT8_MAX); + *uint8Contents = randomByte; + + JS::RootedValue v(cx); + CHECK(JS_GetElement(cx, view, 0, &v)); + CHECK(v.toInt32() == randomByte); + + view = nullptr; + GC(cx); + + CHECK(JS_DetachArrayBuffer(cx, buffer)); + GC(cx); + CHECK(*uint8Contents == randomByte); + JS_free(cx, contents); + GC(cx); + buffer = nullptr; + GC(cx); + + return true; +} + +static void GC(JSContext* cx) +{ + JS_GC(cx); + JS_GC(cx); // Trigger another to wait for background finalization to end +} + +static bool +hasExpectedLength(JSContext* cx, JS::HandleObject obj, uint32_t* len) +{ + JS::RootedValue v(cx); + if (!JS_GetProperty(cx, obj, "byteLength", &v)) + return false; + *len = v.toInt32(); + return true; +} + +END_TEST(testArrayBuffer_externalize) diff --git a/pool/shard000/C++/0000147_ExpressionClassifier.cpp b/pool/shard000/C++/0000147_ExpressionClassifier.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3faef14300ccd8e23a6c1e73f2707d86b29f3ffb --- /dev/null +++ b/pool/shard000/C++/0000147_ExpressionClassifier.cpp @@ -0,0 +1,128 @@ +#include "ExpressionClassifier.h" + +using namespace cv; + + +/* + sigma describes the classification sharpness. A larger sigma means the + boundary between different expressions is more blurry. It won't change + the classification, but will give you probabilities that are smoother. +*/ + +ExpressionClassifier::ExpressionClassifier() +:sigma(10.0) { +} + +void ExpressionClassifier::save(string directory) const { + ofDirectory dir(directory); + dir.create(true); + for(int i = 0; i < size(); i++) { + string filename = dir.path() + "/" + expressions[i].getDescription() + ".yml"; + cout << "saving to " << filename << endl; + expressions[i].save(filename); + } +} + +void ExpressionClassifier::load(string directory) { + ofDirectory dir(directory); + dir.listDir(); + int n = dir.size(); + expressions.resize(n); + for(int i = 0; i < n; i++) { + expressions[i].load(dir.getPath(i)); + } +} + +unsigned int ExpressionClassifier::classify(const ofxFaceTracker& tracker) { + Mat cur; + tracker.getObjectPointsMat().copyTo(cur); + norm(cur); + int n = size(); + probability.resize(n); + if(n == 0) { + return 0; + } + vector > val(n); + double sum = 0; + for(int i = 0; i < n; i++){ + int m = expressions[i].size(); + for(int j = 0; j < m; j++){ + double v = norm(cur, expressions[i].getExample(j)); + double p = exp(-v * v / sigma); + val[i].push_back(p); + sum += p; + } + } + for(int i = 0; i < n; i++){ + probability[i] = 0; + int m = expressions[i].size(); + for(int j = 0; j < m; j++) { + probability[i] += val[i][j]; + } + probability[i] /= sum; + } + return getPrimaryExpression(); +} + +unsigned int ExpressionClassifier::getPrimaryExpression() const { + int maxExpression = 0; + double maxProbability = 0; + for(int i = 0; i < probability.size(); i++) { + double cur = getProbability(i); + if(cur > maxProbability) { + maxExpression = i; + maxProbability = cur; + } + } + return maxExpression; +} + +double ExpressionClassifier::getProbability(unsigned int i) const { + if(i < probability.size()) { + return probability[i]; + } else { + return 0; + } +} + +string ExpressionClassifier::getDescription(unsigned int i) const { + return expressions[i].getDescription(); +} + +Expression& ExpressionClassifier::getExpression(unsigned int i) { + return expressions[i]; +} + +void ExpressionClassifier::setSigma(double sigma) { + this->sigma = sigma; +} + +double ExpressionClassifier::getSigma() const { + return sigma; +} + +unsigned int ExpressionClassifier::size() const { + return expressions.size(); +} + +void ExpressionClassifier::addExpression(string description) { + if(description == "") { + description = ofToString(expressions.size()); + } + expressions.push_back(Expression(description)); +} + +void ExpressionClassifier::addExpression(Expression& expression) { + expressions.push_back(expression); +} + +void ExpressionClassifier::addSample(const ofxFaceTracker& tracker) { + if(size() == 0) { + addExpression(); + } + expressions.back().addSample(tracker.getObjectPointsMat()); +} + +void ExpressionClassifier::reset() { + expressions.clear(); +} \ No newline at end of file diff --git a/pool/shard000/C++/0000148_random_unittest.cc b/pool/shard000/C++/0000148_random_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..00d4b2b5e861ec20489b5fa72ec47da15676111f --- /dev/null +++ b/pool/shard000/C++/0000148_random_unittest.cc @@ -0,0 +1,27 @@ +// 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 "crypto/random.h" + +#include "base/strings/string_util.h" +#include "testing/gtest/include/gtest/gtest.h" + +// Basic functionality tests. Does NOT test the security of the random data. + +// Ensures we don't have all trivial data, i.e. that the data is indeed random. +// Currently, that means the bytes cannot be all the same (e.g. all zeros). +bool IsTrivial(const std::string& bytes) { + for (size_t i = 0; i < bytes.size(); i++) { + if (bytes[i] != bytes[0]) { + return false; + } + } + return true; +} + +TEST(RandBytes, RandBytes) { + std::string bytes(16, '\0'); + crypto::RandBytes(base::WriteInto(&bytes, bytes.size()), bytes.size()); + EXPECT_TRUE(!IsTrivial(bytes)); +} diff --git a/pool/shard000/C++/0000174_DataFlashFileReader.cpp b/pool/shard000/C++/0000174_DataFlashFileReader.cpp new file mode 100644 index 0000000000000000000000000000000000000000..911ba2f9465fa85af7741fef7bb802038afa7219 --- /dev/null +++ b/pool/shard000/C++/0000174_DataFlashFileReader.cpp @@ -0,0 +1,63 @@ +#include + +#include +#include +#include +#include +#include + +DataFlashFileReader::DataFlashFileReader() : fd(-1) {} + +bool DataFlashFileReader::open_log(const char *logfile) +{ + fd = ::open(logfile, O_RDONLY); + if (fd == -1) { + return false; + } + return true; +} + +bool DataFlashFileReader::update(char type[5]) +{ + uint8_t hdr[3]; + if (::read(fd, hdr, 3) != 3) { + return false; + } + if (hdr[0] != HEAD_BYTE1 || hdr[1] != HEAD_BYTE2) { + printf("bad log header\n"); + return false; + } + + if (hdr[2] == LOG_FORMAT_MSG) { + struct log_Format f; + memcpy(&f, hdr, 3); + if (::read(fd, &f.type, sizeof(f)-3) != sizeof(f)-3) { + return false; + } + memcpy(&formats[f.type], &f, sizeof(formats[f.type])); + strncpy(type, "FMT", 3); + type[3] = 0; + + return handle_log_format_msg(f); + } + + const struct log_Format &f = formats[hdr[2]]; + if (f.length == 0) { + // can't just throw these away as the format specifies the + // number of bytes in the message + ::printf("No format defined for type (%d)\n", hdr[2]); + exit(1); + } + + uint8_t msg[f.length]; + + memcpy(msg, hdr, 3); + if (::read(fd, &msg[3], f.length-3) != f.length-3) { + return false; + } + + strncpy(type, f.name, 4); + type[4] = 0; + + return handle_msg(f,msg); +} diff --git a/pool/shard000/C++/0000179_for_each_suffix.cpp b/pool/shard000/C++/0000179_for_each_suffix.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3cfa7725a00913a6c7402f859091ae462b7806d2 --- /dev/null +++ b/pool/shard000/C++/0000179_for_each_suffix.cpp @@ -0,0 +1,31 @@ +#define _SCL_SECURE_NO_WARNINGS +#include +#include +#include + +using namespace nark; + +static void on_suffix(size_t nth, fstring suffix) { + printf("%06zd\t%.*s\n", nth, suffix.ilen(), suffix.data()); +} + +int main(int argc, char* argv[]) { + const char* ifile = NULL; // input dfa file name + for (int opt=0; (opt = getopt(argc, argv, "i:")) != -1; ) { + switch (opt) { + case '?': return 3; + case 'i': ifile = optarg; break; + } + } + std::auto_ptr dfa; + if (ifile) dfa.reset(DFA_Interface::load_from(ifile)); // by filename + else dfa.reset(DFA_Interface::load_from(stdin)); // by FILE* + + for(int i = optind; i < argc; ++i) { + const char* exact_prefix = argv[i]; + printf("%s ----------\n", exact_prefix); + dfa->for_each_suffix(exact_prefix, on_suffix); + } + return 0; +} + diff --git a/pool/shard000/C++/0000187_Event.cpp b/pool/shard000/C++/0000187_Event.cpp new file mode 100644 index 0000000000000000000000000000000000000000..73bda8475627acd9457a6400759e03872f48ed8d --- /dev/null +++ b/pool/shard000/C++/0000187_Event.cpp @@ -0,0 +1,59 @@ +/* +Copyright (C) 2005 Matthias Braun + +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 "Event.hpp" + +#include + +Event::Event(SDL_Event& event) + : inside(true) +{ + switch(event.type) { + case SDL_KEYUP: + type = KEYUP; + keysym = event.key.keysym; + break; + case SDL_KEYDOWN: + type = KEYDOWN; + keysym = event.key.keysym; + break; + case SDL_MOUSEMOTION: + type = MOUSEMOTION; + mousepos = Vector2(event.motion.x, event.motion.y); + mousemove = Vector2(event.motion.xrel, event.motion.yrel); + break; + case SDL_MOUSEBUTTONUP: + type = MOUSEBUTTONUP; + mousepos = Vector2(event.button.x, event.button.y); + mousebutton = event.button.button; + break; + case SDL_MOUSEBUTTONDOWN: + type = MOUSEBUTTONDOWN; + mousepos = Vector2(event.button.x, event.button.y); + mousebutton = event.button.button; + break; + default: + assert(false); + } +} + +Event::Event(float _elapsedTime) + : type(UPDATE), inside(false), elapsedTime(_elapsedTime) +{ +} diff --git a/pool/shard000/C++/0000190_trim_strings.cpp b/pool/shard000/C++/0000190_trim_strings.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8949e060108ec84105bd139764e2105bb7bcb68c --- /dev/null +++ b/pool/shard000/C++/0000190_trim_strings.cpp @@ -0,0 +1,44 @@ +#include +#include +#include + +std::string trim_left(const std::string& source) { + std::string res = source; + res.erase( res.begin(), std::find_if( res.begin(), res.end(), []( const char c ) { return !std::isspace(c); } ) ); + return res; +} + +std::string trim_right(const std::string& source) { + std::string res = source; + res.erase( std::find_if( res.rbegin(), res.rend(), []( const char c ) { return !std::isspace(c); } ).base( ), res.end( ) ); + return res; +} + +std::string trim( const std::string& source ) { + return trim_right( trim_left( source ) ); +} + +std::string& trim_ref( std::string& src ) { + src.erase( std::find_if( src.rbegin(), src.rend(), []( const int c ) { return !std::isspace(c); } ).base( ), src.end( ) ); + src.erase( src.begin(), std::find_if( src.begin(), src.end(), []( const int c ) { return !std::isspace(c); } ) ); + return src; +} + +bool test( const std::string& source, const std::string& result ) { + return source == trim_left( trim_right( result ) ); +} + +int main() { + const std::string const_source = " This is string with spacebars. "; + std::string source = " This is string with spacebars. "; + + std::cout << "Source:[" << const_source << "]" << std::endl; + std::cout << "TrimLeft:[" << trim_left( const_source ) << "]" < +#include +#include +using std::wstringstream; + +vector> common::proc_snapshot() +{ + vector> ret; + HANDLE hProcs=0; + if ( hProcs = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) ) + { + PROCESSENTRY32 pe32; + pe32.dwSize = sizeof( PROCESSENTRY32 ); + BOOL ok = Process32First(hProcs, &pe32); + while (ok) + { + vector line; + wstringstream ss; + ss<; + + +nes_bandai_pt554_device::nes_bandai_pt554_device(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock) + : nes_cnrom_device(mconfig, NES_BANDAI_PT554, "NES Cart Bandai PT-554 PCB", tag, owner, clock, "nes_bandai_pt554", __FILE__), + m_samples(*this, "samples") +{ +} + + + +/*------------------------------------------------- + mapper specific handlers + -------------------------------------------------*/ + +/*------------------------------------------------- + + Bandai PT-554 board emulation + + This is used by Aerobics Studio. It is basically a CNROM board + with an Mitsubishi M50805 LPC / PARCOR speech synthesis chip + with internal tables stored in ROM which have not yet been dumped. + + iNES: mapper 3? + + -------------------------------------------------*/ + +WRITE8_MEMBER(nes_bandai_pt554_device::write_m) +{ + LOG_MMC(("Bandai PT-554 Sound write, data: %02x\n", data)); + + if (!BIT(data, 6)) + m_samples->start(data & 0x07, data & 0x07); + else + m_samples->stop(data & 0x07); +} + +static const char *const pt554_sample_names[] = +{ + "*ftaerobi", + "00", + "01", + "02", + "03", + "04", + "05", + "06", + "07", + nullptr +}; + +//------------------------------------------------- +// MACHINE_DRIVER +//------------------------------------------------- + +static MACHINE_CONFIG_FRAGMENT( pt554 ) + + // additional sound hardware + MCFG_SPEAKER_STANDARD_MONO("addon") + + MCFG_SOUND_ADD("samples", SAMPLES, 0) + MCFG_SAMPLES_CHANNELS(8) + MCFG_SAMPLES_NAMES(pt554_sample_names) + MCFG_SOUND_ROUTE(ALL_OUTPUTS, "addon", 0.50) +MACHINE_CONFIG_END + +//------------------------------------------------- +// machine_config_additions +//------------------------------------------------- + +machine_config_constructor nes_bandai_pt554_device::device_mconfig_additions() const +{ + return MACHINE_CONFIG_NAME( pt554 ); +} diff --git a/pool/shard000/C++/0000200_pmic.cpp b/pool/shard000/C++/0000200_pmic.cpp new file mode 100644 index 0000000000000000000000000000000000000000..66ccdd5caa2bb01caf0cc99f075436fb5f3df2f4 --- /dev/null +++ b/pool/shard000/C++/0000200_pmic.cpp @@ -0,0 +1,284 @@ +/** + ****************************************************************************** + * @file pmic.cpp + * @author Mohit Bhoite + * @version V1.0.0 + * @date 11-August-2015 + * @brief driver for the power managment IC BQ24195 + ****************************************************************************** + Copyright (c) 2013-2015 Particle Industries, Inc. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation, either + version 3 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, see . + ****************************************************************************** + */ + + +#include "PMIC.h" + +PMIC::PMIC() +{ + +} + + +/******************************************************************************* + * Function Name : + * Description : + * Input : + * Return : + *******************************************************************************/ +bool PMIC::begin() +{ + Wire3.begin(); + return 1; +} + + +// Return the version number of the chip +// Value at reset: 00100011, 0x23 +byte PMIC::getVersion() { + + byte DATA = 0; + DATA = readRegister(PMIC_VERSION_REGISTER); + return DATA; +} + +/* +//----------------------------------------------------------------------------- +//System Status Register +//----------------------------------------------------------------------------- +//NOTE: This is a read-only register + +REG08 +BIT +--- VBUS status +7: VBUS_STAT[1] | 00: Unknown (no input, or DPDM detection incomplete), 01: USB host +6: VBUS_STAT[0] | 10: Adapter port, 11: OTG +--- Charging status +5: CHRG_STAT[1] | 00: Not Charging, 01: Pre-charge ( VSYSMIN) + 1: In VSYSMIN regulation (BAT < VSYSMIN) +*/ + +/******************************************************************************* + * Function Name : + * Description : + * Input : + * Return : + *******************************************************************************/ +bool PMIC::isPowerGood(void) { + + byte DATA = 0; + DATA = readRegister(SYSTEM_STATUS_REGISTER); + if(DATA & 0b00000100) return 1; + else return 0; +} + +/******************************************************************************* + * Function Name : + * Description : + * Input : + * Return : + *******************************************************************************/ +bool PMIC::isHot(void) { + + byte DATA = 0; + DATA = readRegister(SYSTEM_STATUS_REGISTER); + if(DATA & 0b00000010) return 1; + else return 0; +} + +/******************************************************************************* + * Function Name : + * Description : + * Input : + * Return : + *******************************************************************************/ +byte PMIC::getSystemStatus() { + + byte DATA = 0; + DATA = readRegister(SYSTEM_STATUS_REGISTER); + return DATA; +} + +/******************************************************************************* + * Function Name : + * Description : + * Input : + * Return : + *******************************************************************************/ +byte PMIC::getFault() { + + byte DATA = 0; + DATA = readRegister(FAULT_REGISTER); + return DATA; + +} + +/* +//----------------------------------------------------------------------------- +// Input source control register +//----------------------------------------------------------------------------- + +REG00 +BIT +7 : 0:Enable Buck regulator 1:disable buck regulator (powered only from a LiPo) +--- input volatge limit. this is used to determine if USB source is overloaded +6 : VINDPM[3] 640mV | offset is 3.88V, Range is 3.88 to 5.08 +5 : VINDPM[2] 320mV | enabling bits 3 to 6 adds the volatges to 3.88 base value +4 : VINDPM[1] 160mV | Default is 4.36 (0110) +3 : VINDPM[0] 80mV | +--- input current limit +2 : INLIM[2] 000: 100mA, 001: 150mA, 010: 500mA, | Default: 100mA when OTG pin is LOW and +1 : INLIM[1] 011: 900mA, 100: 1.2A, 101: 1.5A | 500mA when OTG pin is HIGH +0 : INLIM[0] 110: 2.0A, 111: 3.0A | when charging port detected, 1.5A + +//----------------------------------------------------------------------------- +*/ + + +/******************************************************************************* + * Function Name : setInputCurrentLimit + * Description : Sets the input current limit for the PMIC + * Input : 100,150,500,900,1200,1500,2000,3000 (mAmp) + * Return : 0 Error, 1 Success + *******************************************************************************/ + +bool PMIC::setInputCurrentLimit(uint16_t current) { + + + byte DATA = readRegister(INPUT_SOURCE_REGISTER); + byte mask = DATA & 0b11111000; + + switch (current) { + + case 100: + writeRegister(INPUT_SOURCE_REGISTER, (mask | 0b00000000)); + break; + + case 150: + writeRegister(INPUT_SOURCE_REGISTER, (mask | 0b00000001)); + break; + + case 500: + writeRegister(INPUT_SOURCE_REGISTER, (mask | 0b00000010)); + break; + + case 900: + writeRegister(INPUT_SOURCE_REGISTER, (mask | 0b00000011)); + break; + + case 1200: + writeRegister(INPUT_SOURCE_REGISTER, (mask | 0b00000100)); + break; + + case 1500: + writeRegister(INPUT_SOURCE_REGISTER, (mask | 0b00000101)); + break; + + case 2000: + writeRegister(INPUT_SOURCE_REGISTER, (mask | 0b00000110)); + break; + + case 3000: + writeRegister(INPUT_SOURCE_REGISTER, (mask | 0b00000111)); + break; + + default: + return 0; // return error since the value passed didn't match + } + + return 1; // value was written successfully +} + +/******************************************************************************* + * Function Name : readInputSourceRegister + * Description : + * Input : NONE + * Return : + *******************************************************************************/ + +byte PMIC::readInputSourceRegister(void) { + + + return readRegister(INPUT_SOURCE_REGISTER); +} + +/******************************************************************************* + * Function Name : enableBuck + * Description : + * Input : NONE + * Return : + *******************************************************************************/ + +bool PMIC::enableBuck(void) { + + byte DATA = readRegister(INPUT_SOURCE_REGISTER); + writeRegister(INPUT_SOURCE_REGISTER, (DATA & 0b01111111)); + return 1; +} + +/******************************************************************************* + * Function Name : disableBuck + * Description : + * Input : NONE + * Return : + *******************************************************************************/ + +bool PMIC::disableBuck(void) { + + byte DATA = readRegister(INPUT_SOURCE_REGISTER); + writeRegister(INPUT_SOURCE_REGISTER, (DATA | 0b10000000)); + return 1; +} + +/******************************************************************************* + * Function Name : + * Description : + * Input : + * Return : + *******************************************************************************/ +byte PMIC::readRegister(byte startAddress) { + + byte DATA = 0; + Wire3.beginTransmission(PMIC_ADDRESS); + Wire3.write(startAddress); + Wire3.endTransmission(true); + + Wire3.requestFrom(PMIC_ADDRESS, 1, true); + DATA = Wire3.read(); + return DATA; +} + + +/******************************************************************************* + * Function Name : + * Description : + * Input : + * Return : + *******************************************************************************/ +void PMIC::writeRegister(byte address, byte DATA) { + + Wire3.beginTransmission(PMIC_ADDRESS); + Wire3.write(address); + Wire3.write(DATA); + Wire3.endTransmission(true); +} diff --git a/pool/shard000/C++/0000205_10526279.cpp b/pool/shard000/C++/0000205_10526279.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fffdb97ebafdada4373a55754d8a36d96976c8f5 --- /dev/null +++ b/pool/shard000/C++/0000205_10526279.cpp @@ -0,0 +1,132 @@ +//Language: GNU C++ + + +// +// main.cpp +// Practice +// +// Created by Neel Shah on 11/27/14. +// Copyright (c) 2014 Neel Shah. All rights reserved. +// + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#define MAXN 100005 +#define MAXLG 17 +#define rep(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end))) + +using namespace std; +typedef long long int ll; +typedef pair mp; +template void chmin(T &t, const T &f) { if (t > f) t = f; } +template void chmax(T &t, const T &f) { if (t < f) t = f; } + +map v[2*MAXN];; +vector > ans; +int n, m, deg[2*MAXN], eid = 0, self[2*MAXN]={0}; + +int main() +{ + scanf("%d %d", &n, &m); + for(int i=0; i odd; + for(int i=0; i path; + stack s; + s.push(0); + + while(!s.empty()) + { + int node = s.top(); + if(v[node].size() == 0) + { + s.pop(); + path.push_back(node); + if(self[node] > 0) + { + for(int i=0; i::iterator it = v[node].begin(); + int id = it->first; + int next = it->second; + + map::iterator it1 = v[next].find(id); + v[next].erase(it1); + map::iterator it2 = v[node].find(id); + v[node].erase(it2); + + s.push(next); + } + +// for(int i=0; iLoadIcon(IDR_MAINFRAME); +} + +void CReadEditDemoDlg::DoDataExchange(CDataExchange* pDX) +{ + CDialog::DoDataExchange(pDX); + //{{AFX_DATA_MAP(CReadEditDemoDlg) + DDX_Control(pDX, IDC_READEDIT, m_ctlRead); + //}}AFX_DATA_MAP +} + +BEGIN_MESSAGE_MAP(CReadEditDemoDlg, CDialog) + //{{AFX_MSG_MAP(CReadEditDemoDlg) + ON_WM_SYSCOMMAND() + ON_WM_PAINT() + ON_WM_QUERYDRAGICON() + ON_BN_CLICKED(IDC_ADD, OnAdd) + ON_BN_CLICKED(IDC_CLEAR, OnClear) + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// CReadEditDemoDlg message handlers + +BOOL CReadEditDemoDlg::OnInitDialog() +{ + CDialog::OnInitDialog(); + + // Add "About..." menu item to system menu. + + // IDM_ABOUTBOX must be in the system command range. + ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); + ASSERT(IDM_ABOUTBOX < 0xF000); + + CMenu* pSysMenu = GetSystemMenu(FALSE); + if (pSysMenu != NULL) + { + CString strAboutMenu; + strAboutMenu.LoadString(IDS_ABOUTBOX); + if (!strAboutMenu.IsEmpty()) + { + pSysMenu->AppendMenu(MF_SEPARATOR); + pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); + } + } + + // Set the icon for this dialog. The framework does this automatically + // when the application's main window is not a dialog + SetIcon(m_hIcon, TRUE); // Set big icon + SetIcon(m_hIcon, FALSE); // Set small icon + + // TODO: Add extra initialization here + + return TRUE; // return TRUE unless you set the focus to a control +} + +void CReadEditDemoDlg::OnSysCommand(UINT nID, LPARAM lParam) +{ + if ((nID & 0xFFF0) == IDM_ABOUTBOX) + { + CAboutDlg dlgAbout; + dlgAbout.DoModal(); + } + else + { + CDialog::OnSysCommand(nID, lParam); + } +} + +// If you add a minimize button to your dialog, you will need the code below +// to draw the icon. For MFC applications using the document/view model, +// this is automatically done for you by the framework. + +void CReadEditDemoDlg::OnPaint() +{ + if (IsIconic()) + { + CPaintDC dc(this); // device context for painting + + SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0); + + // Center icon in client rectangle + int cxIcon = GetSystemMetrics(SM_CXICON); + int cyIcon = GetSystemMetrics(SM_CYICON); + CRect rect; + GetClientRect(&rect); + int x = (rect.Width() - cxIcon + 1) / 2; + int y = (rect.Height() - cyIcon + 1) / 2; + + // Draw the icon + dc.DrawIcon(x, y, m_hIcon); + } + else + { + CDialog::OnPaint(); + } +} + +// The system calls this to obtain the cursor to display while the user drags +// the minimized window. +HCURSOR CReadEditDemoDlg::OnQueryDragIcon() +{ + return (HCURSOR) m_hIcon; +} + +void CReadEditDemoDlg::OnAdd() +{ + // TODO: Add your control notification handler code here + CString strText; + GetDlgItemText (IDC_WRITEEDIT, strText);//»ñÈ¡±à¼­¿ò¿Ø¼þÎı¾ + m_ctlRead.AppendString (strText);//Ìí¼Óµ½Ö»¶Á±à¼­¿ò¿Ø¼þÖÐ + SetDlgItemText (IDC_WRITEEDIT, ""); +} + +void CReadEditDemoDlg::OnClear() +{ + // TODO: Add your control notification handler code here + SetDlgItemText (IDC_READEDIT, ""); +} diff --git a/pool/shard000/C++/0000211_SVGFETurbulenceElement.cpp b/pool/shard000/C++/0000211_SVGFETurbulenceElement.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a357e4e5c5edade3d63a288ced40fbef8c4e32c8 --- /dev/null +++ b/pool/shard000/C++/0000211_SVGFETurbulenceElement.cpp @@ -0,0 +1,182 @@ +/* + * Copyright (C) 2004, 2005, 2007 Nikolas Zimmermann + * Copyright (C) 2004, 2005, 2006 Rob Buis + * + * 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" + +#if ENABLE(SVG) && ENABLE(FILTERS) +#include "SVGFETurbulenceElement.h" + +#include "Attribute.h" +#include "SVGElementInstance.h" +#include "SVGNames.h" +#include "SVGParserUtilities.h" + +namespace WebCore { + +// Animated property definitions +DEFINE_ANIMATED_NUMBER_MULTIPLE_WRAPPERS(SVGFETurbulenceElement, SVGNames::baseFrequencyAttr, baseFrequencyXIdentifier(), BaseFrequencyX, baseFrequencyX) +DEFINE_ANIMATED_NUMBER_MULTIPLE_WRAPPERS(SVGFETurbulenceElement, SVGNames::baseFrequencyAttr, baseFrequencyYIdentifier(), BaseFrequencyY, baseFrequencyY) +DEFINE_ANIMATED_INTEGER(SVGFETurbulenceElement, SVGNames::numOctavesAttr, NumOctaves, numOctaves) +DEFINE_ANIMATED_NUMBER(SVGFETurbulenceElement, SVGNames::seedAttr, Seed, seed) +DEFINE_ANIMATED_ENUMERATION(SVGFETurbulenceElement, SVGNames::stitchTilesAttr, StitchTiles, stitchTiles, SVGStitchOptions) +DEFINE_ANIMATED_ENUMERATION(SVGFETurbulenceElement, SVGNames::typeAttr, Type, type, TurbulenceType) + +BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGFETurbulenceElement) + REGISTER_LOCAL_ANIMATED_PROPERTY(baseFrequencyX) + REGISTER_LOCAL_ANIMATED_PROPERTY(baseFrequencyY) + REGISTER_LOCAL_ANIMATED_PROPERTY(numOctaves) + REGISTER_LOCAL_ANIMATED_PROPERTY(seed) + REGISTER_LOCAL_ANIMATED_PROPERTY(stitchTiles) + REGISTER_LOCAL_ANIMATED_PROPERTY(type) + REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes) +END_REGISTER_ANIMATED_PROPERTIES + +inline SVGFETurbulenceElement::SVGFETurbulenceElement(const QualifiedName& tagName, Document& document) + : SVGFilterPrimitiveStandardAttributes(tagName, document) + , m_numOctaves(1) + , m_stitchTiles(SVG_STITCHTYPE_NOSTITCH) + , m_type(FETURBULENCE_TYPE_TURBULENCE) +{ + ASSERT(hasTagName(SVGNames::feTurbulenceTag)); + registerAnimatedPropertiesForSVGFETurbulenceElement(); +} + +PassRefPtr SVGFETurbulenceElement::create(const QualifiedName& tagName, Document& document) +{ + return adoptRef(new SVGFETurbulenceElement(tagName, document)); +} + +const AtomicString& SVGFETurbulenceElement::baseFrequencyXIdentifier() +{ + DEFINE_STATIC_LOCAL(AtomicString, s_identifier, ("SVGBaseFrequencyX", AtomicString::ConstructFromLiteral)); + return s_identifier; +} + +const AtomicString& SVGFETurbulenceElement::baseFrequencyYIdentifier() +{ + DEFINE_STATIC_LOCAL(AtomicString, s_identifier, ("SVGBaseFrequencyY", AtomicString::ConstructFromLiteral)); + return s_identifier; +} + +bool SVGFETurbulenceElement::isSupportedAttribute(const QualifiedName& attrName) +{ + DEFINE_STATIC_LOCAL(HashSet, supportedAttributes, ()); + if (supportedAttributes.isEmpty()) { + supportedAttributes.add(SVGNames::baseFrequencyAttr); + supportedAttributes.add(SVGNames::numOctavesAttr); + supportedAttributes.add(SVGNames::seedAttr); + supportedAttributes.add(SVGNames::stitchTilesAttr); + supportedAttributes.add(SVGNames::typeAttr); + } + return supportedAttributes.contains(attrName); +} + +void SVGFETurbulenceElement::parseAttribute(const QualifiedName& name, const AtomicString& value) +{ + if (!isSupportedAttribute(name)) { + SVGFilterPrimitiveStandardAttributes::parseAttribute(name, value); + return; + } + + if (name == SVGNames::typeAttr) { + TurbulenceType propertyValue = SVGPropertyTraits::fromString(value); + if (propertyValue > 0) + setTypeBaseValue(propertyValue); + return; + } + + if (name == SVGNames::stitchTilesAttr) { + SVGStitchOptions propertyValue = SVGPropertyTraits::fromString(value); + if (propertyValue > 0) + setStitchTilesBaseValue(propertyValue); + return; + } + + if (name == SVGNames::baseFrequencyAttr) { + float x, y; + if (parseNumberOptionalNumber(value, x, y)) { + setBaseFrequencyXBaseValue(x); + setBaseFrequencyYBaseValue(y); + } + return; + } + + if (name == SVGNames::seedAttr) { + setSeedBaseValue(value.toFloat()); + return; + } + + if (name == SVGNames::numOctavesAttr) { + setNumOctavesBaseValue(value.string().toUIntStrict()); + return; + } + + ASSERT_NOT_REACHED(); +} + +bool SVGFETurbulenceElement::setFilterEffectAttribute(FilterEffect* effect, const QualifiedName& attrName) +{ + FETurbulence* turbulence = static_cast(effect); + if (attrName == SVGNames::typeAttr) + return turbulence->setType(type()); + if (attrName == SVGNames::stitchTilesAttr) + return turbulence->setStitchTiles(stitchTiles()); + if (attrName == SVGNames::baseFrequencyAttr) + return (turbulence->setBaseFrequencyX(baseFrequencyX()) || turbulence->setBaseFrequencyY(baseFrequencyY())); + if (attrName == SVGNames::seedAttr) + return turbulence->setSeed(seed()); + if (attrName == SVGNames::numOctavesAttr) + return turbulence->setNumOctaves(numOctaves()); + + ASSERT_NOT_REACHED(); + return false; +} + +void SVGFETurbulenceElement::svgAttributeChanged(const QualifiedName& attrName) +{ + if (!isSupportedAttribute(attrName)) { + SVGFilterPrimitiveStandardAttributes::svgAttributeChanged(attrName); + return; + } + + SVGElementInstance::InvalidationGuard invalidationGuard(this); + + if (attrName == SVGNames::baseFrequencyAttr + || attrName == SVGNames::numOctavesAttr + || attrName == SVGNames::seedAttr + || attrName == SVGNames::stitchTilesAttr + || attrName == SVGNames::typeAttr) { + primitiveAttributeChanged(attrName); + return; + } + + ASSERT_NOT_REACHED(); +} + +PassRefPtr SVGFETurbulenceElement::build(SVGFilterBuilder*, Filter* filter) +{ + if (baseFrequencyX() < 0 || baseFrequencyY() < 0) + return 0; + return FETurbulence::create(filter, type(), baseFrequencyX(), baseFrequencyY(), numOctaves(), seed(), stitchTiles() == SVG_STITCHTYPE_STITCH); +} + +} + +#endif // ENABLE(SVG) diff --git a/pool/shard000/C++/0000212_mis_fun.cc b/pool/shard000/C++/0000212_mis_fun.cc new file mode 100644 index 0000000000000000000000000000000000000000..92a987ba6d8590004f4dc91527e2e8d3f97838b1 --- /dev/null +++ b/pool/shard000/C++/0000212_mis_fun.cc @@ -0,0 +1,110 @@ +/*! + * @file mis_fun.cc + * @brief Thread utility functions. + * + * @author Piotr Trojanek + * + * @ingroup LIB + */ + +#include +#include +#include +#include +#include +#include + +#include "base/lib/mis_fun.h" + +#if defined(linux) +#include +#elif defined(__FreeBSD__) +#include +#endif + +namespace mrrocpp { +namespace lib { + +//! Set the process scheduler +void set_process_sched() +{ + struct sched_param param; + + int policy_priority_min = sched_get_priority_min(SCHED_FIFO); + if (policy_priority_min == -1) { + perror("sched_get_priority_min() "); + } + + param.sched_priority = policy_priority_min; + + if (sched_setscheduler(getpid(), SCHED_FIFO, ¶m) == -1) { + perror("sched_setscheduler() "); + } +} + +void set_thread_priority(int sched_priority_l) +{ + const pthread_t thread = pthread_self(); + + int policy; + struct sched_param param; + + if (pthread_getschedparam(thread, &policy, ¶m)) { + perror("pthread_getschedparam() "); + } + + // check priority range + int policy_priority_min = sched_get_priority_min(SCHED_FIFO); + if (policy_priority_min == -1) { + perror("sched_get_priority_min() "); + } + + int policy_priority_max = sched_get_priority_max(SCHED_FIFO); + if (policy_priority_max == -1) { + perror("sched_get_priority_max() "); + } + + //pthread_setscheduler(thread, SCHED_FIFO, sched_priority_l); + + if ((sched_priority_l < policy_priority_min) || (sched_priority_l > policy_priority_max)) { + fprintf(stderr, "requested thread priority (%d) not in <%d:%d> priority range\n", sched_priority_l, policy_priority_min, policy_priority_max); + } else { + param.sched_priority = sched_priority_l; + if (pthread_setschedparam(thread, SCHED_FIFO, ¶m)) { + fprintf(stderr, "pthread_setschedparam(%lu, SCHED_FIFO, %d) failed: %s\n", thread, sched_priority_l, strerror(errno)); + //perror("pthread_setschedparam() "); + } + } +} + +//! set the thread name for debugging +int set_thread_name(const char * newname) +{ +#if defined(linux) + char comm[16]; + snprintf(comm, sizeof(comm), "%s", newname); + return prctl(PR_SET_NAME, comm, 0l, 0l, 0l); +#elif defined(__FreeBSD__) + // FreeBSD defines this call to void + pthread_set_name_np(pthread_self(), newname); + + return 0; +#endif + return -1; +} + +#ifndef TIMESPEC_VALID +# define TIMESPEC_VALID(__ts) ((__ts)->tv_nsec >= 0 && (__ts)->tv_nsec < 1000000000L) +#endif + +void timespec_increment_ns(struct timespec * ts, unsigned long increment) +{ + ts->tv_nsec += increment; + while (ts->tv_nsec >= 1000000000) { + ts->tv_sec += 1; + ts->tv_nsec -= 1000000000; + } +} + +} // namespace lib +} // namespace mrrocpp diff --git a/pool/shard000/C++/0000213_SensorProcessor.cpp b/pool/shard000/C++/0000213_SensorProcessor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9298f840ce32c34cc67cd5650099ee80ff1387af --- /dev/null +++ b/pool/shard000/C++/0000213_SensorProcessor.cpp @@ -0,0 +1,174 @@ +/** + * @file SensorProcessor.cpp + * @author George Andrew Brindeiro (georgebrindeiro@lara.unb.br) + * @date Dec 10, 2013 + * + * @ingroup ros-nodes + * + * @attention Copyright (C) 2013 + * @attention Laboratório de Automação e Robótica (LARA) + * @attention Universidade de Brasília (UnB) + */ + +#include + +bool print_msgs = false; +bool display_features = true; + +ros::Publisher pub_cloud; +ros::Publisher pub_pose; // TODO: remove this when filter is running + +int main (int argc, char** argv) +{ + // Initialize ROS + ros::init (argc, argv, "hs_sensor_processor"); + ros::NodeHandle nh; + + // Create ROS subscribers for sensor data + ros::Subscriber sub_cloud = nh.subscribe ("kinect_cloud", 1, cloud_cb); + + // Create a ROS publisher for processed sensor data + pub_cloud = nh.advertise ("feature_cloud", 1); + + // Create a CV window for debugging + if(display_features) + cv::namedWindow("Display window", CV_WINDOW_AUTOSIZE); + + // TODO: remove this when filter is running + ros::Subscriber sub_odom = nh.subscribe ("odometry", 1, odom_cb); + pub_pose = nh.advertise ("estimated_pose", 1); + + // Spin + ros::spin (); +} + +void cloud_cb(const sensor_msgs::PointCloud2::ConstPtr& cloud_msg) +{ + // Print cloud message + if(print_msgs) + print_cloud_msg(cloud_msg); + + // Extract RGB image from cloud + cv::Mat img; + extract_rgb_image(cloud_msg, img); + + // Detect keypoints from RGB image + std::vector keypoints; + extract_keypoints(img, keypoints); + + // Build feature cloud from keypoints + sensor_msgs::PointCloud2::Ptr feature_cloud_msg(new sensor_msgs::PointCloud2); + build_feature_cloud(keypoints, cloud_msg, feature_cloud_msg); + + // Publish the data + pub_cloud.publish(feature_cloud_msg); +} + +void odom_cb(const nav_msgs::Odometry::ConstPtr& odom_msg) +{ + // Fake pose estimate from odometry + geometry_msgs::PoseWithCovarianceStamped::Ptr estimated_pose_msg(new geometry_msgs::PoseWithCovarianceStamped); + estimated_pose_msg->header = odom_msg->header; + estimated_pose_msg->pose = odom_msg->pose; + + pub_pose.publish(estimated_pose_msg); +} + +void print_cloud_msg(const sensor_msgs::PointCloud2::ConstPtr& cloud_msg) +{ + // Parse cloud message + int seq = cloud_msg->header.seq; + int time_sec = cloud_msg->header.stamp.sec; + int time_nsec = cloud_msg->header.stamp.nsec; + std::string frame_id = cloud_msg->header.frame_id; + int width = cloud_msg->width; + int height = cloud_msg->height; + bool is_bigendian = cloud_msg->is_bigendian; + int point_step = cloud_msg->point_step; + int row_step = cloud_msg->row_step; + bool is_dense = cloud_msg->is_dense; + + // Print cloud message for debugging + ROS_INFO("Point cloud\n"); + ROS_INFO("seq: %d", seq); + ROS_INFO("timestamp: %d.%d", time_sec, time_nsec); + ROS_INFO("frame_id: %s", frame_id.c_str()); + ROS_INFO("dimensions: %dx%d", width, height); + ROS_INFO("is_bigendian: %d", is_bigendian); + ROS_INFO("point_step: %d\n", point_step); + ROS_INFO("row_step: %d\n", row_step); + ROS_INFO("is_dense: %d\n", is_dense); + ROS_INFO("------------------------------------------------------"); +} + +void extract_rgb_image(const sensor_msgs::PointCloud2::ConstPtr& cloud_msg, cv::Mat& img) +{ + // Copy the RGB fields of a sensor_msgs::PointCloud2 into a sensor_msgs::Image + sensor_msgs::Image image_msg; + pcl::toROSMsg(*cloud_msg, image_msg); + + // Convert a sensor_msgs::Image to an OpenCV-compatible CvImage, copying the image data. + cv_bridge::CvImagePtr cv_image_ptr; + cv_image_ptr = cv_bridge::toCvCopy(image_msg); + + // Assign cv::Mat portion of CvImage to output + img = cv_image_ptr->image; +} + +void extract_keypoints(cv::Mat& img, std::vector& keypoints) +{ + // Extract SURF keypoints + int minHessian = 400; + + cv::SurfFeatureDetector detector(minHessian); + detector.detect(img, keypoints); + + // Display detected keypoints + if(display_features) + { + // Print out number of features + //ROS_INFO("# features: %ld", keypoints.size()); + + // Overlay keypoints on image + cv::drawKeypoints(img, keypoints, img, cv::Scalar::all(-1), cv::DrawMatchesFlags::DEFAULT); + + // Show results in display window + cv::imshow("Display window", img); + cv::waitKey(10); + } +} + +void build_feature_cloud(const std::vector& keypoints, const sensor_msgs::PointCloud2::ConstPtr& cloud_msg, sensor_msgs::PointCloud2::Ptr& feature_cloud_msg) +{ + // Work with PCL compatible variables + pcl::PointIndices::Ptr keypoint_indices(new pcl::PointIndices()); + pcl::PCLPointCloud2::Ptr pcl_input(new pcl::PCLPointCloud2); + pcl::PCLPointCloud2::Ptr pcl_output(new pcl::PCLPointCloud2); + + // Convert keypoints to PCL format + for(int i=0; i < keypoints.size(); i++) + { + int x = keypoints[i].pt.x;//1-640 + int y = keypoints[i].pt.y;//1-480 + + keypoint_indices->indices.push_back(cloud_msg->width*y+x); + } + + // Convert cloud_msg to PCL format + pcl_conversions::toPCL(*cloud_msg, *pcl_input); + + // Use ExtractIndices filter to build feature cloud + pcl::ExtractIndices extract; + + extract.setInputCloud(pcl_input); + extract.setIndices(keypoint_indices); + extract.setNegative(false); + extract.filter(*pcl_output); + + // Convert pcl_output to ROS format + pcl_conversions::fromPCL(*pcl_output, *feature_cloud_msg); + + // Print out number of features for debugging + if(display_features) + ROS_INFO("# feature cloud points: %d", pcl_output->width * pcl_output->height); +} diff --git a/pool/shard000/C++/0000216_moc_qaccessibleplugin.cpp b/pool/shard000/C++/0000216_moc_qaccessibleplugin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1e92c1fc306bdde8e5763441978e31a9c7865d5b --- /dev/null +++ b/pool/shard000/C++/0000216_moc_qaccessibleplugin.cpp @@ -0,0 +1,87 @@ +/**************************************************************************** +** Meta object code from reading C++ file 'qaccessibleplugin.h' +** +** Created: Mon 26. Nov 09:30:49 2012 +** by: The Qt Meta Object Compiler version 63 (Qt 4.8.4) +** +** WARNING! All changes made in this file will be lost! +*****************************************************************************/ + +#include "../../../accessible/qaccessibleplugin.h" +#if !defined(Q_MOC_OUTPUT_REVISION) +#error "The header file 'qaccessibleplugin.h' doesn't include ." +#elif Q_MOC_OUTPUT_REVISION != 63 +#error "This file was generated using the moc from 4.8.4. It" +#error "cannot be used with the include files from this version of Qt." +#error "(The moc has changed too much.)" +#endif + +QT_BEGIN_MOC_NAMESPACE +static const uint qt_meta_data_QAccessiblePlugin[] = { + + // content: + 6, // revision + 0, // classname + 0, 0, // classinfo + 0, 0, // methods + 0, 0, // properties + 0, 0, // enums/sets + 0, 0, // constructors + 0, // flags + 0, // signalCount + + 0 // eod +}; + +static const char qt_meta_stringdata_QAccessiblePlugin[] = { + "QAccessiblePlugin\0" +}; + +void QAccessiblePlugin::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) +{ + Q_UNUSED(_o); + Q_UNUSED(_id); + Q_UNUSED(_c); + Q_UNUSED(_a); +} + +const QMetaObjectExtraData QAccessiblePlugin::staticMetaObjectExtraData = { + 0, qt_static_metacall +}; + +const QMetaObject QAccessiblePlugin::staticMetaObject = { + { &QObject::staticMetaObject, qt_meta_stringdata_QAccessiblePlugin, + qt_meta_data_QAccessiblePlugin, &staticMetaObjectExtraData } +}; + +#ifdef Q_NO_DATA_RELOCATION +const QMetaObject &QAccessiblePlugin::getStaticMetaObject() { return staticMetaObject; } +#endif //Q_NO_DATA_RELOCATION + +const QMetaObject *QAccessiblePlugin::metaObject() const +{ + return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; +} + +void *QAccessiblePlugin::qt_metacast(const char *_clname) +{ + if (!_clname) return 0; + if (!strcmp(_clname, qt_meta_stringdata_QAccessiblePlugin)) + return static_cast(const_cast< QAccessiblePlugin*>(this)); + if (!strcmp(_clname, "QAccessibleFactoryInterface")) + return static_cast< QAccessibleFactoryInterface*>(const_cast< QAccessiblePlugin*>(this)); + if (!strcmp(_clname, QAccessibleFactoryInterface_iid)) + return static_cast< QAccessibleFactoryInterface*>(const_cast< QAccessiblePlugin*>(this)); + if (!strcmp(_clname, "com.trolltech.Qt.QFactoryInterface")) + return static_cast< QFactoryInterface*>(static_cast< QAccessibleFactoryInterface*>(const_cast< QAccessiblePlugin*>(this))); + return QObject::qt_metacast(_clname); +} + +int QAccessiblePlugin::qt_metacall(QMetaObject::Call _c, int _id, void **_a) +{ + _id = QObject::qt_metacall(_c, _id, _a); + if (_id < 0) + return _id; + return _id; +} +QT_END_MOC_NAMESPACE diff --git a/pool/shard000/C++/0000219_MonitoredProcess.cpp b/pool/shard000/C++/0000219_MonitoredProcess.cpp new file mode 100644 index 0000000000000000000000000000000000000000..72405c67f1f634c70b323d1328e644320db8406b --- /dev/null +++ b/pool/shard000/C++/0000219_MonitoredProcess.cpp @@ -0,0 +1,137 @@ +// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. + +#include "CorePrivatePCH.h" +#include "Misc/MonitoredProcess.h" + +/* FMonitoredProcess structors + *****************************************************************************/ + +FMonitoredProcess::FMonitoredProcess( const FString& InURL, const FString& InParams, bool InHidden, bool InCreatePipes ) + : Canceling(false) + , EndTime(0) + , Hidden(InHidden) + , KillTree(false) + , Params(InParams) + , ReadPipe(nullptr) + , ReturnCode(0) + , StartTime(0) + , Thread(nullptr) + , URL(InURL) + , WritePipe(nullptr) + , bCreatePipes(InCreatePipes) + , SleepInterval(0.0f) +{ } + + +FMonitoredProcess::~FMonitoredProcess() +{ + if (IsRunning()) + { + Cancel(true); + Thread->WaitForCompletion(); + delete Thread; + } +} + + +/* FMonitoredProcess interface + *****************************************************************************/ + +FTimespan FMonitoredProcess::GetDuration() const +{ + if (IsRunning()) + { + return (FDateTime::UtcNow() - StartTime); + } + + return (EndTime - StartTime); +} + + +bool FMonitoredProcess::Launch() +{ + if (IsRunning()) + { + return false; + } + + if (bCreatePipes && !FPlatformProcess::CreatePipe(ReadPipe, WritePipe)) + { + return false; + } + + ProcessHandle = FPlatformProcess::CreateProc(*URL, *Params, false, Hidden, Hidden, nullptr, 0, *FPaths::RootDir(), WritePipe); + + if (!ProcessHandle.IsValid()) + { + return false; + } + + static int32 MonitoredProcessIndex = 0; + const FString MonitoredProcessName = FString::Printf( TEXT( "FMonitoredProcess %d" ), MonitoredProcessIndex ); + MonitoredProcessIndex++; + + Thread = FRunnableThread::Create(this, *MonitoredProcessName, 128 * 1024, TPri_AboveNormal); + + return true; +} + + +/* FMonitoredProcess implementation + *****************************************************************************/ + +void FMonitoredProcess::ProcessOutput( const FString& Output ) +{ + TArray LogLines; + + Output.ParseIntoArray(LogLines, TEXT("\n"), false); + + for (int32 LogIndex = 0; LogIndex < LogLines.Num(); ++LogIndex) + { + OutputDelegate.ExecuteIfBound(LogLines[LogIndex]); + } +} + + +/* FRunnable interface + *****************************************************************************/ + +uint32 FMonitoredProcess::Run() +{ + // monitor the process + StartTime = FDateTime::UtcNow(); + { + do + { + FPlatformProcess::Sleep(SleepInterval); + + ProcessOutput(FPlatformProcess::ReadPipe(ReadPipe)); + + if (Canceling) + { + FPlatformProcess::TerminateProc(ProcessHandle, KillTree); + CanceledDelegate.ExecuteIfBound(); + Thread = nullptr; + + return 0; + } + } + while (FPlatformProcess::IsProcRunning(ProcessHandle)); + } + EndTime = FDateTime::UtcNow(); + + // close output pipes + FPlatformProcess::ClosePipe(ReadPipe, WritePipe); + ReadPipe = WritePipe = nullptr; + + // get completion status + if (!FPlatformProcess::GetProcReturnCode(ProcessHandle, &ReturnCode)) + { + ReturnCode = -1; + } + + CompletedDelegate.ExecuteIfBound(ReturnCode); + Thread = nullptr; + + return 0; +} diff --git a/pool/shard000/C++/0000221_UI.cpp b/pool/shard000/C++/0000221_UI.cpp new file mode 100644 index 0000000000000000000000000000000000000000..378e26bd39fee25d4fabc090bc004aec2054da46 --- /dev/null +++ b/pool/shard000/C++/0000221_UI.cpp @@ -0,0 +1,150 @@ +#include "UI.h" +#include "App.h" + +#include +#include + +using namespace Zephyr; + +Zephyr::UI::UI(const std::string & windowTitle, App * pApp) : mpApp(pApp), mZoom(0) +{ + mpForm.reset( new nana::form(nana::rectangle{ 0, 0, mpApp->getWidth(), mpApp->getHeight() }) ); + mpForm->caption(windowTitle); + + nana::rectangle UIRect = nana::rectangle{ 10, 10, 145, 260 }; + + mpNfm.reset(new nana::nested_form(*mpForm, UIRect, nana::form::appear::bald<>())); + + // set the HWND from the UI framework to the App + mpApp->getHwnd() = reinterpret_cast(mpForm->native_handle()); + + initialize(); +} + +Zephyr::UI::~UI() +{ +} + +bool Zephyr::UI::initialize() +{ + // Mouse events + setupMouseMouseEvent(); + setupMouseClickEvent(); + setupMouseWheelEvent(); + + return true; +} + +void Zephyr::UI::show() +{ + mpNfm->show(); + mpForm->show(); +} + +std::shared_ptr Zephyr::UI::getForm() +{ + return mpForm; +} + +std::shared_ptr Zephyr::UI::getNestedForm() +{ + return mpNfm; +} + +std::shared_ptr Zephyr::UI::getLabel(const std::string & labelName) +{ + return std::shared_ptr(dynamic_cast(mWidgetList[labelName].get())); +} + +std::shared_ptr Zephyr::UI::createLabel(std::shared_ptr parent, const std::string & labelName, nana::rectangle & rect) +{ + std::shared_ptr pLabel(new nana::label(*parent, rect)); + pLabel->caption(labelName); + + mWidgetList.insert(std::make_pair(labelName, pLabel)); + + return pLabel; +} + +void Zephyr::UI::updateCaption(const std::string & widgetName, const std::string caption) +{ + auto widget = mWidgetList[widgetName]; + widget->caption(caption); +} + +std::shared_ptr Zephyr::UI::getButton(const std::string & buttonName) +{ + return std::shared_ptr(dynamic_cast(mWidgetList[buttonName].get())); +} + +std::shared_ptr Zephyr::UI::createButton(std::shared_ptr parent, const std::string & buttonName, nana::rectangle& rect) +{ + std::shared_ptr pButton(new nana::button(*parent, rect)); + pButton->caption(buttonName); + + mWidgetList.insert(std::make_pair(buttonName, pButton)); + + return pButton; +} + +std::shared_ptr Zephyr::UI::getSlider(const std::string & sliderName) +{ + return std::shared_ptr(dynamic_cast(mWidgetList[sliderName].get())); +} + +std::shared_ptr Zephyr::UI::createSlider(std::shared_ptr parent, const std::string & sliderName, nana::rectangle & rect) +{ + std::shared_ptr pSlider(new nana::slider(*parent, rect)); + pSlider->caption(sliderName); + + mWidgetList.insert(std::make_pair(sliderName, pSlider)); + + return pSlider; +} + +void Zephyr::UI::setupMouseMouseEvent() +{ + mpForm->events().mouse_move([&](const nana::arg_mouse& mouseEvent) + { + int deltaX = mouseEvent.pos.x - mMousePosition[0]; + int deltaY = mouseEvent.pos.y - mMousePosition[1]; + + // hold Mid mouse for zoom + if (mouseEvent.mid_button) + { + mpApp->getCamera()->zoom((float)-deltaY); + } + + if (mouseEvent.right_button) + { + mpApp->getCamera()->rotation((float)deltaX * 0.75f, (float)deltaY * 0.75f); + } + + mMousePosition[0] = mouseEvent.pos.x; + mMousePosition[1] = mouseEvent.pos.y; + }); +} + +void Zephyr::UI::setupMouseClickEvent() +{ + mpForm->events().click([&](const nana::arg_click& clickEvent) + { + if (clickEvent.mouse_args->is_left_button()) + { + auto pickingRay = mpApp->getCamera()->getPickingRay(clickEvent.mouse_args->pos.x, clickEvent.mouse_args->pos.y); + } + }); +} + +void Zephyr::UI::setupMouseWheelEvent() +{ + // one notch of mouse wheel delta is 120 + const float MOUSE_WHEEL_DELTA = 120.0f; + mpForm->events().mouse_wheel([&](const nana::arg_wheel& mouseWheelEvent) + { + auto distance = (mouseWheelEvent.distance / MOUSE_WHEEL_DELTA) * 10; + distance = mouseWheelEvent.upwards ? distance : -distance; + + mpApp->getCamera()->zoom(distance); + }); +} \ No newline at end of file diff --git a/pool/shard000/C++/0000225_MethodOfGettingAValueProfile.cpp b/pool/shard000/C++/0000225_MethodOfGettingAValueProfile.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a0f301a0c3c85deae78c0238a03226b8bce337df --- /dev/null +++ b/pool/shard000/C++/0000225_MethodOfGettingAValueProfile.cpp @@ -0,0 +1,69 @@ +/* + * Copyright (C) 2012 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 "MethodOfGettingAValueProfile.h" + +#if ENABLE(DFG_JIT) + +#include "CodeBlock.h" + +namespace JSC { + +MethodOfGettingAValueProfile MethodOfGettingAValueProfile::fromLazyOperand( + CodeBlock* codeBlock, const LazyOperandValueProfileKey& key) +{ + MethodOfGettingAValueProfile result; + result.m_kind = LazyOperand; + result.u.lazyOperand.codeBlock = codeBlock; + result.u.lazyOperand.bytecodeOffset = key.bytecodeOffset(); + result.u.lazyOperand.operand = key.operand(); + return result; +} + +EncodedJSValue* MethodOfGettingAValueProfile::getSpecFailBucket(unsigned index) const +{ + switch (m_kind) { + case None: + return 0; + + case Ready: + return u.profile->specFailBucket(index); + + case LazyOperand: + return u.lazyOperand.codeBlock->lazyOperandValueProfiles().add( + LazyOperandValueProfileKey( + u.lazyOperand.bytecodeOffset, u.lazyOperand.operand))->specFailBucket(index); + + default: + RELEASE_ASSERT_NOT_REACHED(); + return 0; + } +} + +} // namespace JSC + +#endif // ENABLE(DFG_JIT) + diff --git a/pool/shard000/C++/0000238_c_te_bubbletrail.cpp b/pool/shard000/C++/0000238_c_te_bubbletrail.cpp new file mode 100644 index 0000000000000000000000000000000000000000..aa007660732e4edaf33e016f148087c8cf739443 --- /dev/null +++ b/pool/shard000/C++/0000238_c_te_bubbletrail.cpp @@ -0,0 +1,83 @@ +//======== (C) Copyright 1999, 2000 Valve, L.L.C. All rights reserved. ======== +// +// The copyright to the contents herein is the property of Valve, L.L.C. +// The contents may be used and/or copied only with the written permission of +// Valve, L.L.C., or in accordance with the terms and conditions stipulated in +// the agreement/contract under which the contents have been supplied. +// +// Purpose: +// +// $Workfile: $ +// $Date: $ +// $NoKeywords: $ +//============================================================================= +#include "cbase.h" +#include "c_basetempentity.h" +#include "c_te_legacytempents.h" + +//----------------------------------------------------------------------------- +// Purpose: Bubble Trail TE +//----------------------------------------------------------------------------- +class C_TEBubbleTrail : public C_BaseTempEntity +{ +public: + DECLARE_CLASS( C_TEBubbleTrail, C_BaseTempEntity ); + DECLARE_CLIENTCLASS(); + + C_TEBubbleTrail( void ); + virtual ~C_TEBubbleTrail( void ); + + virtual void PostDataUpdate( DataUpdateType_t updateType ); + +public: + Vector m_vecMins; + Vector m_vecMaxs; + float m_fHeight; + int m_nModelIndex; + int m_nCount; + float m_fSpeed; +}; + +//----------------------------------------------------------------------------- +// Purpose: +//----------------------------------------------------------------------------- +C_TEBubbleTrail::C_TEBubbleTrail( void ) +{ + m_vecMins.Init(); + m_vecMaxs.Init(); + m_fHeight = 0.0; + m_nModelIndex = 0; + m_nCount = 0; + m_fSpeed = 0; +} + +//----------------------------------------------------------------------------- +// Purpose: +//----------------------------------------------------------------------------- +C_TEBubbleTrail::~C_TEBubbleTrail( void ) +{ +} + +void TE_BubbleTrail( IRecipientFilter& filter, float delay, + const Vector* mins, const Vector* maxs, float height, int modelindex, int count, float speed ) +{ + tempents->BubbleTrail( *mins, *maxs, height, modelindex, count, speed ); +} + +//----------------------------------------------------------------------------- +// Purpose: +// Input : bool - +//----------------------------------------------------------------------------- +void C_TEBubbleTrail::PostDataUpdate( DataUpdateType_t updateType ) +{ + tempents->BubbleTrail( m_vecMins, m_vecMaxs, m_fHeight, m_nModelIndex, m_nCount, m_fSpeed ); +} + +IMPLEMENT_CLIENTCLASS_EVENT_DT(C_TEBubbleTrail, DT_TEBubbleTrail, CTEBubbleTrail) + RecvPropVector( RECVINFO(m_vecMins)), + RecvPropVector( RECVINFO(m_vecMaxs)), + RecvPropInt( RECVINFO(m_nModelIndex)), + RecvPropFloat( RECVINFO(m_fHeight )), + RecvPropInt( RECVINFO(m_nCount)), + RecvPropFloat( RECVINFO(m_fSpeed )), +END_RECV_TABLE() diff --git a/pool/shard000/C++/0000239_2.cc b/pool/shard000/C++/0000239_2.cc new file mode 100644 index 0000000000000000000000000000000000000000..b6f94c070cb3c2388228be24524ed5a575a7435e --- /dev/null +++ b/pool/shard000/C++/0000239_2.cc @@ -0,0 +1,70 @@ +// Set iterator invalidation tests + +// Copyright (C) 2003-2013 Free Software Foundation, Inc. +// +// This file is part of the GNU ISO C++ Library. This library is free +// software; you can redistribute it and/or modify it under the +// terms of the GNU General Public License as published by the +// Free Software Foundation; either version 3, or (at your option) +// any later version. + +// This 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 General Public License for more details. + +// You should have received a copy of the GNU General Public License along +// with this library; see the file COPYING3. If not see +// . + +#include +#include +#include + +using __gnu_debug::set; +using std::advance; + +// Erase +void test02() +{ + bool test __attribute__((unused)) = true; + + set v; + for (int i = 0; i < 20; ++i) + v.insert(i); + + // Single element erase (middle) + set::iterator before = v.begin(); + set::iterator at = before; + advance(at, 3); + set::iterator after = at; + ++after; + v.erase(at); + VERIFY(before._M_dereferenceable()); + VERIFY(at._M_singular()); + VERIFY(after._M_dereferenceable()); + + // Multiple element erase + before = v.begin(); + at = before; + advance(at, 3); + after = at; + advance(after, 4); + v.erase(at, after); + VERIFY(before._M_dereferenceable()); + VERIFY(at._M_singular()); + + // clear() + before = v.begin(); + set::iterator finish = v.end(); + VERIFY(before._M_dereferenceable()); + v.clear(); + VERIFY(before._M_singular()); + VERIFY(!finish._M_singular() && !finish._M_dereferenceable()); +} + +int main() +{ + test02(); + return 0; +} diff --git a/pool/shard000/C++/0000240_tfs_random.cpp b/pool/shard000/C++/0000240_tfs_random.cpp new file mode 100644 index 0000000000000000000000000000000000000000..eec649dd7f021b4203327b531eae7b89fc245557 --- /dev/null +++ b/pool/shard000/C++/0000240_tfs_random.cpp @@ -0,0 +1,77 @@ +/****************************************** +* TrafficFS +* v0.2 +* ---------------------------- +* Traffic Flow Simulator +* +* Coded in C++ +* Copyright (c) 2010 by Dr.Kameleon +******************************************* +* file : tfs_utils.cpp +*******************************************/ + +#include "trafficfs.h" + +Random::Random() +{ + unsigned seed = time (0); + srand (seed); +} + +string Random::genLicense() +{ + const char* const plateLetters = "ABEHIKMNOPTXYZ"; + string output = ""; + + for (int i=0; i<3; i++) + { + int r = rand()%14; + output += plateLetters[r]; + } + + for (int i=0; i<4; i++) + { + int r = (rand()%9)+1; + + stringstream out; + out << r; + + output += out.str(); + } + + return output; +} + +string Random::genName() +{ + const char* const Letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + string output = ""; + + for (int i=0; i<5; i++) + { + int r = rand()%26; + output += Letters[r]; + } + + return output; +} + +float Random::genSpeed() +{ + return (rand()%100)+40; +} + +directionType Random::genDirection() +{ + int r = rand()%2; + + if (r==1) + return ALPHA; + else + return BETA; +} + +float Random::genDistance() +{ + return ((rand()%TFS_MAXDISTANCE)+5)*1000; +} diff --git a/pool/shard000/C++/0000261_setup_touch.cpp b/pool/shard000/C++/0000261_setup_touch.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6bfe313387eaf294295997f6e26a346dd7157cda --- /dev/null +++ b/pool/shard000/C++/0000261_setup_touch.cpp @@ -0,0 +1,151 @@ +/* + * The ManaPlus Client + * Copyright (C) 2012-2015 The ManaPlus Developers + * + * This file is part of The ManaPlus Client. + * + * 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 + * 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 "gui/widgets/tabs/setup_touch.h" + +#include "gui/models/touchactionmodel.h" + +#include "gui/widgets/containerplacer.h" +#include "gui/widgets/layouthelper.h" +#include "gui/widgets/setuptouchitem.h" +#include "gui/widgets/scrollarea.h" + +#include "configuration.h" + +#include "utils/delete2.h" +#include "utils/gettext.h" +#include "utils/stringutils.h" + +#include "debug.h" + +extern Configuration inputConfig; + +static const int sizeListSize = 4; + +static const char *const sizeList[] = +{ + // TRANSLATORS: onscreen button size + N_("Small"), + // TRANSLATORS: onscreen button size + N_("Normal"), + // TRANSLATORS: onscreen button size + N_("Medium"), + // TRANSLATORS: onscreen button size + N_("Large") +}; + +static const int formatListSize = 6; + +static const char *const formatList[] = +{ + "2x1", + "2x2", + "2x3", + "3x1", + "3x2", + "3x3" +}; + +Setup_Touch::Setup_Touch(const Widget2 *const widget) : + SetupTabScroll(widget), + mSizeList(new NamesModel), + mFormatList(new NamesModel), + mActionsList(new TouchActionsModel) +{ + // TRANSLATORS: touch settings tab + setName(_("Touch")); + + LayoutHelper h(this); + ContainerPlacer place = h.getPlacer(0, 0); + place(0, 0, mScroll, 10, 10); + mSizeList->fillFromArray(&sizeList[0], sizeListSize); + mFormatList->fillFromArray(&formatList[0], formatListSize); + + // TRANSLATORS: settings option + new SetupItemCheckBox(&inputConfig, _("Show onscreen keyboard icon"), "", + "showScreenKeyboard", this, "showScreenKeyboardEvent"); + + + // TRANSLATORS: settings option + new SetupItemCheckBox(&inputConfig, _("Show onscreen joystick"), "", + "showScreenJoystick", this, "showScreenJoystickEvent"); + + // TRANSLATORS: settings option + new SetupItemDropDown(&inputConfig, _("Joystick size"), "", "screenJoystickSize", this, + "screenJoystickEvent", mSizeList, 100); + + + // TRANSLATORS: settings option + new SetupItemCheckBox(&inputConfig, _("Show onscreen buttons"), "", + "showScreenButtons", this, "showScreenButtonsEvent"); + + // TRANSLATORS: settings option + new SetupItemDropDown(&inputConfig, _("Buttons format"), "", "screenButtonsFormat", this, + "screenButtonsFormatEvent", mFormatList, 100); + + // TRANSLATORS: settings option + new SetupItemDropDown(&inputConfig, _("Buttons size"), "", "screenButtonsSize", this, + "screenButtonsSizeEvent", mSizeList, 100); + + // TRANSLATORS: settings option + new SetupActionDropDown(&inputConfig, _("Button \"1\" action"), "", "screenActionButton0", + this, "screenActionButton0Event", mActionsList, 250); + + // TRANSLATORS: settings option + new SetupActionDropDown(&inputConfig, _("Button \"2\" action"), "", "screenActionButton1", + this, "screenActionButton1Event", mActionsList, 250); + + // TRANSLATORS: settings option + new SetupActionDropDown(&inputConfig, _("Button \"3\" action"), "", "screenActionButton2", + this, "screenActionButton2Event", mActionsList, 250); + + // TRANSLATORS: settings option + new SetupActionDropDown(&inputConfig, _("Button \"A\" action"), "", "screenActionButton3", + this, "screenActionButton3Event", mActionsList, 250); + + // TRANSLATORS: settings option + new SetupActionDropDown(&inputConfig, _("Button \"B\" action"), "", "screenActionButton4", + this, "screenActionButton4Event", mActionsList, 250); + + // TRANSLATORS: settings option + new SetupActionDropDown(&inputConfig, _("Button \"C\" action"), "", "screenActionButton5", + this, "screenActionButton5Event", mActionsList, 250); + + // TRANSLATORS: settings option + new SetupActionDropDown(&inputConfig, _("Button \"X\" action"), "", "screenActionButton6", + this, "screenActionButton6Event", mActionsList, 250); + + // TRANSLATORS: settings option + new SetupActionDropDown(&inputConfig, _("Button \"Y\" action"), "", "screenActionButton7", + this, "screenActionButton7Event", mActionsList, 250); + + // TRANSLATORS: settings option + new SetupActionDropDown(&inputConfig, _("Button \"Z\" action"), "", "screenActionButton8", + this, "screenActionButton8Event", mActionsList, 250); + + setDimension(Rect(0, 0, 550, 350)); +} + +Setup_Touch::~Setup_Touch() +{ + delete2(mSizeList); + delete2(mFormatList); + delete2(mActionsList); +} diff --git a/pool/shard000/C++/0000265_VelocityVerletOnRadius.cpp b/pool/shard000/C++/0000265_VelocityVerletOnRadius.cpp new file mode 100644 index 0000000000000000000000000000000000000000..51327d7244461b94eed850372c72c79fb64c9c5e --- /dev/null +++ b/pool/shard000/C++/0000265_VelocityVerletOnRadius.cpp @@ -0,0 +1,119 @@ +/* + Copyright (C) 2012,2013 + Max Planck Institute for Polymer Research + Copyright (C) 2008,2009,2010,2011 + Max-Planck-Institute for Polymer Research & Fraunhofer SCAI + + This file is part of ESPResSo++. + + ESPResSo++ 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. + + ESPResSo++ 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 "python.hpp" +#include "VelocityVerletOnRadius.hpp" + +#include "types.hpp" +#include "System.hpp" +#include "storage/Storage.hpp" +#include "iterator/CellListIterator.hpp" + +namespace espresso { + + using namespace iterator; + + namespace integrator { + + LOG4ESPP_LOGGER(VelocityVerletOnRadius::theLogger, "VelocityVerletOnRadius"); + + VelocityVerletOnRadius::VelocityVerletOnRadius(shared_ptr system, real _radialDampingMass) + : Extension(system), radialDampingMass(_radialDampingMass) + { + LOG4ESPP_INFO(theLogger, "VelocityVerletOnRadius constructed"); + } + + void VelocityVerletOnRadius::disconnect(){ + _aftIntP.disconnect(); + _aftIntV.disconnect(); + _aftInitF.disconnect(); + } + + void VelocityVerletOnRadius::connect(){ + // connection to initialisation + _aftIntP = integrator->aftIntP.connect( boost::bind(&VelocityVerletOnRadius::integrate1, this)); + _aftIntV = integrator->aftIntV.connect( boost::bind(&VelocityVerletOnRadius::integrate2, this)); + _aftInitF = integrator->aftInitF.connect( boost::bind(&VelocityVerletOnRadius::initForces, this)); + } + + void VelocityVerletOnRadius::integrate1() { + System& system = getSystemRef(); + CellList realCells = system.storage->getRealCells(); + // loop over all particles of the local cells + real dt = integrator->getTimeStep(); + for(CellListIterator cit(realCells); !cit.isDone(); ++cit) { + LOG4ESPP_DEBUG(theLogger, "Particle " << cit->id() << ", forceRadius = " << cit->fradius()); + } + for(CellListIterator cit(realCells); !cit.isDone(); ++cit) { + //LOG4ESPP_DEBUG(theLogger, "Particle " << cit->id() << ", radius = " << cit->radius()); + real dtfm = 0.5 * dt / radialDampingMass; + // Propagate velocities: v(t+0.5*dt) = v(t) + 0.5*dt * f(t) + cit->vradius() += dtfm * cit->fradius(); + // Propagate radius (only NVT): p(t + dt) = p(t) + dt * v(t+0.5*dt) + real deltaP = cit->vradius(); + deltaP *= dt; + cit->radius() += deltaP; + } + } + + void VelocityVerletOnRadius::integrate2() { + System& system = getSystemRef(); + CellList realCells = system.storage->getRealCells(); + // loop over all particles of the local cells + real dt = integrator->getTimeStep(); + real half_dt = 0.5 * dt; + for(CellListIterator cit(realCells); !cit.isDone(); ++cit) { + real dtfm = half_dt / radialDampingMass; + /* Propagate radius velocities: v(t+0.5*dt) = v(t) + 0.5*dt * f(t) */ + cit->vradius() += dtfm * cit->fradius(); + } + } + + void VelocityVerletOnRadius::initForces() { + // fradius is initialized for real + ghost particles + System& system = getSystemRef(); + CellList realCells = system.storage->getRealCells(); + LOG4ESPP_INFO(theLogger, "init fradius for real particles"); + for(CellListIterator cit(realCells); !cit.isDone(); ++cit) { + cit->fradius() = 0.0; + } + } + + + /**************************************************** + ** REGISTRATION WITH PYTHON + ****************************************************/ + + void VelocityVerletOnRadius::registerPython() { + + using namespace espresso::python; + + class_, bases > + ("integrator_VelocityVerletOnRadius", init< shared_ptr< System >, real >()) + .def("connect", &VelocityVerletOnRadius::connect) + .def("disconnect", &VelocityVerletOnRadius::disconnect) + .add_property("radialDampingMass" ,&VelocityVerletOnRadius::getRadialDampingMass, &VelocityVerletOnRadius::setRadialDampingMass ) + ; + } + + } +} diff --git a/pool/shard000/C++/0000271_IntShuffleGen.cpp b/pool/shard000/C++/0000271_IntShuffleGen.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ad9d260cdc99a1a4d63d1a2c753d30e5d4371e24 --- /dev/null +++ b/pool/shard000/C++/0000271_IntShuffleGen.cpp @@ -0,0 +1,62 @@ +// IntShuffleGen.cpp ---------------------------------------------// +/* + * Copyright (c) 2012, Martin Smole. All rights reserved. + * + * This file is part of the CBSF. + * + * The CBSF 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 CBSF 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 CBSF. If not, see . + */ + +#include "stdafx.h" +#include "IntShuffleGen.h" + + +using namespace std; + +namespace codemm { +namespace cbsf { +namespace minhash { + + +IntShuffleGen::IntShuffleGen(void) +{ +} + + +IntShuffleGen::~IntShuffleGen(void) +{ +} + + +void IntShuffleGen::Generate (int numFunctions, int numDimensions, vector& hashFunctions) +{ + hashFunctions.clear (); + + HashFunction hashFunction; + for (int i = 0; i < numDimensions; i++) + { + hashFunction.push_back ((float) (i + 1)); + } + + for (int i = 0; i < numFunctions; i++) + { + random_shuffle (hashFunction.begin(), hashFunction.end()); + hashFunctions.push_back (HashFunction(hashFunction)); + } +} + + +} // namespace minhash +} // namespace cbsf +} // namespace codemm \ No newline at end of file diff --git a/pool/shard000/C++/0000276_QuickFixDlg.cpp b/pool/shard000/C++/0000276_QuickFixDlg.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cafc1140c77811fec1362947d273c9f4cc75031b --- /dev/null +++ b/pool/shard000/C++/0000276_QuickFixDlg.cpp @@ -0,0 +1,170 @@ +// QuickFixDlg.cpp : Implementation of CQuickFixDlg + +#include "stdafx.h" +#include "QuickFixDlg.h" + +LRESULT CQuickFixDlg::OnInitDialog(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) +{ + CAxDialogImpl::OnInitDialog(uMsg, wParam, lParam, bHandled); + bHandled = TRUE; + return 1; // Let the system set the focus +} + +LRESULT CQuickFixDlg::OnQuickFix(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled) +{ + OPTIONS options; + Command cmd = cmdAromatize; + + if(wID == ID_STRUCTURE_VALIDATE) + { + TCHAR msg[ONE_KB]; + + COMMANDPARAMS params(cmdValidate, m_activeBuffer, NULL); + std::auto_ptr outBuffer(pExecuteFunc(¶ms, &options)); + if(outBuffer->DataLength > 0) + swprintf(msg, ONE_KB, _T("%hs"), (const char*) outBuffer->pData); + else + swprintf(msg, ONE_KB, _T("No problems found.")); + + MessageBox(msg, _T("Validate"), MB_ICONINFORMATION); + return 0; + } + else if(wID == ID_STRUCTURE_RESETTODEFAULT) + { + // release the existing buffer if it is not the original structure buffer + if(m_activeBuffer != m_sourceBuffer) DeleteAndNull(m_activeBuffer); + m_activeBuffer = m_sourceBuffer; + } + else + { + switch(wID) + { + case ID_STRUCTURE_AROMATIZE: + cmd = cmdAromatize; + break; + case ID_STRUCTURE_DEAROMATIZE: + cmd = cmdDearomatize; + break; + case ID_STRUCTURE_CLEANUP: + cmd = cmdCleanup; + break; + case ID_STRUCTURE_NORMALIZE: + cmd = cmdNormalize; + break; + case ID_STRUCTURE_FOLDHYDROGENS: + cmd = cmdFoldHydrogens; + break; + case ID_STRUCTURE_UNFOLDHYDROGENS: + cmd = cmdUnfoldHydrogens; + break; + } + + COMMANDPARAMS params(cmd, m_activeBuffer, NULL); + std::auto_ptr outBuffer(pExecuteFunc(¶ms, &options)); + + if((outBuffer.get() != NULL) && (outBuffer->DataLength > 0)) + { + // release the existing buffer if it is not the original structure buffer + if(m_activeBuffer != m_sourceBuffer) DeleteAndNull(m_activeBuffer); + + // init activeBuffer with output data + m_activeBuffer = new BUFFER(); + + // Indigo does not support saving as SMARTS so SMARTS format is converted to MOL V3000 + // during Perform operation so we need to set the correct format here + m_activeBuffer->DataFormat = (m_sourceBuffer->DataFormat == fmtSMARTS) ? fmtMOLV3 : m_sourceBuffer->DataFormat; + m_activeBuffer->pData = outBuffer->pData; + m_activeBuffer->DataLength = outBuffer->DataLength; + } + else + { + MessageBox(_T("There was some problem applying the fix."), _T("Structure QuickFix"), 0); + } + } + + // refresh windows to display changed structure + Invalidate(); + UpdateWindow(); + + return 0; +} + +LRESULT CQuickFixDlg::OnPaint(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) +{ + UNREFERENCED_PARAMETER(uMsg); + UNREFERENCED_PARAMETER(wParam); + UNREFERENCED_PARAMETER(lParam); + + PAINTSTRUCT ps; + BeginPaint(&ps); + + // get picture box handle and draw the active buffer data in it + HWND hPict = GetDlgItem(IDC_QFPICT); + if(hPict != NULL) + { + RECT rect; + OPTIONS options; + + // get client area of picture box + ::GetClientRect(hPict, &rect); + + DRAWPARAMS drawParams(::GetDC(hPict), rect); + COMMANDPARAMS params((int)cmdDraw, m_activeBuffer, &drawParams); + std::auto_ptr outBuffer(pExecuteFunc(¶ms, &options)); + } + + EndPaint(&ps); + bHandled = TRUE; + return 0; +} + +LRESULT CQuickFixDlg::OnApplyChanges(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled) +{ + HANDLE hFile; + DWORD dwBytesWritten = 0; + BOOL bErrorFlag = FALSE; + PCHAR buffer = (PCHAR)m_activeBuffer->pData; + DWORD dwBytesToWrite = (DWORD)m_activeBuffer->DataLength; + + if(MessageBox(_T("Are you sure you want to overwrite the existing file with current changes? This action cannot be undone."), + _T("Structure QuickFix"), MB_YESNO | MB_ICONQUESTION) == IDNO) + return 0; + + //INFO: SMARTS file will be saved as MOLV3 + + // truncate the existing file and write changed data + hFile = CreateFile(m_sourceFile, GENERIC_WRITE, 0, NULL, TRUNCATE_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + if (hFile != INVALID_HANDLE_VALUE) + { + bErrorFlag = WriteFile(hFile, buffer, dwBytesToWrite, &dwBytesWritten, NULL); + if ((FALSE == bErrorFlag) || (dwBytesWritten != dwBytesToWrite)) + { + pantheios::log_ERROR(_T("Problem writing to file="), m_sourceFile, + _T(", GetLastError="), pantheios::integer(GetLastError())); + MessageBox(_T("There was an error trying to save changes."), _T("File Write Error"), MB_OK | MB_ICONERROR); + return S_FALSE; + } + CloseHandle(hFile); + } + else + { + pantheios::log_ERROR(_T("Problem opening file="), m_sourceFile, _T(", GetLastError="), + pantheios::integer(GetLastError())); + MessageBox(_T("There was a problem opening the existing file. Please check the file and try again."), + _T("File Write Error"), MB_OK | MB_ICONERROR); + return S_FALSE; + } + + // update the original buffer + m_sourceBuffer = m_activeBuffer; + + MessageBox(_T("Changes applied successfully."), _T("Structure QuickFix"), MB_OK | MB_ICONINFORMATION); + + return S_OK; +} + +LRESULT CQuickFixDlg::OnCancel(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled) +{ + EndDialog(wID); + return 0; +} diff --git a/pool/shard000/C++/0000282_LibraryPage.cpp b/pool/shard000/C++/0000282_LibraryPage.cpp new file mode 100644 index 0000000000000000000000000000000000000000..643341e89633340ccb455524ff112a5ce905ea7e --- /dev/null +++ b/pool/shard000/C++/0000282_LibraryPage.cpp @@ -0,0 +1,52 @@ +#include "LibraryPage.h" +#include "Symbol.h" +#include "config.h" + +#include +#include +#include +#include +#include +#include + +namespace eterrain2d +{ + +LibraryPage::LibraryPage(wxWindow* parent) + : ee::LibraryPage(parent, "Terrain2D") +{ + InitLayout(); + m_list->SetFileter(ee::SymbolFile::Instance()->Tag(ee::SYM_TERRAIN2D)); +} + +bool LibraryPage::IsHandleSymbol(const ee::SymPtr& sym) const +{ + return sym->Type() == ee::SYM_TERRAIN2D; +} + +void LibraryPage::OnAddPress(wxCommandEvent& event) +{ + std::string filter = ee::SymbolFile::Instance()->Tag(ee::SYM_TERRAIN2D); + filter = wxT("*_") + filter + wxT(".json"); + wxFileDialog dlg(this, wxT("µ¼Èëterrain2dÎļþ"), wxEmptyString, + wxEmptyString, filter, wxFD_OPEN | wxFD_MULTIPLE); + if (dlg.ShowModal() == wxID_OK) + { + wxArrayString filenames; + dlg.GetPaths(filenames); + for (size_t i = 0, n = filenames.size(); i < n; ++i) + { + std::string filepath = filenames[i].ToStdString(); + try { + auto sym = ee::SymbolMgr::Instance()->FetchSymbol(filepath); + sym->RefreshThumbnail(filepath); + AddItem(sym); + } catch (ee::Exception& e) { + ee::ExceptionDlg dlg(m_parent, e); + dlg.ShowModal(); + } + } + } +} + +} \ No newline at end of file diff --git a/pool/shard000/C++/0000285_copy_assign.cc b/pool/shard000/C++/0000285_copy_assign.cc new file mode 100644 index 0000000000000000000000000000000000000000..3e0c2f8557cd85d83734de85d66b366f7627f3bc --- /dev/null +++ b/pool/shard000/C++/0000285_copy_assign.cc @@ -0,0 +1,77 @@ +// Copyright (C) 2013-2014 Free Software Foundation, Inc. +// +// This file is part of the GNU ISO C++ Library. This library is free +// software; you can redistribute it and/or modify it under the +// terms of the GNU General Public License as published by the +// Free Software Foundation; either version 3, or (at your option) +// any later version. + +// This 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 General Public License for more details. + +// You should have received a copy of the GNU General Public License along +// with this library; see the file COPYING3. If not see +// . + +// { dg-options "-std=gnu++11" } + +#include +#include +#include + +struct T { int i; }; + +struct hash +{ + std::size_t operator()(const T t) const noexcept + { return t.i; } +}; + +struct equal_to +{ + bool operator()(const T& lhs, const T& rhs) const noexcept + { return lhs.i == rhs.i; } +}; + +using __gnu_test::propagating_allocator; + +void test01() +{ + bool test __attribute__((unused)) = true; + typedef propagating_allocator alloc_type; + typedef std::unordered_map test_type; + test_type v1(alloc_type(1)); + v1.emplace(std::piecewise_construct, + std::make_tuple(T()), std::make_tuple(T())); + test_type v2(alloc_type(2)); + v2.emplace(std::piecewise_construct, + std::make_tuple(T()), std::make_tuple(T())); + v2 = v1; + VERIFY(1 == v1.get_allocator().get_personality()); + VERIFY(2 == v2.get_allocator().get_personality()); +} + +void test02() +{ + bool test __attribute__((unused)) = true; + typedef propagating_allocator alloc_type; + typedef std::unordered_map test_type; + test_type v1(alloc_type(1)); + v1.emplace(std::piecewise_construct, + std::make_tuple(T()), std::make_tuple(T())); + test_type v2(alloc_type(2)); + v2.emplace(std::piecewise_construct, + std::make_tuple(T()), std::make_tuple(T())); + v2 = v1; + VERIFY(1 == v1.get_allocator().get_personality()); + VERIFY(1 == v2.get_allocator().get_personality()); +} + +int main() +{ + test01(); + test02(); + return 0; +} diff --git a/pool/shard000/C++/0000289_ob_check_runnable.cc b/pool/shard000/C++/0000289_ob_check_runnable.cc new file mode 100644 index 0000000000000000000000000000000000000000..164007e8058f8fa7764f9d0b2cd542dec5f4974f --- /dev/null +++ b/pool/shard000/C++/0000289_ob_check_runnable.cc @@ -0,0 +1,160 @@ +/** + * (C) 2010-2011 Alibaba Group Holding Limited. + * + * 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. + * + * Version: $Id$ + * + * ob_check_runnable.cc for ... + * + * Authors: + * yanran + * + */ +#include "ob_check_runnable.h" +#include "ob_lease_common.h" + +using namespace sb::common; + +ObCheckRunnable::ObCheckRunnable() { + role_mgr_ = NULL; + vip_ = 0; + lease_on_ = false; + lease_interval_ = 0; + lease_time_ = 0; + renew_interval_ = 0; + rpc_stub_ = NULL; + server_ = NULL; + renew_lease_timeout_ = 0; +} + +ObCheckRunnable::~ObCheckRunnable() { +} + +void ObCheckRunnable::run(tbsys::CThread* thread, void* arg) { + UNUSED(thread); + UNUSED(arg); + int err = OB_SUCCESS; + + while (!_stop) { + if (tbsys::CNetUtil::isLocalAddr(vip_)) { + if (ObRoleMgr::SLAVE == role_mgr_->get_role()) { + struct in_addr vip_addr; + vip_addr.s_addr = vip_; + TBSYS_LOG(INFO, "vip found on slave, vip=%s", inet_ntoa(vip_addr)); + int64_t status = LEASE_NORMAL; + if (lease_on_) { + status = get_lease_status_(); + } + + if (LEASE_INVALID != status) { + role_mgr_->set_state(ObRoleMgr::SWITCHING); + } else { + TBSYS_LOG(ERROR, "vip found on slave, but slave lease is invalid, vip=%s", inet_ntoa(vip_addr)); + } + } + } else { + if (ObRoleMgr::MASTER == role_mgr_->get_role()) { + struct in_addr vip_addr; + vip_addr.s_addr = vip_; + TBSYS_LOG(ERROR, "Incorrect vip, STOP server, vip=%s", inet_ntoa(vip_addr)); + role_mgr_->set_state(ObRoleMgr::STOP); + stop(); + } else if (ObRoleMgr::SLAVE == role_mgr_->get_role() && lease_on_) { + if (ObRoleMgr::ACTIVE == role_mgr_->get_state()) { + int64_t status = get_lease_status_(); + if (LEASE_INVALID == status) { + TBSYS_LOG(ERROR, "Invalid lease, set server to INIT state"); + role_mgr_->set_state(ObRoleMgr::INIT); // set to init state, slave will re-register + } else if (LEASE_SHOULD_RENEW == status) { + err = renew_lease_(); + if (OB_SUCCESS != err) { + TBSYS_LOG(WARN, "failed to renew_lease_, err=%d", err); + } + } + } + } + } + usleep(check_period_); + } +} + +int ObCheckRunnable::init(ObRoleMgr* role_mgr, const uint32_t vip, const int64_t check_period, + ObCommonRpcStub* rpc_stub, ObServer* server, ObServer* slave_addr) { + int ret = OB_SUCCESS; + + if (NULL == role_mgr) { + TBSYS_LOG(WARN, "Parameter is invalid[role_mgr=%p]", role_mgr); + ret = OB_INVALID_ARGUMENT; + } else { + role_mgr_ = role_mgr; + vip_ = vip; + check_period_ = check_period; + rpc_stub_ = rpc_stub; + server_ = server; + slave_addr_ = slave_addr; + } + + return ret; +} + +void ObCheckRunnable::reset_vip(const int32_t vip) { + vip_ = vip; +} + +int64_t ObCheckRunnable::get_lease_status_() { + LeaseStatus status = LEASE_NORMAL; + timeval time_val; + gettimeofday(&time_val, NULL); + int64_t cur_time_us = time_val.tv_sec * 1000 * 1000 + time_val.tv_usec; + if (lease_time_ + lease_interval_ < cur_time_us) { + TBSYS_LOG(WARN, "Lease expired, lease_time_=%ld, lease_interval_=%ld, cur_time_us=%ld", + lease_time_, lease_interval_, cur_time_us); + status = LEASE_INVALID; + } else if (lease_time_ + lease_interval_ < cur_time_us + renew_interval_) { + TBSYS_LOG(DEBUG, "Lease will expire, lease_time_=%ld, lease_interval_=%ld, " + "cur_time_us=%ld, renew_interval_=%ld", lease_time_, lease_interval_, + cur_time_us, renew_interval_); + status = LEASE_SHOULD_RENEW; + } + + return status; +} + +int ObCheckRunnable::renew_lease_() { + int err = OB_SUCCESS; + + if (NULL == rpc_stub_ || NULL == server_) { + TBSYS_LOG(WARN, "invalid status, rpc_stub_=%p, server_=%p", rpc_stub_, server_); + err = OB_ERROR; + } else { + err = rpc_stub_->renew_lease(*server_, *slave_addr_, renew_lease_timeout_); + if (OB_SUCCESS != err) { + TBSYS_LOG(WARN, "failed to renew lease, err=%d, timeout=%ld", err, renew_lease_timeout_); + } + } + + return err; +} + +int ObCheckRunnable::renew_lease(const ObLease& lease) { + int err = OB_SUCCESS; + + lease_on_ = true; + lease_time_ = lease.lease_time; + lease_interval_ = lease.lease_interval; + renew_interval_ = lease.renew_interval; + + TBSYS_LOG(DEBUG, "Renew lease, lease_time=%ld lease_interval=%ld renew_interval=%ld", + lease_time_, lease_interval_, renew_interval_); + + return err; +} + +void ObCheckRunnable::set_renew_lease_timeout(const int64_t renew_lease_timeout) { + renew_lease_timeout_ = renew_lease_timeout; +} + + diff --git a/pool/shard000/C++/0000298_hsl.cpp b/pool/shard000/C++/0000298_hsl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7cec527033ed63879c706e8c5f45300007df78ee --- /dev/null +++ b/pool/shard000/C++/0000298_hsl.cpp @@ -0,0 +1,22 @@ +#include +#include + +#include "color/color.hpp" + +int main( int argc, char *argv[] ) + { + color::hsl h; + + // Do some initialization + h = color::constant::black_t{}; + + // First check has to be OK + std::cout << "true == color::check::unique( h ) == " << color::check::unique( h ) << std::endl; + + h.set<0>( 120 ); h.set<1>( 50 ); h.set<2>( 100 ); + + // This one has to fail + std::cout << "false == color::check::unique( h ) == " << color::check::unique( h ) << std::endl; + + return EXIT_SUCCESS; + } diff --git a/pool/shard000/C++/0000305_PxPvdObjectRegistrar.cpp b/pool/shard000/C++/0000305_PxPvdObjectRegistrar.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0836201003be65acbf2ecd4b252fe07168751861 --- /dev/null +++ b/pool/shard000/C++/0000305_PxPvdObjectRegistrar.cpp @@ -0,0 +1,80 @@ +// +// 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 NVIDIA 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 ``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. +// +// Copyright (c) 2008-2018 NVIDIA Corporation. All rights reserved. +// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. +// Copyright (c) 2001-2004 NovodeX AG. All rights reserved. + +#include "PxPvdObjectRegistrar.h" + +namespace physx +{ +namespace pvdsdk +{ + +bool ObjectRegistrar::addItem(const void* inItem) +{ + physx::shdfnd::Mutex::ScopedLock lock(mRefCountMapLock); + + if(mRefCountMap.find(inItem)) + { + uint32_t& counter = mRefCountMap[inItem]; + counter++; + return false; + } + else + { + mRefCountMap.insert(inItem, 1); + return true; + } +} + +bool ObjectRegistrar::decItem(const void* inItem) +{ + physx::shdfnd::Mutex::ScopedLock lock(mRefCountMapLock); + const physx::shdfnd::HashMap::Entry* entry = mRefCountMap.find(inItem); + if(entry) + { + uint32_t& retval(const_cast(entry->second)); + if(retval) + --retval; + uint32_t theValue = retval; + if(theValue == 0) + { + mRefCountMap.erase(inItem); + return true; + } + } + return false; +} + +void ObjectRegistrar::clear() +{ + physx::shdfnd::Mutex::ScopedLock lock(mRefCountMapLock); + mRefCountMap.clear(); +} + +} // pvdsdk +} // physx diff --git a/pool/shard000/C++/0000308_ht_camera_component.cpp b/pool/shard000/C++/0000308_ht_camera_component.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f2bcac758ca7f037315ac5c0c2dc1f651fa97f97 --- /dev/null +++ b/pool/shard000/C++/0000308_ht_camera_component.cpp @@ -0,0 +1,195 @@ +/** +** Hatchit Engine +** Copyright(c) 2015-2016 Third-Degree +** +** GNU Lesser General Public License +** This file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free +** Software Foundation and appearing in the file LICENSE.LGPLv3 included +** in the packaging of this file. Please review the following information +** to ensure the GNU Lesser General Public License requirements +** will be met: https://www.gnu.org/licenses/lgpl.html +** +**/ + +#include +#include +#include +#include +#include +#include + +namespace Hatchit { + + namespace Game { + + Camera::Camera() + { + m_useWindowScale = false; + m_fov = Math::MMDegreesToRadians(90.0f); + m_width = 1280; + m_height = 720; + m_near = 1.0f; + m_far = 100.0f; + m_layer = 1; + + m_speed = 0.01f; + m_yaw = 0.0f; + m_pitch = 0.0f; + + m_camera = Graphics::Camera(Math::Matrix4(), Math::MMMatrixPerspProj(m_fov, m_width, m_height, m_near, m_far)); + m_renderer = Renderer::instance().GetRenderer(); + } + + Core::JSON Camera::VSerialize(void) + { + return Core::JSON(); + } + + bool Camera::VDeserialize(const Core::JSON& jsonObject) + { + if (!Core::JsonExtract(jsonObject, "UseWindowScale", m_useWindowScale)) + HT_WARNING_PRINTF("Camera::VDeserialize: Failed to load window scale preference; defaulting to false\n"); + + if (!Core::JsonExtract(jsonObject, "FOV", m_fov)) + HT_WARNING_PRINTF("Camera::VDeserialize: Failed to load FOV; defaulting to 90 degrees\n"); + else + m_fov = Math::MMDegreesToRadians(m_fov); //Convert FOV to radians if we loaded properly + + if (!Core::JsonExtract(jsonObject, "Width", m_width)) + HT_WARNING_PRINTF("Camera::VDeserialize: Failed to load width; defaulting to 1280\n"); + + if (!Core::JsonExtract(jsonObject, "Height", m_height)) + HT_WARNING_PRINTF("Camera::VDeserialize: Failed to load height; defaulting to 720\n"); + + if (!Core::JsonExtract(jsonObject, "Near", m_near)) + HT_WARNING_PRINTF("Camera::VDeserialize: Failed to load near plane; defaulting to 0.1\n"); + + if (!Core::JsonExtract(jsonObject, "Far", m_far)) + HT_WARNING_PRINTF("Camera::VDeserialize: Failed to load far plane; defaulting to 100\n"); + + if (!Core::JsonExtract(jsonObject, "Layer", m_layer)) + HT_WARNING_PRINTF("Camera::VDeserialize: Failed to load layer; defaulting to 1\n"); + + //If we want to use window scale lets make m_width and m_height relative to the renderer's swapchain size + if (m_useWindowScale) + { + Graphics::SwapChain* swapchain = m_renderer->GetSwapChain(); + + //m_width and m_height should be "percentage" values until this step if m_useWindowScale is defined + m_width = m_width * swapchain->GetWidth(); + m_height = m_height * swapchain->GetHeight(); + + //Now m_width and m_height should be relative to the swapchain's screen size + } + + m_camera = Graphics::Camera(Math::Matrix4(), Math::MMMatrixPerspProj(m_fov, m_width, m_height, m_near, m_far)); + m_camera.SetLayerFlags(m_layer); + return true; + } + + void Camera::VOnInit() + { + + } + + void Camera::VOnUpdate() + { + Transform& t = m_owner->GetTransform(); + + Move(); + Rotate(); + + //Send transform data to the GPU by registering the camera with the renderer + m_camera.SetView(Math::MMMatrixLookAt(t.GetPosition(), t.GetPosition() + t.GetForward(), t.GetUp())); + m_camera.SetProjection(Math::MMMatrixPerspProj(m_fov, m_width, m_height, m_near, m_far)); + m_renderer->RegisterCamera(m_camera); + } + + void Camera::VOnEnabled() + { + + } + + void Camera::VOnDisabled() + { + + } + + void Camera::VOnDestroy() + { + + } + + Component* Camera::VClone(void) const + { + HT_DEBUG_PRINTF("Cloned Camera Component.\n"); + return new Camera(*this); + } + + /** + * \brief Retrieves the id associated with this class of Component. + * \return The Core::Guid associated with this Component type. + * \sa Component(), GameObject() + */ + Core::Guid Camera::VGetComponentId(void) const + { + return Component::GetComponentId(); + } + + void Camera::Move() + { + Transform& t = m_owner->GetTransform(); + + if (Input::KeyPressed(IKeyboard::Key::W) || Input::KeyPressed(IKeyboard::Key::Up)) + t.SetPosition(t.GetPosition() + (t.GetForward() * m_speed)); + if (Input::KeyPressed(IKeyboard::Key::A) || Input::KeyPressed(IKeyboard::Key::Left)) + t.SetPosition(t.GetPosition() - (t.GetRight() * m_speed)); + if (Input::KeyPressed(IKeyboard::Key::S) || Input::KeyPressed(IKeyboard::Key::Down)) + t.SetPosition(t.GetPosition() - (t.GetForward() * m_speed)); + if (Input::KeyPressed(IKeyboard::Key::D) || Input::KeyPressed(IKeyboard::Key::Right)) + t.SetPosition(t.GetPosition() + (t.GetRight() * m_speed)); + if (Input::KeyPressed(IKeyboard::Key::E)) + t.SetPosition(t.GetPosition() + (Math::Vector3(0.0f, 1.0f, 0.0f) * m_speed)); + if (Input::KeyPressed(IKeyboard::Key::Q)) + t.SetPosition(t.GetPosition() + (Math::Vector3(0.0f, -1.0f, 0.0f) * m_speed)); + } + + void Camera::Rotate() + { + if (Input::MouseButtonPress(MouseButton::Left)) + { + Transform& t = m_owner->GetTransform(); + + float xOffset = static_cast(Input::PreviousMouseX() - Input::MouseX()); + float yOffset = static_cast(Input::PreviousMouseY() - Input::MouseY()); + float sensitivity = 0.1f; + + xOffset *= sensitivity; + yOffset *= sensitivity; + + m_yaw += xOffset; + m_pitch += yOffset; + + if (m_pitch > 89.9f) + m_pitch = 89.9f; + if (m_pitch < -89.9f) + m_pitch = -89.9f; + + if (xOffset != 0 && yOffset != 0) + { + float yawRad = Math::MMDegreesToRadians(m_yaw); + float pitchRad = Math::MMDegreesToRadians(m_pitch); + + Math::Vector3 camFront = Math::Vector3(); + camFront.x = cosf(yawRad) * cosf(pitchRad); + camFront.y = sinf(pitchRad); + camFront.z = sinf(yawRad) * cosf(pitchRad); + + t.SetRotation(Math::Vector3(-pitchRad, -yawRad, 0.0f)); + } + } + } + } + +} diff --git a/pool/shard000/C++/0000313_unlink.cpp b/pool/shard000/C++/0000313_unlink.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9cf403e2a99951c801eedfee685420e58196b3a9 --- /dev/null +++ b/pool/shard000/C++/0000313_unlink.cpp @@ -0,0 +1,103 @@ +/* + Copyright (c) 2016, Antonio SJ Musumeci + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted, provided that the above + copyright notice and this permission notice appear in all copies. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +*/ + +#include + +#include + +#include +#include + +#include "config.hpp" +#include "errno.hpp" +#include "fs_base_unlink.hpp" +#include "fs_path.hpp" +#include "rv.hpp" +#include "rwlock.hpp" +#include "ugid.hpp" + +using std::string; +using std::vector; +using mergerfs::Policy; + +static +int +_unlink_loop_core(const string *basepath, + const char *fusepath, + const int error) +{ + int rv; + string fullpath; + + fs::path::make(basepath,fusepath,fullpath); + + rv = fs::unlink(fullpath); + + return error::calc(rv,error,errno); +} + +static +int +_unlink_loop(const vector &basepaths, + const char *fusepath) +{ + int error; + + error = -1; + for(size_t i = 0, ei = basepaths.size(); i != ei; i++) + { + error = _unlink_loop_core(basepaths[i],fusepath,error); + } + + return -error; +} + +static +int +_unlink(Policy::Func::Action actionFunc, + const vector &srcmounts, + const uint64_t minfreespace, + const char *fusepath) +{ + int rv; + vector basepaths; + + rv = actionFunc(srcmounts,fusepath,minfreespace,basepaths); + if(rv == -1) + return -errno; + + return _unlink_loop(basepaths,fusepath); +} + +namespace mergerfs +{ + namespace fuse + { + int + unlink(const char *fusepath) + { + const fuse_context *fc = fuse_get_context(); + const Config &config = Config::get(fc); + const ugid::Set ugid(fc->uid,fc->gid); + const rwlock::ReadGuard readlock(&config.srcmountslock); + + return _unlink(config.unlink, + config.srcmounts, + config.minfreespace, + fusepath); + } + } +} diff --git a/pool/shard000/C++/0000315_video-state.cpp b/pool/shard000/C++/0000315_video-state.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ba53efb3a3e531fa30d2a8cd7470bc2d37ad48dd --- /dev/null +++ b/pool/shard000/C++/0000315_video-state.cpp @@ -0,0 +1,222 @@ +/* Mednafen - Multi-system Emulator + * + * 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 + */ + +// Code for drawing save states and mooovies +// all functions should be called from the main thread +#include "main.h" +#include "video.h" +#include +#include + +#define MK_COLOR_A(tmp_surface, r,g,b,a) (tmp_surface->MakeColor(r, g, b, a)) + +static MDFN_Surface *PreviewSurface = NULL, *TextSurface = NULL; +static MDFN_Rect PreviewRect, TextRect; + +static StateStatusStruct *StateStatus; +static uint32 StateShow; +static bool IsMovie; + +void DrawStateMovieRow(MDFN_Surface *surface, int *nstatus, int cur, int recently_saved, uint8 *text) +{ + uint32 *XBuf = surface->pixels; + uint32 pitch32 = surface->pitchinpix; + + MDFN_DrawFillRect(surface, 0, 0, 230, 40, surface->MakeColor(0x00, 0x00, 0x00, 170)); + + // nstatus + for(int i = 1; i < 11; i++) + { + char stringie[2]; + uint32 bordercol; + uint32 rect_bg_color = MK_COLOR_A(surface, 0x00, 0x00, 0x00, 0xFF); + + if(cur == (i % 10)) + bordercol = MK_COLOR_A(surface, 0x60, 0x20, 0xb0, 0xFF); + else + bordercol = MK_COLOR_A(surface, 0, 0, 0, 0xFF); + + stringie[0] = '0' + (i % 10); + stringie[1] = 0; + + if(nstatus[i % 10]) + { + rect_bg_color = MK_COLOR_A(surface, 0x00, 0x38, 0x28, 0xFF); + + if(recently_saved == (i % 10)) + rect_bg_color = MK_COLOR_A(surface, 0x48, 0x00, 0x34, 0xFF); + } + + MDFN_DrawFillRect(surface, (i - 1) * 23, 0, 23, 18 + 1, bordercol, rect_bg_color); + + DrawTextTransShadow(XBuf + (i - 1) * 23 + 7, pitch32 << 2, 230, (UTF8*)stringie, MK_COLOR_A(surface, 0xE0, 0xFF, 0xE0, 0xFF), MK_COLOR_A(surface, 0x00, 0x00, 0x00, 0xFF), FALSE); + } + DrawTextTransShadow(XBuf + 20 * pitch32, pitch32 << 2, 230, text, MK_COLOR_A(surface, 0xE0, 0xFF, 0xE0, 0xFF), MK_COLOR_A(surface, 0x00, 0x00, 0x00, 0xFF), TRUE); +} + + +bool SaveStatesActive(void) +{ + return(StateStatus); +} + +static void SSCleanup(void) +{ + if(PreviewSurface) + { + delete PreviewSurface; + PreviewSurface = NULL; + } + + if(TextSurface) + { + delete TextSurface; + TextSurface = NULL; + } + + if(StateStatus) + { + if(StateStatus->gfx) + free(StateStatus->gfx); + free(StateStatus); + StateStatus = NULL; + } +} + +void DrawSaveStates(SDL_Surface *screen, double exs, double eys, int rs, int gs, int bs, int as) +{ + if(StateShow < MDFND_GetTime()) + { + SSCleanup(); + } + + if(StateStatus) + { + if(!PreviewSurface) + { + PreviewSurface = new MDFN_Surface(NULL, StateStatus->w + 2, StateStatus->h + 2, StateStatus->w + 2, MDFN_PixelFormat(MDFN_COLORSPACE_RGB, rs, gs, bs, as)); + + if(!PreviewSurface) + { + printf("Iyee: %d %d\n", StateStatus->w, StateStatus->h); + return; + } + + PreviewRect.x = PreviewRect.y = 0; + PreviewRect.w = StateStatus->w + 2; + PreviewRect.h = StateStatus->h + 2; + + MDFN_DrawFillRect(PreviewSurface, 0, 0, StateStatus->w + 2, StateStatus->h + 2, MK_COLOR_A(PreviewSurface, 0x00, 0x00, 0x9F, 0xFF), MK_COLOR_A(PreviewSurface, 0x00, 0x00, 0x00, 0x80)); + + uint32 *psp = PreviewSurface->pixels; + + psp += PreviewSurface->pitchinpix; + psp++; + + if(StateStatus->gfx) + { + for(uint32 y = 0; y < StateStatus->h; y++) + { + uint8 *src_row = StateStatus->gfx + y * StateStatus->w * 3; + + for(uint32 x = 0; x < StateStatus->w; x++) + { + psp[x] = MK_COLOR_A(PreviewSurface, src_row[0], src_row[1], src_row[2], 0xFF); + src_row += 3; + } + psp += PreviewSurface->pitchinpix; + } + } + + if(!TextSurface) + { + TextSurface = new MDFN_Surface(NULL, 230, 40, 230, MDFN_PixelFormat(MDFN_COLORSPACE_RGB, rs, gs, bs, as)); + + TextRect.x = TextRect.y = 0; + TextRect.w = 230; + TextRect.h = 40; + } + + if(IsMovie) + { + UTF8 text[256]; + + if(StateStatus->current_movie > 0) + trio_snprintf((char *)text, 256, _("-recording movie %d-"), StateStatus->current_movie-1); + else if (StateStatus->current_movie < 0) + trio_snprintf((char *)text, 256, _("-playing movie %d-"),-1 - StateStatus->current_movie); + else + trio_snprintf((char *)text, 256, _("-select movie-")); + + DrawStateMovieRow(TextSurface, StateStatus->status, StateStatus->current, StateStatus->recently_saved, text); + } + else + DrawStateMovieRow(TextSurface, StateStatus->status, StateStatus->current, StateStatus->recently_saved, (UTF8 *)_("-select state-")); + } + } // end if(StateStatus) + + if(PreviewSurface) + { + MDFN_Rect tdrect, drect; + + int meow = ((screen->w / CurGame->nominal_width) + 1) / 2; + if(!meow) meow = 1; + + tdrect.w = TextRect.w * meow; + tdrect.h = TextRect.h * meow; + tdrect.x = (screen->w - tdrect.w) / 2; + tdrect.y = screen->h - tdrect.h; + + BlitRaw(TextSurface, &TextRect, &tdrect); + + drect.w = PreviewRect.w * meow; + drect.h = PreviewRect.h * meow; + drect.x = (screen->w - drect.w) / 2; + drect.y = screen->h - drect.h - tdrect.h - 4; + + BlitRaw(PreviewSurface, &PreviewRect, &drect); + + } + +} + +void MT_SetStateStatus(StateStatusStruct *status) +{ + SSCleanup(); + + IsMovie = FALSE; + StateStatus = status; + + if(status) + StateShow = MDFND_GetTime() + MDFN_GetSettingUI("osd.state_display_time"); + else + StateShow = 0; +} + +void MT_SetMovieStatus(StateStatusStruct *status) +{ + SSCleanup(); + + IsMovie = TRUE; + StateStatus = status; + + if(status) + StateShow = MDFND_GetTime() + MDFN_GetSettingUI("osd.state_display_time"); + else + StateShow = 0; +} + diff --git a/pool/shard000/C++/0000318_GUI_List.cpp b/pool/shard000/C++/0000318_GUI_List.cpp new file mode 100644 index 0000000000000000000000000000000000000000..607f4e83ec0c19057c79b0a490f6133c2c68783f --- /dev/null +++ b/pool/shard000/C++/0000318_GUI_List.cpp @@ -0,0 +1,136 @@ +// +// GUI_List.cpp +// GUI_CheckBox +// +// Created by Panutat Tejasen on 16/1/2562 BE. +// Copyright © 2562 Jimmy Software Co., Ltd. All rights reserved. +// + +#include "GUI_List.h" +#include "GUI_shapes.h" + +GUI_ListItem *GUI_ListItem::create( GUI_View *parent, const char *title, int x, int y, int width, int height, + std::functioncallbackFunction ) { + return new GUI_ListItem( parent, title, x, y, width, height, callbackFunction ); +} + +GUI_ListItem::GUI_ListItem(GUI_View *parent, const char *title, int x, int y, int width, int height, + std::functioncallbackFunction ) : +GUI_View( parent, title, x, y, width, height ) +{ + dragable = false; + //clickable = true; + clickable = false; + capture_on_click = false; + callback_on_mouse_up = true; + + focusable = true; + showInteract = true; + mouseReceive = true; + + setBackgroundColor(cWhite); + showInteract = true; + + setLayout(GUI_LAYOUT_HORIZONTAL); + setBorder( 0 ); +} + +GUI_ListItem::~GUI_ListItem() { + +} + +void GUI_ListItem::setSelected( bool s ) { + selected = s; + if( selected ) { + setBackgroundColor( cHightLightSelection ); + } + else { + setBackgroundColor( cWhite ); + } +} + +void GUI_ListItem::postdraw() { + GUI_View::postdraw(); + + GUI_DrawHLine( 0, rectView.w, rectView.h-1, cBlack ); +} + +// ------------------------------------------------------------------------------------------------ + +GUI_List *GUI_List::create( GUI_View *parent, const char *title, int x, int y, int width, int height, + std::functioncallbackFunction ) { + return new GUI_List( parent, title, x, y, width, height, callbackFunction ); +} + +GUI_List::GUI_List(GUI_View *parent, const char *title, int x, int y, int width, int height, + std::functioncallbackFunction ) : +GUI_View( parent, title, x, y, width, height ), +scrollView(NULL) +{ + setCallback( callbackFunction ); + + setPadding(5, 0, 5, 0); + setBackgroundColor(cEmptyContent); + setLayout(GUI_LAYOUT_VERTICAL); + setBorder( 1 ); + setCorner( 4 ); + + scrollView = GUI_ScrollView::create( this, "Scroll", 0, 0, -1, -1 ); + +} + +GUI_List::~GUI_List() { + +} + +void GUI_List::add(GUI_ListItem* child) { + if( child->parent ) { + child->parent->remove_child( child ); + } + scrollView->scrollContent->add_child(child); + child->in_scroll_bed = true; + + listItems.push_back(child); + child->setCallback( [=](GUI_View *v) { + GUI_ListItem *lit = (GUI_ListItem *)v; + for (std::vector::iterator it = listItems.begin() ; it != listItems.end(); ++it) { + GUI_ListItem *c = *it; + if( lit == c ) { + c->setSelected(true); + GUI_Log( "%s\n", c->title.c_str()); + this->selectedItem = c; + if( this->callback ) { + this->callback(this); + } + } + else { + c->setSelected(false); + } + } + }); +} + +void GUI_List::remove(GUI_ListItem* child) { + scrollView->scrollContent->remove_child(child); + child->in_scroll_bed = false; + for (std::vector::iterator it = listItems.begin() ; it != listItems.end(); ++it) { + if( child == *it ) { + listItems.erase( it ); + break; + } + } + child->setCallback(NULL); +} + +void GUI_List::addSimpleItem( const char *title ) { + GUI_ListItem *item1 = GUI_ListItem::create( NULL, title, 0, 0, -1, 0 ); + item1->setPadding( 5, 10, 5, 10 ); + + + GUI_Label *lb1 = GUI_Label::create( item1, title, 0, 0, -1, 0 ); + lb1->setAlign( GUI_ALIGN_LEFT | GUI_ALIGN_VCENTER ); + lb1->setBackgroundColor(cClear); + + add( item1 ); + updateLayout(); +} diff --git a/pool/shard000/C/0013677_armobsd-tdep.c b/pool/shard000/C/0013677_armobsd-tdep.c new file mode 100644 index 0000000000000000000000000000000000000000..58bcc5df0cea4bec4e70b415b5292c10ecbd151c --- /dev/null +++ b/pool/shard000/C/0013677_armobsd-tdep.c @@ -0,0 +1,140 @@ +/* Target-dependent code for OpenBSD/arm. + + Copyright (C) 2006-2015 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 "osabi.h" +#include "trad-frame.h" +#include "tramp-frame.h" + +#include "obsd-tdep.h" +#include "arm-tdep.h" +#include "solib-svr4.h" + +/* Signal trampolines. */ + +static void +armobsd_sigframe_init (const struct tramp_frame *self, + struct frame_info *this_frame, + struct trad_frame_cache *cache, + CORE_ADDR func) +{ + CORE_ADDR sp, sigcontext_addr, addr; + int regnum; + + /* We find the appropriate instance of `struct sigcontext' at a + fixed offset in the signal frame. */ + sp = get_frame_register_signed (this_frame, ARM_SP_REGNUM); + sigcontext_addr = sp + 16; + + /* PC. */ + trad_frame_set_reg_addr (cache, ARM_PC_REGNUM, sigcontext_addr + 76); + + /* GPRs. */ + for (regnum = ARM_A1_REGNUM, addr = sigcontext_addr + 12; + regnum <= ARM_LR_REGNUM; regnum++, addr += 4) + trad_frame_set_reg_addr (cache, regnum, addr); + + trad_frame_set_id (cache, frame_id_build (sp, func)); +} + +static const struct tramp_frame armobsd_sigframe = +{ + SIGTRAMP_FRAME, + 4, + { + { 0xe28d0010, -1 }, /* add r0, sp, #16 */ + { 0xef000067, -1 }, /* swi SYS_sigreturn */ + { 0xef000001, -1 }, /* swi SYS_exit */ + { 0xeafffffc, -1 }, /* b . - 8 */ + { TRAMP_SENTINEL_INSN, -1 } + }, + armobsd_sigframe_init +}; + + +/* Override default thumb breakpoints. */ +static const gdb_byte arm_obsd_thumb_le_breakpoint[] = {0xfe, 0xdf}; +static const gdb_byte arm_obsd_thumb_be_breakpoint[] = {0xdf, 0xfe}; + +static void +armobsd_init_abi (struct gdbarch_info info, + struct gdbarch *gdbarch) +{ + struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch); + + if (tdep->fp_model == ARM_FLOAT_AUTO) + tdep->fp_model = ARM_FLOAT_SOFT_VFP; + + tramp_frame_prepend_unwinder (gdbarch, &armobsd_sigframe); + + /* OpenBSD/arm uses SVR4-style shared libraries. */ + set_solib_svr4_fetch_link_map_offsets + (gdbarch, svr4_ilp32_fetch_link_map_offsets); + set_gdbarch_skip_solib_resolver (gdbarch, obsd_skip_solib_resolver); + + tdep->jb_pc = 24; + tdep->jb_elt_size = 4; + + set_gdbarch_iterate_over_regset_sections + (gdbarch, armbsd_iterate_over_regset_sections); + + /* OpenBSD/arm uses -fpcc-struct-return by default. */ + tdep->struct_return = pcc_struct_return; + + /* Single stepping. */ + set_gdbarch_software_single_step (gdbarch, arm_software_single_step); + + /* Breakpoints. */ + switch (info.byte_order) + { + case BFD_ENDIAN_BIG: + tdep->thumb_breakpoint = arm_obsd_thumb_be_breakpoint; + tdep->thumb_breakpoint_size = sizeof (arm_obsd_thumb_be_breakpoint); + break; + + case BFD_ENDIAN_LITTLE: + tdep->thumb_breakpoint = arm_obsd_thumb_le_breakpoint; + tdep->thumb_breakpoint_size = sizeof (arm_obsd_thumb_le_breakpoint); + break; + } +} + + +static enum gdb_osabi +armobsd_core_osabi_sniffer (bfd *abfd) +{ + if (strcmp (bfd_get_target (abfd), "netbsd-core") == 0) + return GDB_OSABI_OPENBSD_ELF; + + return GDB_OSABI_UNKNOWN; +} + +/* Provide a prototype to silence -Wmissing-prototypes. */ +extern initialize_file_ftype _initialize_armobsd_tdep; + +void +_initialize_armobsd_tdep (void) +{ + /* BFD doesn't set a flavour for NetBSD style a.out core files. */ + gdbarch_register_osabi_sniffer (bfd_arch_arm, bfd_target_unknown_flavour, + armobsd_core_osabi_sniffer); + + gdbarch_register_osabi (bfd_arch_arm, 0, GDB_OSABI_OPENBSD_ELF, + armobsd_init_abi); +} diff --git a/pool/shard000/C/0013678_convert.c b/pool/shard000/C/0013678_convert.c new file mode 100644 index 0000000000000000000000000000000000000000..7a05550ee04a8022e32069f56813b355fafaf867 --- /dev/null +++ b/pool/shard000/C/0013678_convert.c @@ -0,0 +1,76 @@ +/* convert.c - Hex conversion functions. + * Copyright (C) 2006, 2008 Free Software Foundation, Inc. + * + * This file is part of GnuPG. + * + * GnuPG 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. + * + * GnuPG 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 + +#include "util.h" + + +#define tohex(n) ((n) < 10 ? ((n) + '0') : (((n) - 10) + 'A')) + +static char * +do_bin2hex (const void *buffer, size_t length, char *stringbuf, int with_colon) +{ + const unsigned char *s; + char *p; + + if (!stringbuf) + { + /* Not really correct for with_colon but we don't care about the + one wasted byte. */ + size_t n = with_colon? 3:2; + size_t nbytes = n * length + 1; + if (length && (nbytes-1) / n != length) + { + errno = ENOMEM; + return NULL; + } + stringbuf = xtrymalloc (nbytes); + if (!stringbuf) + return NULL; + } + + for (s = buffer, p = stringbuf; length; length--, s++) + { + if (with_colon && s != buffer) + *p++ = ':'; + *p++ = tohex ((*s>>4)&15); + *p++ = tohex (*s&15); + } + *p = 0; + + return stringbuf; +} + + +/* Convert LENGTH bytes of data in BUFFER into hex encoding and store + that at the provided STRINGBUF. STRINGBUF must be allocated of at + least (2*LENGTH+1) bytes or be NULL so that the function mallocs an + appropriate buffer. Returns STRINGBUF or NULL on error (which may + only occur if STRINGBUF has been NULL and the internal malloc + failed). */ +char * +bin2hex (const void *buffer, size_t length, char *stringbuf) +{ + return do_bin2hex (buffer, length, stringbuf, 0); +} diff --git a/pool/shard000/C/0013680_b2d.c b/pool/shard000/C/0013680_b2d.c new file mode 100644 index 0000000000000000000000000000000000000000..1d9c48180a0eedae3f2e777ff712f6d9a4470612 --- /dev/null +++ b/pool/shard000/C/0013680_b2d.c @@ -0,0 +1,13 @@ +#include + +int main(){ + char b[] = "Box2D"; + int i; + int sum = 0; + for(i = 0; i < strlen(b); i++){ + printf("%c: %d\n",b[i],b[i]); + sum += b[i]; + } + printf("%d\n",sum); + return 0; +} diff --git a/pool/shard000/C/0013686_CWE194_Unexpected_Sign_Extension__fscanf_memmove_41.c b/pool/shard000/C/0013686_CWE194_Unexpected_Sign_Extension__fscanf_memmove_41.c new file mode 100644 index 0000000000000000000000000000000000000000..35ec31a862077ccdf7a2a45707f9032ed7dca28b --- /dev/null +++ b/pool/shard000/C/0013686_CWE194_Unexpected_Sign_Extension__fscanf_memmove_41.c @@ -0,0 +1,114 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE194_Unexpected_Sign_Extension__fscanf_memmove_41.c +Label Definition File: CWE194_Unexpected_Sign_Extension.label.xml +Template File: sources-sink-41.tmpl.c +*/ +/* + * @description + * CWE: 194 Unexpected Sign Extension + * BadSource: fscanf Read data from the console using fscanf() + * GoodSource: Positive integer + * Sink: memmove + * BadSink : Copy strings using memmove() with the length of data + * Flow Variant: 41 Data flow: data passed as an argument from one function to another in the same source file + * + * */ + +#include "std_testcase.h" + +#ifndef OMITBAD + +void CWE194_Unexpected_Sign_Extension__fscanf_memmove_41_badSink(short data) +{ + { + char source[100]; + char dest[100] = ""; + memset(source, 'A', 100-1); + source[100-1] = '\0'; + if (data < 100) + { + /* POTENTIAL FLAW: data is interpreted as an unsigned int - if its value is negative, + * the sign extension could result in a very large number */ + memmove(dest, source, data); + dest[data] = '\0'; /* NULL terminate */ + } + printLine(dest); + } +} + +void CWE194_Unexpected_Sign_Extension__fscanf_memmove_41_bad() +{ + short data; + /* Initialize data */ + data = 0; + /* FLAW: Use a value input from the console using fscanf() */ + fscanf (stdin, "%hd", &data); + CWE194_Unexpected_Sign_Extension__fscanf_memmove_41_badSink(data); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +void CWE194_Unexpected_Sign_Extension__fscanf_memmove_41_goodG2BSink(short data) +{ + { + char source[100]; + char dest[100] = ""; + memset(source, 'A', 100-1); + source[100-1] = '\0'; + if (data < 100) + { + /* POTENTIAL FLAW: data is interpreted as an unsigned int - if its value is negative, + * the sign extension could result in a very large number */ + memmove(dest, source, data); + dest[data] = '\0'; /* NULL terminate */ + } + printLine(dest); + } +} + +/* goodG2B uses the GoodSource with the BadSink */ +static void goodG2B() +{ + short data; + /* Initialize data */ + data = 0; + /* FIX: Use a positive integer less than &InitialDataSize&*/ + data = 100-1; + CWE194_Unexpected_Sign_Extension__fscanf_memmove_41_goodG2BSink(data); +} + +void CWE194_Unexpected_Sign_Extension__fscanf_memmove_41_good() +{ + goodG2B(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + * its own for testing or for building a binary to use in testing binary + * analysis tools. It is not used when compiling all the testcases as one + * application, which is how source code analysis tools are tested. + */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE194_Unexpected_Sign_Extension__fscanf_memmove_41_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE194_Unexpected_Sign_Extension__fscanf_memmove_41_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard000/C/0013694_displays.c b/pool/shard000/C/0013694_displays.c new file mode 100644 index 0000000000000000000000000000000000000000..d41d26656b10b2d816b85fe9d2b4439cef975069 --- /dev/null +++ b/pool/shard000/C/0013694_displays.c @@ -0,0 +1,222 @@ +/** + * flightpanel - A Cortex-M4 based USB flight panel for flight simulators. + * Copyright (C) 2017-2017 Johannes Bauer + * + * This file is part of flightpanel. + * + * flightpanel 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; this program is ONLY licensed under + * version 3 of the License, later versions are explicitly excluded. + * + * flightpanel 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 flightpanel; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * Johannes Bauer +**/ + +#include +#include +#include "ssd1306.h" +#include "displays.h" +#include "pinmap.h" +#include "timer.h" +#include "surface.h" +#include "spi.h" +#include "fncmap.h" +#include "font.h" +#include "atomic.h" + +static bool inhibit; +static atomic_t dma_running; +static uint8_t last_updated_display; + +static const struct ssd1306_display_t displays[DISPLAY_COUNT] = { + [0] = { + .CS_GPIO = Display1_CS_GPIO, + .CS_Pin = Display1_CS_Pin, + .surface = &(const struct surface_t) { + .width = 128, + .height = 64, + .data = (uint8_t[128 * 64 / 8]) { }, + }, + }, + [1] = { + .CS_GPIO = Display2_CS_GPIO, + .CS_Pin = Display2_CS_Pin, + .surface = &(const struct surface_t) { + .width = 128, + .height = 64, + .data = (uint8_t[128 * 64 / 8]) { }, + }, + }, + [2] = { + .CS_GPIO = Display3_CS_GPIO, + .CS_Pin = Display3_CS_Pin, + .surface = &(const struct surface_t) { + .width = 128, + .height = 64, + .data = (uint8_t[128 * 64 / 8]) { }, + }, + }, + [3] = { + .CS_GPIO = Display4_CS_GPIO, + .CS_Pin = Display4_CS_Pin, + .surface = &(const struct surface_t) { + .width = 128, + .height = 64, + .data = (uint8_t[128 * 64 / 8]) { }, + }, + }, + [4] = { + .CS_GPIO = Display5_CS_GPIO, + .CS_Pin = Display5_CS_Pin, + .surface = &(const struct surface_t) { + .width = 128, + .height = 64, + .data = (uint8_t[128 * 64 / 8]) { }, + }, + }, + [5] = { + .CS_GPIO = Display6_CS_GPIO, + .CS_Pin = Display6_CS_Pin, + .surface = &(const struct surface_t) { + .width = 128, + .height = 64, + .data = (uint8_t[128 * 64 / 8]) { }, + }, + }, + [6] = { + .CS_GPIO = Display7_CS_GPIO, + .CS_Pin = Display7_CS_Pin, + .surface = &(const struct surface_t) { + .width = 128, + .height = 64, + .data = (uint8_t[128 * 64 / 8]) { }, + }, + }, + [7] = { + .CS_GPIO = Display8_CS_GPIO, + .CS_Pin = Display8_CS_Pin, + .surface = &(const struct surface_t) { + .width = 128, + .height = 64, + .data = (uint8_t[128 * 64 / 8]) { }, + }, + }, + [8] = { + .CS_GPIO = Display9_CS_GPIO, + .CS_Pin = Display9_CS_Pin, + .surface = &(const struct surface_t) { + .width = 128, + .height = 64, + .data = (uint8_t[128 * 64 / 8]) { }, + }, + }, + [9] = { + .CS_GPIO = Display10_CS_GPIO, + .CS_Pin = Display10_CS_Pin, + .surface = &(const struct surface_t) { + .width = 128, + .height = 64, + .data = (uint8_t[128 * 64 / 8]) { }, + }, + }, + [10] = { + .CS_GPIO = Display11_CS_GPIO, + .CS_Pin = Display11_CS_Pin, + .surface = &(const struct surface_t) { + .width = 128, + .height = 64, + .data = (uint8_t[128 * 64 / 8]) { }, + }, + }, + [11] = { + .CS_GPIO = Display12_CS_GPIO, + .CS_Pin = Display12_CS_Pin, + .surface = &(const struct surface_t) { + .width = 128, + .height = 64, + .data = (uint8_t[128 * 64 / 8]) { }, + }, + }, +}; +static bool surface_dirty[DISPLAY_COUNT]; + +static void displays_enable_cs(int display_index) { + GPIO_ResetBits(displays[display_index].CS_GPIO, displays[display_index].CS_Pin); +} + +static void displays_disable_cs(int display_index) { + GPIO_SetBits(displays[display_index].CS_GPIO, displays[display_index].CS_Pin); +} + +static void display_dma_start(int display_index) { + /* Only start if no DMA is running right now */ + if (!inhibit && atomic_lock(&dma_running)) { + surface_dirty[display_index] = false; + last_updated_display = display_index; + displays_enable_cs(display_index); + spi_tx_rx_data_dma(DisplaySPI_SPI, DisplaySPI_DMAStream_TX, displays[display_index].surface->data, DisplaySPI_DMAStream_RX, NULL, 128 * 64 / 8); + } +} + +void isr_display_dma_finished(void) { + displays_disable_cs(last_updated_display); +} + +void dsr_display_dma_finished(void) { + atomic_unlock(&dma_running); + displays_check_dma_schedule(); +} + +void displays_check_dma_schedule(void) { + if (!spi_dma_tx_rx_ready(DisplaySPI_DMAStream_TX, DisplaySPI_DMAStream_RX)) { + /* Transmission in progress. */ + return; + } + for (int i = 0; i < DISPLAY_COUNT; i++) { + int display_index = (i + last_updated_display) % DISPLAY_COUNT; + if (surface_dirty[display_index]) { + display_dma_start(display_index); + return; + } + } +} + +void display_mark_surface_dirty(int display_index) { + surface_dirty[display_index] = true; + displays_check_dma_schedule(); +} + +const struct surface_t* displays_get_surface(int display_index) { + return displays[display_index].surface; +} + +void init_displays(void) { + /* First disable all updates */ + inhibit = true; + + /* Then wait for any DMA to stop that might be running right now */ + while (!spi_dma_tx_rx_ready(DisplaySPI_DMAStream_TX, DisplaySPI_DMAStream_RX)); + + /* Reset all displays. Do busy waiting here because this might be triggered + * from ISR and therefore delay_millis() would deadlock. */ + Display_RESET_set_ACTIVE(); + delay_loopcnt(LOOPCOUNT_1MS); + Display_RESET_set_INACTIVE(); + + for (int did = 0; did < DISPLAY_COUNT; did++) { + surface_clear(displays[did].surface); + ssd1306_init(&displays[did]); + } + + /* Then allow display updates again */ + inhibit = false; +} diff --git a/pool/shard000/C/0013713_main.c b/pool/shard000/C/0013713_main.c new file mode 100644 index 0000000000000000000000000000000000000000..1da9c16a5f2a6870c01900e2a0bde57c2cf3e04a --- /dev/null +++ b/pool/shard000/C/0013713_main.c @@ -0,0 +1,318 @@ +/* + / _____) _ | | +( (____ _____ ____ _| |_ _____ ____| |__ + \____ \| ___ | (_ _) ___ |/ ___) _ \ + _____) ) ____| | | || |_| ____( (___| | | | +(______/|_____)_|_|_| \__)_____)\____)_| |_| + (C)2013 Semtech + +Description: Ping-Pong implementation + +License: Revised BSD License, see LICENSE.TXT file include in the project + +Maintainer: Miguel Luis and Gregory Cristian +*/ +#include +#include "board.h" +#include "radio.h" + +#define USE_MODEM_LORA + +#if defined( USE_BAND_868 ) + +#define RF_FREQUENCY 868000000 // Hz + +#elif defined( USE_BAND_915 ) + +#define RF_FREQUENCY 915000000 // Hz + +#else + #error "Please define a frequency band in the compiler options." +#endif + +#define TX_OUTPUT_POWER 14 // dBm + +#if defined( USE_MODEM_LORA ) + +#define LORA_BANDWIDTH 0 // [0: 125 kHz, + // 1: 250 kHz, + // 2: 500 kHz, + // 3: Reserved] +#define LORA_SPREADING_FACTOR 7 // [SF7..SF12] +#define LORA_CODINGRATE 1 // [1: 4/5, + // 2: 4/6, + // 3: 4/7, + // 4: 4/8] +#define LORA_PREAMBLE_LENGTH 8 // Same for Tx and Rx +#define LORA_SYMBOL_TIMEOUT 5 // Symbols +#define LORA_FIX_LENGTH_PAYLOAD_ON false +#define LORA_IQ_INVERSION_ON false + +#elif defined( USE_MODEM_FSK ) + +#define FSK_FDEV 25e3 // Hz +#define FSK_DATARATE 50e3 // bps +#define FSK_BANDWIDTH 50e3 // Hz +#define FSK_AFC_BANDWIDTH 83.333e3 // Hz +#define FSK_PREAMBLE_LENGTH 5 // Same for Tx and Rx +#define FSK_FIX_LENGTH_PAYLOAD_ON false + +#else + #error "Please define a modem in the compiler options." +#endif + +typedef enum +{ + LOWPOWER, + RX, + RX_TIMEOUT, + RX_ERROR, + TX, + TX_TIMEOUT, +}States_t; + +#define RX_TIMEOUT_VALUE 1000 +#define BUFFER_SIZE 64 // Define the payload size here + +const uint8_t PingMsg[] = "PING"; +const uint8_t PongMsg[] = "PONG"; + +uint16_t BufferSize = BUFFER_SIZE; +uint8_t Buffer[BUFFER_SIZE]; + +States_t State = LOWPOWER; + +int8_t RssiValue = 0; +int8_t SnrValue = 0; + +/*! + * Radio events function pointer + */ +static RadioEvents_t RadioEvents; + +/*! + * \brief Function to be executed on Radio Tx Done event + */ +void OnTxDone( void ); + +/*! + * \brief Function to be executed on Radio Rx Done event + */ +void OnRxDone( uint8_t *payload, uint16_t size, int16_t rssi, int8_t snr ); + +/*! + * \brief Function executed on Radio Tx Timeout event + */ +void OnTxTimeout( void ); + +/*! + * \brief Function executed on Radio Rx Timeout event + */ +void OnRxTimeout( void ); + +/*! + * \brief Function executed on Radio Rx Error event + */ +void OnRxError( void ); + +/** + * Main application entry point. + */ +int main( void ) +{ + bool isMaster = true; + uint8_t i; + + // Target board initialisation + BoardInitMcu( ); + BoardInitPeriph( ); + + // Radio initialization + RadioEvents.TxDone = OnTxDone; + RadioEvents.RxDone = OnRxDone; + RadioEvents.TxTimeout = OnTxTimeout; + RadioEvents.RxTimeout = OnRxTimeout; + RadioEvents.RxError = OnRxError; + + Radio.Init( &RadioEvents ); + + Radio.SetChannel( RF_FREQUENCY ); + +#if defined( USE_MODEM_LORA ) + + Radio.SetTxConfig( MODEM_LORA, TX_OUTPUT_POWER, 0, LORA_BANDWIDTH, + LORA_SPREADING_FACTOR, LORA_CODINGRATE, + LORA_PREAMBLE_LENGTH, LORA_FIX_LENGTH_PAYLOAD_ON, + true, 0, 0, LORA_IQ_INVERSION_ON, 3000 ); + + Radio.SetRxConfig( MODEM_LORA, LORA_BANDWIDTH, LORA_SPREADING_FACTOR, + LORA_CODINGRATE, 0, LORA_PREAMBLE_LENGTH, + LORA_SYMBOL_TIMEOUT, LORA_FIX_LENGTH_PAYLOAD_ON, + 0, true, 0, 0, LORA_IQ_INVERSION_ON, true ); + +#elif defined( USE_MODEM_FSK ) + + Radio.SetTxConfig( MODEM_FSK, TX_OUTPUT_POWER, FSK_FDEV, 0, + FSK_DATARATE, 0, + FSK_PREAMBLE_LENGTH, FSK_FIX_LENGTH_PAYLOAD_ON, + true, 0, 0, 0, 3000 ); + + Radio.SetRxConfig( MODEM_FSK, FSK_BANDWIDTH, FSK_DATARATE, + 0, FSK_AFC_BANDWIDTH, FSK_PREAMBLE_LENGTH, + 0, FSK_FIX_LENGTH_PAYLOAD_ON, 0, true, + 0, 0,false, true ); + +#else + #error "Please define a frequency band in the compiler options." +#endif + + Radio.Rx( RX_TIMEOUT_VALUE ); + + while( 1 ) + { + switch( State ) + { + case RX: + if( isMaster == true ) + { + if( BufferSize > 0 ) + { + if( strncmp( ( const char* )Buffer, ( const char* )PongMsg, 4 ) == 0 ) + { + // Indicates on a LED that the received frame is a PONG + GpioWrite( &Led0, GpioRead( &Led0 ) ^ 1 ); + + // Send the next PING frame + Buffer[0] = 'P'; + Buffer[1] = 'I'; + Buffer[2] = 'N'; + Buffer[3] = 'G'; + // We fill the buffer with numbers for the payload + for( i = 4; i < BufferSize; i++ ) + { + Buffer[i] = i - 4; + } + DelayMs( 1 ); + Radio.Send( Buffer, BufferSize ); + } + else if( strncmp( ( const char* )Buffer, ( const char* )PingMsg, 4 ) == 0 ) + { // A master already exists then become a slave + isMaster = false; + GpioWrite( &Led1, 0 ); // Set LED off + Radio.Rx( RX_TIMEOUT_VALUE ); + } + else // valid reception but neither a PING or a PONG message + { // Set device as master ans start again + isMaster = true; + Radio.Rx( RX_TIMEOUT_VALUE ); + } + } + } + else + { + if( BufferSize > 0 ) + { + if( strncmp( ( const char* )Buffer, ( const char* )PingMsg, 4 ) == 0 ) + { + // Indicates on a LED that the received frame is a PING + GpioWrite( &Led0, GpioRead( &Led0 ) ^ 1 ); + + // Send the reply to the PONG string + Buffer[0] = 'P'; + Buffer[1] = 'O'; + Buffer[2] = 'N'; + Buffer[3] = 'G'; + // We fill the buffer with numbers for the payload + for( i = 4; i < BufferSize; i++ ) + { + Buffer[i] = i - 4; + } + DelayMs( 1 ); + Radio.Send( Buffer, BufferSize ); + } + else // valid reception but not a PING as expected + { // Set device as master and start again + isMaster = true; + Radio.Rx( RX_TIMEOUT_VALUE ); + } + } + } + State = LOWPOWER; + break; + case TX: + // Indicates on a LED that we have sent a PING [Master] + // Indicates on a LED that we have sent a PONG [Slave] + GpioWrite( &Led1, GpioRead( &Led1 ) ^ 1 ); + Radio.Rx( RX_TIMEOUT_VALUE ); + State = LOWPOWER; + break; + case RX_TIMEOUT: + case RX_ERROR: + if( isMaster == true ) + { + // Send the next PING frame + Buffer[0] = 'P'; + Buffer[1] = 'I'; + Buffer[2] = 'N'; + Buffer[3] = 'G'; + for( i = 4; i < BufferSize; i++ ) + { + Buffer[i] = i - 4; + } + DelayMs( 1 ); + Radio.Send( Buffer, BufferSize ); + } + else + { + Radio.Rx( RX_TIMEOUT_VALUE ); + } + State = LOWPOWER; + break; + case TX_TIMEOUT: + Radio.Rx( RX_TIMEOUT_VALUE ); + State = LOWPOWER; + break; + case LOWPOWER: + default: + // Set low power + break; + } + + TimerLowPowerHandler( ); + + } +} + +void OnTxDone( void ) +{ + Radio.Sleep( ); + State = TX; +} + +void OnRxDone( uint8_t *payload, uint16_t size, int16_t rssi, int8_t snr ) +{ + Radio.Sleep( ); + BufferSize = size; + memcpy( Buffer, payload, BufferSize ); + RssiValue = rssi; + SnrValue = snr; + State = RX; +} + +void OnTxTimeout( void ) +{ + Radio.Sleep( ); + State = TX_TIMEOUT; +} + +void OnRxTimeout( void ) +{ + Radio.Sleep( ); + State = RX_TIMEOUT; +} + +void OnRxError( void ) +{ + Radio.Sleep( ); + State = RX_ERROR; +} diff --git a/pool/shard000/C/0013725_h_locking.c b/pool/shard000/C/0013725_h_locking.c new file mode 100644 index 0000000000000000000000000000000000000000..4ff3fc4f07656603c6ce19291b458c95e62d5029 --- /dev/null +++ b/pool/shard000/C/0013725_h_locking.c @@ -0,0 +1,149 @@ +/*- + * Copyright (c) 2011 The NetBSD Foundation, Inc. + * All rights reserved. + * + * This code is derived from software contributed to The NetBSD Foundation + * by Joerg Sonnenberger. + * + * 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 THE NETBSD FOUNDATION, INC. 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 FOUNDATION 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 +#include +#include +#include +#include +#include +#include + +int sleep_init; +int sleep_fini; +int dlopen_cookie; +int dlclose_cookie; + +void (*tls_callback_sym)(void); + +static int +dl_iterate_phdr_cb(struct dl_phdr_info *info, size_t size, void *data) +{ + (*tls_callback_sym)(); + return 0; +} + +static void * +test_dl_iterate_phdr_helper(void *dummy) +{ + sleep(10); + _exit(1); +} + +static void +test_dl_iterate_phdr(void) +{ + pthread_t t; + void *dso; + sleep_init = 0; + sleep_fini = 0; + if ((dso = dlopen("libh_helper_dso2.so", RTLD_LAZY)) == NULL) { + fprintf(stderr, "opening helper failed\n"); + _exit(1); + } + tls_callback_sym = dlsym(dso, "tls_callback"); + if (tls_callback_sym == NULL) { + fprintf(stderr, "bad helper\n"); + _exit(1); + } + pthread_create(&t, NULL, test_dl_iterate_phdr_helper, NULL); + if (dl_iterate_phdr(dl_iterate_phdr_cb, NULL)) + _exit(1); + _exit(0); +} + +static void * +init_fini_helper(void *arg) +{ + void *dso; + if ((dso = dlopen(arg, RTLD_LAZY)) == NULL) { + fprintf(stderr, "opening %s failed\n", (char *)arg); + exit(1); + } + dlclose(dso); + return NULL; +} + +static void +test_dlopen(void) +{ + pthread_t t1, t2; + sleep_init = 1; + sleep_fini = 0; + printf("%d\n", dlopen_cookie); + pthread_create(&t1, NULL, init_fini_helper, + __UNCONST("libh_helper_dso2.so")); + sleep(1); + printf("%d\n", dlopen_cookie); + if (dlopen_cookie != 1) + _exit(1); + sleep(1); + pthread_create(&t2, NULL, init_fini_helper, + __UNCONST("libutil.so")); + printf("%d\n", dlopen_cookie); + if (dlopen_cookie != 1) + _exit(1); + _exit(0); +} + +static void +test_dlclose(void) +{ + pthread_t t1, t2; + sleep_init = 0; + sleep_fini = 1; + printf("%d\n", dlclose_cookie); + pthread_create(&t1, NULL, init_fini_helper, + __UNCONST("libh_helper_dso2.so")); + sleep(1); + printf("%d\n", dlclose_cookie); + if (dlclose_cookie != 2) + _exit(1); + pthread_create(&t2, NULL, init_fini_helper, + __UNCONST("libutil.so")); + sleep(1); + printf("%d\n", dlclose_cookie); + if (dlclose_cookie != 2) + _exit(1); + _exit(0); +} + +int +main(int argc, char **argv) +{ + if (argc != 2) + return 1; + if (strcmp(argv[1], "dl_iterate_phdr") == 0) + test_dl_iterate_phdr(); + if (strcmp(argv[1], "dlopen") == 0) + test_dlopen(); + if (strcmp(argv[1], "dlclose") == 0) + test_dlclose(); + return 1; +} diff --git a/pool/shard000/C/0013732_spi.c b/pool/shard000/C/0013732_spi.c new file mode 100644 index 0000000000000000000000000000000000000000..884485d64aa3ab813a07a5c61397efb83c2c877c --- /dev/null +++ b/pool/shard000/C/0013732_spi.c @@ -0,0 +1,189 @@ +#include "spi.h" + +//variables for a standerd connection. mode0,0 8 bits wide. transfer speed 500Khz +//static const char *spi_device = "/dev/spidev0.0"; +uint8_t spi_mode = 0; +uint8_t spi_bits = 8; +uint32_t spi_speed = 500000; +uint16_t spi_delay = 0; + + +//prints error message and aborts. (exits) +void pabort(const char *s) +{ + perror(s); + abort(); +} + +//this function sets spi mode +int spi_set_mode(int fd, int mode) +{ + int ret; + /* + * spi mode + */ + spi_mode = mode; + ret = ioctl(fd, SPI_IOC_WR_MODE, &mode); + if (ret == -1) + pabort("can't set spi mode"); + + ret = ioctl(fd, SPI_IOC_RD_MODE, &mode); + if (ret == -1) + pabort("can't get spi mode"); + return ret; +} +//this function sets word length (bits per word) +int spi_set_word(int fd, int bits) +{ + int ret; + /* + * bits per word + */ + spi_bits = bits; + ret = ioctl(fd, SPI_IOC_WR_BITS_PER_WORD, &bits); + if (ret == -1) + pabort("can't set bits per word"); + + ret = ioctl(fd, SPI_IOC_RD_BITS_PER_WORD, &bits); + if (ret == -1) + pabort("can't get bits per word"); + return ret; + +} +//this function sets communication speed. +int spi_set_speed(int fd, int speed) +{ + int ret = 0; + /* + * max speed hz + */ + spi_speed = speed; + ret = ioctl(fd, SPI_IOC_WR_MAX_SPEED_HZ, &speed); + if (ret == -1) + pabort("can't set max speed hz"); + + ret = ioctl(fd, SPI_IOC_RD_MAX_SPEED_HZ, &speed); + if (ret == -1) + pabort("can't get max speed hz"); + return ret; +} +/* + * how long to delay after the last bit transfer + * before optionally deselecting the device before the next transfer. + * */ +void spi_set_delay(int delay) +{ + spi_delay = delay; +} + +//send and recieve data. +int transfer(int fd, uint8_t *data, uint8_t *receive) +{ + int ret,i; + uint8_t tx[SPI_BUFFER_SIZE]; + static uint8_t rx[SPI_BUFFER_SIZE] = {0, }; + //fill tx with data to be send. + for(i = 0;i. */ + +/* Written by Bruno Haible , 2008. */ + +#include + +#include "unilbrk.h" + +#include + +#include "macros.h" + +int +main () +{ + /* Test case n = 0. */ + u16_possible_linebreaks (NULL, 0, "GB18030", NULL); + + { + static const uint16_t input[61] = + /* "Grüß Gott. Здравствуйте! x=(-b±sqrt(b²-4ac))/(2a) 日本語,中文,한글" */ + { 'G', 'r', 0x00FC, 0x00DF, ' ', 'G', 'o', 't', 't', '.', ' ', + 0x0417, 0x0434, 0x0440, 0x0430, 0x0432, 0x0441, 0x0442, 0x0432, 0x0443, + 0x0439, 0x0442, 0x0435, '!', ' ', + 'x', '=', '(', '-', 'b', 0x00B1, 's', 'q', 'r', 't', '(', 'b', 0x00B2, + '-', '4', 'a', 'c', ')', ')', '/', '(', '2', 'a', ')', ' ', ' ', + 0x65E5, 0x672C, 0x8A9E, ',', 0x4E2D, 0x6587, ',', 0xD55C, 0xAE00, '\n' + }; + + { + char *p = (char *) malloc (SIZEOF (input)); + size_t i; + + u16_possible_linebreaks (input, SIZEOF (input), "GB18030", p); + for (i = 0; i < 61; i++) + { + ASSERT (p[i] == (i == 60 ? UC_BREAK_MANDATORY : + i == 5 + || i == 11 || i == 25 + || i == 27 || i == 29 || i == 30 || i == 35 + || i == 45 || i == 51 + || i == 52 || i == 53 || i == 55 || i == 56 + || i == 58 || i == 59 ? UC_BREAK_POSSIBLE : + UC_BREAK_PROHIBITED)); + } + free (p); + } + + { + char *p = (char *) malloc (SIZEOF (input)); + size_t i; + + u16_possible_linebreaks (input, SIZEOF (input), "GB2312", p); + for (i = 0; i < 61; i++) + { + ASSERT (p[i] == (i == 60 ? UC_BREAK_MANDATORY : + i == 5 + || i == 11 || i == 25 + || i == 27 || i == 29 || i == 30 || i == 35 + || i == 37 || i == 45 || i == 51 + || i == 52 || i == 53 || i == 55 || i == 56 + || i == 58 || i == 59 ? UC_BREAK_POSSIBLE : + UC_BREAK_PROHIBITED)); + } + free (p); + } + } + + return 0; +} diff --git a/pool/shard000/C/0013766_fixme.c b/pool/shard000/C/0013766_fixme.c new file mode 100644 index 0000000000000000000000000000000000000000..3771a064c73e5ec3e6342e28a6c366c32312380d --- /dev/null +++ b/pool/shard000/C/0013766_fixme.c @@ -0,0 +1,51 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ + +#include +#include +#include +#include +#include +#include + +void amd_initcpuio(void) +{ + UINT64 MsrReg; + UINT32 PciData; + PCI_ADDR PciAddress; + AMD_CONFIG_PARAMS StdHeader; + + /* Enable legacy video routing: D18F1xF4 VGA Enable */ + PciAddress.AddressValue = MAKE_SBDFO (0, 0, 0x18, 1, 0xF4); + PciData = 1; + LibAmdPciWrite(AccessWidth32, PciAddress, &PciData, &StdHeader); + + /* The platform BIOS needs to ensure the memory ranges of SB800 legacy + * devices (TPM, HPET, BIOS RAM, Watchdog Timer, I/O APIC and ACPI) are + * set to non-posted regions. + */ + PciAddress.AddressValue = MAKE_SBDFO (0, 0, 0x18, 1, 0x84); + PciData = 0x00FEDF00; /* last address before processor local APIC at FEE00000 */ + PciData |= 1 << 7; /* set NP (non-posted) bit */ + LibAmdPciWrite(AccessWidth32, PciAddress, &PciData, &StdHeader); + PciAddress.AddressValue = MAKE_SBDFO (0, 0, 0x18, 1, 0x80); + PciData = (0xFED00000 >> 8) | 3; /* lowest NP address is HPET at FED00000 */ + LibAmdPciWrite(AccessWidth32, PciAddress, &PciData, &StdHeader); + + /* Map the remaining PCI hole as posted MMIO */ + PciAddress.AddressValue = MAKE_SBDFO (0, 0, 0x18, 1, 0x8C); + PciData = 0x00FECF00; /* last address before non-posted range */ + LibAmdPciWrite(AccessWidth32, PciAddress, &PciData, &StdHeader); + LibAmdMsrRead(TOP_MEM, &MsrReg, &StdHeader); + MsrReg = (MsrReg >> 8) | 3; + PciAddress.AddressValue = MAKE_SBDFO (0, 0, 0x18, 1, 0x88); + PciData = (UINT32)MsrReg; + LibAmdPciWrite(AccessWidth32, PciAddress, &PciData, &StdHeader); + + /* Send all IO (0000-FFFF) to southbridge. */ + PciAddress.AddressValue = MAKE_SBDFO (0, 0, 0x18, 1, 0xC4); + PciData = 0x0000F000; + LibAmdPciWrite(AccessWidth32, PciAddress, &PciData, &StdHeader); + PciAddress.AddressValue = MAKE_SBDFO (0, 0, 0x18, 1, 0xC0); + PciData = 0x00000003; + LibAmdPciWrite(AccessWidth32, PciAddress, &PciData, &StdHeader); +} diff --git a/pool/shard000/C/0013770_test_tar_large.c b/pool/shard000/C/0013770_test_tar_large.c new file mode 100644 index 0000000000000000000000000000000000000000..adc81551cecd47367d867bfc965fd0395380466d --- /dev/null +++ b/pool/shard000/C/0013770_test_tar_large.c @@ -0,0 +1,312 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * 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 THE AUTHOR(S) ``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 AUTHOR(S) 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 "test.h" +__FBSDID("$FreeBSD: head/lib/libarchive/test/test_tar_large.c 201247 2009-12-30 05:59:21Z kientzle $"); + +#include +#include +#include + +/* + * This is a somewhat tricky test that verifies the ability to + * write and read very large entries to tar archives. It + * writes entries from 2GB up to 1TB to an archive in memory. + * The memory storage here carefully avoids actually storing + * any part of the file bodies, so it runs very quickly and requires + * very little memory. If you're willing to wait a few minutes, + * you should be able to exercise petabyte entries with this code. + */ + +/* + * Each file is built up by duplicating the following block. + */ +static size_t filedatasize; +static void *filedata; + +/* + * We store the archive as blocks of data generated by libarchive, + * each possibly followed by bytes of file data. + */ +struct memblock { + struct memblock *next; + size_t size; + void *buff; + int64_t filebytes; +}; + +/* + * The total memory store is just a list of memblocks plus + * some accounting overhead. + */ +struct memdata { + int64_t filebytes; + void *buff; + struct memblock *first; + struct memblock *last; +}; + +/* The following size definitions simplify things below. */ +#define KB ((int64_t)1024) +#define MB ((int64_t)1024 * KB) +#define GB ((int64_t)1024 * MB) +#define TB ((int64_t)1024 * GB) + +#if ARCHIVE_VERSION_NUMBER < 2000000 +static ssize_t memory_read_skip(struct archive *, void *, size_t request); +#else +static off_t memory_read_skip(struct archive *, void *, off_t request); +#endif +static ssize_t memory_read(struct archive *, void *, const void **buff); +static ssize_t memory_write(struct archive *, void *, const void *, size_t); + + +static ssize_t +memory_write(struct archive *a, void *_private, const void *buff, size_t size) +{ + struct memdata *private = _private; + struct memblock *block; + + (void)a; + + /* + * Since libarchive tries to behave in a zero-copy manner, if + * you give a pointer to filedata to the library, a pointer + * into that data will (usually) pop out here. This way, we + * can tell the difference between filedata and library header + * and metadata. + */ + if ((const char *)filedata <= (const char *)buff + && (const char *)buff < (const char *)filedata + filedatasize) { + /* We don't need to store a block of file data. */ + private->last->filebytes += (int64_t)size; + } else { + /* Yes, we're assuming the very first write is metadata. */ + /* It's header or metadata, copy and save it. */ + block = (struct memblock *)malloc(sizeof(*block)); + memset(block, 0, sizeof(*block)); + block->size = size; + block->buff = malloc(size); + memcpy(block->buff, buff, size); + if (private->last == NULL) { + private->first = private->last = block; + } else { + private->last->next = block; + private->last = block; + } + block->next = NULL; + } + return ((long)size); +} + +static ssize_t +memory_read(struct archive *a, void *_private, const void **buff) +{ + struct memdata *private = _private; + struct memblock *block; + ssize_t size; + + (void)a; + + free(private->buff); + private->buff = NULL; + if (private->first == NULL) { + private->last = NULL; + return (ARCHIVE_EOF); + } + if (private->filebytes > 0) { + /* + * We're returning file bytes, simulate it by + * passing blocks from the template data. + */ + if (private->filebytes > (int64_t)filedatasize) + size = (ssize_t)filedatasize; + else + size = (ssize_t)private->filebytes; + private->filebytes -= size; + *buff = filedata; + } else { + /* + * We need to get some real data to return. + */ + block = private->first; + private->first = block->next; + size = (ssize_t)block->size; + if (block->buff != NULL) { + private->buff = block->buff; + *buff = block->buff; + } else { + private->buff = NULL; + *buff = filedata; + } + private->filebytes = block->filebytes; + free(block); + } + return (size); +} + + +#if ARCHIVE_VERSION_NUMBER < 2000000 +static ssize_t +memory_read_skip(struct archive *a, void *private, size_t skip) +{ + (void)a; /* UNUSED */ + (void)private; /* UNUSED */ + (void)skip; /* UNUSED */ + return (0); +} +#else +static off_t +memory_read_skip(struct archive *a, void *_private, off_t skip) +{ + struct memdata *private = _private; + + (void)a; + + if (private->first == NULL) { + private->last = NULL; + return (0); + } + if (private->filebytes > 0) { + if (private->filebytes < skip) + skip = (off_t)private->filebytes; + private->filebytes -= skip; + } else { + skip = 0; + } + return (skip); +} +#endif + +DEFINE_TEST(test_tar_large) +{ + /* The sizes of the entries we're going to generate. */ + static int64_t tests[] = { + /* Test for 32-bit signed overflow. */ + 2 * GB - 1, 2 * GB, 2 * GB + 1, + /* Test for 32-bit unsigned overflow. */ + 4 * GB - 1, 4 * GB, 4 * GB + 1, + /* 8GB is the "official" max for ustar. */ + 8 * GB - 1, 8 * GB, 8 * GB + 1, + /* Bend ustar a tad and you can get 64GB (12 octal digits). */ + 64 * GB - 1, 64 * GB, + /* And larger entries that require non-ustar extensions. */ + 256 * GB, 1 * TB, 0 }; + int i; + char namebuff[64]; + struct memdata memdata; + struct archive_entry *ae; + struct archive *a; + int64_t filesize; + size_t writesize; + + filedatasize = (size_t)(1 * MB); + filedata = malloc(filedatasize); + memset(filedata, 0xAA, filedatasize); + memset(&memdata, 0, sizeof(memdata)); + + /* + * Open an archive for writing. + */ + a = archive_write_new(); + archive_write_set_format_pax_restricted(a); + archive_write_set_bytes_per_block(a, 0); /* No buffering. */ + archive_write_open(a, &memdata, NULL, memory_write, NULL); + + /* + * Write a series of large files to it. + */ + for (i = 0; tests[i] != 0; i++) { + assert((ae = archive_entry_new()) != NULL); + sprintf(namebuff, "file_%d", i); + archive_entry_copy_pathname(ae, namebuff); + archive_entry_set_mode(ae, S_IFREG | 0755); + filesize = tests[i]; + + archive_entry_set_size(ae, filesize); + + assertA(0 == archive_write_header(a, ae)); + archive_entry_free(ae); + + /* + * Write the actual data to the archive. + */ + while (filesize > 0) { + writesize = filedatasize; + if ((int64_t)writesize > filesize) + writesize = (size_t)filesize; + assertA((int)writesize + == archive_write_data(a, filedata, writesize)); + filesize -= writesize; + } + } + + assert((ae = archive_entry_new()) != NULL); + archive_entry_copy_pathname(ae, "lastfile"); + archive_entry_set_mode(ae, S_IFREG | 0755); + assertA(0 == archive_write_header(a, ae)); + archive_entry_free(ae); + + + /* Close out the archive. */ + assertA(0 == archive_write_close(a)); +#if ARCHIVE_VERSION_NUMBER < 2000000 + archive_write_finish(a); +#else + assertA(0 == archive_write_finish(a)); +#endif + + /* + * Open the same archive for reading. + */ + a = archive_read_new(); + archive_read_support_format_tar(a); + archive_read_open2(a, &memdata, NULL, + memory_read, memory_read_skip, NULL); + + /* + * Read entries back. + */ + for (i = 0; tests[i] > 0; i++) { + assertEqualIntA(a, 0, archive_read_next_header(a, &ae)); + sprintf(namebuff, "file_%d", i); + assertEqualString(namebuff, archive_entry_pathname(ae)); + assert(tests[i] == archive_entry_size(ae)); + } + assertEqualIntA(a, 0, archive_read_next_header(a, &ae)); + assertEqualString("lastfile", archive_entry_pathname(ae)); + + assertEqualIntA(a, ARCHIVE_EOF, archive_read_next_header(a, &ae)); + + /* Close out the archive. */ + assertA(0 == archive_read_close(a)); +#if ARCHIVE_VERSION_NUMBER < 2000000 + archive_read_finish(a); +#else + assertA(0 == archive_read_finish(a)); +#endif + + free(memdata.buff); + free(filedata); +} diff --git a/pool/shard000/C/0013777_pci_dlpar.c b/pool/shard000/C/0013777_pci_dlpar.c new file mode 100644 index 0000000000000000000000000000000000000000..203cbf0dc101a7b4bb93aec27f8a89cf4f015ecb --- /dev/null +++ b/pool/shard000/C/0013777_pci_dlpar.c @@ -0,0 +1,143 @@ +/* + * PCI Dynamic LPAR, PCI Hot Plug and PCI EEH recovery code + * for RPA-compliant PPC64 platform. + * Copyright (C) 2003 Linda Xie + * Copyright (C) 2005 International Business Machines + * + * Updates, 2005, John Rose + * Updates, 2005, Linas Vepstas + * + * 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. + * + * 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, GOOD TITLE or + * NON INFRINGEMENT. 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., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +#include +#include +#include +#include +#include +#include + +static struct pci_bus * +find_bus_among_children(struct pci_bus *bus, + struct device_node *dn) +{ + struct pci_bus *child = NULL; + struct pci_bus *tmp; + struct device_node *busdn; + + busdn = pci_bus_to_OF_node(bus); + if (busdn == dn) + return bus; + + list_for_each_entry(tmp, &bus->children, node) { + child = find_bus_among_children(tmp, dn); + if (child) + break; + }; + return child; +} + +struct pci_bus * +pcibios_find_pci_bus(struct device_node *dn) +{ + struct pci_dn *pdn = dn->data; + + if (!pdn || !pdn->phb || !pdn->phb->bus) + return NULL; + + return find_bus_among_children(pdn->phb->bus, dn); +} +EXPORT_SYMBOL_GPL(pcibios_find_pci_bus); + +struct pci_controller *init_phb_dynamic(struct device_node *dn) +{ + struct pci_controller *phb; + + pr_debug("PCI: Initializing new hotplug PHB %s\n", dn->full_name); + + phb = pcibios_alloc_controller(dn); + if (!phb) + return NULL; + rtas_setup_phb(phb); + pci_process_bridge_OF_ranges(phb, dn, 0); + + pci_devs_phb_init_dynamic(phb); + + /* Create EEH devices for the PHB */ + eeh_dev_phb_init_dynamic(phb); + + if (dn->child) + eeh_add_device_tree_early(dn); + + pcibios_scan_phb(phb); + pcibios_finish_adding_to_bus(phb->bus); + + return phb; +} +EXPORT_SYMBOL_GPL(init_phb_dynamic); + +/* RPA-specific bits for removing PHBs */ +int remove_phb_dynamic(struct pci_controller *phb) +{ + struct pci_bus *b = phb->bus; + struct resource *res; + int rc, i; + + pr_debug("PCI: Removing PHB %04x:%02x...\n", + pci_domain_nr(b), b->number); + + /* We cannot to remove a root bus that has children */ + if (!(list_empty(&b->children) && list_empty(&b->devices))) + return -EBUSY; + + /* We -know- there aren't any child devices anymore at this stage + * and thus, we can safely unmap the IO space as it's not in use + */ + res = &phb->io_resource; + if (res->flags & IORESOURCE_IO) { + rc = pcibios_unmap_io_space(b); + if (rc) { + printk(KERN_ERR "%s: failed to unmap IO on bus %s\n", + __func__, b->name); + return 1; + } + } + + /* Unregister the bridge device from sysfs and remove the PCI bus */ + device_unregister(b->bridge); + phb->bus = NULL; + pci_remove_bus(b); + + /* Now release the IO resource */ + if (res->flags & IORESOURCE_IO) + release_resource(res); + + /* Release memory resources */ + for (i = 0; i < 3; ++i) { + res = &phb->mem_resources[i]; + if (!(res->flags & IORESOURCE_MEM)) + continue; + release_resource(res); + } + + /* Free pci_controller data structure */ + pcibios_free_controller(phb); + + return 0; +} +EXPORT_SYMBOL_GPL(remove_phb_dynamic); diff --git a/pool/shard000/C/0013794_ax25_iface.c b/pool/shard000/C/0013794_ax25_iface.c new file mode 100644 index 0000000000000000000000000000000000000000..aff3e652c2d110ad55448ae2e41dd15fcac5affc --- /dev/null +++ b/pool/shard000/C/0013794_ax25_iface.c @@ -0,0 +1,225 @@ +/* + * 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. + * + * Copyright (C) Jonathan Naylor G4KLX (g4klx@g4klx.demon.co.uk) + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static struct ax25_protocol *protocol_list; +static DEFINE_RWLOCK(protocol_list_lock); + +static HLIST_HEAD(ax25_linkfail_list); +static DEFINE_SPINLOCK(linkfail_lock); + +static struct listen_struct { + struct listen_struct *next; + ax25_address callsign; + struct net_device *dev; +} *listen_list = NULL; +static DEFINE_SPINLOCK(listen_lock); + +/* + * Do not register the internal protocols AX25_P_TEXT, AX25_P_SEGMENT, + * AX25_P_IP or AX25_P_ARP ... + */ +void ax25_register_pid(struct ax25_protocol *ap) +{ + write_lock_bh(&protocol_list_lock); + ap->next = protocol_list; + protocol_list = ap; + write_unlock_bh(&protocol_list_lock); +} + +EXPORT_SYMBOL_GPL(ax25_register_pid); + +void ax25_protocol_release(unsigned int pid) +{ + struct ax25_protocol *s, *protocol; + + write_lock_bh(&protocol_list_lock); + protocol = protocol_list; + if (protocol == NULL) { + write_unlock_bh(&protocol_list_lock); + return; + } + + if (protocol->pid == pid) { + protocol_list = protocol->next; + write_unlock_bh(&protocol_list_lock); + kfree(protocol); + return; + } + + while (protocol != NULL && protocol->next != NULL) { + if (protocol->next->pid == pid) { + s = protocol->next; + protocol->next = protocol->next->next; + write_unlock_bh(&protocol_list_lock); + kfree(s); + return; + } + + protocol = protocol->next; + } + write_unlock_bh(&protocol_list_lock); +} + +EXPORT_SYMBOL(ax25_protocol_release); + +void ax25_linkfail_register(struct ax25_linkfail *lf) +{ + spin_lock_bh(&linkfail_lock); + hlist_add_head(&lf->lf_node, &ax25_linkfail_list); + spin_unlock_bh(&linkfail_lock); +} + +EXPORT_SYMBOL(ax25_linkfail_register); + +void ax25_linkfail_release(struct ax25_linkfail *lf) +{ + spin_lock_bh(&linkfail_lock); + hlist_del_init(&lf->lf_node); + spin_unlock_bh(&linkfail_lock); +} + +EXPORT_SYMBOL(ax25_linkfail_release); + +int ax25_listen_register(ax25_address *callsign, struct net_device *dev) +{ + struct listen_struct *listen; + + if (ax25_listen_mine(callsign, dev)) + return 0; + + if ((listen = kmalloc(sizeof(*listen), GFP_ATOMIC)) == NULL) + return -ENOMEM; + + listen->callsign = *callsign; + listen->dev = dev; + + spin_lock_bh(&listen_lock); + listen->next = listen_list; + listen_list = listen; + spin_unlock_bh(&listen_lock); + + return 0; +} + +EXPORT_SYMBOL(ax25_listen_register); + +void ax25_listen_release(ax25_address *callsign, struct net_device *dev) +{ + struct listen_struct *s, *listen; + + spin_lock_bh(&listen_lock); + listen = listen_list; + if (listen == NULL) { + spin_unlock_bh(&listen_lock); + return; + } + + if (ax25cmp(&listen->callsign, callsign) == 0 && listen->dev == dev) { + listen_list = listen->next; + spin_unlock_bh(&listen_lock); + kfree(listen); + return; + } + + while (listen != NULL && listen->next != NULL) { + if (ax25cmp(&listen->next->callsign, callsign) == 0 && listen->next->dev == dev) { + s = listen->next; + listen->next = listen->next->next; + spin_unlock_bh(&listen_lock); + kfree(s); + return; + } + + listen = listen->next; + } + spin_unlock_bh(&listen_lock); +} + +EXPORT_SYMBOL(ax25_listen_release); + +int (*ax25_protocol_function(unsigned int pid))(struct sk_buff *, ax25_cb *) +{ + int (*res)(struct sk_buff *, ax25_cb *) = NULL; + struct ax25_protocol *protocol; + + read_lock(&protocol_list_lock); + for (protocol = protocol_list; protocol != NULL; protocol = protocol->next) + if (protocol->pid == pid) { + res = protocol->func; + break; + } + read_unlock(&protocol_list_lock); + + return res; +} + +int ax25_listen_mine(ax25_address *callsign, struct net_device *dev) +{ + struct listen_struct *listen; + + spin_lock_bh(&listen_lock); + for (listen = listen_list; listen != NULL; listen = listen->next) + if (ax25cmp(&listen->callsign, callsign) == 0 && + (listen->dev == dev || listen->dev == NULL)) { + spin_unlock_bh(&listen_lock); + return 1; + } + spin_unlock_bh(&listen_lock); + + return 0; +} + +void ax25_link_failed(ax25_cb *ax25, int reason) +{ + struct ax25_linkfail *lf; + struct hlist_node *node; + + spin_lock_bh(&linkfail_lock); + hlist_for_each_entry(lf, node, &ax25_linkfail_list, lf_node) + lf->func(ax25, reason); + spin_unlock_bh(&linkfail_lock); +} + +int ax25_protocol_is_registered(unsigned int pid) +{ + struct ax25_protocol *protocol; + int res = 0; + + read_lock_bh(&protocol_list_lock); + for (protocol = protocol_list; protocol != NULL; protocol = protocol->next) + if (protocol->pid == pid) { + res = 1; + break; + } + read_unlock_bh(&protocol_list_lock); + + return res; +} diff --git a/pool/shard000/C/0013808_test_utils_avltree.c b/pool/shard000/C/0013808_test_utils_avltree.c new file mode 100644 index 0000000000000000000000000000000000000000..00d14e1615c597adedb6f9144dadf90a0eab3b9c --- /dev/null +++ b/pool/shard000/C/0013808_test_utils_avltree.c @@ -0,0 +1,82 @@ +/** + * collectd - src/tests/test_utils_avltree.c + * Copyright (C) 2013 Florian octo Forster + * + * 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. + * + * Authors: + * Florian octo Forster + */ + +#include "tests/macros.h" +#include "collectd.h" +#include "utils_avltree.h" + +static int compare_total_count = 0; +#define RESET_COUNTS() do { compare_total_count = 0; } while (0) + +static int compare_callback (void const *v0, void const *v1) +{ + assert (v0 != NULL); + assert (v1 != NULL); + + compare_total_count++; + return (strcmp (v0, v1)); +} + +DEF_TEST(success) +{ + c_avl_tree_t *t; + char key_orig[] = "foo"; + char value_orig[] = "bar"; + char *key_ret = NULL; + char *value_ret = NULL; + + RESET_COUNTS (); + t = c_avl_create (compare_callback); + OK (t != NULL); + + OK (c_avl_insert (t, key_orig, value_orig) == 0); + OK (c_avl_size (t) == 1); + + /* Key already exists. */ + OK (c_avl_insert (t, "foo", "qux") > 0); + + OK (c_avl_get (t, "foo", (void *) &value_ret) == 0); + OK (value_ret == &value_orig[0]); + + key_ret = value_ret = NULL; + OK (c_avl_remove (t, "foo", (void *) &key_ret, (void *) &value_ret) == 0); + OK (key_ret == &key_orig[0]); + OK (value_ret == &value_orig[0]); + OK (c_avl_size (t) == 0); + + c_avl_destroy (t); + + return (0); +} + +int main (void) +{ + RUN_TEST(success); + + END_TEST; +} + +/* vim: set sw=2 sts=2 et : */ diff --git a/pool/shard000/C/0013817_ping.c b/pool/shard000/C/0013817_ping.c new file mode 100644 index 0000000000000000000000000000000000000000..bc0bcb0da4e67da63b6e382d150742afc2f57e56 --- /dev/null +++ b/pool/shard000/C/0013817_ping.c @@ -0,0 +1,80 @@ +#include +#include +#include +#include +#include +#define NTHREADS 10 +//Network IP +char ipaddr[]="192.168.250.0"; +//Thread IP +int ipactual=1; +pthread_mutex_t p; + +int ping(void) { + char *command = NULL; + char buffer[1024]; + FILE *fp; + int stat = 0; + //asprintf (&command, "%s %s -q 2>&1", "fping", ipaddr); + asprintf (&command, "%s %s -c 1", "ping", ipaddr); + printf("%s\n", command); + + fp = popen(command, "r"); + if (fp == NULL) { + fprintf(stderr, "Failed to execute fping command\n"); + free(command); + return -1; + } + + while(fread(buffer, sizeof(char), 1024, fp)) { + if (strstr(buffer, "1 received")) + return 0; + } + stat = pclose(fp); + free(command); + return 1; +} + +void* pingtest(void* actual){ + int *ptr= (int*) actual; + pthread_mutex_lock (&p); + //char str[1]; + //sprintf(str, "%d", ipactual); + ipaddr[12]=ipactual+'0'; + ipactual++; + int status=ping(); + if (status == 0) { + printf("Could ping %s successfully, status %d\n", ipaddr, status); + } + else { + printf("Machine not reachable, status %d\n", status); + } + pthread_mutex_unlock (&p); + pthread_exit(NULL); +} + +int main(int argc, char *argv[]){ + int i, start, tids[NTHREADS]; + pthread_t threads[NTHREADS]; + pthread_attr_t attr; + + /* Pthreads setup: initialize mutex and explicitly create threads in a + joinable state (for portability). Pass each thread its loop offset */ + pthread_mutex_init(&p, NULL); + pthread_attr_init(&attr); + pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); + for (i=0; i +#include +#include +#include +#include + +#include "provenance.h" + +#define CHILD 0 +#define PARENT 1 + +int main( void ){ + int fd[2]; + pid_t pid; + char buffer[256]; + char message[] = "hello world!"; + + if(provenance_set_tracked(true)){ + printf("Failed Tracking, error %d\n", errno); + printf("%s\n\n",strerror(errno)); + } + if(provenance_set_propagate(true)){ + printf("Failed propagate, error %d\n", errno); + printf("%s\n\n",strerror(errno)); + } + socketpair(PF_LOCAL, SOCK_STREAM, 0, fd); + + pid = fork(); + + if (pid == 0) { + close(fd[PARENT]); + write(fd[CHILD], message, sizeof(message)); + } else { + close(fd[CHILD]); + read(fd[PARENT], buffer, 256); + printf("%s\n", buffer); + } + exit(0); +} diff --git a/pool/shard000/C/0013830_dhd_ip.c b/pool/shard000/C/0013830_dhd_ip.c new file mode 100644 index 0000000000000000000000000000000000000000..2dcbe4ea86559d0f081a658a2793aaa43dbcfd72 --- /dev/null +++ b/pool/shard000/C/0013830_dhd_ip.c @@ -0,0 +1,93 @@ +/* + * IP Packet Parser Module. + * + * $Copyright Open Broadcom Corporation$ + * + * $Id: dhd_ip.c 388059 2013-02-27 23:59:15Z $ + */ +#include +#include + +#include +#include +#include +#include +#include + +#include + +#include + +/* special values */ +/* 802.3 llc/snap header */ +static const uint8 llc_snap_hdr[SNAP_HDR_LEN] = {0xaa, 0xaa, 0x03, 0x00, 0x00, 0x00}; + +pkt_frag_t pkt_frag_info(osl_t *osh, void *p) +{ + uint8 *frame; + int length; + uint8 *pt; /* Pointer to type field */ + uint16 ethertype; + struct ipv4_hdr *iph; /* IP frame pointer */ + int ipl; /* IP frame length */ + uint16 iph_frag; + + ASSERT(osh && p); + + frame = PKTDATA(osh, p); + length = PKTLEN(osh, p); + + /* Process Ethernet II or SNAP-encapsulated 802.3 frames */ + if (length < ETHER_HDR_LEN) { + DHD_INFO(("%s: short eth frame (%d)\n", __FUNCTION__, length)); + return DHD_PKT_FRAG_NONE; + } else if (ntoh16(*(uint16 *)(frame + ETHER_TYPE_OFFSET)) >= ETHER_TYPE_MIN) { + /* Frame is Ethernet II */ + pt = frame + ETHER_TYPE_OFFSET; + } else if (length >= ETHER_HDR_LEN + SNAP_HDR_LEN + ETHER_TYPE_LEN && + !bcmp(llc_snap_hdr, frame + ETHER_HDR_LEN, SNAP_HDR_LEN)) { + pt = frame + ETHER_HDR_LEN + SNAP_HDR_LEN; + } else { + DHD_INFO(("%s: non-SNAP 802.3 frame\n", __FUNCTION__)); + return DHD_PKT_FRAG_NONE; + } + + ethertype = ntoh16(*(uint16 *)pt); + + /* Skip VLAN tag, if any */ + if (ethertype == ETHER_TYPE_8021Q) { + pt += VLAN_TAG_LEN; + + if (pt + ETHER_TYPE_LEN > frame + length) { + DHD_INFO(("%s: short VLAN frame (%d)\n", __FUNCTION__, length)); + return DHD_PKT_FRAG_NONE; + } + + ethertype = ntoh16(*(uint16 *)pt); + } + + if (ethertype != ETHER_TYPE_IP) { + DHD_INFO(("%s: non-IP frame (ethertype 0x%x, length %d)\n", + __FUNCTION__, ethertype, length)); + return DHD_PKT_FRAG_NONE; + } + + iph = (struct ipv4_hdr *)(pt + ETHER_TYPE_LEN); + ipl = length - (pt + ETHER_TYPE_LEN - frame); + + /* We support IPv4 only */ + if ((ipl < IPV4_OPTIONS_OFFSET) || (IP_VER(iph) != IP_VER_4)) { + DHD_INFO(("%s: short frame (%d) or non-IPv4\n", __FUNCTION__, ipl)); + return DHD_PKT_FRAG_NONE; + } + + iph_frag = ntoh16(iph->frag); + + if (iph_frag & IPV4_FRAG_DONT) { + return DHD_PKT_FRAG_NONE; + } else if ((iph_frag & IPV4_FRAG_MORE) == 0) { + return DHD_PKT_FRAG_LAST; + } else { + return (iph_frag & IPV4_FRAG_OFFSET_MASK)? DHD_PKT_FRAG_CONT : DHD_PKT_FRAG_FIRST; + } +} diff --git a/pool/shard000/C/0013835_ieee80211_crypt.c b/pool/shard000/C/0013835_ieee80211_crypt.c new file mode 100644 index 0000000000000000000000000000000000000000..9cf90d040cfe1e33221ec3bda6504ebb484b9491 --- /dev/null +++ b/pool/shard000/C/0013835_ieee80211_crypt.c @@ -0,0 +1,239 @@ +/* + * Host AP crypto routines + * + * Copyright (c) 2002-2003, Jouni Malinen + * Portions Copyright (C) 2004, Intel Corporation + * + * 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. See README and COPYING for + * more details. + * + */ + +#include +#include +#include +#include +#include + +#include "ieee80211.h" + +MODULE_AUTHOR("Jouni Malinen"); +MODULE_DESCRIPTION("HostAP crypto"); +MODULE_LICENSE("GPL"); + +struct ieee80211_crypto_alg { + struct list_head list; + struct ieee80211_crypto_ops *ops; +}; + + +struct ieee80211_crypto { + struct list_head algs; + spinlock_t lock; +}; + +static struct ieee80211_crypto *hcrypt; + +void ieee80211_crypt_deinit_entries(struct ieee80211_device *ieee, + int force) +{ + struct list_head *ptr, *n; + struct ieee80211_crypt_data *entry; + + for (ptr = ieee->crypt_deinit_list.next, n = ptr->next; + ptr != &ieee->crypt_deinit_list; ptr = n, n = ptr->next) { + entry = list_entry(ptr, struct ieee80211_crypt_data, list); + + if (atomic_read(&entry->refcnt) != 0 && !force) + continue; + + list_del(ptr); + + if (entry->ops) + entry->ops->deinit(entry->priv); + kfree(entry); + } +} + +void ieee80211_crypt_deinit_handler(unsigned long data) +{ + struct ieee80211_device *ieee = (struct ieee80211_device *)data; + unsigned long flags; + + spin_lock_irqsave(&ieee->lock, flags); + ieee80211_crypt_deinit_entries(ieee, 0); + if (!list_empty(&ieee->crypt_deinit_list)) { + netdev_dbg(ieee->dev, "%s: entries remaining in delayed crypt deletion list\n", + ieee->dev->name); + ieee->crypt_deinit_timer.expires = jiffies + HZ; + add_timer(&ieee->crypt_deinit_timer); + } + spin_unlock_irqrestore(&ieee->lock, flags); + +} + +void ieee80211_crypt_delayed_deinit(struct ieee80211_device *ieee, + struct ieee80211_crypt_data **crypt) +{ + struct ieee80211_crypt_data *tmp; + unsigned long flags; + + if (*crypt == NULL) + return; + + tmp = *crypt; + *crypt = NULL; + + /* must not run ops->deinit() while there may be pending encrypt or + * decrypt operations. Use a list of delayed deinits to avoid needing + * locking. */ + + spin_lock_irqsave(&ieee->lock, flags); + list_add(&tmp->list, &ieee->crypt_deinit_list); + if (!timer_pending(&ieee->crypt_deinit_timer)) { + ieee->crypt_deinit_timer.expires = jiffies + HZ; + add_timer(&ieee->crypt_deinit_timer); + } + spin_unlock_irqrestore(&ieee->lock, flags); +} + +int ieee80211_register_crypto_ops(struct ieee80211_crypto_ops *ops) +{ + unsigned long flags; + struct ieee80211_crypto_alg *alg; + + if (hcrypt == NULL) + return -1; + + alg = kzalloc(sizeof(*alg), GFP_KERNEL); + if (alg == NULL) + return -ENOMEM; + + alg->ops = ops; + + spin_lock_irqsave(&hcrypt->lock, flags); + list_add(&alg->list, &hcrypt->algs); + spin_unlock_irqrestore(&hcrypt->lock, flags); + + pr_debug("ieee80211_crypt: registered algorithm '%s'\n", + ops->name); + + return 0; +} + +int ieee80211_unregister_crypto_ops(struct ieee80211_crypto_ops *ops) +{ + unsigned long flags; + struct list_head *ptr; + struct ieee80211_crypto_alg *del_alg = NULL; + + if (hcrypt == NULL) + return -1; + + spin_lock_irqsave(&hcrypt->lock, flags); + for (ptr = hcrypt->algs.next; ptr != &hcrypt->algs; ptr = ptr->next) { + struct ieee80211_crypto_alg *alg = + (struct ieee80211_crypto_alg *) ptr; + if (alg->ops == ops) { + list_del(&alg->list); + del_alg = alg; + break; + } + } + spin_unlock_irqrestore(&hcrypt->lock, flags); + + if (del_alg) { + pr_debug("ieee80211_crypt: unregistered algorithm '%s'\n", + ops->name); + kfree(del_alg); + } + + return del_alg ? 0 : -1; +} + + +struct ieee80211_crypto_ops *ieee80211_get_crypto_ops(const char *name) +{ + unsigned long flags; + struct list_head *ptr; + struct ieee80211_crypto_alg *found_alg = NULL; + + if (hcrypt == NULL) + return NULL; + + spin_lock_irqsave(&hcrypt->lock, flags); + for (ptr = hcrypt->algs.next; ptr != &hcrypt->algs; ptr = ptr->next) { + struct ieee80211_crypto_alg *alg = + (struct ieee80211_crypto_alg *) ptr; + if (strcmp(alg->ops->name, name) == 0) { + found_alg = alg; + break; + } + } + spin_unlock_irqrestore(&hcrypt->lock, flags); + + if (found_alg) + return found_alg->ops; + return NULL; +} + + +static void *ieee80211_crypt_null_init(int keyidx) { return (void *) 1; } +static void ieee80211_crypt_null_deinit(void *priv) {} + +static struct ieee80211_crypto_ops ieee80211_crypt_null = { + .name = "NULL", + .init = ieee80211_crypt_null_init, + .deinit = ieee80211_crypt_null_deinit, + .encrypt_mpdu = NULL, + .decrypt_mpdu = NULL, + .encrypt_msdu = NULL, + .decrypt_msdu = NULL, + .set_key = NULL, + .get_key = NULL, + .extra_prefix_len = 0, + .extra_postfix_len = 0, + .owner = THIS_MODULE, +}; + +int __init ieee80211_crypto_init(void) +{ + int ret = -ENOMEM; + + hcrypt = kzalloc(sizeof(*hcrypt), GFP_KERNEL); + if (!hcrypt) + goto out; + + INIT_LIST_HEAD(&hcrypt->algs); + spin_lock_init(&hcrypt->lock); + + ret = ieee80211_register_crypto_ops(&ieee80211_crypt_null); + if (ret < 0) { + kfree(hcrypt); + hcrypt = NULL; + } +out: + return ret; +} + +void __exit ieee80211_crypto_deinit(void) +{ + struct list_head *ptr, *n; + + if (hcrypt == NULL) + return; + + for (ptr = hcrypt->algs.next, n = ptr->next; ptr != &hcrypt->algs; + ptr = n, n = ptr->next) { + struct ieee80211_crypto_alg *alg = + (struct ieee80211_crypto_alg *) ptr; + list_del(ptr); + pr_debug("ieee80211_crypt: unregistered algorithm '%s' (deinit)\n", + alg->ops->name); + kfree(alg); + } + + kfree(hcrypt); +} diff --git a/pool/shard000/C/0013845_number.c b/pool/shard000/C/0013845_number.c new file mode 100644 index 0000000000000000000000000000000000000000..a44d16240770c676fd41cf147f980d5d523ecb7f --- /dev/null +++ b/pool/shard000/C/0013845_number.c @@ -0,0 +1,185 @@ +/* + * edgar - an interpreter for the edgar programming language + * Copyright (c) 2013, 2014, 2015, 2020 Thomas Cort + * + * 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 "config.h" + +#include +#include +#include +#include +#include + +#include "number.h" +#include "obj.h" + +/* + * Put numbers in a form GMP can parse. + */ +obj_t * number_filter(obj_t * o) { + + if (IS_INT(o)) { + + char *s; + + s = ATOM(o); + + /* gmp doesn't like leading '+' */ + if (s[0] == '+') { + char *tmp = strdup(s+1); + memcpy(s, tmp, strlen(tmp) + 1); + free(tmp); + } + + /* Ensure 0 == +0 == -0 by rewriting all to "0" */ + if (strcmp(s, "-0") == 0 && strlen("-0") == strlen(s)) { + s[0] = '0'; + s[1] = '\0'; + } + } + + return o; +} + +int is_int_obj(obj_t *o) { + + size_t i; + size_t len; + char *s; + + if (o == NULL || !IS_ATOM(o)) { + return 0; + } + + s = ATOM(o); + if (s[0] == '\0') { + return 0; + } + + /* first byte can be sign or digit */ + if (s[0] != '+' && s[0] != '-' && !isdigit(s[0])) { + return 0; + } + + /* cannot have a lonely sign -- signs must be followed by a digit */ + if ((s[0] == '+' || s[0] == '-') && !isdigit(s[1])) { + return 0; + } + + /* rest of bytes must be digits */ + for (i = 1, len = strlen(s); i < len; i++) { + if (!isdigit(s[i])) { + return 0; + } + } + + return 1; +} + +static obj_t * int_op(obj_t *op1, obj_t *op2, void (*op)(mpz_t rop, const mpz_t op1, const mpz_t op2), char *op_name) { + + mpz_t op1z; + mpz_t op2z; + mpz_t rz; + char *s1; + char *s2; + char *sr; + obj_t *result; + + if (!IS_INT(op1) || !IS_INT(op2)) { + fprintf(stdout, "%s: expecting INT arguments.\n", op_name); + return alloc_fail(); + } + + s1 = strdup(ATOM(op1)); + s2 = strdup(ATOM(op2)); + + mpz_init_set_str(op1z, s1, 10); + mpz_init_set_str(op2z, s2, 10); + mpz_init_set_str(rz, "0", 10); + + (*op)(rz, op1z, op2z); + sr = mpz_get_str(NULL, 10, rz); + + result = number_filter(alloc_atom(sr)); + + mpz_clear(op1z); + mpz_clear(op2z); + mpz_clear(rz); + + free(s1); + free(s2); + + return result; +} + +obj_t * edgar_plus(obj_t *op1, obj_t *op2) { + return int_op(op1, op2, mpz_add, "PLUS"); +} + +obj_t * edgar_minus(obj_t *op1, obj_t *op2) { + return int_op(op1, op2, mpz_sub, "MINUS"); +} + +obj_t * edgar_times(obj_t *op1, obj_t *op2) { + return int_op(op1, op2, mpz_mul, "TIMES"); +} + +obj_t * edgar_quotient(obj_t *op1, obj_t *op2) { + if (IS_ATOM(op2) && strcmp(ATOM(op2), "0") == 0) { + fprintf(stdout, "QUOTIENT: Divide by 0 Error.\n"); + return alloc_fail(); + } + return int_op(op1, op2, mpz_cdiv_q, "QUOTIENT"); +} + +obj_t * edgar_remainder(obj_t *op1, obj_t *op2) { + if (IS_ATOM(op2) && strcmp(ATOM(op2), "0") == 0) { + fprintf(stdout, "REMAINDER: Divide by 0 Error.\n"); + return alloc_fail(); + } + return int_op(op1, op2, mpz_mod, "REMAINDER"); +} + +int edgar_cmp(obj_t *op1, obj_t *op2, char *op_name) { + mpz_t op1z; + mpz_t op2z; + char *s1; + char *s2; + int r; + + if (!IS_INT(op1) || !IS_INT(op2)) { + fprintf(stdout, "%s: expecting INT arguments.\n", op_name); + return 77; + } + + s1 = strdup(ATOM(op1)); + s2 = strdup(ATOM(op2)); + + mpz_init_set_str(op1z, s1, 10); + mpz_init_set_str(op2z, s2, 10); + + r = mpz_cmp(op1z, op2z); + + mpz_clear(op1z); + mpz_clear(op2z); + + free(s1); + free(s2); + + return r; +} diff --git a/pool/shard000/C/0013857_flex_array.c b/pool/shard000/C/0013857_flex_array.c new file mode 100644 index 0000000000000000000000000000000000000000..7baed2fc3bc82920f97183c6fa70532250d165b4 --- /dev/null +++ b/pool/shard000/C/0013857_flex_array.c @@ -0,0 +1,268 @@ +/* + * Flexible array managed in PAGE_SIZE parts + * + * 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. + * + * Copyright IBM Corporation, 2009 + * + * Author: Dave Hansen + */ + +#include +#include +#include + +struct flex_array_part { + char elements[FLEX_ARRAY_PART_SIZE]; +}; + +static inline int __elements_per_part(int element_size) +{ + return FLEX_ARRAY_PART_SIZE / element_size; +} + +static inline int bytes_left_in_base(void) +{ + int element_offset = offsetof(struct flex_array, parts); + int bytes_left = FLEX_ARRAY_BASE_SIZE - element_offset; + return bytes_left; +} + +static inline int nr_base_part_ptrs(void) +{ + return bytes_left_in_base() / sizeof(struct flex_array_part *); +} + +/* + * If a user requests an allocation which is small + * enough, we may simply use the space in the + * flex_array->parts[] array to store the user + * data. + */ +static inline int elements_fit_in_base(struct flex_array *fa) +{ + int data_size = fa->element_size * fa->total_nr_elements; + if (data_size <= bytes_left_in_base()) + return 1; + return 0; +} + +/** + * flex_array_alloc - allocate a new flexible array + * @element_size: the size of individual elements in the array + * @total: total number of elements that this should hold + * + * Note: all locking must be provided by the caller. + * + * @total is used to size internal structures. If the user ever + * accesses any array indexes >=@total, it will produce errors. + * + * The maximum number of elements is defined as: the number of + * elements that can be stored in a page times the number of + * page pointers that we can fit in the base structure or (using + * integer math): + * + * (PAGE_SIZE/element_size) * (PAGE_SIZE-8)/sizeof(void *) + * + * Here's a table showing example capacities. Note that the maximum + * index that the get/put() functions is just nr_objects-1. This + * basically means that you get 4MB of storage on 32-bit and 2MB on + * 64-bit. + * + * + * Element size | Objects | Objects | + * PAGE_SIZE=4k | 32-bit | 64-bit | + * ---------------------------------| + * 1 bytes | 4186112 | 2093056 | + * 2 bytes | 2093056 | 1046528 | + * 3 bytes | 1395030 | 697515 | + * 4 bytes | 1046528 | 523264 | + * 32 bytes | 130816 | 65408 | + * 33 bytes | 126728 | 63364 | + * 2048 bytes | 2044 | 1022 | + * 2049 bytes | 1022 | 511 | + * void * | 1046528 | 261632 | + * + * Since 64-bit pointers are twice the size, we lose half the + * capacity in the base structure. Also note that no effort is made + * to efficiently pack objects across page boundaries. + */ +struct flex_array *flex_array_alloc(int element_size, unsigned int total, + gfp_t flags) +{ + struct flex_array *ret; + int max_size = nr_base_part_ptrs() * __elements_per_part(element_size); + + /* max_size will end up 0 if element_size > PAGE_SIZE */ + if (total > max_size) + return NULL; + ret = kzalloc(sizeof(struct flex_array), flags); + if (!ret) + return NULL; + ret->element_size = element_size; + ret->total_nr_elements = total; + return ret; +} + +static int fa_element_to_part_nr(struct flex_array *fa, + unsigned int element_nr) +{ + return element_nr / __elements_per_part(fa->element_size); +} + +/** + * flex_array_free_parts - just free the second-level pages + * + * This is to be used in cases where the base 'struct flex_array' + * has been statically allocated and should not be free. + */ +void flex_array_free_parts(struct flex_array *fa) +{ + int part_nr; + int max_part = nr_base_part_ptrs(); + + if (elements_fit_in_base(fa)) + return; + for (part_nr = 0; part_nr < max_part; part_nr++) + kfree(fa->parts[part_nr]); +} + +void flex_array_free(struct flex_array *fa) +{ + flex_array_free_parts(fa); + kfree(fa); +} + +static unsigned int index_inside_part(struct flex_array *fa, + unsigned int element_nr) +{ + unsigned int part_offset; + + part_offset = element_nr % __elements_per_part(fa->element_size); + return part_offset * fa->element_size; +} + +static struct flex_array_part * +__fa_get_part(struct flex_array *fa, int part_nr, gfp_t flags) +{ + struct flex_array_part *part = fa->parts[part_nr]; + if (!part) { + /* + * This leaves the part pages uninitialized + * and with potentially random data, just + * as if the user had kmalloc()'d the whole. + * __GFP_ZERO can be used to zero it. + */ + part = kmalloc(FLEX_ARRAY_PART_SIZE, flags); + if (!part) + return NULL; + fa->parts[part_nr] = part; + } + return part; +} + +/** + * flex_array_put - copy data into the array at @element_nr + * @src: address of data to copy into the array + * @element_nr: index of the position in which to insert + * the new element. + * + * Note that this *copies* the contents of @src into + * the array. If you are trying to store an array of + * pointers, make sure to pass in &ptr instead of ptr. + * + * Locking must be provided by the caller. + */ +int flex_array_put(struct flex_array *fa, unsigned int element_nr, void *src, + gfp_t flags) +{ + int part_nr = fa_element_to_part_nr(fa, element_nr); + struct flex_array_part *part; + void *dst; + + if (element_nr >= fa->total_nr_elements) + return -ENOSPC; + if (elements_fit_in_base(fa)) + part = (struct flex_array_part *)&fa->parts[0]; + else { + part = __fa_get_part(fa, part_nr, flags); + if (!part) + return -ENOMEM; + } + dst = &part->elements[index_inside_part(fa, element_nr)]; + memcpy(dst, src, fa->element_size); + return 0; +} + +/** + * flex_array_prealloc - guarantee that array space exists + * @start: index of first array element for which space is allocated + * @end: index of last (inclusive) element for which space is allocated + * + * This will guarantee that no future calls to flex_array_put() + * will allocate memory. It can be used if you are expecting to + * be holding a lock or in some atomic context while writing + * data into the array. + * + * Locking must be provided by the caller. + */ +int flex_array_prealloc(struct flex_array *fa, unsigned int start, + unsigned int end, gfp_t flags) +{ + int start_part; + int end_part; + int part_nr; + struct flex_array_part *part; + + if (start >= fa->total_nr_elements || end >= fa->total_nr_elements) + return -ENOSPC; + if (elements_fit_in_base(fa)) + return 0; + start_part = fa_element_to_part_nr(fa, start); + end_part = fa_element_to_part_nr(fa, end); + for (part_nr = start_part; part_nr <= end_part; part_nr++) { + part = __fa_get_part(fa, part_nr, flags); + if (!part) + return -ENOMEM; + } + return 0; +} + +/** + * flex_array_get - pull data back out of the array + * @element_nr: index of the element to fetch from the array + * + * Returns a pointer to the data at index @element_nr. Note + * that this is a copy of the data that was passed in. If you + * are using this to store pointers, you'll get back &ptr. + * + * Locking must be provided by the caller. + */ +void *flex_array_get(struct flex_array *fa, unsigned int element_nr) +{ + int part_nr = fa_element_to_part_nr(fa, element_nr); + struct flex_array_part *part; + + if (element_nr >= fa->total_nr_elements) + return NULL; + if (elements_fit_in_base(fa)) + part = (struct flex_array_part *)&fa->parts[0]; + else { + part = fa->parts[part_nr]; + if (!part) + return NULL; + } + return &part->elements[index_inside_part(fa, element_nr)]; +} diff --git a/pool/shard000/C/0013861_i2c-amd756-s4882.c b/pool/shard000/C/0013861_i2c-amd756-s4882.c new file mode 100644 index 0000000000000000000000000000000000000000..a2f5f992af7aa7e21d70294d302891c08054f4da --- /dev/null +++ b/pool/shard000/C/0013861_i2c-amd756-s4882.c @@ -0,0 +1,254 @@ +/* + * i2c-amd756-s4882.c - i2c-amd756 extras for the Tyan S4882 motherboard + * + * Copyright (C) 2004, 2008 Jean Delvare + * + * 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. + */ + +/* + * We select the channels by sending commands to the Philips + * PCA9556 chip at I2C address 0x18. The main adapter is used for + * the non-multiplexed part of the bus, and 4 virtual adapters + * are defined for the multiplexed addresses: 0x50-0x53 (memory + * module EEPROM) located on channels 1-4, and 0x4c (LM63) + * located on multiplexed channels 0 and 5-7. We define one + * virtual adapter per CPU, which corresponds to two multiplexed + * channels: + * CPU0: virtual adapter 1, channels 1 and 0 + * CPU1: virtual adapter 2, channels 2 and 5 + * CPU2: virtual adapter 3, channels 3 and 6 + * CPU3: virtual adapter 4, channels 4 and 7 + */ + +#include +#include +#include +#include +#include +#include + +extern struct i2c_adapter amd756_smbus; + +static struct i2c_adapter *s4882_adapter; +static struct i2c_algorithm *s4882_algo; + +/* Wrapper access functions for multiplexed SMBus */ +static DEFINE_MUTEX(amd756_lock); + +static s32 amd756_access_virt0(struct i2c_adapter * adap, u16 addr, + unsigned short flags, char read_write, + u8 command, int size, + union i2c_smbus_data * data) +{ + int error; + + /* We exclude the multiplexed addresses */ + if (addr == 0x4c || (addr & 0xfc) == 0x50 || (addr & 0xfc) == 0x30 + || addr == 0x18) + return -ENXIO; + + mutex_lock(&amd756_lock); + + error = amd756_smbus.algo->smbus_xfer(adap, addr, flags, read_write, + command, size, data); + + mutex_unlock(&amd756_lock); + + return error; +} + +/* We remember the last used channels combination so as to only switch + channels when it is really needed. This greatly reduces the SMBus + overhead, but also assumes that nobody will be writing to the PCA9556 + in our back. */ +static u8 last_channels; + +static inline s32 amd756_access_channel(struct i2c_adapter * adap, u16 addr, + unsigned short flags, char read_write, + u8 command, int size, + union i2c_smbus_data * data, + u8 channels) +{ + int error; + + /* We exclude the non-multiplexed addresses */ + if (addr != 0x4c && (addr & 0xfc) != 0x50 && (addr & 0xfc) != 0x30) + return -ENXIO; + + mutex_lock(&amd756_lock); + + if (last_channels != channels) { + union i2c_smbus_data mplxdata; + mplxdata.byte = channels; + + error = amd756_smbus.algo->smbus_xfer(adap, 0x18, 0, + I2C_SMBUS_WRITE, 0x01, + I2C_SMBUS_BYTE_DATA, + &mplxdata); + if (error) + goto UNLOCK; + last_channels = channels; + } + error = amd756_smbus.algo->smbus_xfer(adap, addr, flags, read_write, + command, size, data); + +UNLOCK: + mutex_unlock(&amd756_lock); + return error; +} + +static s32 amd756_access_virt1(struct i2c_adapter * adap, u16 addr, + unsigned short flags, char read_write, + u8 command, int size, + union i2c_smbus_data * data) +{ + /* CPU0: channels 1 and 0 enabled */ + return amd756_access_channel(adap, addr, flags, read_write, command, + size, data, 0x03); +} + +static s32 amd756_access_virt2(struct i2c_adapter * adap, u16 addr, + unsigned short flags, char read_write, + u8 command, int size, + union i2c_smbus_data * data) +{ + /* CPU1: channels 2 and 5 enabled */ + return amd756_access_channel(adap, addr, flags, read_write, command, + size, data, 0x24); +} + +static s32 amd756_access_virt3(struct i2c_adapter * adap, u16 addr, + unsigned short flags, char read_write, + u8 command, int size, + union i2c_smbus_data * data) +{ + /* CPU2: channels 3 and 6 enabled */ + return amd756_access_channel(adap, addr, flags, read_write, command, + size, data, 0x48); +} + +static s32 amd756_access_virt4(struct i2c_adapter * adap, u16 addr, + unsigned short flags, char read_write, + u8 command, int size, + union i2c_smbus_data * data) +{ + /* CPU3: channels 4 and 7 enabled */ + return amd756_access_channel(adap, addr, flags, read_write, command, + size, data, 0x90); +} + +static int __init amd756_s4882_init(void) +{ + int i, error; + union i2c_smbus_data ioconfig; + + if (!amd756_smbus.dev.parent) + return -ENODEV; + + /* Configure the PCA9556 multiplexer */ + ioconfig.byte = 0x00; /* All I/O to output mode */ + error = i2c_smbus_xfer(&amd756_smbus, 0x18, 0, I2C_SMBUS_WRITE, 0x03, + I2C_SMBUS_BYTE_DATA, &ioconfig); + if (error) { + dev_err(&amd756_smbus.dev, "PCA9556 configuration failed\n"); + error = -EIO; + goto ERROR0; + } + + /* Unregister physical bus */ + i2c_del_adapter(&amd756_smbus); + + printk(KERN_INFO "Enabling SMBus multiplexing for Tyan S4882\n"); + /* Define the 5 virtual adapters and algorithms structures */ + if (!(s4882_adapter = kcalloc(5, sizeof(struct i2c_adapter), + GFP_KERNEL))) { + error = -ENOMEM; + goto ERROR1; + } + if (!(s4882_algo = kcalloc(5, sizeof(struct i2c_algorithm), + GFP_KERNEL))) { + error = -ENOMEM; + goto ERROR2; + } + + /* Fill in the new structures */ + s4882_algo[0] = *(amd756_smbus.algo); + s4882_algo[0].smbus_xfer = amd756_access_virt0; + s4882_adapter[0] = amd756_smbus; + s4882_adapter[0].algo = s4882_algo; + s4882_adapter[0].dev.parent = amd756_smbus.dev.parent; + for (i = 1; i < 5; i++) { + s4882_algo[i] = *(amd756_smbus.algo); + s4882_adapter[i] = amd756_smbus; + snprintf(s4882_adapter[i].name, sizeof(s4882_adapter[i].name), + "SMBus 8111 adapter (CPU%d)", i-1); + s4882_adapter[i].algo = s4882_algo+i; + s4882_adapter[i].dev.parent = amd756_smbus.dev.parent; + } + s4882_algo[1].smbus_xfer = amd756_access_virt1; + s4882_algo[2].smbus_xfer = amd756_access_virt2; + s4882_algo[3].smbus_xfer = amd756_access_virt3; + s4882_algo[4].smbus_xfer = amd756_access_virt4; + + /* Register virtual adapters */ + for (i = 0; i < 5; i++) { + error = i2c_add_adapter(s4882_adapter+i); + if (error) { + printk(KERN_ERR "i2c-amd756-s4882: " + "Virtual adapter %d registration " + "failed, module not inserted\n", i); + for (i--; i >= 0; i--) + i2c_del_adapter(s4882_adapter+i); + goto ERROR3; + } + } + + return 0; + +ERROR3: + kfree(s4882_algo); + s4882_algo = NULL; +ERROR2: + kfree(s4882_adapter); + s4882_adapter = NULL; +ERROR1: + /* Restore physical bus */ + i2c_add_adapter(&amd756_smbus); +ERROR0: + return error; +} + +static void __exit amd756_s4882_exit(void) +{ + if (s4882_adapter) { + int i; + + for (i = 0; i < 5; i++) + i2c_del_adapter(s4882_adapter+i); + kfree(s4882_adapter); + s4882_adapter = NULL; + } + kfree(s4882_algo); + s4882_algo = NULL; + + /* Restore physical bus */ + if (i2c_add_adapter(&amd756_smbus)) + printk(KERN_ERR "i2c-amd756-s4882: " + "Physical bus restoration failed\n"); +} + +MODULE_AUTHOR("Jean Delvare "); +MODULE_DESCRIPTION("S4882 SMBus multiplexing"); +MODULE_LICENSE("GPL"); + +module_init(amd756_s4882_init); +module_exit(amd756_s4882_exit); diff --git a/pool/shard000/C/0013867_wm8994-regulator.c b/pool/shard000/C/0013867_wm8994-regulator.c new file mode 100644 index 0000000000000000000000000000000000000000..6ff872342648cc2cacbf23565826715b0d3bbff7 --- /dev/null +++ b/pool/shard000/C/0013867_wm8994-regulator.c @@ -0,0 +1,187 @@ +/* + * wm8994-regulator.c -- Regulator driver for the WM8994 + * + * Copyright 2009 Wolfson Microelectronics PLC. + * + * Author: Mark Brown + * + * 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 + +struct wm8994_ldo { + struct regulator_dev *regulator; + struct wm8994 *wm8994; +}; + +#define WM8994_LDO1_MAX_SELECTOR 0x7 +#define WM8994_LDO2_MAX_SELECTOR 0x3 + +static struct regulator_ops wm8994_ldo1_ops = { + .list_voltage = regulator_list_voltage_linear, + .map_voltage = regulator_map_voltage_linear, + .get_voltage_sel = regulator_get_voltage_sel_regmap, + .set_voltage_sel = regulator_set_voltage_sel_regmap, +}; + +static int wm8994_ldo2_list_voltage(struct regulator_dev *rdev, + unsigned int selector) +{ + struct wm8994_ldo *ldo = rdev_get_drvdata(rdev); + + if (selector > WM8994_LDO2_MAX_SELECTOR) + return -EINVAL; + + switch (ldo->wm8994->type) { + case WM8994: + return (selector * 100000) + 900000; + case WM8958: + return (selector * 100000) + 1000000; + case WM1811: + switch (selector) { + case 0: + return -EINVAL; + default: + return (selector * 100000) + 950000; + } + break; + default: + return -EINVAL; + } +} + +static struct regulator_ops wm8994_ldo2_ops = { + .list_voltage = wm8994_ldo2_list_voltage, + .get_voltage_sel = regulator_get_voltage_sel_regmap, + .set_voltage_sel = regulator_set_voltage_sel_regmap, +}; + +static const struct regulator_desc wm8994_ldo_desc[] = { + { + .name = "LDO1", + .id = 1, + .type = REGULATOR_VOLTAGE, + .n_voltages = WM8994_LDO1_MAX_SELECTOR + 1, + .vsel_reg = WM8994_LDO_1, + .vsel_mask = WM8994_LDO1_VSEL_MASK, + .ops = &wm8994_ldo1_ops, + .min_uV = 2400000, + .uV_step = 100000, + .enable_time = 3000, + .owner = THIS_MODULE, + }, + { + .name = "LDO2", + .id = 2, + .type = REGULATOR_VOLTAGE, + .n_voltages = WM8994_LDO2_MAX_SELECTOR + 1, + .vsel_reg = WM8994_LDO_2, + .vsel_mask = WM8994_LDO2_VSEL_MASK, + .ops = &wm8994_ldo2_ops, + .enable_time = 3000, + .owner = THIS_MODULE, + }, +}; + +static int wm8994_ldo_probe(struct platform_device *pdev) +{ + struct wm8994 *wm8994 = dev_get_drvdata(pdev->dev.parent); + struct wm8994_pdata *pdata = wm8994->dev->platform_data; + int id = pdev->id % ARRAY_SIZE(pdata->ldo); + struct regulator_config config = { }; + struct wm8994_ldo *ldo; + int ret; + + dev_dbg(&pdev->dev, "Probing LDO%d\n", id + 1); + + ldo = devm_kzalloc(&pdev->dev, sizeof(struct wm8994_ldo), GFP_KERNEL); + if (ldo == NULL) { + dev_err(&pdev->dev, "Unable to allocate private data\n"); + return -ENOMEM; + } + + ldo->wm8994 = wm8994; + + config.dev = wm8994->dev; + config.driver_data = ldo; + config.regmap = wm8994->regmap; + if (pdata) { + config.init_data = pdata->ldo[id].init_data; + config.ena_gpio = pdata->ldo[id].enable; + } + + ldo->regulator = regulator_register(&wm8994_ldo_desc[id], &config); + if (IS_ERR(ldo->regulator)) { + ret = PTR_ERR(ldo->regulator); + dev_err(wm8994->dev, "Failed to register LDO%d: %d\n", + id + 1, ret); + goto err; + } + + platform_set_drvdata(pdev, ldo); + + return 0; + +err: + return ret; +} + +static int wm8994_ldo_remove(struct platform_device *pdev) +{ + struct wm8994_ldo *ldo = platform_get_drvdata(pdev); + + platform_set_drvdata(pdev, NULL); + + regulator_unregister(ldo->regulator); + + return 0; +} + +static struct platform_driver wm8994_ldo_driver = { + .probe = wm8994_ldo_probe, + .remove = wm8994_ldo_remove, + .driver = { + .name = "wm8994-ldo", + .owner = THIS_MODULE, + }, +}; + +static int __init wm8994_ldo_init(void) +{ + int ret; + + ret = platform_driver_register(&wm8994_ldo_driver); + if (ret != 0) + pr_err("Failed to register Wm8994 GP LDO driver: %d\n", ret); + + return ret; +} +subsys_initcall(wm8994_ldo_init); + +static void __exit wm8994_ldo_exit(void) +{ + platform_driver_unregister(&wm8994_ldo_driver); +} +module_exit(wm8994_ldo_exit); + +/* Module information */ +MODULE_AUTHOR("Mark Brown "); +MODULE_DESCRIPTION("WM8994 LDO driver"); +MODULE_LICENSE("GPL"); +MODULE_ALIAS("platform:wm8994-ldo"); diff --git a/pool/shard000/C/0013873_sbc_gxx.c b/pool/shard000/C/0013873_sbc_gxx.c new file mode 100644 index 0000000000000000000000000000000000000000..8806f68e8ead542717efe1d537291894951beec0 --- /dev/null +++ b/pool/shard000/C/0013873_sbc_gxx.c @@ -0,0 +1,277 @@ +/* sbc_gxx.c -- MTD map driver for Arcom Control Systems SBC-MediaGX, + SBC-GXm and SBC-GX1 series boards. + + Copyright (C) 2001 Arcom Control System Ltd + + 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 + + $Id: sbc_gxx.c,v 1.1.1.1 2004/09/28 06:06:12 sure Exp $ + +The SBC-MediaGX / SBC-GXx has up to 16 MiB of +Intel StrataFlash (28F320/28F640) in x8 mode. + +This driver uses the CFI probe and Intel Extended Command Set drivers. + +The flash is accessed as follows: + + 16 KiB memory window at 0xdc000-0xdffff + + Two IO address locations for paging + + 0x258 + bit 0-7: address bit 14-21 + 0x259 + bit 0-1: address bit 22-23 + bit 7: 0 - reset/powered down + 1 - device enabled + +The single flash device is divided into 3 partition which appear as +separate MTD devices. + +25/04/2001 AJL (Arcom) Modified signon strings and partition sizes + (to support bzImages up to 638KiB-ish) +*/ + +// Includes + +#include +#include +#include +#include +#include + +#include +#include +#include + +// Defines + +// - Hardware specific + +#define WINDOW_START 0xdc000 + +/* Number of bits in offset. */ +#define WINDOW_SHIFT 14 +#define WINDOW_LENGTH (1 << WINDOW_SHIFT) + +/* The bits for the offset into the window. */ +#define WINDOW_MASK (WINDOW_LENGTH-1) +#define PAGE_IO 0x258 +#define PAGE_IO_SIZE 2 + +/* bit 7 of 0x259 must be 1 to enable device. */ +#define DEVICE_ENABLE 0x8000 + +// - Flash / Partition sizing + +#define MAX_SIZE_KiB 16384 +#define BOOT_PARTITION_SIZE_KiB 768 +#define DATA_PARTITION_SIZE_KiB 1280 +#define APP_PARTITION_SIZE_KiB 6144 + +// Globals + +static volatile int page_in_window = -1; // Current page in window. +static unsigned long iomapadr; +static spinlock_t sbc_gxx_spin = SPIN_LOCK_UNLOCKED; + +/* partition_info gives details on the logical partitions that the split the + * single flash device into. If the size if zero we use up to the end of the + * device. */ +static struct mtd_partition partition_info[]={ + { name: "SBC-GXx flash boot partition", + offset: 0, + size: BOOT_PARTITION_SIZE_KiB*1024 }, + { name: "SBC-GXx flash data partition", + offset: BOOT_PARTITION_SIZE_KiB*1024, + size: (DATA_PARTITION_SIZE_KiB)*1024 }, + { name: "SBC-GXx flash application partition", + offset: (BOOT_PARTITION_SIZE_KiB+DATA_PARTITION_SIZE_KiB)*1024 } +}; + +#define NUM_PARTITIONS 3 + +static inline void sbc_gxx_page(struct map_info *map, unsigned long ofs) +{ + unsigned long page = ofs >> WINDOW_SHIFT; + + if( page!=page_in_window ) { + outw( page | DEVICE_ENABLE, PAGE_IO ); + page_in_window = page; + } +} + + +static __u8 sbc_gxx_read8(struct map_info *map, unsigned long ofs) +{ + __u8 ret; + spin_lock(&sbc_gxx_spin); + sbc_gxx_page(map, ofs); + ret = readb(iomapadr + (ofs & WINDOW_MASK)); + spin_unlock(&sbc_gxx_spin); + return ret; +} + +static __u16 sbc_gxx_read16(struct map_info *map, unsigned long ofs) +{ + __u16 ret; + spin_lock(&sbc_gxx_spin); + sbc_gxx_page(map, ofs); + ret = readw(iomapadr + (ofs & WINDOW_MASK)); + spin_unlock(&sbc_gxx_spin); + return ret; +} + +static __u32 sbc_gxx_read32(struct map_info *map, unsigned long ofs) +{ + __u32 ret; + spin_lock(&sbc_gxx_spin); + sbc_gxx_page(map, ofs); + ret = readl(iomapadr + (ofs & WINDOW_MASK)); + spin_unlock(&sbc_gxx_spin); + return ret; +} + +static void sbc_gxx_copy_from(struct map_info *map, void *to, unsigned long from, ssize_t len) +{ + while(len) { + unsigned long thislen = len; + if (len > (WINDOW_LENGTH - (from & WINDOW_MASK))) + thislen = WINDOW_LENGTH-(from & WINDOW_MASK); + + spin_lock(&sbc_gxx_spin); + sbc_gxx_page(map, from); + memcpy_fromio(to, iomapadr + (from & WINDOW_MASK), thislen); + spin_unlock(&sbc_gxx_spin); + (__u8*)to += thislen; + from += thislen; + len -= thislen; + } +} + +static void sbc_gxx_write8(struct map_info *map, __u8 d, unsigned long adr) +{ + spin_lock(&sbc_gxx_spin); + sbc_gxx_page(map, adr); + writeb(d, iomapadr + (adr & WINDOW_MASK)); + spin_unlock(&sbc_gxx_spin); +} + +static void sbc_gxx_write16(struct map_info *map, __u16 d, unsigned long adr) +{ + spin_lock(&sbc_gxx_spin); + sbc_gxx_page(map, adr); + writew(d, iomapadr + (adr & WINDOW_MASK)); + spin_unlock(&sbc_gxx_spin); +} + +static void sbc_gxx_write32(struct map_info *map, __u32 d, unsigned long adr) +{ + spin_lock(&sbc_gxx_spin); + sbc_gxx_page(map, adr); + writel(d, iomapadr + (adr & WINDOW_MASK)); + spin_unlock(&sbc_gxx_spin); +} + +static void sbc_gxx_copy_to(struct map_info *map, unsigned long to, const void *from, ssize_t len) +{ + while(len) { + unsigned long thislen = len; + if (len > (WINDOW_LENGTH - (to & WINDOW_MASK))) + thislen = WINDOW_LENGTH-(to & WINDOW_MASK); + + spin_lock(&sbc_gxx_spin); + sbc_gxx_page(map, to); + memcpy_toio(iomapadr + (to & WINDOW_MASK), from, thislen); + spin_unlock(&sbc_gxx_spin); + to += thislen; + from += thislen; + len -= thislen; + } +} + +static struct map_info sbc_gxx_map = { + name: "SBC-GXx flash", + size: MAX_SIZE_KiB*1024, /* this must be set to a maximum possible amount + of flash so the cfi probe routines find all + the chips */ + buswidth: 1, + read8: sbc_gxx_read8, + read16: sbc_gxx_read16, + read32: sbc_gxx_read32, + copy_from: sbc_gxx_copy_from, + write8: sbc_gxx_write8, + write16: sbc_gxx_write16, + write32: sbc_gxx_write32, + copy_to: sbc_gxx_copy_to +}; + +/* MTD device for all of the flash. */ +static struct mtd_info *all_mtd; + +static void cleanup_sbc_gxx(void) +{ + if( all_mtd ) { + del_mtd_partitions( all_mtd ); + map_destroy( all_mtd ); + } + + iounmap((void *)iomapadr); + release_region(PAGE_IO,PAGE_IO_SIZE); +} + +int __init init_sbc_gxx(void) +{ + if (check_region(PAGE_IO,PAGE_IO_SIZE) != 0) { + printk( KERN_ERR"%s: IO ports 0x%x-0x%x in use\n", + sbc_gxx_map.name, + PAGE_IO, PAGE_IO+PAGE_IO_SIZE-1 ); + return -EAGAIN; + } + iomapadr = (unsigned long)ioremap(WINDOW_START, WINDOW_LENGTH); + if (!iomapadr) { + printk( KERN_ERR"%s: failed to ioremap memory region\n", + sbc_gxx_map.name ); + return -EIO; + } + + request_region( PAGE_IO, PAGE_IO_SIZE, "SBC-GXx flash" ); + + printk( KERN_INFO"%s: IO:0x%x-0x%x MEM:0x%x-0x%x\n", + sbc_gxx_map.name, + PAGE_IO, PAGE_IO+PAGE_IO_SIZE-1, + WINDOW_START, WINDOW_START+WINDOW_LENGTH-1 ); + + /* Probe for chip. */ + all_mtd = do_map_probe( "cfi_probe", &sbc_gxx_map ); + if( !all_mtd ) { + cleanup_sbc_gxx(); + return -ENXIO; + } + + all_mtd->module=THIS_MODULE; + + /* Create MTD devices for each partition. */ + add_mtd_partitions(all_mtd, partition_info, NUM_PARTITIONS ); + + return 0; +} + +module_init(init_sbc_gxx); +module_exit(cleanup_sbc_gxx); + +MODULE_LICENSE("GPL"); +MODULE_AUTHOR("Arcom Control Systems Ltd."); +MODULE_DESCRIPTION("MTD map driver for SBC-GXm and SBC-GX1 series boards"); diff --git a/pool/shard000/C/0013882_intelh263dec.c b/pool/shard000/C/0013882_intelh263dec.c new file mode 100644 index 0000000000000000000000000000000000000000..ffe91dbd5dad5891d51dce1184cbe1e4e5e17813 --- /dev/null +++ b/pool/shard000/C/0013882_intelh263dec.c @@ -0,0 +1,138 @@ +/* + * H.263i decoder + * + * This file is part of FFmpeg. + * + * FFmpeg 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. + * + * FFmpeg 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 FFmpeg; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "mpegvideo.h" +#include "h263.h" + +/* don't understand why they choose a different header ! */ +int ff_intel_h263_decode_picture_header(MpegEncContext *s) +{ + int format; + + /* picture header */ + if (get_bits_long(&s->gb, 22) != 0x20) { + av_log(s->avctx, AV_LOG_ERROR, "Bad picture start code\n"); + return -1; + } + s->picture_number = get_bits(&s->gb, 8); /* picture timestamp */ + + if (get_bits1(&s->gb) != 1) { + av_log(s->avctx, AV_LOG_ERROR, "Bad marker\n"); + return -1; /* marker */ + } + if (get_bits1(&s->gb) != 0) { + av_log(s->avctx, AV_LOG_ERROR, "Bad H263 id\n"); + return -1; /* h263 id */ + } + skip_bits1(&s->gb); /* split screen off */ + skip_bits1(&s->gb); /* camera off */ + skip_bits1(&s->gb); /* freeze picture release off */ + + format = get_bits(&s->gb, 3); + if (format == 0 || format == 6) { + av_log(s->avctx, AV_LOG_ERROR, "Intel H263 free format not supported\n"); + return -1; + } + s->h263_plus = 0; + + s->pict_type = AV_PICTURE_TYPE_I + get_bits1(&s->gb); + + s->unrestricted_mv = get_bits1(&s->gb); + s->h263_long_vectors = s->unrestricted_mv; + + if (get_bits1(&s->gb) != 0) { + av_log(s->avctx, AV_LOG_ERROR, "SAC not supported\n"); + return -1; /* SAC: off */ + } + s->obmc= get_bits1(&s->gb); + s->pb_frame = get_bits1(&s->gb); + + if (format < 6) { + s->width = ff_h263_format[format][0]; + s->height = ff_h263_format[format][1]; + s->avctx->sample_aspect_ratio.num = 12; + s->avctx->sample_aspect_ratio.den = 11; + } else { + format = get_bits(&s->gb, 3); + if(format == 0 || format == 7){ + av_log(s->avctx, AV_LOG_ERROR, "Wrong Intel H263 format\n"); + return -1; + } + if(get_bits(&s->gb, 2)) + av_log(s->avctx, AV_LOG_ERROR, "Bad value for reserved field\n"); + s->loop_filter = get_bits1(&s->gb) * !s->avctx->lowres; + if(get_bits1(&s->gb)) + av_log(s->avctx, AV_LOG_ERROR, "Bad value for reserved field\n"); + if(get_bits1(&s->gb)) + s->pb_frame = 2; + if(get_bits(&s->gb, 5)) + av_log(s->avctx, AV_LOG_ERROR, "Bad value for reserved field\n"); + if(get_bits(&s->gb, 5) != 1) + av_log(s->avctx, AV_LOG_ERROR, "Invalid marker\n"); + } + if(format == 6){ + int ar = get_bits(&s->gb, 4); + skip_bits(&s->gb, 9); // display width + skip_bits1(&s->gb); + skip_bits(&s->gb, 9); // display height + if(ar == 15){ + s->avctx->sample_aspect_ratio.num = get_bits(&s->gb, 8); // aspect ratio - width + s->avctx->sample_aspect_ratio.den = get_bits(&s->gb, 8); // aspect ratio - height + } else { + s->avctx->sample_aspect_ratio = ff_h263_pixel_aspect[ar]; + } + if (s->avctx->sample_aspect_ratio.num == 0) + av_log(s->avctx, AV_LOG_ERROR, "Invalid aspect ratio.\n"); + } + + s->chroma_qscale= s->qscale = get_bits(&s->gb, 5); + skip_bits1(&s->gb); /* Continuous Presence Multipoint mode: off */ + + if(s->pb_frame){ + skip_bits(&s->gb, 3); //temporal reference for B-frame + skip_bits(&s->gb, 2); //dbquant + } + + /* PEI */ + while (get_bits1(&s->gb) != 0) { + skip_bits(&s->gb, 8); + } + s->f_code = 1; + + s->y_dc_scale_table= + s->c_dc_scale_table= ff_mpeg1_dc_scale_table; + + ff_h263_show_pict_info(s); + + return 0; +} + +AVCodec ff_h263i_decoder = { + .name = "h263i", + .type = AVMEDIA_TYPE_VIDEO, + .id = CODEC_ID_H263I, + .priv_data_size = sizeof(MpegEncContext), + .init = ff_h263_decode_init, + .close = ff_h263_decode_end, + .decode = ff_h263_decode_frame, + .capabilities = CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1, + .long_name = NULL_IF_CONFIG_SMALL("Intel H.263"), + .pix_fmts = ff_pixfmt_list_420, +}; diff --git a/pool/shard000/C/0013897_utmutex.c b/pool/shard000/C/0013897_utmutex.c new file mode 100644 index 0000000000000000000000000000000000000000..f6e7cc36522df617bce9d2899f41e2bb0af58b1b --- /dev/null +++ b/pool/shard000/C/0013897_utmutex.c @@ -0,0 +1,477 @@ +/******************************************************************************* + * + * Module Name: utmutex - local mutex support + * + ******************************************************************************/ + +/****************************************************************************** + * + * 1. Copyright Notice + * + * Some or all of this work - Copyright (c) 1999 - 2009, Intel Corp. + * All rights reserved. + * + * 2. License + * + * 2.1. This is your license from Intel Corp. under its intellectual property + * rights. You may have additional license terms from the party that provided + * you this software, covering your right to use that party's intellectual + * property rights. + * + * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a + * copy of the source code appearing in this file ("Covered Code") an + * irrevocable, perpetual, worldwide license under Intel's copyrights in the + * base code distributed originally by Intel ("Original Intel Code") to copy, + * make derivatives, distribute, use and display any portion of the Covered + * Code in any form, with the right to sublicense such rights; and + * + * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent + * license (with the right to sublicense), under only those claims of Intel + * patents that are infringed by the Original Intel Code, to make, use, sell, + * offer to sell, and import the Covered Code and derivative works thereof + * solely to the minimum extent necessary to exercise the above copyright + * license, and in no event shall the patent license extend to any additions + * to or modifications of the Original Intel Code. No other license or right + * is granted directly or by implication, estoppel or otherwise; + * + * The above copyright and patent license is granted only if the following + * conditions are met: + * + * 3. Conditions + * + * 3.1. Redistribution of Source with Rights to Further Distribute Source. + * Redistribution of source code of any substantial portion of the Covered + * Code or modification with rights to further distribute source must include + * the above Copyright Notice, the above License, this list of Conditions, + * and the following Disclaimer and Export Compliance provision. In addition, + * Licensee must cause all Covered Code to which Licensee contributes to + * contain a file documenting the changes Licensee made to create that Covered + * Code and the date of any change. Licensee must include in that file the + * documentation of any changes made by any predecessor Licensee. Licensee + * must include a prominent statement that the modification is derived, + * directly or indirectly, from Original Intel Code. + * + * 3.2. Redistribution of Source with no Rights to Further Distribute Source. + * Redistribution of source code of any substantial portion of the Covered + * Code or modification without rights to further distribute source must + * include the following Disclaimer and Export Compliance provision in the + * documentation and/or other materials provided with distribution. In + * addition, Licensee may not authorize further sublicense of source of any + * portion of the Covered Code, and must include terms to the effect that the + * license from Licensee to its licensee is limited to the intellectual + * property embodied in the software Licensee provides to its licensee, and + * not to intellectual property embodied in modifications its licensee may + * make. + * + * 3.3. Redistribution of Executable. Redistribution in executable form of any + * substantial portion of the Covered Code or modification must reproduce the + * above Copyright Notice, and the following Disclaimer and Export Compliance + * provision in the documentation and/or other materials provided with the + * distribution. + * + * 3.4. Intel retains all right, title, and interest in and to the Original + * Intel Code. + * + * 3.5. Neither the name Intel nor any other trademark owned or controlled by + * Intel shall be used in advertising or otherwise to promote the sale, use or + * other dealings in products derived from or relating to the Covered Code + * without prior written authorization from Intel. + * + * 4. Disclaimer and Export Compliance + * + * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED + * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE + * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, + * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY + * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY + * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A + * PARTICULAR PURPOSE. + * + * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES + * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR + * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, + * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY + * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL + * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS + * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY + * LIMITED REMEDY. + * + * 4.3. Licensee shall not export, either directly or indirectly, any of this + * software or system incorporating such software without first obtaining any + * required license or other approval from the U. S. Department of Commerce or + * any other agency or department of the United States Government. In the + * event Licensee exports any such software from the United States or + * re-exports any such software from a foreign destination, Licensee shall + * ensure that the distribution and export/re-export of the software is in + * compliance with all laws, regulations, orders, or other restrictions of the + * U.S. Export Administration Regulations. Licensee agrees that neither it nor + * any of its subsidiaries will export/re-export any technical data, process, + * software, or service, directly or indirectly, to any country for which the + * United States government or any agency thereof requires an export license, + * other governmental approval, or letter of assurance, without first obtaining + * such license, approval or letter. + * + *****************************************************************************/ + + +#define __UTMUTEX_C__ + +#include "acpi.h" +#include "accommon.h" + +#define _COMPONENT ACPI_UTILITIES + ACPI_MODULE_NAME ("utmutex") + +/* Local prototypes */ + +static ACPI_STATUS +AcpiUtCreateMutex ( + ACPI_MUTEX_HANDLE MutexId); + +static ACPI_STATUS +AcpiUtDeleteMutex ( + ACPI_MUTEX_HANDLE MutexId); + + +/******************************************************************************* + * + * FUNCTION: AcpiUtMutexInitialize + * + * PARAMETERS: None. + * + * RETURN: Status + * + * DESCRIPTION: Create the system mutex objects. This includes mutexes, + * spin locks, and reader/writer locks. + * + ******************************************************************************/ + +ACPI_STATUS +AcpiUtMutexInitialize ( + void) +{ + UINT32 i; + ACPI_STATUS Status; + + + ACPI_FUNCTION_TRACE (UtMutexInitialize); + + + /* Create each of the predefined mutex objects */ + + for (i = 0; i < ACPI_NUM_MUTEX; i++) + { + Status = AcpiUtCreateMutex (i); + if (ACPI_FAILURE (Status)) + { + return_ACPI_STATUS (Status); + } + } + + /* Create the spinlocks for use at interrupt level */ + + Status = AcpiOsCreateLock (&AcpiGbl_GpeLock); + if (ACPI_FAILURE (Status)) + { + return_ACPI_STATUS (Status); + } + + Status = AcpiOsCreateLock (&AcpiGbl_HardwareLock); + if (ACPI_FAILURE (Status)) + { + return_ACPI_STATUS (Status); + } + + /* Create the reader/writer lock for namespace access */ + + Status = AcpiUtCreateRwLock (&AcpiGbl_NamespaceRwLock); + return_ACPI_STATUS (Status); +} + + +/******************************************************************************* + * + * FUNCTION: AcpiUtMutexTerminate + * + * PARAMETERS: None. + * + * RETURN: None. + * + * DESCRIPTION: Delete all of the system mutex objects. This includes mutexes, + * spin locks, and reader/writer locks. + * + ******************************************************************************/ + +void +AcpiUtMutexTerminate ( + void) +{ + UINT32 i; + + + ACPI_FUNCTION_TRACE (UtMutexTerminate); + + + /* Delete each predefined mutex object */ + + for (i = 0; i < ACPI_NUM_MUTEX; i++) + { + (void) AcpiUtDeleteMutex (i); + } + + /* Delete the spinlocks */ + + AcpiOsDeleteLock (AcpiGbl_GpeLock); + AcpiOsDeleteLock (AcpiGbl_HardwareLock); + + /* Delete the reader/writer lock */ + + AcpiUtDeleteRwLock (&AcpiGbl_NamespaceRwLock); + return_VOID; +} + + +/******************************************************************************* + * + * FUNCTION: AcpiUtCreateMutex + * + * PARAMETERS: MutexID - ID of the mutex to be created + * + * RETURN: Status + * + * DESCRIPTION: Create a mutex object. + * + ******************************************************************************/ + +static ACPI_STATUS +AcpiUtCreateMutex ( + ACPI_MUTEX_HANDLE MutexId) +{ + ACPI_STATUS Status = AE_OK; + + + ACPI_FUNCTION_TRACE_U32 (UtCreateMutex, MutexId); + + + if (MutexId > ACPI_MAX_MUTEX) + { + return_ACPI_STATUS (AE_BAD_PARAMETER); + } + + if (!AcpiGbl_MutexInfo[MutexId].Mutex) + { + Status = AcpiOsCreateMutex (&AcpiGbl_MutexInfo[MutexId].Mutex); + AcpiGbl_MutexInfo[MutexId].ThreadId = ACPI_MUTEX_NOT_ACQUIRED; + AcpiGbl_MutexInfo[MutexId].UseCount = 0; + } + + return_ACPI_STATUS (Status); +} + + +/******************************************************************************* + * + * FUNCTION: AcpiUtDeleteMutex + * + * PARAMETERS: MutexID - ID of the mutex to be deleted + * + * RETURN: Status + * + * DESCRIPTION: Delete a mutex object. + * + ******************************************************************************/ + +static ACPI_STATUS +AcpiUtDeleteMutex ( + ACPI_MUTEX_HANDLE MutexId) +{ + + ACPI_FUNCTION_TRACE_U32 (UtDeleteMutex, MutexId); + + + if (MutexId > ACPI_MAX_MUTEX) + { + return_ACPI_STATUS (AE_BAD_PARAMETER); + } + + AcpiOsDeleteMutex (AcpiGbl_MutexInfo[MutexId].Mutex); + + AcpiGbl_MutexInfo[MutexId].Mutex = NULL; + AcpiGbl_MutexInfo[MutexId].ThreadId = ACPI_MUTEX_NOT_ACQUIRED; + + return_ACPI_STATUS (AE_OK); +} + + +/******************************************************************************* + * + * FUNCTION: AcpiUtAcquireMutex + * + * PARAMETERS: MutexID - ID of the mutex to be acquired + * + * RETURN: Status + * + * DESCRIPTION: Acquire a mutex object. + * + ******************************************************************************/ + +ACPI_STATUS +AcpiUtAcquireMutex ( + ACPI_MUTEX_HANDLE MutexId) +{ + ACPI_STATUS Status; + ACPI_THREAD_ID ThisThreadId; + + + ACPI_FUNCTION_NAME (UtAcquireMutex); + + + if (MutexId > ACPI_MAX_MUTEX) + { + return (AE_BAD_PARAMETER); + } + + ThisThreadId = AcpiOsGetThreadId (); + +#ifdef ACPI_MUTEX_DEBUG + { + UINT32 i; + /* + * Mutex debug code, for internal debugging only. + * + * Deadlock prevention. Check if this thread owns any mutexes of value + * greater than or equal to this one. If so, the thread has violated + * the mutex ordering rule. This indicates a coding error somewhere in + * the ACPI subsystem code. + */ + for (i = MutexId; i < ACPI_NUM_MUTEX; i++) + { + if (AcpiGbl_MutexInfo[i].ThreadId == ThisThreadId) + { + if (i == MutexId) + { + ACPI_ERROR ((AE_INFO, + "Mutex [%s] already acquired by this thread [%p]", + AcpiUtGetMutexName (MutexId), + ACPI_CAST_PTR (void, ThisThreadId))); + + return (AE_ALREADY_ACQUIRED); + } + + ACPI_ERROR ((AE_INFO, + "Invalid acquire order: Thread %p owns [%s], wants [%s]", + ACPI_CAST_PTR (void, ThisThreadId), AcpiUtGetMutexName (i), + AcpiUtGetMutexName (MutexId))); + + return (AE_ACQUIRE_DEADLOCK); + } + } + } +#endif + + ACPI_DEBUG_PRINT ((ACPI_DB_MUTEX, + "Thread %p attempting to acquire Mutex [%s]\n", + ACPI_CAST_PTR (void, ThisThreadId), AcpiUtGetMutexName (MutexId))); + + Status = AcpiOsAcquireMutex (AcpiGbl_MutexInfo[MutexId].Mutex, + ACPI_WAIT_FOREVER); + if (ACPI_SUCCESS (Status)) + { + ACPI_DEBUG_PRINT ((ACPI_DB_MUTEX, "Thread %p acquired Mutex [%s]\n", + ACPI_CAST_PTR (void, ThisThreadId), AcpiUtGetMutexName (MutexId))); + + AcpiGbl_MutexInfo[MutexId].UseCount++; + AcpiGbl_MutexInfo[MutexId].ThreadId = ThisThreadId; + } + else + { + ACPI_EXCEPTION ((AE_INFO, Status, + "Thread %p could not acquire Mutex [%X]", + ACPI_CAST_PTR (void, ThisThreadId), MutexId)); + } + + return (Status); +} + + +/******************************************************************************* + * + * FUNCTION: AcpiUtReleaseMutex + * + * PARAMETERS: MutexID - ID of the mutex to be released + * + * RETURN: Status + * + * DESCRIPTION: Release a mutex object. + * + ******************************************************************************/ + +ACPI_STATUS +AcpiUtReleaseMutex ( + ACPI_MUTEX_HANDLE MutexId) +{ + ACPI_THREAD_ID ThisThreadId; + + + ACPI_FUNCTION_NAME (UtReleaseMutex); + + + ThisThreadId = AcpiOsGetThreadId (); + ACPI_DEBUG_PRINT ((ACPI_DB_MUTEX, "Thread %p releasing Mutex [%s]\n", + ACPI_CAST_PTR (void, ThisThreadId), AcpiUtGetMutexName (MutexId))); + + if (MutexId > ACPI_MAX_MUTEX) + { + return (AE_BAD_PARAMETER); + } + + /* + * Mutex must be acquired in order to release it! + */ + if (AcpiGbl_MutexInfo[MutexId].ThreadId == ACPI_MUTEX_NOT_ACQUIRED) + { + ACPI_ERROR ((AE_INFO, + "Mutex [%X] is not acquired, cannot release", MutexId)); + + return (AE_NOT_ACQUIRED); + } + +#ifdef ACPI_MUTEX_DEBUG + { + UINT32 i; + /* + * Mutex debug code, for internal debugging only. + * + * Deadlock prevention. Check if this thread owns any mutexes of value + * greater than this one. If so, the thread has violated the mutex + * ordering rule. This indicates a coding error somewhere in + * the ACPI subsystem code. + */ + for (i = MutexId; i < ACPI_NUM_MUTEX; i++) + { + if (AcpiGbl_MutexInfo[i].ThreadId == ThisThreadId) + { + if (i == MutexId) + { + continue; + } + + ACPI_ERROR ((AE_INFO, + "Invalid release order: owns [%s], releasing [%s]", + AcpiUtGetMutexName (i), AcpiUtGetMutexName (MutexId))); + + return (AE_RELEASE_DEADLOCK); + } + } + } +#endif + + /* Mark unlocked FIRST */ + + AcpiGbl_MutexInfo[MutexId].ThreadId = ACPI_MUTEX_NOT_ACQUIRED; + + AcpiOsReleaseMutex (AcpiGbl_MutexInfo[MutexId].Mutex); + return (AE_OK); +} + + diff --git a/pool/shard000/C/0013904_gpio_jni.c b/pool/shard000/C/0013904_gpio_jni.c new file mode 100644 index 0000000000000000000000000000000000000000..dd678d316909fc45a5df763f5b4905c676c6151e --- /dev/null +++ b/pool/shard000/C/0013904_gpio_jni.c @@ -0,0 +1,200 @@ +/* Copyright Statement: + * + * This software/firmware and related documentation ("MediaTek Software") are + * protected under relevant copyright laws. The information contained herein + * is confidential and proprietary to MediaTek Inc. and/or its licensors. + * Without the prior written permission of MediaTek inc. and/or its licensors, + * any reproduction, modification, use or disclosure of MediaTek Software, + * and information contained herein, in whole or in part, shall be strictly prohibited. + */ +/* MediaTek Inc. (C) 2010. All rights reserved. + * + * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES + * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") + * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER ON + * AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT. + * NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE + * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR + * SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH + * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES + * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES + * CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK + * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR + * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND + * CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE, + * AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE, + * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO + * MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. + * + * The following software/firmware and/or related documentation ("MediaTek Software") + * have been modified by MediaTek Inc. All revisions are subject to any receiver's + * applicable license agreements with MediaTek Inc. + */ + +/***************************************************************************** +* Copyright Statement: +* -------------------- +* This software is protected by Copyright and the information contained +* herein is confidential. The software may not be copied and the information +* contained herein may not be used or disclosed except with the written +* permission of MediaTek Inc. (C) 2008 +* +* BY OPENING THIS FILE, BUYER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES +* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") +* RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO BUYER ON +* AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES, +* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF +* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT. +* NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE +* SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR +* SUPPLIED WITH THE MEDIATEK SOFTWARE, AND BUYER AGREES TO LOOK ONLY TO SUCH +* THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. MEDIATEK SHALL ALSO +* NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE RELEASES MADE TO BUYER'S +* SPECIFICATION OR TO CONFORM TO A PARTICULAR STANDARD OR OPEN FORUM. +* +* BUYER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND CUMULATIVE +* LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE, +* AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE, +* OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY BUYER TO +* MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. +* +* THE TRANSACTION CONTEMPLATED HEREUNDER SHALL BE CONSTRUED IN ACCORDANCE +* WITH THE LAWS OF THE STATE OF CALIFORNIA, USA, EXCLUDING ITS CONFLICT OF +* LAWS PRINCIPLES. ANY DISPUTES, CONTROVERSIES OR CLAIMS ARISING THEREOF AND +* RELATED THERETO SHALL BE SETTLED BY ARBITRATION IN SAN FRANCISCO, CA, UNDER +* THE RULES OF THE INTERNATIONAL CHAMBER OF COMMERCE (ICC). +* +*****************************************************************************/ + + +/******************************************************************************* + * + * Filename: + * --------- + * gpio_jni.c + * + * Project: + * -------- + * Android + * + * Description: + * ------------ + * c file of gpio jni function + * + * Author: + * ------- + * MTK80905 + + *******************************************************************************/ +/* DO NOT EDIT THIS FILE - it is machine generated */ +#include "gpio_jni.h" +#include "string.h" +#include "Meta_GPIO_Para.h" +#include "funk.h" + + +/* + * Class: com_mediatek_engineermode_gpio + * Method: GPIO_Init + * Signature: ()Z + */ +JNIEXPORT jboolean JNICALL Java_com_mediatek_engineermode_io_EmGpio_gpioInit + (JNIEnv * env, jobject obj) + { + return Meta_GPIO_Init()? JNI_TRUE: JNI_FALSE; + + } + +/* + * Class: com_mediatek_engineermode_gpio + * Method: GPIO_UnInit + * Signature: ()Z + */ +JNIEXPORT jboolean JNICALL Java_com_mediatek_engineermode_io_EmGpio_gpioUnInit + (JNIEnv * env, jobject obj) + { + return Meta_GPIO_Deinit()? JNI_TRUE: JNI_FALSE; + } + +/* + * Class: com_mediatek_engineermode_gpio + * Method: Get_gpio_max_number + * Signature: ()I + */ +JNIEXPORT jint JNICALL Java_com_mediatek_engineermode_io_EmGpio_getGpioMaxNumber + (JNIEnv *env, jobject obj) + { + return (jint)HW_GPIO_MAX; + } + +/* + * Class: com_mediatek_engineermode_gpio + * Method: Set_gpio_input + * Signature: (I)Z + */ +JNIEXPORT jboolean JNICALL Java_com_mediatek_engineermode_io_EmGpio_setGpioInput + (JNIEnv *env, jobject obj, jint n) + { + GPIO_REQ req; + memset(&req, 0, sizeof(GPIO_REQ)); + req.pin = (int)n; + req.op = SET_DIR_IN; + + GPIO_CNF r = Meta_GPIO_OP(req, 0, 0); + return r.status == META_SUCCESS ? JNI_TRUE : JNI_FALSE; + } + +/* + * Class: com_mediatek_engineermode_gpio + * Method: Set_gpio_output + * Signature: (I)Z + */ +JNIEXPORT jboolean JNICALL Java_com_mediatek_engineermode_io_EmGpio_setGpioOutput + (JNIEnv * env, jobject obj, jint n) + { + GPIO_REQ req; + memset(&req, 0, sizeof(GPIO_REQ)); + req.pin = (int)n; + req.op = SET_DIR_OUT; + + GPIO_CNF r = Meta_GPIO_OP(req, 0, 0); + return r.status == META_SUCCESS ? JNI_TRUE : JNI_FALSE; + } + +/* + * Class: com_mediatek_engineermode_gpio + * Method: Set_gpio_data_high + * Signature: (I)Z + */ +JNIEXPORT jboolean JNICALL Java_com_mediatek_engineermode_io_EmGpio_setGpioDataHigh + (JNIEnv * env, jobject obj, jint n) + { + GPIO_REQ req; + memset(&req, 0, sizeof(GPIO_REQ)); + req.pin = (int)n; + req.op = SET_DATA_HIGH; + + GPIO_CNF r = Meta_GPIO_OP(req, 0, 0); + return r.status == META_SUCCESS ? JNI_TRUE : JNI_FALSE; + } + +/* + * Class: com_mediatek_engineermode_gpio + * Method: Set_gpio_data_low + * Signature: (I)Z + */ +JNIEXPORT jboolean JNICALL Java_com_mediatek_engineermode_io_EmGpio_setGpioDataLow + (JNIEnv * env, jobject obj, jint n) + { + GPIO_REQ req; + memset(&req, 0, sizeof(GPIO_REQ)); + req.pin = (int)n; + req.op = SET_DATA_LOW; + + GPIO_CNF r = Meta_GPIO_OP(req, 0, 0); + return r.status == META_SUCCESS ? JNI_TRUE : JNI_FALSE; + } + + diff --git a/pool/shard000/C/0013909_ppc-target-4.c b/pool/shard000/C/0013909_ppc-target-4.c new file mode 100644 index 0000000000000000000000000000000000000000..08e189de49e418e99925b1b0a873a10511785e7a --- /dev/null +++ b/pool/shard000/C/0013909_ppc-target-4.c @@ -0,0 +1,85 @@ +/* { dg-do compile { target { powerpc*-*-* } } } */ +/* { dg-skip-if "" { powerpc*-*-darwin* } { "*" } { "" } } */ +/* { dg-require-effective-target powerpc_vsx_ok } */ +/* { dg-skip-if "do not override -mcpu" { powerpc*-*-* } { "-mcpu=*" } { "-mcpu=power5" } } */ +/* { dg-options "-O2 -ffast-math -mcpu=power5 -mno-altivec -mabi=altivec -fno-unroll-loops" } */ +/* { dg-final { scan-assembler-times "vaddfp" 1 } } */ +/* { dg-final { scan-assembler-times "xvaddsp" 1 } } */ +/* { dg-final { scan-assembler-times "fadds" 1 } } */ + +#ifndef SIZE +#define SIZE 1024 +#endif + +#ifdef __ALTIVEC__ +#error "__ALTIVEC__ should not be defined." +#endif + +#ifdef __VSX__ +#error "__VSX__ should not be defined." +#endif + +#pragma GCC target("vsx") +#include +#pragma GCC reset_options + +#pragma GCC push_options +#pragma GCC target("altivec,no-vsx") + +#ifndef __ALTIVEC__ +#error "__ALTIVEC__ should be defined." +#endif + +#ifdef __VSX__ +#error "__VSX__ should not be defined." +#endif + +void +av_add (vector float *a, vector float *b, vector float *c) +{ + unsigned long i; + unsigned long n = SIZE / 4; + + for (i = 0; i < n; i++) + a[i] = vec_add (b[i], c[i]); +} + +#pragma GCC target("vsx") + +#ifndef __ALTIVEC__ +#error "__ALTIVEC__ should be defined." +#endif + +#ifndef __VSX__ +#error "__VSX__ should be defined." +#endif + +void +vsx_add (vector float *a, vector float *b, vector float *c) +{ + unsigned long i; + unsigned long n = SIZE / 4; + + for (i = 0; i < n; i++) + a[i] = vec_add (b[i], c[i]); +} + +#pragma GCC pop_options +#pragma GCC target("no-vsx,no-altivec") + +#ifdef __ALTIVEC__ +#error "__ALTIVEC__ should not be defined." +#endif + +#ifdef __VSX__ +#error "__VSX__ should not be defined." +#endif + +void +norm_add (float *a, float *b, float *c) +{ + unsigned long i; + + for (i = 0; i < SIZE; i++) + a[i] = b[i] + c[i]; +} diff --git a/pool/shard000/C/0013916_tevrtprecv.c b/pool/shard000/C/0013916_tevrtprecv.c new file mode 100644 index 0000000000000000000000000000000000000000..ee6ffdbecb869d762d465c08efb38b3c16793a76 --- /dev/null +++ b/pool/shard000/C/0013916_tevrtprecv.c @@ -0,0 +1,108 @@ +/* + The oRTP LinPhone RTP library intends to provide basics for a RTP stack. + Copyright (C) 2001 Simon MORLAT simon.morlat@linphone.org + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + +#include +#include +#include +#include +#include +#include +#ifndef _WIN32 +#include +#else +#include +#endif +#include + +int runcond=1; + +static int dtmf_tab[16]={'0','1','2','3','4','5','6','7','8','9','*','#','A','B','C','D'}; + +void stophandler(int signum) +{ + runcond=0; +} + +static char *help="usage: test_tevrecv filename loc_port\n"; + +int dtmf_count=0; + +void recv_tev_cb(RtpSession *session,unsigned long type, unsigned long dummy, void* user_data) +{ + printf("Receiving telephony event:%i\n",type); + if (type<16) printf("This is dtmf %c\n",dtmf_tab[type]); + dtmf_count++; +} + +int main(int argc, char *argv[]) +{ + RtpSession *session; + unsigned char buffer[160]; + int err; + FILE *outfile; + uint32_t ts=0; + int have_more; + + if (argc<3){ + printf("%s",help); + return -1; + } + + ortp_init(); + ortp_scheduler_init(); + + /* set the telephony event payload type to 96 in the av profile.*/ + rtp_profile_set_payload(&av_profile,96,&payload_type_telephone_event); + + session=rtp_session_new(RTP_SESSION_RECVONLY); + + rtp_session_set_scheduling_mode(session,1); + rtp_session_set_blocking_mode(session,1); + rtp_session_set_local_addr(session,"0.0.0.0",atoi(argv[2]),-1); + rtp_session_set_payload_type(session,0); + + /* register for telephony events */ + rtp_session_signal_connect(session,"telephone-event",(RtpCallback)recv_tev_cb,0); + + outfile=fopen(argv[1],"wb"); + if (outfile==NULL) { + perror("Cannot open file"); + return -1; + } + signal(SIGINT,stophandler); + while(runcond) + { + have_more=1; + while (have_more){ + err=rtp_session_recv_with_ts(session,buffer,160,ts,&have_more); + if (err>0) { + size_t ret = fwrite(buffer,1,err,outfile); + assert( ret == err ); + } + } + ts+=160; + //ortp_message("Receiving packet."); + } + fclose(outfile); + rtp_session_destroy(session); + ortp_exit(); + ortp_global_stats_display(); + printf("Total dtmf events received: %i\n",dtmf_count); + return 0; +} diff --git a/pool/shard000/C/0013921_plugin_test.c b/pool/shard000/C/0013921_plugin_test.c new file mode 100644 index 0000000000000000000000000000000000000000..26d913f553effa7d8a3bf85c45059f1eea71ca35 --- /dev/null +++ b/pool/shard000/C/0013921_plugin_test.c @@ -0,0 +1,123 @@ +/* + * plugin_test.c + * + * Copyright 2010-2011 Enrico Tröger + * Copyright 2010-2011 Nick Treleaven + * + * 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. + */ + + +/* This code tries to load the passed Geany plugin + * (passed as path, e.g. pluginname.so) and looks up some symbols. + * Example use case for this tool is to test whether a plugin is + * loadable and defines all required symbols. + * + * This file is not built during the normal build process, instead + * compile it on your with the following command in the root of the Geany source tree: + * + * cc -o plugin_test scripts/plugin_test.c `pkg-config --cflags --libs glib-2.0 gmodule-2.0` + */ + +#include +#include +#include + + +static gboolean tp_check_version(GModule *module) +{ + /* TODO implement me */ + return TRUE; +} + + +static void tp_close_module(GModule *module) +{ + if (! g_module_close(module)) + g_warning("%s: %s", g_module_name(module), g_module_error()); +} + + +/* Emulate loading a plugin and looking up some symbols, + * similar to what Geany would do on loading the plugin. + */ +static gboolean test_plugin(const gchar *filename) +{ + GModule *module; + void (*plugin_set_info)(void*); + void (*init) (void *data); + void (*cleanup) (void); + + g_return_val_if_fail(filename, FALSE); + g_return_val_if_fail(g_module_supported(), FALSE); + + module = g_module_open(filename, G_MODULE_BIND_LOCAL); + if (! module) + { + g_warning("Can't load plugin: \"%s\": %s", filename, g_module_error()); + return FALSE; + } + + if (! tp_check_version(module)) + { + tp_close_module(module); + return FALSE; + } + + g_module_symbol(module, "plugin_set_info", (void *) &plugin_set_info); + if (plugin_set_info == NULL) + { + g_warning("No plugin_set_info() defined for \"%s\" - consider fixing the plugin!", filename); + tp_close_module(module); + return FALSE; + } + + g_module_symbol(module, "plugin_init", (void *) &init); + if (init == NULL) + { + g_warning("Plugin '%s' has no plugin_init() function - consider fixing the plugin!", filename); + tp_close_module(module); + return FALSE; + } + + g_module_symbol(module, "plugin_cleanup", (void *) &cleanup); + if (cleanup == NULL) + { + g_warning("Plugin '%s' has no plugin_cleanup() function - there may be memory leaks!", filename); + } + + tp_close_module(module); + + return TRUE; +} + + +gint main(gint argc, gchar **argv) +{ + gint i; + gint result = 0; + + g_set_prgname("plugin_test"); + /* we could perform better argument processing here as well as more error checking but + * it's probably not worth at all */ + for (i = 1; i < argc; i++) + { + if (! test_plugin(argv[i])) + result = 1; + } + + return result; +} diff --git a/pool/shard000/C/0013928_gkmsScat.c b/pool/shard000/C/0013928_gkmsScat.c new file mode 100644 index 0000000000000000000000000000000000000000..a6d15acda3233d44dc34577003f97157b2feeb4c --- /dev/null +++ b/pool/shard000/C/0013928_gkmsScat.c @@ -0,0 +1,100 @@ +/* + Teem: Tools to process and visualize scientific data and images . + Copyright (C) 2012, 2011, 2010, 2009 University of Chicago + Copyright (C) 2008, 2007, 2006, 2005 Gordon Kindlmann + Copyright (C) 2004, 2003, 2002, 2001, 2000, 1999, 1998 University of Utah + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public License + (LGPL) as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + The terms of redistributing and/or modifying this software also + include exceptions to the LGPL that facilitate static linking. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with this library; if not, write to Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include "bane.h" +#include "privateBane.h" + +#define SCAT_INFO "Make V-G and V-H scatterplots" +static const char *_baneGkms_scatInfoL = + (SCAT_INFO + ". These provide a quick way to inspect a histogram volume, in order to " + "verify that the derivative inclusion ranges were appropriate, and to " + "get an initial sense of what sorts of boundaries were present in the " + "original volume."); +int +baneGkms_scatMain(int argc, const char **argv, const char *me, + hestParm *hparm) { + hestOpt *opt = NULL; + char *out[2], *perr; + Nrrd *hvol, *nvgRaw, *nvhRaw, *nvgQuant, *nvhQuant; + NrrdRange *vgRange, *vhRange; + airArray *mop; + int pret, E; + double gamma; + + hestOptAdd(&opt, "g", "gamma", airTypeDouble, 1, 1, &gamma, "1.0", + "gamma used to brighten/darken scatterplots. " + "gamma > 1.0 brightens; gamma < 1.0 darkens. " + "Negative gammas invert values (like in xv). "); + hestOptAdd(&opt, "i", "hvolIn", airTypeOther, 1, 1, &hvol, NULL, + "input histogram volume (from \"gkms hvol\")", + NULL, NULL, nrrdHestNrrd); + hestOptAdd(&opt, "o", "vgOut vhOut", airTypeString, 2, 2, out, NULL, + "Filenames to use for two output scatterplots, (gradient " + "magnitude versus value, and 2nd derivative versus value); " + "can use PGM or PNG format"); + + mop = airMopNew(); + airMopAdd(mop, opt, (airMopper)hestOptFree, airMopAlways); + USAGE(_baneGkms_scatInfoL); + PARSE(); + airMopAdd(mop, opt, (airMopper)hestParseFree, airMopAlways); + + nvgRaw = nrrdNew(); + nvhRaw = nrrdNew(); + nvgQuant = nrrdNew(); + nvhQuant = nrrdNew(); + airMopAdd(mop, nvgRaw, (airMopper)nrrdNuke, airMopAlways); + airMopAdd(mop, nvhRaw, (airMopper)nrrdNuke, airMopAlways); + airMopAdd(mop, nvgQuant, (airMopper)nrrdNuke, airMopAlways); + airMopAdd(mop, nvhQuant, (airMopper)nrrdNuke, airMopAlways); + if (baneRawScatterplots(nvgRaw, nvhRaw, hvol, AIR_TRUE)) { + biffAddf(BANE, "%s: trouble creating raw scatterplots", me); + airMopError(mop); return 1; + } + vgRange = nrrdRangeNewSet(nvgRaw, nrrdBlind8BitRangeFalse); + vhRange = nrrdRangeNewSet(nvhRaw, nrrdBlind8BitRangeFalse); + airMopAdd(mop, vgRange, (airMopper)nrrdRangeNix, airMopAlways); + airMopAdd(mop, vhRange, (airMopper)nrrdRangeNix, airMopAlways); + E = 0; + if (!E) E |= nrrdArithGamma(nvgRaw, nvgRaw, vgRange, gamma); + if (!E) E |= nrrdArithGamma(nvhRaw, nvhRaw, vhRange, gamma); + if (!E) E |= nrrdQuantize(nvgQuant, nvgRaw, vgRange, 8); + if (!E) E |= nrrdQuantize(nvhQuant, nvhRaw, vhRange, 8); + if (E) { + biffMovef(BANE, NRRD, "%s: trouble doing gamma or quantization", me); + airMopError(mop); return 1; + } + + if (!E) E |= nrrdSave(out[0], nvgQuant, NULL); + if (!E) E |= nrrdSave(out[1], nvhQuant, NULL); + if (E) { + biffMovef(BANE, NRRD, "%s: trouble saving scatterplot images", me); + airMopError(mop); return 1; + } + + airMopOkay(mop); + return 0; +} +BANE_GKMS_CMD(scat, SCAT_INFO); + diff --git a/pool/shard000/C/0013940_vp56dsp_init_arm.c b/pool/shard000/C/0013940_vp56dsp_init_arm.c new file mode 100644 index 0000000000000000000000000000000000000000..f53cbae1edfcc8b0d9c194a31866d36c7d52b5ce --- /dev/null +++ b/pool/shard000/C/0013940_vp56dsp_init_arm.c @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2010 Mans Rullgard + * + * This file is part of FFmpeg. + * + * FFmpeg 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. + * + * FFmpeg 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 FFmpeg; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include + +#include "libavutil/attributes.h" +#include "libavutil/arm/cpu.h" +#include "libavcodec/avcodec.h" +#include "libavcodec/vp56dsp.h" + +void ff_vp6_edge_filter_hor_neon(uint8_t *yuv, int stride, int t); +void ff_vp6_edge_filter_ver_neon(uint8_t *yuv, int stride, int t); + +av_cold void ff_vp56dsp_init_arm(VP56DSPContext *s, enum AVCodecID codec) +{ + int cpu_flags = av_get_cpu_flags(); + + if (codec != AV_CODEC_ID_VP5 && have_neon(cpu_flags)) { + s->edge_filter_hor = ff_vp6_edge_filter_hor_neon; + s->edge_filter_ver = ff_vp6_edge_filter_ver_neon; + } +} diff --git a/pool/shard000/C/0013948_rdft-serial.c b/pool/shard000/C/0013948_rdft-serial.c new file mode 100644 index 0000000000000000000000000000000000000000..091c115bbe6c487e718c7943a6e65fdda26071b8 --- /dev/null +++ b/pool/shard000/C/0013948_rdft-serial.c @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2003, 2007-11 Matteo Frigo + * Copyright (c) 2003, 2007-11 Massachusetts Institute of Technology + * + * 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 + * + */ + +/* "MPI" RDFTs where all of the data is on one processor...just + call through to serial API. */ + +#include "mpi-rdft.h" + +typedef struct { + plan_mpi_rdft super; + plan *cld; +} P; + +static void apply(const plan *ego_, R *I, R *O) +{ + const P *ego = (const P *) ego_; + plan_rdft *cld = (plan_rdft *) ego->cld; + cld->apply(ego->cld, I, O); +} + +static void awake(plan *ego_, enum wakefulness wakefulness) +{ + P *ego = (P *) ego_; + X(plan_awake)(ego->cld, wakefulness); +} + +static void destroy(plan *ego_) +{ + P *ego = (P *) ego_; + X(plan_destroy_internal)(ego->cld); +} + +static void print(const plan *ego_, printer *p) +{ + const P *ego = (const P *) ego_; + p->print(p, "(mpi-rdft-serial %(%p%))", ego->cld); +} + +int XM(rdft_serial_applicable)(const problem_mpi_rdft *p) +{ + return (1 + && p->flags == 0 /* TRANSPOSED/SCRAMBLED_IN/OUT not supported */ + && ((XM(is_local)(p->sz, IB) && XM(is_local)(p->sz, OB)) + || p->vn == 0)); +} + +static plan *mkplan(const solver *ego, const problem *p_, planner *plnr) +{ + const problem_mpi_rdft *p = (const problem_mpi_rdft *) p_; + P *pln; + plan *cld; + int my_pe; + static const plan_adt padt = { + XM(rdft_solve), awake, print, destroy + }; + + UNUSED(ego); + + /* check whether applicable: */ + if (!XM(rdft_serial_applicable)(p)) + return (plan *) 0; + + MPI_Comm_rank(p->comm, &my_pe); + if (my_pe == 0 && p->vn > 0) { + int i, rnk = p->sz->rnk; + tensor *sz = X(mktensor)(rnk); + rdft_kind *kind + = (rdft_kind *) MALLOC(sizeof(rdft_kind) * rnk, PROBLEMS); + sz->dims[rnk - 1].is = sz->dims[rnk - 1].os = p->vn; + sz->dims[rnk - 1].n = p->sz->dims[rnk - 1].n; + for (i = rnk - 1; i > 0; --i) { + sz->dims[i - 1].is = sz->dims[i - 1].os = + sz->dims[i].is * sz->dims[i].n; + sz->dims[i - 1].n = p->sz->dims[i - 1].n; + } + for (i = 0; i < rnk; ++i) + kind[i] = p->kind[i]; + + cld = X(mkplan_d)(plnr, + X(mkproblem_rdft_d)(sz, + X(mktensor_1d)(p->vn, 1, 1), + p->I, p->O, kind)); + X(ifree0)(kind); + } + else { /* idle process: make nop plan */ + cld = X(mkplan_d)(plnr, + X(mkproblem_rdft_0_d)(X(mktensor_1d)(0,0,0), + p->I, p->O)); + } + if (XM(any_true)(!cld, p->comm)) return (plan *) 0; + + pln = MKPLAN_MPI_RDFT(P, &padt, apply); + pln->cld = cld; + X(ops_cpy)(&cld->ops, &pln->super.super.ops); + return &(pln->super.super); +} + +static solver *mksolver(void) +{ + static const solver_adt sadt = { PROBLEM_MPI_RDFT, mkplan, 0 }; + return MKSOLVER(solver, &sadt); +} + +void XM(rdft_serial_register)(planner *p) +{ + REGISTER_SOLVER(p, mksolver()); +} diff --git a/pool/shard000/C/0013952_netutils.c b/pool/shard000/C/0013952_netutils.c new file mode 100644 index 0000000000000000000000000000000000000000..84b4405c41d38a07e449da4c4f79907e20b179df --- /dev/null +++ b/pool/shard000/C/0013952_netutils.c @@ -0,0 +1,94 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2013, 2014 Damien P. George + * Copyright (c) 2015 Daniel Campora + * + * 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 "py/runtime.h" +#include "shared/netutils/netutils.h" + +// Takes an array with a raw IPv4 address and returns something like '192.168.0.1'. +mp_obj_t netutils_format_ipv4_addr(uint8_t *ip, netutils_endian_t endian) { + char ip_str[16]; + mp_uint_t ip_len; + if (endian == NETUTILS_LITTLE) { + ip_len = snprintf(ip_str, 16, "%u.%u.%u.%u", ip[3], ip[2], ip[1], ip[0]); + } else { + ip_len = snprintf(ip_str, 16, "%u.%u.%u.%u", ip[0], ip[1], ip[2], ip[3]); + } + return mp_obj_new_str(ip_str, ip_len); +} + +// Takes an array with a raw IP address, and a port, and returns a net-address +// tuple such as ('192.168.0.1', 8080). +mp_obj_t netutils_format_inet_addr(uint8_t *ip, mp_uint_t port, netutils_endian_t endian) { + mp_obj_t tuple[2] = { + tuple[0] = netutils_format_ipv4_addr(ip, endian), + tuple[1] = mp_obj_new_int(port), + }; + return mp_obj_new_tuple(2, tuple); +} + +void netutils_parse_ipv4_addr(mp_obj_t addr_in, uint8_t *out_ip, netutils_endian_t endian) { + size_t addr_len; + const char *addr_str = mp_obj_str_get_data(addr_in, &addr_len); + if (addr_len == 0) { + // special case of no address given + memset(out_ip, 0, NETUTILS_IPV4ADDR_BUFSIZE); + return; + } + const char *s = addr_str; + const char *s_top = addr_str + addr_len; + for (mp_uint_t i = 3; ; i--) { + mp_uint_t val = 0; + for (; s < s_top && *s != '.'; s++) { + val = val * 10 + *s - '0'; + } + if (endian == NETUTILS_LITTLE) { + out_ip[i] = val; + } else { + out_ip[NETUTILS_IPV4ADDR_BUFSIZE - 1 - i] = val; + } + if (i == 0 && s == s_top) { + return; + } else if (i > 0 && s < s_top && *s == '.') { + s++; + } else { + mp_raise_ValueError(MP_ERROR_TEXT("invalid arguments")); + } + } +} + +// Takes an address of the form ('192.168.0.1', 8080), returns the port and +// puts IP in out_ip (which must take at least IPADDR_BUF_SIZE bytes). +mp_uint_t netutils_parse_inet_addr(mp_obj_t addr_in, uint8_t *out_ip, netutils_endian_t endian) { + mp_obj_t *addr_items; + mp_obj_get_array_fixed_n(addr_in, 2, &addr_items); + netutils_parse_ipv4_addr(addr_items[0], out_ip, endian); + return mp_obj_get_int(addr_items[1]); +} diff --git a/pool/shard000/C/0013965_mspdebug_simio.c b/pool/shard000/C/0013965_mspdebug_simio.c new file mode 100644 index 0000000000000000000000000000000000000000..13a590e3b0e0dc2b9d62d2d6eb7b5575703d4bf3 --- /dev/null +++ b/pool/shard000/C/0013965_mspdebug_simio.c @@ -0,0 +1,35 @@ +/** + * @file + * @brief mspdebug simio console driver + * + * @author Anton Kozlov + * @date 06.05.2015 + */ + +#include +#include + +#define MSPDEBUG_CONSOLE_BASE 0x00ff + +static int mspdebug_diag_init(const struct diag *diag) { + return 0; +} + +static void mspdebug_diag_putc(const struct diag *diag, char ch) { + REG_STORE(MSPDEBUG_CONSOLE_BASE, ch); +} + +static char mspdebug_diag_getc(const struct diag *diag) { + return 0; +} + +static int mspdebug_diag_kbhit(const struct diag *diag) { + return 0; +} + +DIAG_OPS_DECLARE( + .init = mspdebug_diag_init, + .putc = mspdebug_diag_putc, + .getc = mspdebug_diag_getc, + .kbhit = mspdebug_diag_kbhit, +); diff --git a/pool/shard000/C/0013974_altq.c b/pool/shard000/C/0013974_altq.c new file mode 100644 index 0000000000000000000000000000000000000000..ba6b6399b7269e3abfa1269f1c8a76c2f51d467c --- /dev/null +++ b/pool/shard000/C/0013974_altq.c @@ -0,0 +1,151 @@ +/* + * Copyright (c) 2002-2003 Luigi Rizzo + * Copyright (c) 1996 Alex Nash, Paul Traina, Poul-Henning Kamp + * Copyright (c) 1994 Ugen J.S.Antsilevich + * + * Idea and grammar partially left from: + * Copyright (c) 1993 Daniel Boulet + * + * Redistribution and use in source forms, with and without modification, + * are permitted provided that this entire comment appears intact. + * + * Redistribution in binary form may occur without any restrictions. + * Obviously, it would be nice if you gave credit where credit is due + * but requiring it would be too onerous. + * + * This software is provided ``AS IS'' without any warranties of any kind. + * + * NEW command line interface for IP firewall facility + * + * $FreeBSD: head/sbin/ipfw/altq.c 270424 2014-08-23 17:37:18Z melifaro $ + * + * altq interface + */ + +#include +#include +#include + +#include "ipfw2.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include /* IFNAMSIZ */ +#include +#include /* in_addr */ +#include + +/* + * Map between current altq queue id numbers and names. + */ +static TAILQ_HEAD(, pf_altq) altq_entries = + TAILQ_HEAD_INITIALIZER(altq_entries); + +void +altq_set_enabled(int enabled) +{ + int pffd; + + pffd = open("/dev/pf", O_RDWR); + if (pffd == -1) + err(EX_UNAVAILABLE, + "altq support opening pf(4) control device"); + if (enabled) { + if (ioctl(pffd, DIOCSTARTALTQ) != 0 && errno != EEXIST) + err(EX_UNAVAILABLE, "enabling altq"); + } else { + if (ioctl(pffd, DIOCSTOPALTQ) != 0 && errno != ENOENT) + err(EX_UNAVAILABLE, "disabling altq"); + } + close(pffd); +} + +static void +altq_fetch(void) +{ + struct pfioc_altq pfioc; + struct pf_altq *altq; + int pffd; + unsigned int mnr; + static int altq_fetched = 0; + + if (altq_fetched) + return; + altq_fetched = 1; + pffd = open("/dev/pf", O_RDONLY); + if (pffd == -1) { + warn("altq support opening pf(4) control device"); + return; + } + bzero(&pfioc, sizeof(pfioc)); + if (ioctl(pffd, DIOCGETALTQS, &pfioc) != 0) { + warn("altq support getting queue list"); + close(pffd); + return; + } + mnr = pfioc.nr; + for (pfioc.nr = 0; pfioc.nr < mnr; pfioc.nr++) { + if (ioctl(pffd, DIOCGETALTQ, &pfioc) != 0) { + if (errno == EBUSY) + break; + warn("altq support getting queue list"); + close(pffd); + return; + } + if (pfioc.altq.qid == 0) + continue; + altq = safe_calloc(1, sizeof(*altq)); + *altq = pfioc.altq; + TAILQ_INSERT_TAIL(&altq_entries, altq, entries); + } + close(pffd); +} + +u_int32_t +altq_name_to_qid(const char *name) +{ + struct pf_altq *altq; + + altq_fetch(); + TAILQ_FOREACH(altq, &altq_entries, entries) + if (strcmp(name, altq->qname) == 0) + break; + if (altq == NULL) + errx(EX_DATAERR, "altq has no queue named `%s'", name); + return altq->qid; +} + +static const char * +altq_qid_to_name(u_int32_t qid) +{ + struct pf_altq *altq; + + altq_fetch(); + TAILQ_FOREACH(altq, &altq_entries, entries) + if (qid == altq->qid) + break; + if (altq == NULL) + return NULL; + return altq->qname; +} + +void +print_altq_cmd(struct buf_pr *bp, ipfw_insn_altq *altqptr) +{ + if (altqptr) { + const char *qname; + + qname = altq_qid_to_name(altqptr->qid); + if (qname == NULL) + bprintf(bp, " altq ?<%u>", altqptr->qid); + else + bprintf(bp, " altq %s", qname); + } +} diff --git a/pool/shard000/C/0013975_at_var_lvalue.c b/pool/shard000/C/0013975_at_var_lvalue.c new file mode 100644 index 0000000000000000000000000000000000000000..9d14e801f7eee32f104d17f80f3f6c0652f62c8f --- /dev/null +++ b/pool/shard000/C/0013975_at_var_lvalue.c @@ -0,0 +1,29 @@ +#include + +struct foo +{ + int bar; +}; + +static struct foo foo; + +void sub(const char *file) +{ + struct timeval times[2]; + times[0].tv_sec = 1; + times[0].tv_usec = 2; + times[1].tv_sec = 3; + times[1].tv_usec = 4; + utimes (file, times); + foo.bar -= 2; /* 40 */ +} + +int +main (int argc, char **argv) +{ + foo.bar = 41 + argc; /* 42 */ + sub(argv[0]); + sub(argv[0]); + sub(argv[0]); + return 0; +} diff --git a/pool/shard000/C/0013981_adjustment.c b/pool/shard000/C/0013981_adjustment.c new file mode 100644 index 0000000000000000000000000000000000000000..10701851991ab7a4924f81ed7e709093f5543e5f --- /dev/null +++ b/pool/shard000/C/0013981_adjustment.c @@ -0,0 +1,173 @@ +/* + SDL_guitk - GUI toolkit designed for SDL environnements. + + Copyright (C) 2020 Trave Roman + + 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, 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 + +#ifdef HAVE_CONFIG_H +#include +#endif + +#ifdef STDC_HEADERS +#include +#endif + +#ifdef HAVE_STRING_H +#include +#endif + +#include + +#include "debug.h" +#include "mysdl.h" +#include "myttf.h" +#include "signal.h" +#include "object_prot.h" +#include "widget_prot.h" + +#include "adjustment_prot.h" + + +static int current_id=0; + +void PROT__adjustment_attach(SDLGuiTK_Adjustment *adjustment, + SDLGuiTK_Widget *parent) +{ + SDLGuiTK_list_append (adjustment->parents, + (SDLGuiTK_Object *)parent); +#if DEBUG_LEVEL >= 2 + SDLGUITK_LOG ("__adjustment_attach(): "); + printf("%s attached to %s\n", + adjustment->object->name, parent->object->name); +#endif + +} + +void PROT__adjustment_detach(SDLGuiTK_Adjustment *adjustment, + SDLGuiTK_Widget *parent) +{ + SDLGuiTK_Widget *current; + current = (SDLGuiTK_Widget *) + SDLGuiTK_list_remove(adjustment->parents, + (SDLGuiTK_Object *)parent); + if(current) { +#if DEBUG_LEVEL >= 2 + SDLGUITK_LOG ("__adjustment_detach(): "); + printf("%s detached from %s\n", + adjustment->object->name, parent->object->name); +#endif + } else + SDLGUITK_ERROR("__adjustment_detach(): widget not found!\n"); + if(SDLGuiTK_list_length (adjustment->parents)==0) { +#if DEBUG_LEVEL >= 2 + SDLGUITK_LOG ("__adjustment_detach(): last parent .. free adjustment\n"); +#endif + SDLGuiTK_list_destroy (adjustment->parents); + PROT__object_destroy (adjustment->object); + free(adjustment); + } +} + + +SDLGuiTK_Object *SDLGuiTK_ADJUSTMENT( SDLGuiTK_Adjustment *adjustment ) +{ + return adjustment->object; +} + +SDLGuiTK_Adjustment * SDLGuiTK_adjustment_new(double value, + double lower, + double upper, + double step_increment) +{ + SDLGuiTK_Adjustment * new_adjustment; + + new_adjustment = malloc( sizeof( struct SDLGuiTK_Adjustment ) ); + new_adjustment->object = PROT__object_new(); + new_adjustment->object->adjustment = new_adjustment; + sprintf( new_adjustment->object->name, "adjustment%d", ++current_id ); + + new_adjustment->parents = SDLGuiTK_list_new (); + new_adjustment->value = value; + new_adjustment->lower = lower; + new_adjustment->upper = upper; + new_adjustment->step_increment = step_increment; + + return new_adjustment; +} + +void SDLGuiTK_adjustment_set_value(SDLGuiTK_Adjustment *adjustment, + double value) +{ + if(valuelower) + value = adjustment->lower; + if(value>adjustment->upper) + value = adjustment->upper; + adjustment->value = value; + PROT__signal_push(adjustment->object, + SDLGUITK_SIGNAL_TYPE_VALUECHANGED ); + + SDLGuiTK_Widget * current; + current = (SDLGuiTK_Widget*) + SDLGuiTK_list_ref_init (adjustment->parents); + while(current) { + PROT__signal_push ( current->object, + SDLGUITK_SIGNAL_TYPE_CHILDNOTIFY); + current = (SDLGuiTK_Widget*) + SDLGuiTK_list_ref_next (adjustment->parents); + } +} + +double SDLGuiTK_adjustment_get_value(SDLGuiTK_Adjustment *adjustment) +{ + return adjustment->value; +} + +double SDLGuiTK_adjustment_get_fraction(SDLGuiTK_Adjustment *adjustment) +{ + return (adjustment->value-adjustment->lower) / + (adjustment->upper-adjustment->lower); +} + +void PROT__adjustment_set_fraction(SDLGuiTK_Adjustment *adjustment, + double fraction) +{ + double value; + value = (adjustment->lower + fraction*(adjustment->upper-adjustment->lower)); + if(valuelower) + value = adjustment->lower; + if(value>adjustment->upper) + value = adjustment->upper; + adjustment->value = value; + PROT__signal_push(adjustment->object, + SDLGUITK_SIGNAL_TYPE_VALUECHANGED ); + + SDLGuiTK_Widget * current; + current = (SDLGuiTK_Widget*) + SDLGuiTK_list_ref_init (adjustment->parents); + while(current) { + PROT__signal_push ( current->object, + SDLGUITK_SIGNAL_TYPE_CHILDNOTIFY); + current = (SDLGuiTK_Widget*) + SDLGuiTK_list_ref_next (adjustment->parents); + } +} + diff --git a/pool/shard000/C/0013986_count_1_l.c b/pool/shard000/C/0013986_count_1_l.c new file mode 100644 index 0000000000000000000000000000000000000000..8b1892c0faa4802a728c78f76065e606a596f1f8 --- /dev/null +++ b/pool/shard000/C/0013986_count_1_l.c @@ -0,0 +1,214 @@ +/* Implementation of the COUNT intrinsic + Copyright (C) 2002-2017 Free Software Foundation, Inc. + Contributed by Paul Brook + +This file is part of the GNU Fortran runtime library (libgfortran). + +Libgfortran is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public +License as published by the Free Software Foundation; either +version 3 of the License, or (at your option) any later version. + +Libgfortran is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +Under Section 7 of GPL version 3, you are granted additional +permissions described in the GCC Runtime Library Exception, version +3.1, as published by the Free Software Foundation. + +You should have received a copy of the GNU General Public License and +a copy of the GCC Runtime Library Exception along with this program; +see the files COPYING3 and COPYING.RUNTIME respectively. If not, see +. */ + +#include "libgfortran.h" + + +#if defined (HAVE_GFC_INTEGER_1) + + +extern void count_1_l (gfc_array_i1 * const restrict, + gfc_array_l1 * const restrict, const index_type * const restrict); +export_proto(count_1_l); + +void +count_1_l (gfc_array_i1 * const restrict retarray, + gfc_array_l1 * const restrict array, + const index_type * const restrict pdim) +{ + index_type count[GFC_MAX_DIMENSIONS]; + index_type extent[GFC_MAX_DIMENSIONS]; + index_type sstride[GFC_MAX_DIMENSIONS]; + index_type dstride[GFC_MAX_DIMENSIONS]; + const GFC_LOGICAL_1 * restrict base; + GFC_INTEGER_1 * restrict dest; + index_type rank; + index_type n; + index_type len; + index_type delta; + index_type dim; + int src_kind; + int continue_loop; + + /* Make dim zero based to avoid confusion. */ + dim = (*pdim) - 1; + rank = GFC_DESCRIPTOR_RANK (array) - 1; + + src_kind = GFC_DESCRIPTOR_SIZE (array); + + len = GFC_DESCRIPTOR_EXTENT(array,dim); + if (len < 0) + len = 0; + + delta = GFC_DESCRIPTOR_STRIDE_BYTES(array,dim); + + for (n = 0; n < dim; n++) + { + sstride[n] = GFC_DESCRIPTOR_STRIDE_BYTES(array,n); + extent[n] = GFC_DESCRIPTOR_EXTENT(array,n); + + if (extent[n] < 0) + extent[n] = 0; + } + for (n = dim; n < rank; n++) + { + sstride[n] = GFC_DESCRIPTOR_STRIDE_BYTES(array,n + 1); + extent[n] = GFC_DESCRIPTOR_EXTENT(array,n + 1); + + if (extent[n] < 0) + extent[n] = 0; + } + + if (retarray->base_addr == NULL) + { + size_t alloc_size, str; + + for (n = 0; n < rank; n++) + { + if (n == 0) + str = 1; + else + str = GFC_DESCRIPTOR_STRIDE(retarray,n-1) * extent[n-1]; + + GFC_DIMENSION_SET(retarray->dim[n], 0, extent[n] - 1, str); + + } + + retarray->offset = 0; + retarray->dtype = (array->dtype & ~GFC_DTYPE_RANK_MASK) | rank; + + alloc_size = GFC_DESCRIPTOR_STRIDE(retarray,rank-1) * extent[rank-1]; + + if (alloc_size == 0) + { + /* Make sure we have a zero-sized array. */ + GFC_DIMENSION_SET(retarray->dim[0], 0, -1, 1); + return; + } + else + retarray->base_addr = xmallocarray (alloc_size, sizeof (GFC_INTEGER_1)); + } + else + { + if (rank != GFC_DESCRIPTOR_RANK (retarray)) + runtime_error ("rank of return array incorrect in" + " COUNT intrinsic: is %ld, should be %ld", + (long int) GFC_DESCRIPTOR_RANK (retarray), + (long int) rank); + + if (unlikely (compile_options.bounds_check)) + { + for (n=0; n < rank; n++) + { + index_type ret_extent; + + ret_extent = GFC_DESCRIPTOR_EXTENT(retarray,n); + if (extent[n] != ret_extent) + runtime_error ("Incorrect extent in return value of" + " COUNT intrinsic in dimension %d:" + " is %ld, should be %ld", (int) n + 1, + (long int) ret_extent, (long int) extent[n]); + } + } + } + + for (n = 0; n < rank; n++) + { + count[n] = 0; + dstride[n] = GFC_DESCRIPTOR_STRIDE(retarray,n); + if (extent[n] <= 0) + return; + } + + base = array->base_addr; + + if (src_kind == 1 || src_kind == 2 || src_kind == 4 || src_kind == 8 +#ifdef HAVE_GFC_LOGICAL_16 + || src_kind == 16 +#endif + ) + { + if (base) + base = GFOR_POINTER_TO_L1 (base, src_kind); + } + else + internal_error (NULL, "Funny sized logical array in COUNT intrinsic"); + + dest = retarray->base_addr; + + continue_loop = 1; + while (continue_loop) + { + const GFC_LOGICAL_1 * restrict src; + GFC_INTEGER_1 result; + src = base; + { + + result = 0; + if (len <= 0) + *dest = 0; + else + { + for (n = 0; n < len; n++, src += delta) + { + + if (*src) + result++; + } + *dest = result; + } + } + /* Advance to the next element. */ + count[0]++; + base += sstride[0]; + dest += dstride[0]; + n = 0; + while (count[n] == extent[n]) + { + /* When we get to the end of a dimension, reset it and increment + the next dimension. */ + count[n] = 0; + /* We could precalculate these products, but this is a less + frequently used path so probably not worth it. */ + base -= sstride[n] * extent[n]; + dest -= dstride[n] * extent[n]; + n++; + if (n >= rank) + { + /* Break out of the loop. */ + continue_loop = 0; + break; + } + else + { + count[n]++; + base += sstride[n]; + dest += dstride[n]; + } + } + } +} + +#endif diff --git a/pool/shard000/C/0014002_gamepad-monitor.c b/pool/shard000/C/0014002_gamepad-monitor.c new file mode 100644 index 0000000000000000000000000000000000000000..855e7a1aa0820dc8d4773f1c026d0c8ac0aadfac --- /dev/null +++ b/pool/shard000/C/0014002_gamepad-monitor.c @@ -0,0 +1,241 @@ +// This file is part of GNOME Games. License: GPL-3.0+. + +#include "gamepad-monitor.h" + +#include +#include +#include "gamepad-mapping-error.h" +#include "gamepad-mappings-manager.h" +#include "linux/linux-raw-gamepad-monitor.h" +#include "raw-gamepad.h" +#include "raw-gamepad-monitor.h" + +struct _GamesGamepadMonitor { + GObject parent_instance; + + GHashTable *gamepads; +}; + +G_DEFINE_TYPE (GamesGamepadMonitor, games_gamepad_monitor, G_TYPE_OBJECT) + +enum { + SIGNAL_GAMEPAD_PLUGGED, + SIGNAL_GAMEPAD_UNPLUGGED, + LAST_SIGNAL, +}; + +static guint signals[LAST_SIGNAL] = { 0 }; + +static GamesGamepadMonitor *instance = NULL; + +typedef struct { + GamesGamepadCallback callback; + gpointer target; +} ForeachGamepadData; + +/* Private */ + +static void +on_gamepad_unplugged (GamesGamepad *sender, + gpointer data) +{ + GamesGamepadMonitor *self; + + self = GAMES_GAMEPAD_MONITOR (data); + + g_return_if_fail (self != NULL); + g_return_if_fail (sender != NULL); + + g_hash_table_remove (self->gamepads, sender); + g_signal_emit (self, signals[SIGNAL_GAMEPAD_UNPLUGGED], 0); +} + +static GamesGamepad * +add_gamepad (GamesGamepadMonitor *self, + GamesRawGamepad *raw_gamepad) +{ + GamesGamepad *gamepad = NULL; + GError *inner_error = NULL; + const gchar *guid; + gchar *mapping_string; + GamesGamepadMappingsManager *mappings_manager; + GamesGamepadMapping *mapping = NULL; + + g_return_val_if_fail (self != NULL, NULL); + g_return_val_if_fail (raw_gamepad != NULL, NULL); + + gamepad = games_gamepad_new (raw_gamepad); + + mappings_manager = games_gamepad_mappings_manager_get_instance (); + guid = games_raw_gamepad_get_guid (raw_gamepad); + mapping_string = games_gamepad_mappings_manager_get_mapping (mappings_manager, guid); + mapping = games_gamepad_mapping_new_from_sdl_string (mapping_string, &inner_error); + if (G_UNLIKELY (inner_error != NULL)) { + g_debug ("%s", inner_error->message); + g_clear_error (&inner_error); + } + games_gamepad_set_mapping (gamepad, mapping); + + if (mapping != NULL) + g_object_unref (mapping); + if (mapping_string != NULL) + g_free (mapping_string); + + g_hash_table_add (self->gamepads, g_object_ref (gamepad)); + g_signal_connect_object (gamepad, + "unplugged", + (GCallback) on_gamepad_unplugged, + self, + 0); + + return gamepad; +} + +static void +on_raw_gamepad_plugged (GamesRawGamepadMonitor *sender, + GamesRawGamepad *raw_gamepad, + gpointer target) +{ + GamesGamepadMonitor *self; + GamesGamepad *gamepad; + + self = GAMES_GAMEPAD_MONITOR (target); + + g_return_if_fail (self != NULL); + g_return_if_fail (raw_gamepad != NULL); + + gamepad = add_gamepad (self, raw_gamepad); + if (gamepad != NULL) { + g_signal_emit (self, signals[SIGNAL_GAMEPAD_PLUGGED], 0, gamepad); + g_object_unref (gamepad); + } +} + +static void +add_raw_gamepad (GamesRawGamepad *raw_gamepad, + gpointer target) +{ + GamesGamepadMonitor *self; + GamesGamepad *gamepad; + + self = GAMES_GAMEPAD_MONITOR (target); + + g_return_if_fail (self != NULL); + g_return_if_fail (raw_gamepad != NULL); + + g_object_unref (add_gamepad (self, raw_gamepad)); +} + +static void +foreach_gamepad_do (gpointer key, + gpointer value, + gpointer data) +{ + ForeachGamepadData *callback_data; + GamesGamepad *gamepad; + + callback_data = (ForeachGamepadData *) data; + gamepad = (GamesGamepad *) value; + + g_return_if_fail (gamepad != NULL); + + callback_data->callback (gamepad, callback_data->target); +} + +static GamesGamepadMonitor * +games_gamepad_monitor_new (void) +{ + GamesGamepadMonitor *self = NULL; + GamesRawGamepadMonitor *raw_gamepad_monitor; + + self = (GamesGamepadMonitor*) g_object_new (GAMES_TYPE_GAMEPAD_MONITOR, NULL); + self->gamepads = g_hash_table_new_full (g_direct_hash, g_direct_equal, NULL, g_object_unref); + +#if ENABLE_LINUX_GAMEPADS + raw_gamepad_monitor = GAMES_RAW_GAMEPAD_MONITOR (games_linux_raw_gamepad_monitor_get_instance ()); + g_signal_connect_object (raw_gamepad_monitor, + "gamepad-plugged", + (GCallback) on_raw_gamepad_plugged, + self, + 0); + games_raw_gamepad_monitor_foreach_gamepad (raw_gamepad_monitor, + add_raw_gamepad, + self); + g_object_unref (raw_gamepad_monitor); +#endif /* ENABLE_LINUX_GAMEPADS */ + + return self; +} + +/* Public */ + +GamesGamepadMonitor *games_gamepad_monitor_get_instance (void) { + if (instance == NULL) + instance = games_gamepad_monitor_new (); + + return g_object_ref (instance); +} + +void +games_gamepad_monitor_foreach_gamepad (GamesGamepadMonitor *self, + GamesGamepadCallback callback, + gpointer target) +{ + ForeachGamepadData data; + + g_return_if_fail (self != NULL); + g_return_if_fail (callback != NULL); + + data.callback = callback; + data.target = target; + g_hash_table_foreach (self->gamepads, foreach_gamepad_do, &data); +} + +/* Type */ + +static void +finalize (GObject *object) +{ + GamesGamepadMonitor *self = GAMES_GAMEPAD_MONITOR (object); + + g_hash_table_unref (self->gamepads); + + G_OBJECT_CLASS (games_gamepad_monitor_parent_class)->finalize (object); +} + +static void games_gamepad_monitor_class_init (GamesGamepadMonitorClass *klass) { + games_gamepad_monitor_parent_class = g_type_class_peek_parent (klass); + G_OBJECT_CLASS (klass)->finalize = finalize; + + /** + * GamesGamepad::unplugged: + * + * Emitted when the gamepad is unplugged. + */ + signals[SIGNAL_GAMEPAD_PLUGGED] = + g_signal_new ("gamepad-plugged", + GAMES_TYPE_GAMEPAD_MONITOR, + G_SIGNAL_RUN_LAST, + 0, NULL, NULL, + g_cclosure_marshal_VOID__OBJECT, + G_TYPE_NONE, 1, + GAMES_TYPE_GAMEPAD); + + /** + * GamesGamepad::unplugged: + * + * Emitted when a gamepad is unplugged. + */ + signals[SIGNAL_GAMEPAD_UNPLUGGED] = + g_signal_new ("gamepad-unplugged", + GAMES_TYPE_GAMEPAD_MONITOR, + G_SIGNAL_RUN_LAST, + 0, NULL, NULL, + g_cclosure_marshal_VOID__VOID, + G_TYPE_NONE, 0); +} + +static void +games_gamepad_monitor_init (GamesGamepadMonitor *self) +{ +} diff --git a/pool/shard000/C/0014037_setup_usrv.c b/pool/shard000/C/0014037_setup_usrv.c new file mode 100644 index 0000000000000000000000000000000000000000..f5b4b5ac31e7c0bbf4dc5bf7c38a185698974065 --- /dev/null +++ b/pool/shard000/C/0014037_setup_usrv.c @@ -0,0 +1,249 @@ +/* + * linux/arch/m32r/kernel/setup_usrv.c + * + * Setup routines for MITSUBISHI uServer + * + * Copyright (c) 2001, 2002, 2003 Hiroyuki Kondo, Hirokazu Takata, + * Hitoshi Yamamoto + */ + +#include +#include +#include + +#include +#include +#include + +#define irq2port(x) (M32R_ICU_CR1_PORTL + ((x - 1) * sizeof(unsigned long))) + +icu_data_t icu_data[M32700UT_NUM_CPU_IRQ]; + +static void disable_mappi_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_mappi_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_and_ack_mappi(unsigned int irq) +{ + disable_mappi_irq(irq); +} + +static void end_mappi_irq(unsigned int irq) +{ + enable_mappi_irq(irq); +} + +static unsigned int startup_mappi_irq(unsigned int irq) +{ + enable_mappi_irq(irq); + return 0; +} + +static void shutdown_mappi_irq(unsigned int irq) +{ + unsigned long port; + + port = irq2port(irq); + outl(M32R_ICUCR_ILEVEL7, port); +} + +static struct hw_interrupt_type mappi_irq_type = +{ + .typename = "M32700-IRQ", + .startup = startup_mappi_irq, + .shutdown = shutdown_mappi_irq, + .enable = enable_mappi_irq, + .disable = disable_mappi_irq, + .ack = mask_and_ack_mappi, + .end = end_mappi_irq +}; + +/* + * Interrupt Control Unit of PLD on M32700UT (Level 2) + */ +#define irq2pldirq(x) ((x) - M32700UT_PLD_IRQ_BASE) +#define pldirq2port(x) (unsigned long)((int)PLD_ICUCR1 + \ + (((x) - 1) * sizeof(unsigned short))) + +typedef struct { + unsigned short icucr; /* ICU Control Register */ +} pld_icu_data_t; + +static pld_icu_data_t pld_icu_data[M32700UT_NUM_PLD_IRQ]; + +static void disable_m32700ut_pld_irq(unsigned int irq) +{ + unsigned long port, data; + unsigned int pldirq; + + pldirq = irq2pldirq(irq); + port = pldirq2port(pldirq); + data = pld_icu_data[pldirq].icucr|PLD_ICUCR_ILEVEL7; + outw(data, port); +} + +static void enable_m32700ut_pld_irq(unsigned int irq) +{ + unsigned long port, data; + unsigned int pldirq; + + pldirq = irq2pldirq(irq); + port = pldirq2port(pldirq); + data = pld_icu_data[pldirq].icucr|PLD_ICUCR_IEN|PLD_ICUCR_ILEVEL6; + outw(data, port); +} + +static void mask_and_ack_m32700ut_pld(unsigned int irq) +{ + disable_m32700ut_pld_irq(irq); +} + +static void end_m32700ut_pld_irq(unsigned int irq) +{ + enable_m32700ut_pld_irq(irq); + end_mappi_irq(M32R_IRQ_INT1); +} + +static unsigned int startup_m32700ut_pld_irq(unsigned int irq) +{ + enable_m32700ut_pld_irq(irq); + return 0; +} + +static void shutdown_m32700ut_pld_irq(unsigned int irq) +{ + unsigned long port; + unsigned int pldirq; + + pldirq = irq2pldirq(irq); + port = pldirq2port(pldirq); + outw(PLD_ICUCR_ILEVEL7, port); +} + +static struct hw_interrupt_type m32700ut_pld_irq_type = +{ + .typename = "USRV-PLD-IRQ", + .startup = startup_m32700ut_pld_irq, + .shutdown = shutdown_m32700ut_pld_irq, + .enable = enable_m32700ut_pld_irq, + .disable = disable_m32700ut_pld_irq, + .ack = mask_and_ack_m32700ut_pld, + .end = end_m32700ut_pld_irq +}; + +void __init init_IRQ(void) +{ + static int once = 0; + int i; + + if (once) + return; + else + once++; + + /* MFT2 : system timer */ + irq_desc[M32R_IRQ_MFT2].status = IRQ_DISABLED; + irq_desc[M32R_IRQ_MFT2].chip = &mappi_irq_type; + irq_desc[M32R_IRQ_MFT2].action = 0; + irq_desc[M32R_IRQ_MFT2].depth = 1; + icu_data[M32R_IRQ_MFT2].icucr = M32R_ICUCR_IEN; + disable_mappi_irq(M32R_IRQ_MFT2); + +#if defined(CONFIG_SERIAL_M32R_SIO) + /* SIO0_R : uart receive data */ + irq_desc[M32R_IRQ_SIO0_R].status = IRQ_DISABLED; + irq_desc[M32R_IRQ_SIO0_R].chip = &mappi_irq_type; + irq_desc[M32R_IRQ_SIO0_R].action = 0; + irq_desc[M32R_IRQ_SIO0_R].depth = 1; + icu_data[M32R_IRQ_SIO0_R].icucr = 0; + disable_mappi_irq(M32R_IRQ_SIO0_R); + + /* SIO0_S : uart send data */ + irq_desc[M32R_IRQ_SIO0_S].status = IRQ_DISABLED; + irq_desc[M32R_IRQ_SIO0_S].chip = &mappi_irq_type; + irq_desc[M32R_IRQ_SIO0_S].action = 0; + irq_desc[M32R_IRQ_SIO0_S].depth = 1; + icu_data[M32R_IRQ_SIO0_S].icucr = 0; + disable_mappi_irq(M32R_IRQ_SIO0_S); + + /* SIO1_R : uart receive data */ + irq_desc[M32R_IRQ_SIO1_R].status = IRQ_DISABLED; + irq_desc[M32R_IRQ_SIO1_R].chip = &mappi_irq_type; + irq_desc[M32R_IRQ_SIO1_R].action = 0; + irq_desc[M32R_IRQ_SIO1_R].depth = 1; + icu_data[M32R_IRQ_SIO1_R].icucr = 0; + disable_mappi_irq(M32R_IRQ_SIO1_R); + + /* SIO1_S : uart send data */ + irq_desc[M32R_IRQ_SIO1_S].status = IRQ_DISABLED; + irq_desc[M32R_IRQ_SIO1_S].chip = &mappi_irq_type; + irq_desc[M32R_IRQ_SIO1_S].action = 0; + irq_desc[M32R_IRQ_SIO1_S].depth = 1; + icu_data[M32R_IRQ_SIO1_S].icucr = 0; + disable_mappi_irq(M32R_IRQ_SIO1_S); +#endif /* CONFIG_SERIAL_M32R_SIO */ + + /* INT#67-#71: CFC#0 IREQ on PLD */ + for (i = 0 ; i < CONFIG_CFC_NUM ; i++ ) { + irq_desc[PLD_IRQ_CF0 + i].status = IRQ_DISABLED; + irq_desc[PLD_IRQ_CF0 + i].chip = &m32700ut_pld_irq_type; + irq_desc[PLD_IRQ_CF0 + i].action = 0; + irq_desc[PLD_IRQ_CF0 + i].depth = 1; /* disable nested irq */ + pld_icu_data[irq2pldirq(PLD_IRQ_CF0 + i)].icucr + = PLD_ICUCR_ISMOD01; /* 'L' level sense */ + disable_m32700ut_pld_irq(PLD_IRQ_CF0 + i); + } + +#if defined(CONFIG_SERIAL_8250) || defined(CONFIG_SERIAL_8250_MODULE) + /* INT#76: 16552D#0 IREQ on PLD */ + irq_desc[PLD_IRQ_UART0].status = IRQ_DISABLED; + irq_desc[PLD_IRQ_UART0].chip = &m32700ut_pld_irq_type; + irq_desc[PLD_IRQ_UART0].action = 0; + irq_desc[PLD_IRQ_UART0].depth = 1; /* disable nested irq */ + pld_icu_data[irq2pldirq(PLD_IRQ_UART0)].icucr + = PLD_ICUCR_ISMOD03; /* 'H' level sense */ + disable_m32700ut_pld_irq(PLD_IRQ_UART0); + + /* INT#77: 16552D#1 IREQ on PLD */ + irq_desc[PLD_IRQ_UART1].status = IRQ_DISABLED; + irq_desc[PLD_IRQ_UART1].chip = &m32700ut_pld_irq_type; + irq_desc[PLD_IRQ_UART1].action = 0; + irq_desc[PLD_IRQ_UART1].depth = 1; /* disable nested irq */ + pld_icu_data[irq2pldirq(PLD_IRQ_UART1)].icucr + = PLD_ICUCR_ISMOD03; /* 'H' level sense */ + disable_m32700ut_pld_irq(PLD_IRQ_UART1); +#endif /* CONFIG_SERIAL_8250 || CONFIG_SERIAL_8250_MODULE */ + +#if defined(CONFIG_IDC_AK4524) || defined(CONFIG_IDC_AK4524_MODULE) + /* INT#80: AK4524 IREQ on PLD */ + irq_desc[PLD_IRQ_SNDINT].status = IRQ_DISABLED; + irq_desc[PLD_IRQ_SNDINT].chip = &m32700ut_pld_irq_type; + irq_desc[PLD_IRQ_SNDINT].action = 0; + irq_desc[PLD_IRQ_SNDINT].depth = 1; /* disable nested irq */ + pld_icu_data[irq2pldirq(PLD_IRQ_SNDINT)].icucr + = PLD_ICUCR_ISMOD01; /* 'L' level sense */ + disable_m32700ut_pld_irq(PLD_IRQ_SNDINT); +#endif /* CONFIG_IDC_AK4524 || CONFIG_IDC_AK4524_MODULE */ + + /* + * INT1# is used for UART, MMC, CF Controller in FPGA. + * We enable it here. + */ + icu_data[M32R_IRQ_INT1].icucr = M32R_ICUCR_ISMOD11; + enable_mappi_irq(M32R_IRQ_INT1); +} + diff --git a/pool/shard000/C/0014038_wtkufil2.c b/pool/shard000/C/0014038_wtkufil2.c new file mode 100644 index 0000000000000000000000000000000000000000..e39aeb6e29bda9b4ef46c9b7bf829754effaeec2 --- /dev/null +++ b/pool/shard000/C/0014038_wtkufil2.c @@ -0,0 +1,254 @@ +/****************************** Module Header ******************************\ +* +* Module Name: wtkufil2.c +* +* Source for file and directory helper functions +* +* Copyright (c) WPS Toolkit Project - Christian Langanke 2000 +* +* $Id: wtkufil2.c,v 1.2 2003-04-24 14:33:30 cla Exp $ +* +* =========================================================================== +* +* This file is part of the WPS Toolkit package and 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, in version 2 +* as it comes in the "COPYING.LIB" file of the WPS Toolkit main distribution. +* 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. +* +* =========================================================================== +* +\***************************************************************************/ + +#include +#include +#include +#include + +#define INCL_DOS +#define INCL_ERRORS +#include + +#include "wtkufil.h" +#include "wpstk.ih" + +// --------------------------------------------------------------------------- + +/* +@@WtkCreatePath@SYNTAX +This function creates a complete path. +An error is returned only, if the last subdirectory in the pathname +could not be created. + +@@WtkCreatePath@PARM@pszPath@in +Address of the ASCIIZ path name of the path to be created. +:p. +The path name may contain :hp2.?&colon.:ehp2. for the drive in order to +create the path on the boot drive. + +@@WtkCreatePath@RETURN +Return Code. +:p. +WtkCreatePath returns one of the following return codes&colon. + +:parml compact break=none. +:pt.0 +:pd.NO_ERROR +:pt.87 +:pd.ERROR_INVALID_PARAMETER +:eparml. +:p. +or return codes of the following functions +:ul compact. +:li.DosCreateDir +:eul. + +@@WtkCreatePath@REMARKS +WtkCreatePath tries to create all directories within the path. +An error is returned only, if the last subdirectory in the pathname +could not be created. +:p. +This function supports boot drive recognition. +Specify :hp2.?&colon.:ehp2. for the drive in order to +create the path on the boot drive. + +@@ +*/ + +APIRET APIENTRY WtkCreatePath( PSZ pszPath) + +{ + + BOOL fIsModified = TRUE; + APIRET rc = NO_ERROR; + + CHAR szTmp[ _MAX_PATH]; + PSZ pszEndOfPath; + +do + { + // check parms + if ((!pszPath) || (!pszPath)) + { + rc = ERROR_INVALID_PARAMETER; + break; + } + + // use a copy + strcpy( szTmp, pszPath); + + // copy name and replace ?: with bootdrive + __PatchBootDrive( szTmp); + + // skip over a drive letter + // (or whatever will be before a colon in the future) + pszEndOfPath = strchr( szTmp, ':'); + if (pszEndOfPath) + pszEndOfPath++; + else + pszEndOfPath = szTmp; + + // if UNC name, skip server name and alias + if (!strncmp( pszEndOfPath, "\\\\", 2)) + { + // no server name given ? + // error ! + pszEndOfPath = strchr( pszEndOfPath + 2, '\\'); + if (!pszEndOfPath) + { + rc = ERROR_INVALID_PARAMETER; + break; + } + + // no path specified after aliasname ? + // abort with no error + pszEndOfPath = strchr( pszEndOfPath + 1, '\\'); + if (!pszEndOfPath) + break; + pszEndOfPath++; + if (!*pszEndOfPath) + break; + } + + // go through all path components + pszEndOfPath = strchr( pszEndOfPath, '\\'); + while (pszEndOfPath != NULL) + { + // go through all path components + // ignore errors here ! + *pszEndOfPath = 0; + rc = DosCreateDir( szTmp, NULL); + *pszEndOfPath = '\\'; + pszEndOfPath = strchr( pszEndOfPath + 1, '\\'); + } + + // create final directory and + // return error here + rc = DosCreateDir( szTmp, NULL); + + } while (FALSE); + +return rc; + +} + +// --------------------------------------------------------------------------- + +/* +@@WtkDeletePath@SYNTAX +This function deletes a complete path. An error is returned +only, if the last subdirectory in the pathname +could not be deleted. + +@@WtkDeletePath@PARM@pszPath@in +Address of the ASCIIZ path name of the path to be deleted. +:p. +The path name may contain :hp2.?&colon.:ehp2. for the drive in order to +delete the path on the boot drive. + +@@WtkDeletePath@RETURN +Return Code. +:p. +WtkDeletePath returns one of the following return codes&colon. + +:parml compact break=none. +:pt.0 +:pd.NO_ERROR +:pt.87 +:pd.ERROR_INVALID_PARAMETER +:eparml. +:p. +or return codes of the following functions +:ul compact. +:li.DosDeleteDir +:eul. + +@@WtkDeletePath@REMARKS +WtkDeletePath tries to delete all directories within the path. +An error is returned only, if the last subdirectory in the pathname +could not be deleted. +:p. +This function supports boot drive recognition. +Specify :hp2.?&colon.:ehp2. for the drive in order to +delete the file on the boot drive. + +@@ +*/ + +APIRET APIENTRY WtkDeletePath( PSZ pszPath) + +{ + + APIRET rc = NO_ERROR; + + CHAR szTmp[ _MAX_PATH]; + PSZ pszEndOfPath; + +do + { + // check parms + if ((!pszPath) || (!pszPath)) + { + rc = ERROR_INVALID_PARAMETER; + break; + } + + // use a copy + strcpy( szTmp, pszPath); + + // replace ?: with bootdrive + __PatchBootDrive( szTmp); + + // now remove top level directory + // return error, if that fails + rc = DosDeleteDir( szTmp); + if (rc != NO_ERROR) + break; + + // go through all path components + pszEndOfPath = strrchr( szTmp, '\\'); + while (pszEndOfPath != NULL) + { + // go through all path components + // ignore errors here, as the calls will not + // do any harm + *pszEndOfPath = 0; + rc = DosDeleteDir( szTmp); + if (rc != NO_ERROR) + break; + pszEndOfPath = strrchr( szTmp, '\\'); + } + + // ignore last errors + rc = NO_ERROR; + + } while (FALSE); + +return rc; + +} + + diff --git a/pool/shard000/C/0014062_gva-link-button.c b/pool/shard000/C/0014062_gva-link-button.c new file mode 100644 index 0000000000000000000000000000000000000000..199750aa402363753aab7d08deae405398366aec --- /dev/null +++ b/pool/shard000/C/0014062_gva-link-button.c @@ -0,0 +1,122 @@ +/* Copyright 2007-2009 Matthew Barnes + * + * This file is part of GNOME Video Arcade. + * + * GNOME Video Arcade 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. + * + * GNOME Video Arcade 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 "gva-link-button.h" + +static gpointer parent_class = NULL; + +static void +link_button_size_request (GtkWidget *widget, + GtkRequisition *requisition) +{ + GtkWidget *child; + + child = gtk_bin_get_child (GTK_BIN (widget)); + if (child != NULL && GTK_WIDGET_VISIBLE (child)) + gtk_widget_size_request (child, requisition); +} + +static void +link_button_size_allocate (GtkWidget *widget, + GtkAllocation *allocation) +{ + GtkWidget *child; + GdkWindow *window; + + widget->allocation = *allocation; + + /* XXX GTK+ has no accessor function for this. */ + window = GTK_BUTTON (widget)->event_window; + + if (GTK_WIDGET_REALIZED (widget)) + gdk_window_move_resize ( + window, + widget->allocation.x, + widget->allocation.y, + widget->allocation.width, + widget->allocation.height); + + child = gtk_bin_get_child (GTK_BIN (widget)); + gtk_widget_size_allocate (child, allocation); +} + +static gboolean +link_button_expose_event (GtkWidget *widget, + GdkEventExpose *event) +{ + GtkWidgetClass *widget_class; + + /* Bypass GtkButton's expose_event() method. */ + widget_class = g_type_class_peek (GTK_TYPE_BIN); + return widget_class->expose_event (widget, event); +} + +static void +link_button_class_init (GvaLinkButtonClass *class) +{ + GtkWidgetClass *widget_class; + + parent_class = g_type_class_peek_parent (class); + + widget_class = GTK_WIDGET_CLASS (class); + widget_class->size_request = link_button_size_request; + widget_class->size_allocate = link_button_size_allocate; + widget_class->expose_event = link_button_expose_event; +} + +GType +gva_link_button_get_type (void) +{ + static GType type = 0; + + if (G_UNLIKELY (type == 0)) + { + static const GTypeInfo type_info = + { + sizeof (GvaLinkButtonClass), + (GBaseInitFunc) NULL, + (GBaseFinalizeFunc) NULL, + (GClassInitFunc) link_button_class_init, + (GClassFinalizeFunc) NULL, + NULL, /* class_data */ + sizeof (GvaLinkButton), + 0, /* n_preallocs */ + (GInstanceInitFunc) NULL, + NULL /* value_table */ + }; + + type = g_type_register_static ( + GTK_TYPE_LINK_BUTTON, "GvaLinkButton", &type_info, 0); + } + + return type; +} + +/** + * gva_link_button_new: + * @label: the text of the button + * + * Creates a new #GvaLinkButton with @label as its text. + * + * Returns: a new #GtkLinkButton + **/ +GtkWidget * +gva_link_button_new (const gchar *label) +{ + return g_object_new (GVA_TYPE_LINK_BUTTON, "label", label, NULL); +} diff --git a/pool/shard000/C/0014070_dpofa.c b/pool/shard000/C/0014070_dpofa.c new file mode 100644 index 0000000000000000000000000000000000000000..8286b33767ac1a8906d338b82014411a37b9ceae --- /dev/null +++ b/pool/shard000/C/0014070_dpofa.c @@ -0,0 +1,117 @@ +/* dpofa.f -- translated by f2c (version 20100827). + You must link the resulting object file with libf2c: + on Microsoft Windows system, link with libf2c.lib; + on Linux or Unix systems, link with .../path/to/libf2c.a -lm + or, if you install libf2c.a in a standard place, with -lf2c -lm + -- in that order, at the end of the command line, as in + cc *.o -lf2c -lm + Source for libf2c is in /netlib/f2c/libf2c.zip, e.g., + + http://www.netlib.org/f2c/libf2c.zip +*/ + +#include "f2c.h" + +/* Table of constant values */ + +static integer c__1 = 1; + +/* Subroutine */ int dpofa_(doublereal *a, integer *lda, integer *n, integer * + info) +{ + /* System generated locals */ + integer a_dim1, a_offset, i__1, i__2, i__3; + + /* Builtin functions */ + double sqrt(doublereal); + + /* Local variables */ + integer j, k; + doublereal s, t; + integer jm1; + extern doublereal ddot_(integer *, doublereal *, integer *, doublereal *, + integer *); + + +/* dpofa factors a double precision symmetric positive definite */ +/* matrix. */ + +/* dpofa is usually called by dpoco, but it can be called */ +/* directly with a saving in time if rcond is not needed. */ +/* (time for dpoco) = (1 + 18/n)*(time for dpofa) . */ + +/* on entry */ + +/* a double precision(lda, n) */ +/* the symmetric matrix to be factored. only the */ +/* diagonal and upper triangle are used. */ + +/* lda integer */ +/* the leading dimension of the array a . */ + +/* n integer */ +/* the order of the matrix a . */ + +/* on return */ + +/* a an upper triangular matrix r so that a = trans(r)*r */ +/* where trans(r) is the transpose. */ +/* the strict lower triangle is unaltered. */ +/* if info .ne. 0 , the factorization is not complete. */ + +/* info integer */ +/* = 0 for normal return. */ +/* = k signals an error condition. the leading minor */ +/* of order k is not positive definite. */ + +/* linpack. this version dated 08/14/78 . */ +/* cleve moler, university of new mexico, argonne national lab. */ + +/* subroutines and functions */ + +/* blas ddot */ +/* fortran dsqrt */ + +/* internal variables */ + +/* begin block with ...exits to 40 */ + + + /* Parameter adjustments */ + a_dim1 = *lda; + a_offset = 1 + a_dim1; + a -= a_offset; + + /* Function Body */ + i__1 = *n; + for (j = 1; j <= i__1; ++j) { + *info = j; + s = 0.; + jm1 = j - 1; + if (jm1 < 1) { + goto L20; + } + i__2 = jm1; + for (k = 1; k <= i__2; ++k) { + i__3 = k - 1; + t = a[k + j * a_dim1] - ddot_(&i__3, &a[k * a_dim1 + 1], &c__1, & + a[j * a_dim1 + 1], &c__1); + t /= a[k + k * a_dim1]; + a[k + j * a_dim1] = t; + s += t * t; +/* L10: */ + } +L20: + s = a[j + j * a_dim1] - s; +/* ......exit */ + if (s <= 0.) { + goto L40; + } + a[j + j * a_dim1] = sqrt(s); +/* L30: */ + } + *info = 0; +L40: + return 0; +} /* dpofa_ */ + diff --git a/pool/shard000/C/0014071_ENUMERATED.c b/pool/shard000/C/0014071_ENUMERATED.c new file mode 100644 index 0000000000000000000000000000000000000000..90761a2d70a0426874a9956b7da15f5b55947861 --- /dev/null +++ b/pool/shard000/C/0014071_ENUMERATED.c @@ -0,0 +1,71 @@ +/*- + * Copyright (c) 2003, 2005, 2006 Lev Walkin . + * All rights reserved. + * Redistribution and modifications are permitted subject to BSD license. + */ +#include +#include +#include +#include /* Encoder and decoder of a primitive type */ + +/* + * ENUMERATED basic type description. + */ +static ber_tlv_tag_t asn_DEF_ENUMERATED_tags[] = { + (ASN_TAG_CLASS_UNIVERSAL | (10 << 2)) +}; +asn_TYPE_descriptor_t asn_DEF_ENUMERATED = { + "ENUMERATED", + "ENUMERATED", + ASN__PRIMITIVE_TYPE_free, + INTEGER_print, /* Implemented in terms of INTEGER */ + asn_generic_no_constraint, + ber_decode_primitive, + INTEGER_encode_der, /* Implemented in terms of INTEGER */ + INTEGER_decode_xer, /* This is temporary! */ + INTEGER_encode_xer, + ENUMERATED_decode_uper, /* Unaligned PER decoder */ + ENUMERATED_encode_uper, /* Unaligned PER encoder */ + 0, /* Use generic outmost tag fetcher */ + asn_DEF_ENUMERATED_tags, + sizeof(asn_DEF_ENUMERATED_tags) / sizeof(asn_DEF_ENUMERATED_tags[0]), + asn_DEF_ENUMERATED_tags, /* Same as above */ + sizeof(asn_DEF_ENUMERATED_tags) / sizeof(asn_DEF_ENUMERATED_tags[0]), + 0, /* No PER visible constraints */ + 0, 0, /* No members */ + 0 /* No specifics */ +}; + +asn_dec_rval_t +ENUMERATED_decode_uper(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td, + asn_per_constraints_t *constraints, void **sptr, asn_per_data_t *pd) { + asn_dec_rval_t rval; + ENUMERATED_t *st = (ENUMERATED_t *)*sptr; + long value; + void *vptr = &value; + + if(!st) { + st = (ENUMERATED_t *)(*sptr = CALLOC(1, sizeof(*st))); + if(!st) _ASN_DECODE_FAILED; + } + + rval = NativeEnumerated_decode_uper(opt_codec_ctx, td, constraints, + (void **)&vptr, pd); + if(rval.code == RC_OK) + if(asn_long2INTEGER(st, value)) + rval.code = RC_FAIL; + return rval; +} + +asn_enc_rval_t +ENUMERATED_encode_uper(asn_TYPE_descriptor_t *td, + asn_per_constraints_t *constraints, void *sptr, asn_per_outp_t *po) { + ENUMERATED_t *st = (ENUMERATED_t *)sptr; + long value; + + if(asn_INTEGER2long(st, &value)) + _ASN_ENCODE_FAILED; + + return NativeEnumerated_encode_uper(td, constraints, &value, po); +} + diff --git a/pool/shard000/C/0014077_pcprij128safedec2pxca.c b/pool/shard000/C/0014077_pcprij128safedec2pxca.c new file mode 100644 index 0000000000000000000000000000000000000000..f0f786f56d959dc473cd0e81604d799bee345ef8 --- /dev/null +++ b/pool/shard000/C/0014077_pcprij128safedec2pxca.c @@ -0,0 +1,156 @@ +/******************************************************************************* +* Copyright 2015-2020 Intel 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. +*******************************************************************************/ + +/* +// +// Purpose: +// Cryptography Primitive. +// Decrypt 128-bit data block according to Rijndael +// (compact S-box based implementation) +// +// Contents: +// Safe2Decrypt_RIJ128() +// +// +*/ + +#include "owncp.h" + +#if ((_IPP <_IPP_V8) && (_IPP32E <_IPP32E_U8)) /* no pshufb instruction */ + +#if (_ALG_AES_SAFE_==_ALG_AES_SAFE_COMPACT_SBOX_) + +#include "pcprij128safe2.h" +#include "pcprijtables.h" + + +#include "pcpbnuimpl.h" +#define SELECTION_BITS ((sizeof(BNU_CHUNK_T)/sizeof(Ipp8u)) -1) + +#if defined(__INTEL_COMPILER) +__INLINE Ipp8u getInvSboxValue(Ipp8u x) +{ + BNU_CHUNK_T selection = 0; + const BNU_CHUNK_T* SboxEntry = (BNU_CHUNK_T*)RijDecSbox; + + BNU_CHUNK_T i_sel = x/sizeof(BNU_CHUNK_T); /* selection index */ + BNU_CHUNK_T i; + for(i=0; i>= (x & SELECTION_BITS)*8; + return (Ipp8u)(selection & 0xFF); +} + +#else +#include "pcpmask_ct.h" +__INLINE Ipp8u getInvSboxValue(Ipp8u x) +{ + BNU_CHUNK_T selection = 0; + const BNU_CHUNK_T* SboxEntry = (BNU_CHUNK_T*)RijDecSbox; + + Ipp32u _x = x/sizeof(BNU_CHUNK_T); + Ipp32u i; + for(i=0; i>= (x & SELECTION_BITS)*8; + return (Ipp8u)(selection & 0xFF); +} +#endif + +__INLINE void invSubBytes(Ipp8u state[]) +{ + int i; + for(i=0;i<16;i++) + state[i] = getInvSboxValue(state[i]); +} + +__INLINE void invShiftRows(Ipp32u* state) +{ + state[1] = ROR32(state[1], 24); + state[2] = ROR32(state[2], 16); + state[3] = ROR32(state[3], 8); +} + +__INLINE void invMixColumns(Ipp32u* state) +{ + Ipp32u y0 = state[1] ^ state[2] ^ state[3]; + Ipp32u y1 = state[0] ^ state[2] ^ state[3]; + Ipp32u y2 = state[0] ^ state[1] ^ state[3]; + Ipp32u y3 = state[0] ^ state[1] ^ state[2]; + Ipp32u t02, t13, t0123; + + state[0] = xtime4(state[0]); + state[1] = xtime4(state[1]); + state[2] = xtime4(state[2]); + state[3] = xtime4(state[3]); + + y0 ^= state[0] ^ state[1]; + y1 ^= state[1] ^ state[2]; + y2 ^= state[2] ^ state[3]; + y3 ^= state[3] ^ state[0]; + + t02 = state[0] ^ state[2]; + t13 = state[1] ^ state[3]; + t02 = xtime4(t02); + t13 = xtime4(t13); + + t0123 = t02^t13; + t0123 = xtime4(t0123); + + state[0] = y0 ^t02 ^t0123; + state[1] = y1 ^t13 ^t0123; + state[2] = y2 ^t02 ^t0123; + state[3] = y3 ^t13 ^t0123; +} + + +IPP_OWN_DEFN (void, Safe2Decrypt_RIJ128, (const Ipp8u* in, Ipp8u* out, int Nr, const Ipp8u* RoundKey, const void* sbox)) +{ + Ipp32u state[4]; + + int round=0; + + IPP_UNREFERENCED_PARAMETER(sbox); + + // copy input to the state array + TRANSPOSE((Ipp8u*)state, in); + + // add the round key to the state before starting the rounds. + XorRoundKey((Ipp32u*)state, (Ipp32u*)(RoundKey+Nr*16)); + + // there will be Nr rounds + for(round=Nr-1;round>0;round--) { + invShiftRows(state); + invSubBytes((Ipp8u*)state); + XorRoundKey(state,(Ipp32u*)(RoundKey+round*16)); + invMixColumns(state); + } + + // last round + invShiftRows(state); + invSubBytes((Ipp8u*)state); + XorRoundKey(state,(Ipp32u*)(RoundKey+0*16)); + + // copy from the state to output + TRANSPOSE(out, (Ipp8u*)state); +} +#endif /* _ALG_AES_SAFE_COMPACT_SBOX_ */ + +#endif /* (_IPP <_IPP_V8) && (_IPP32E <_IPP32E_U8) */ diff --git a/pool/shard000/C/0014080_ecalib.c b/pool/shard000/C/0014080_ecalib.c new file mode 100644 index 0000000000000000000000000000000000000000..32d310fd97760f0246f4d1643de136462a3bac12 --- /dev/null +++ b/pool/shard000/C/0014080_ecalib.c @@ -0,0 +1,252 @@ +/* Copyright 2013-2015. The Regents of the University of California. + * Copyright 2015-2021. Martin Uecker. + * All rights reserved. Use of this source code is governed by + * a BSD-style license which can be found in the LICENSE file. + * + * Authors: + * 2012-2021 Martin Uecker + * 2013 Dara Bahri + * 2015 Siddharth Iyer + */ + +#include +#include +#include +#include + +#include "misc/mmio.h" +#include "misc/mri.h" +#include "misc/misc.h" +#include "misc/debug.h" +#include "misc/opts.h" + +#include "num/multind.h" +#include "num/fft.h" +#include "num/init.h" + +#include "calib/calib.h" +#include "calib/estvar.h" + +#ifndef CFL_SIZE +#define CFL_SIZE sizeof(complex float) +#endif + + + +static const char help_str[] = + "Estimate coil sensitivities using ESPIRiT calibration.\n" + "Optionally outputs the eigenvalue maps."; + + + + + +int main_ecalib(int argc, char* argv[argc]) +{ + const char* in_file = NULL; + const char* out_file = NULL; + const char* emaps_file = NULL; + + struct arg_s args[] = { + + ARG_INFILE(true, &in_file, "kspace"), + ARG_OUTFILE(true, &out_file, "sensitivities"), + ARG_OUTFILE(false, &emaps_file, "ev-maps"), + }; + + long calsize[3] = { 24, 24, 24 }; + int maps = 2; + bool one = false; + bool calcen = false; + bool print_svals = false; + + struct ecalib_conf conf = ecalib_defaults; + + const struct opt_s opts[] = { + + OPT_FLOAT('t', &conf.threshold, "threshold", "This determined the size of the null-space."), + OPT_FLOAT('c', &conf.crop, "crop_value", "Crop the sensitivities if the eigenvalue is smaller than {crop_value}."), + OPT_VEC3('k', &conf.kdims, "ksize", "kernel size"), + OPT_VEC3('K', &conf.kdims, "", "()"), + OPT_VEC3('r', &calsize, "cal_size", "Limits the size of the calibration region."), + OPT_VEC3('R', &calsize, "", "()"), + OPT_INT('m', &maps, "maps", "Number of maps to compute."), + OPT_SET('S', &conf.softcrop, "create maps with smooth transitions (Soft-SENSE)."), + OPT_SET('W', &conf.weighting, "soft-weighting of the singular vectors."), + OPT_SET('I', &conf.intensity, "intensity correction"), + OPT_SET('1', &one, "perform only first part of the calibration"), + OPT_CLEAR('P', &conf.rotphase, "Do not rotate the phase with respect to the first principal component"), + OPT_CLEAR('O', &conf.orthiter, "()"), + OPT_FLOAT('b', &conf.perturb, "", "()"), + OPT_SET('V', &print_svals, "()"), + OPT_SET('C', &calcen, "()"), + OPT_SET('g', &conf.usegpu, "()"), + OPT_FLOAT('p', &conf.percentsv, "", "()"), + OPT_INT('n', &conf.numsv, "", "()"), + OPT_FLOAT('v', &conf.var, "variance", "Variance of noise in data."), + OPT_SET('a', &conf.automate, "Automatically pick thresholds."), + OPT_INT('d', &debug_level, "level", "Debug level"), + }; + + cmdline(&argc, argv, ARRAY_SIZE(args), args, help_str, ARRAY_SIZE(opts), opts); + + if (-1. != conf.percentsv) + conf.threshold = -1.; + + if (-1 != conf.numsv) + conf.threshold = -1.; + + if (conf.automate) { + + conf.crop = -1.; + conf.weighting = true; + } + + if (conf.weighting) { + + conf.numsv = -1.; + conf.threshold = 0; + conf.percentsv = -1.; + conf.orthiter = false; + } + + int N = DIMS; + long ksp_dims[N]; + + complex float* in_data = load_cfl(in_file, N, ksp_dims); + + + // assert((kdims[0] < calsize_ro) && (kdims[1] < calsize_ro) && (kdims[2] < calsize_ro)); + // assert((ksp_dims[0] == 1) || (calsize_ro < ksp_dims[0])); + if (1 != ksp_dims[MAPS_DIM]) + error("MAPS dimension is not of size one.\n"); + + + long cal_dims[N]; + complex float* cal_data = NULL; + + if (!calcen) { + +#ifdef USE_CC_EXTRACT_CALIB + cal_data = cc_extract_calib(cal_dims, calsize, ksp_dims, in_data); +#else + cal_data = extract_calib(cal_dims, calsize, ksp_dims, in_data, false); +#endif + } else { + + for (int i = 0; i < 3; i++) + cal_dims[i] = (calsize[i] < ksp_dims[i]) ? calsize[i] : ksp_dims[i]; + + for (int i = 3; i < N; i++) + cal_dims[i] = ksp_dims[i]; + + cal_data = md_alloc(5, cal_dims, CFL_SIZE); + + md_resize_center(5, cal_dims, cal_data, ksp_dims, in_data, CFL_SIZE); + } + + + + for (int i = 0; i < 3; i++) + if (1 == ksp_dims[i]) + conf.kdims[i] = 1; + + + long channels = cal_dims[3]; + int K = conf.kdims[0] * conf.kdims[1] * conf.kdims[2] * channels; + + float svals[K]; + + for (int i = 0; i < 3; i++) + if ((1 == cal_dims[i]) && (1 != ksp_dims[i])) + error("Calibration region not found!\n"); + + + // To reproduce old results turn off rotation of phase. + // conf.rotphase = false; + + + // FIXME: we should scale the data + + (conf.usegpu ? num_init_gpu : num_init)(); + + if ((conf.var < 0.) && (conf.weighting || (conf.crop < 0.))) { + + const char* toolbox = getenv("TOOLBOX_PATH"); + + conf.var = estvar_calreg(toolbox, conf.kdims, cal_dims, cal_data); + } + + if (one) { + +#if 0 + long maps = out_dims[4]; + + assert(caldims[3] == out_dims[3]); + assert(maps <= channels); +#endif + long cov_dims[4]; + + calone_dims(&conf, cov_dims, channels); + complex float* imgcov = md_alloc(4, cov_dims, CFL_SIZE); + + + calone(&conf, cov_dims, imgcov, K, svals, cal_dims, cal_data); + + complex float* out = create_cfl(out_file, 4, cov_dims); + md_copy(4, cov_dims, out, imgcov, CFL_SIZE); + unmap_cfl(4, cov_dims, out); + +// caltwo(crthr, out_dims, out_data, emaps, cov_dims, imgcov, NULL, NULL); + + md_free(imgcov); + + } else { + + long out_dims[N]; + long map_dims[N]; + + for (int i = 0; i < N; i++) { + + out_dims[i] = 1; + map_dims[i] = 1; + + if ((i < 3) && (1 < conf.kdims[i])) { + + out_dims[i] = ksp_dims[i]; + map_dims[i] = ksp_dims[i]; + } + } + + + assert(maps <= ksp_dims[COIL_DIM]); + + + out_dims[COIL_DIM] = ksp_dims[COIL_DIM]; + out_dims[MAPS_DIM] = maps; + map_dims[COIL_DIM] = 1; + map_dims[MAPS_DIM] = maps; + + complex float* out_data = create_cfl(out_file, N, out_dims); + complex float* emaps = (emaps_file ? create_cfl : anon_cfl)(emaps_file, N, map_dims); + + calib(&conf, out_dims, out_data, emaps, K, svals, cal_dims, cal_data); + + unmap_cfl(N, out_dims, out_data); + unmap_cfl(N, map_dims, emaps); + } + + + if (print_svals) + for (int i = 0; i < K; i++) + printf("SVALS %d %f\n", i, svals[i]); + + printf("Done.\n"); + + unmap_cfl(N, ksp_dims, in_data); + md_free(cal_data); + + return 0; +} + + diff --git a/pool/shard000/C/0014094_fifoq.c b/pool/shard000/C/0014094_fifoq.c new file mode 100644 index 0000000000000000000000000000000000000000..7c7f2d89e06334c2d9ad4c44c39e88dc78927444 --- /dev/null +++ b/pool/shard000/C/0014094_fifoq.c @@ -0,0 +1,176 @@ +/* + * $Id$ + * + * Copyright (c) 2011 NLNet Labs. 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 THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. + * + */ + +/** + * FIFO Queue. + * + */ + +#include "config.h" +#include "scheduler/fifoq.h" +#include "shared/log.h" + +#include + +static const char* fifoq_str = "fifo"; + + +/** + * Create new FIFO queue. + * + */ +fifoq_type* +fifoq_create(allocator_type* allocator) +{ + fifoq_type* fifoq; + if (!allocator) { + return NULL; + } + fifoq = (fifoq_type*) allocator_alloc(allocator, sizeof(fifoq_type)); + if (!fifoq) { + ods_log_error("[%s] unable to create fifoq: allocator_alloc() failed", + fifoq_str); + return NULL; + } + fifoq->allocator = allocator; + fifoq_wipe(fifoq); + lock_basic_init(&fifoq->q_lock); + lock_basic_set(&fifoq->q_threshold); + lock_basic_set(&fifoq->q_nonfull); + return fifoq; +} + + +/** + * Wipe queue. + * + */ +void +fifoq_wipe(fifoq_type* q) +{ + size_t i = 0; + for (i=0; i < FIFOQ_MAX_COUNT; i++) { + q->blob[i] = NULL; + q->owner[i] = NULL; + } + q->count = 0; + return; +} + + +/** + * Pop item from queue. + * + */ +void* +fifoq_pop(fifoq_type* q, worker_type** worker) +{ + void* pop = NULL; + size_t i = 0; + if (!q || q->count <= 0) { + return NULL; + } + pop = q->blob[0]; + *worker = q->owner[0]; + for (i = 0; i < q->count-1; i++) { + q->blob[i] = q->blob[i+1]; + q->owner[i] = q->owner[i+1]; + } + q->count -= 1; + if (q->count <= (size_t) FIFOQ_MAX_COUNT * 0.1) { + /** + * Notify waiting workers that they can start queuing again + * If no workers are waiting, this call has no effect. + */ + lock_basic_broadcast(&q->q_nonfull); + } + return pop; +} + + +/** + * Push item to queue. + * + */ +ods_status +fifoq_push(fifoq_type* q, void* item, worker_type* worker, int* tries) +{ + if (!q || !item || !worker) { + return ODS_STATUS_ASSERT_ERR; + } + if (q->count >= FIFOQ_MAX_COUNT) { + /** + * #262: + * If drudgers remain on hold, do additional broadcast. + * If no drudgers are waiting, this call has no effect. + */ + if (*tries > FIFOQ_TRIES_COUNT) { + lock_basic_broadcast(&q->q_threshold); + ods_log_debug("[%s] queue full, notify drudgers again", fifoq_str); + /* reset tries */ + *tries = 0; + } + return ODS_STATUS_UNCHANGED; + } + q->blob[q->count] = item; + q->owner[q->count] = worker; + q->count += 1; + if (q->count == 1) { + ods_log_deeebug("[%s] threshold %u reached, notify drudgers", + fifoq_str, q->count); + /* If no drudgers are waiting, this call has no effect. */ + lock_basic_broadcast(&q->q_threshold); + } + return ODS_STATUS_OK; +} + + +/** + * Clean up queue. + * + */ +void +fifoq_cleanup(fifoq_type* q) +{ + allocator_type* allocator; + lock_basic_type q_lock; + cond_basic_type q_threshold; + cond_basic_type q_nonfull; + if (!q) { + return; + } + allocator = q->allocator; + q_lock = q->q_lock; + q_threshold = q->q_threshold; + q_nonfull = q->q_nonfull; + allocator_deallocate(allocator, (void*) q); + lock_basic_off(&q_threshold); + lock_basic_off(&q_nonfull); + lock_basic_destroy(&q_lock); + return; +} diff --git a/pool/shard000/C/0014099_packet-icp.c b/pool/shard000/C/0014099_packet-icp.c new file mode 100644 index 0000000000000000000000000000000000000000..63ef66e08bd613af459886b05679b30b9ad68fc9 --- /dev/null +++ b/pool/shard000/C/0014099_packet-icp.c @@ -0,0 +1,245 @@ +/* packet-icp.c + * Routines for ICP (internet cache protocol) packet disassembly + * RFC 2186 && RFC 2187 + * By Peter Torvals + * Copyright 1999 Peter Torvals + * + * $Id: packet-icp.c 49920 2013-06-14 01:02:11Z mmann $ + * + * Wireshark - Network traffic analyzer + * By Gerald Combs + * Copyright 1998 + * + * 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. + */ + +#define MAX_TEXTBUF_LENGTH 600 +#include "config.h" + +#include + +#include +#include + +static int proto_icp=-1; +static int hf_icp_length=-1; +static int hf_icp_opcode=-1; +static int hf_icp_version=-1; +static int hf_icp_request_nr=-1; + +static gint ett_icp = -1; +static gint ett_icp_payload = -1; + +#define UDP_PORT_ICP 3130 + +#define CODE_ICP_OP_QUERY 1 +#define CODE_ICP_OP_INVALID 0 +#define CODE_ICP_OP_HIT 2 +#define CODE_ICP_OP_MISS 3 +#define CODE_ICP_OP_ERR 4 +#define CODE_ICP_OP_SEND 5 +#define CODE_ICP_OP_SENDA 6 +#define CODE_ICP_OP_DATABEG 7 +#define CODE_ICP_OP_DATA 8 +#define CODE_ICP_OP_DATAEND 9 +#define CODE_ICP_OP_SECHO 10 +#define CODE_ICP_OP_DECHO 11 +#define CODE_ICP_OP_MISS_NOFETCH 21 +#define CODE_ICP_OP_DENIED 22 +#define CODE_ICP_OP_HIT_OBJ 23 + +static const value_string opcode_vals[] = { +{ CODE_ICP_OP_INVALID , "ICP_INVALID" }, +{ CODE_ICP_OP_QUERY , "ICP_QUERY" }, +{ CODE_ICP_OP_HIT , "ICP_HIT" }, +{ CODE_ICP_OP_MISS , "ICP_MISS" }, +{ CODE_ICP_OP_ERR , "ICP_ERR" }, +{ CODE_ICP_OP_SEND, "ICP_SEND" }, +{ CODE_ICP_OP_SENDA, "ICP_SENDA"}, +{ CODE_ICP_OP_DATABEG, "ICP_DATABEG"}, +{ CODE_ICP_OP_DATA, "ICP_DATA"}, +{ CODE_ICP_OP_DATAEND, "ICP_DATA_END"}, +{ CODE_ICP_OP_SECHO , "ICP_SECHO"}, +{ CODE_ICP_OP_DECHO , "ICP_DECHO"}, +{ CODE_ICP_OP_MISS_NOFETCH , "ICP_MISS_NOFETCH"}, +{ CODE_ICP_OP_DENIED , "ICP_DENIED"}, +{ CODE_ICP_OP_HIT_OBJ , "ICP_HIT_OBJ"}, +{ 0, NULL} +}; + +static void dissect_icp_payload(tvbuff_t *tvb, int offset, + proto_tree *pload_tree, guint8 opcode) +{ + gint stringlength; + guint16 objectlength; + + switch(opcode) + { + case CODE_ICP_OP_QUERY: + /* 4 byte requester host address */ + proto_tree_add_text(pload_tree, tvb,offset,4, + "Requester Host Address %s", + tvb_ip_to_str(tvb, offset)); + offset += 4; + + /* null terminated URL */ + stringlength = tvb_strsize(tvb, offset); + proto_tree_add_text(pload_tree, tvb, offset, stringlength, + "URL: %s", tvb_get_ephemeral_string(tvb, offset, stringlength)); + break; + + case CODE_ICP_OP_SECHO: + case CODE_ICP_OP_DECHO: + case CODE_ICP_OP_HIT: + case CODE_ICP_OP_MISS: + case CODE_ICP_OP_ERR: + case CODE_ICP_OP_MISS_NOFETCH: + case CODE_ICP_OP_DENIED: + stringlength = tvb_strsize(tvb, offset); + proto_tree_add_text(pload_tree, tvb, offset, stringlength, + "URL: %s", tvb_get_ephemeral_string(tvb, offset, stringlength)); + break; + + case CODE_ICP_OP_HIT_OBJ: + /* null terminated URL */ + stringlength = tvb_strsize(tvb, offset); + proto_tree_add_text(pload_tree, tvb, offset, stringlength, + "URL: %s", tvb_get_ephemeral_string(tvb, offset, stringlength)); + offset += stringlength; + + /* 2 byte object size */ + /* object data not recommended by standard*/ + objectlength=tvb_get_ntohs(tvb, offset); + proto_tree_add_text(pload_tree, tvb,offset,2,"Object length: %u", objectlength); + offset += 2; + + /* object data not recommended by standard*/ + proto_tree_add_text(pload_tree, tvb,offset,objectlength,"Object data"); + if (objectlength > tvb_reported_length_remaining(tvb, offset)) + { + proto_tree_add_text(pload_tree, tvb,offset,0, + "Packet is fragmented, rest of object is in next udp packet"); + } + break; + default: + break; + } +} + +static void dissect_icp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree) +{ + proto_tree *icp_tree , *payload_tree; + proto_item *ti , *payloadtf; + guint8 opcode; + guint16 message_length; + guint32 request_number; + guint32 options; + guint32 option_data; + + col_set_str(pinfo->cinfo, COL_PROTOCOL, "ICP"); + col_clear(pinfo->cinfo, COL_INFO); + + opcode=tvb_get_guint8(tvb, 0); + message_length=tvb_get_ntohs(tvb, 2); + request_number=tvb_get_ntohl(tvb, 4); + + col_add_fstr(pinfo->cinfo,COL_INFO,"Opcode: %s (%u), Req Nr: %u", + val_to_str_const(opcode, opcode_vals, "Unknown"), opcode, + request_number); + + if (tree) + { + + ti = proto_tree_add_item(tree,proto_icp, tvb, 0, message_length, ENC_NA); + icp_tree = proto_item_add_subtree(ti, ett_icp); + + proto_tree_add_uint(icp_tree,hf_icp_opcode, tvb, 0, 1, opcode); + + proto_tree_add_item(icp_tree,hf_icp_version, tvb, 1, 1, ENC_BIG_ENDIAN); + + proto_tree_add_uint(icp_tree,hf_icp_length, tvb, 2, 2, message_length); + + proto_tree_add_uint(icp_tree,hf_icp_request_nr, tvb, 4, 4, + request_number); + + options=tvb_get_ntohl(tvb, 8); + if ( (opcode == CODE_ICP_OP_QUERY) && ((options & 0x80000000 ) != 0) ) + { + proto_tree_add_text(icp_tree, tvb,8,4, + "option: ICP_FLAG_HIT_OBJ"); + } + if ( (opcode == CODE_ICP_OP_QUERY)&& ((options & 0x40000000 ) != 0) ) + { + proto_tree_add_text(icp_tree, tvb,8,4, + "option:ICP_FLAG_SRC_RTT"); + } + if ((opcode != CODE_ICP_OP_QUERY)&& ((options & 0x40000000 ) != 0)) + { + option_data=tvb_get_ntohl(tvb, 12); + proto_tree_add_text(icp_tree, tvb,8,8, + "option: ICP_FLAG_SCR_RTT RTT=%u", + option_data & 0x0000ffff); + } + + proto_tree_add_text(icp_tree, tvb, 16, 4, + "Sender Host IP address %s", + tvb_ip_to_str(tvb, 16)); + + payloadtf = proto_tree_add_text(icp_tree, tvb, + 20, message_length - 20, + "Payload"); + payload_tree = proto_item_add_subtree(payloadtf, ett_icp_payload); + dissect_icp_payload(tvb, 20, payload_tree, opcode); + } +} +void +proto_register_icp(void) +{ + static hf_register_info hf[] = { + { &hf_icp_opcode, + { "Opcode", "icp.opcode", FT_UINT8, BASE_HEX, VALS(opcode_vals), + 0x0, NULL, HFILL }}, + + { &hf_icp_version, + { "Version", "icp.version", FT_UINT8, BASE_DEC, NULL, + 0x0, NULL, HFILL }}, + + { &hf_icp_length, + { "Length", "icp.length", FT_UINT16, BASE_DEC, NULL, + 0x0, NULL, HFILL }}, + + { &hf_icp_request_nr, + { "Request Number", "icp.nr", FT_UINT32, BASE_DEC, NULL, + 0x0, NULL, HFILL }}, + }; + static gint *ett[] = { + &ett_icp, + &ett_icp_payload, + }; + + proto_icp = proto_register_protocol("Internet Cache Protocol", + "ICP", "icp"); + proto_register_field_array(proto_icp, hf, array_length(hf)); + proto_register_subtree_array(ett, array_length(ett)); +} + +void +proto_reg_handoff_icp(void) +{ + dissector_handle_t icp_handle; + + icp_handle = create_dissector_handle(dissect_icp, proto_icp); + dissector_add_uint("udp.port", UDP_PORT_ICP, icp_handle); +} diff --git a/pool/shard000/C/0014114_redirect.c b/pool/shard000/C/0014114_redirect.c new file mode 100644 index 0000000000000000000000000000000000000000..f9de297ca14f20cd261e446ee68370cb93cad7db --- /dev/null +++ b/pool/shard000/C/0014114_redirect.c @@ -0,0 +1,265 @@ +/************************************************************************** + * + * Copyright (c) 2013 Alcatel-Lucent + * + * Alcatel Lucent 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. A copy of the License is contained the + * file LICENSE at the top level of this repository. + * You may also 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. + * + ************************************************************************** + * + * redirect: + * + * This code supports the monitor's ability to redirect what was destined for + * the console to a block of memory in RAM. Enough data is maintained so + * that the block of memory can be transferred to a file using tfsadd(). + * + * Description of redirection CLI syntax: + * > buffer_addr,buffer_size[,filename] + * >> [filename] + * + * - Single arrow starts up a redirection to some specified block of memory + * with a specified size. If the filename is specified, then the output + * of that single command is redirected to the buffer then transferred to + * the specified file in TFS. Any previously existent file of the same + * name is overwritten. + * + * - Double arrow with no argument says append output of this command to + * the previously established buffer. + * + * - Double arrow with an argument says append output of this command to + * the previously established buffer and then write that buffer to the + * specified filename. Once again, any previously existent file of the + * same name is overwritten. + * + * Original author: Ed Sutter (ed.sutter@alcatel-lucent.com) + * + */ +#include "config.h" +#include "genlib.h" +#include "stddefs.h" +#include +#include "tfs.h" +#include "tfsprivate.h" + +#if INCLUDE_REDIRECT + +/* Redirect states: + * ACTIVE: the current command has issued some redirection, so + * when RedirectCharacter() is called, it should copy the + * character to the redirect buffer. + * IDLE: the current command has not issued any redirection, so + * when RedirectCharacter() is called, it simply returns. + * UNINITIALIZED: the first call to >base,size[,file] has not been + * made so we don't have a buffer; hence we can't redirect anything. + */ +#define REDIRECT_UNINITIALIZED 0 +#define REDIRECT_ACTIVE 0x12345678 +#define REDIRECT_IDLE 0x87654321 + +static int RedirectSize, RedirectState; +static char *RedirectBase, *RedirectPtr, *RedirectEnd; +static char RedirectFile[TFSNAMESIZE]; + +/* getEnvVal(): + * This function is used under the context of the redirection code + * because of the fact that the docommand() function processes the + * redirection arrow prior to converting shell variables. + * This is important because we want to support the ability to do + * something like... + * + * echo hello >$APPRAMBASE,100 + * + * but we also want to allow a shell variable to contain a right + * arrow that is NOT processed by this redirection code. + */ +static ulong +getEnvVal(char *ptr) +{ +#if INCLUDE_SHELLVARS + char *v; + + /* If the incoming string starts with a '$', then retrieve the + * value and then convert that to a long; otherwise, just convert + * the string to a long immediately. + */ + if (*ptr == '$') { + v = shellsym_chk(*ptr,ptr+1,0,0,0); + if (!v) + return(0); + } + else + v = ptr; + return(strtoul(v,0,0)); +#else + return(0); +#endif +} + +int +RedirectionCheck(char *cmdcpy) +{ + int inquote; + char *arrow, *base, *comma, *space; + + base = cmdcpy; + arrow = (char *)0; + + /* Parse the incoming command line looking for a right arrow. + * This parsing assumes that there will be no negated arrows + * (preceding backslash) after a non-negated arrow is detected. + * Note that a redirection arrow within a double-quote set is + * ignored. This allows a shell variable that contains a right arrow + * to be printed properly if put in double quotes. + * For example... + * set PROMPT "maint> " + * echo $PROMPT # This will generate a redirection syntax error + * echo "$PROMPT" # This won't. + */ + inquote = 0; + while(*cmdcpy) { + if ((*cmdcpy == '"') && ((cmdcpy == base) || (*(cmdcpy-1) != '\\'))) { + inquote = inquote == 1 ? 0 : 1; + cmdcpy++; + continue; + } + if (inquote == 1) { + cmdcpy++; + continue; + } + if (*cmdcpy == '>') { + arrow = cmdcpy; + if (*(arrow-1) == '\\') { + strcpy(arrow-1,arrow); + cmdcpy = arrow+1; + arrow = (char *)0; + continue; + } + break; + } + cmdcpy++; + } + if (arrow == (char *)0) + return(0); + + /* Remove the remaining text from the command line because it is to + * be used only by the redirection mechanism. + */ + *arrow = 0; + + /* Now parse the text after the first non-negated arrow. */ + if (*(arrow+1) == '>') { + if (RedirectState == REDIRECT_UNINITIALIZED) { + printf("Redirection not initialized\n"); + return(-1); + } + arrow += 2; + while(isspace(*arrow)) + arrow++; + if (*arrow != 0) { + strncpy(RedirectFile,*arrow == '$' ? getenv(arrow+1) : arrow, + TFSNAMESIZE); + } + } + else { + RedirectPtr = RedirectBase = (char *)getEnvVal(arrow+1); + comma = strchr(arrow+1,','); + if (comma) { + RedirectSize = (int)getEnvVal(comma+1); + comma = strchr(comma+1,','); + if (RedirectSize <= 0) { + printf("Redirection size error: %d\n",RedirectSize); + return(-1); + } + RedirectEnd = RedirectBase + RedirectSize; + if (comma) { + space = strpbrk(comma," \t\r\n"); + if (space) + *space = 0; + if (*(comma+1) == '$') { + if (getenv(comma+2)) + strncpy(RedirectFile,getenv(comma+2),TFSNAMESIZE); + else + RedirectFile[0] = 0; + } + else + strncpy(RedirectFile,comma+1,TFSNAMESIZE); + } + else + RedirectFile[0] = 0; + } + else { + printf("Redirection syntax error\n"); + return(-1); + } + } + RedirectState = REDIRECT_ACTIVE; + return(0); +} + +/* RedirectCmdDone(): + * As each command completes, this redirection mechanism must be notified. + * When this function is called (by docmd() after the command function has + * completed), if the RedirectFile[] array is populated, it transfers the + * buffer to the specified file; if the array is empty, then no TFS action + * is taken. + * The file specified in RedirectFile[] may have additional commas in it. + * They allow the filename to contain flags and info field. + */ +void +RedirectionCmdDone(void) +{ + + if (RedirectState != REDIRECT_UNINITIALIZED) { + RedirectState = REDIRECT_IDLE; + if (RedirectFile[0]) { + char *comma, *info, *flags; + + comma = info = flags = (char *)0; + comma = strchr(RedirectFile,','); + if (comma) { + *comma = 0; + flags = comma+1; + comma = strchr(flags,','); + if (comma) { + *comma = 0; + info = comma+1; + } + } + tfsadd(RedirectFile,info,flags,(uchar *)RedirectBase, + (int)(RedirectPtr-RedirectBase)); + RedirectFile[0] = 0; + RedirectPtr = RedirectBase; + } + } +} + +/* RedirectCharacter(): + * This function is called from putchar() in chario.c. It simply + * copies the incoming character to the redirection buffer. + */ +void +RedirectCharacter(char c) +{ + if (RedirectState == REDIRECT_ACTIVE) { + if (RedirectPtr < RedirectEnd) + *RedirectPtr++ = c; + } +} +#else +int +RedirectionCheck(char *cmdcpy) +{ + return(0); +} +#endif diff --git a/pool/shard000/C/0014116_cpuidle44xx.c b/pool/shard000/C/0014116_cpuidle44xx.c new file mode 100644 index 0000000000000000000000000000000000000000..c443f2e97e103702531c79b70dccebc11a85218d --- /dev/null +++ b/pool/shard000/C/0014116_cpuidle44xx.c @@ -0,0 +1,217 @@ +/* + * OMAP4+ CPU idle Routines + * + * Copyright (C) 2011-2013 Texas Instruments, Inc. + * Santosh Shilimkar + * Rajendra Nayak + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + */ + +#include +#include +#include +#include + +#include +#include + +#include "common.h" +#include "pm.h" +#include "prm.h" +#include "clockdomain.h" + +/* Machine specific information */ +struct idle_statedata { + u32 cpu_state; + u32 mpu_logic_state; + u32 mpu_state; +}; + +static struct idle_statedata omap4_idle_data[] = { + { + .cpu_state = PWRDM_POWER_ON, + .mpu_state = PWRDM_POWER_ON, + .mpu_logic_state = PWRDM_POWER_RET, + }, + { + .cpu_state = PWRDM_POWER_OFF, + .mpu_state = PWRDM_POWER_RET, + .mpu_logic_state = PWRDM_POWER_RET, + }, + { + .cpu_state = PWRDM_POWER_OFF, + .mpu_state = PWRDM_POWER_RET, + .mpu_logic_state = PWRDM_POWER_OFF, + }, +}; + +static struct powerdomain *mpu_pd, *cpu_pd[NR_CPUS]; +static struct clockdomain *cpu_clkdm[NR_CPUS]; + +static atomic_t abort_barrier; +static bool cpu_done[NR_CPUS]; +static struct idle_statedata *state_ptr = &omap4_idle_data[0]; + +/* Private functions */ + +/** + * omap_enter_idle_[simple/coupled] - OMAP4PLUS cpuidle entry functions + * @dev: cpuidle device + * @drv: cpuidle driver + * @index: the index of state to be entered + * + * Called from the CPUidle framework to program the device to the + * specified low power state selected by the governor. + * Returns the amount of time spent in the low power state. + */ +static int omap_enter_idle_simple(struct cpuidle_device *dev, + struct cpuidle_driver *drv, + int index) +{ + omap_do_wfi(); + return index; +} + +static int omap_enter_idle_coupled(struct cpuidle_device *dev, + struct cpuidle_driver *drv, + int index) +{ + struct idle_statedata *cx = state_ptr + index; + + /* + * CPU0 has to wait and stay ON until CPU1 is OFF state. + * This is necessary to honour hardware recommondation + * of triggeing all the possible low power modes once CPU1 is + * out of coherency and in OFF mode. + */ + if (dev->cpu == 0 && cpumask_test_cpu(1, cpu_online_mask)) { + while (pwrdm_read_pwrst(cpu_pd[1]) != PWRDM_POWER_OFF) { + cpu_relax(); + + /* + * CPU1 could have already entered & exited idle + * without hitting off because of a wakeup + * or a failed attempt to hit off mode. Check for + * that here, otherwise we could spin forever + * waiting for CPU1 off. + */ + if (cpu_done[1]) + goto fail; + + } + } + + /* + * Call idle CPU PM enter notifier chain so that + * VFP and per CPU interrupt context is saved. + */ + cpu_pm_enter(); + + if (dev->cpu == 0) { + pwrdm_set_logic_retst(mpu_pd, cx->mpu_logic_state); + omap_set_pwrdm_state(mpu_pd, cx->mpu_state); + + /* + * Call idle CPU cluster PM enter notifier chain + * to save GIC and wakeupgen context. + */ + if ((cx->mpu_state == PWRDM_POWER_RET) && + (cx->mpu_logic_state == PWRDM_POWER_OFF)) + cpu_cluster_pm_enter(); + } + + omap4_enter_lowpower(dev->cpu, cx->cpu_state); + cpu_done[dev->cpu] = true; + + /* Wakeup CPU1 only if it is not offlined */ + if (dev->cpu == 0 && cpumask_test_cpu(1, cpu_online_mask)) { + clkdm_wakeup(cpu_clkdm[1]); + omap_set_pwrdm_state(cpu_pd[1], PWRDM_POWER_ON); + clkdm_allow_idle(cpu_clkdm[1]); + } + + /* + * Call idle CPU PM exit notifier chain to restore + * VFP and per CPU IRQ context. + */ + cpu_pm_exit(); + + /* + * Call idle CPU cluster PM exit notifier chain + * to restore GIC and wakeupgen context. + */ + if ((cx->mpu_state == PWRDM_POWER_RET) && + (cx->mpu_logic_state == PWRDM_POWER_OFF)) + cpu_cluster_pm_exit(); + +fail: + cpuidle_coupled_parallel_barrier(dev, &abort_barrier); + cpu_done[dev->cpu] = false; + + return index; +} + +static struct cpuidle_driver omap4_idle_driver = { + .name = "omap4_idle", + .owner = THIS_MODULE, + .states = { + { + /* C1 - CPU0 ON + CPU1 ON + MPU ON */ + .exit_latency = 2 + 2, + .target_residency = 5, + .flags = CPUIDLE_FLAG_TIME_VALID, + .enter = omap_enter_idle_simple, + .name = "C1", + .desc = "CPUx ON, MPUSS ON" + }, + { + /* C2 - CPU0 OFF + CPU1 OFF + MPU CSWR */ + .exit_latency = 328 + 440, + .target_residency = 960, + .flags = CPUIDLE_FLAG_TIME_VALID | CPUIDLE_FLAG_COUPLED | + CPUIDLE_FLAG_TIMER_STOP, + .enter = omap_enter_idle_coupled, + .name = "C2", + .desc = "CPUx OFF, MPUSS CSWR", + }, + { + /* C3 - CPU0 OFF + CPU1 OFF + MPU OSWR */ + .exit_latency = 460 + 518, + .target_residency = 1100, + .flags = CPUIDLE_FLAG_TIME_VALID | CPUIDLE_FLAG_COUPLED | + CPUIDLE_FLAG_TIMER_STOP, + .enter = omap_enter_idle_coupled, + .name = "C3", + .desc = "CPUx OFF, MPUSS OSWR", + }, + }, + .state_count = ARRAY_SIZE(omap4_idle_data), + .safe_state_index = 0, +}; + +/* Public functions */ + +/** + * omap4_idle_init - Init routine for OMAP4+ idle + * + * Registers the OMAP4+ specific cpuidle driver to the cpuidle + * framework with the valid set of states. + */ +int __init omap4_idle_init(void) +{ + mpu_pd = pwrdm_lookup("mpu_pwrdm"); + cpu_pd[0] = pwrdm_lookup("cpu0_pwrdm"); + cpu_pd[1] = pwrdm_lookup("cpu1_pwrdm"); + if ((!mpu_pd) || (!cpu_pd[0]) || (!cpu_pd[1])) + return -ENODEV; + + cpu_clkdm[0] = clkdm_lookup("mpu0_clkdm"); + cpu_clkdm[1] = clkdm_lookup("mpu1_clkdm"); + if (!cpu_clkdm[0] || !cpu_clkdm[1]) + return -ENODEV; + + return cpuidle_register(&omap4_idle_driver, cpu_online_mask); +} diff --git a/pool/shard000/C/0014117_CWE123_Write_What_Where_Condition__listen_socket_61a.c b/pool/shard000/C/0014117_CWE123_Write_What_Where_Condition__listen_socket_61a.c new file mode 100644 index 0000000000000000000000000000000000000000..06157328eab30305b1ada8cbb7c45ad552f5d8f9 --- /dev/null +++ b/pool/shard000/C/0014117_CWE123_Write_What_Where_Condition__listen_socket_61a.c @@ -0,0 +1,157 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE123_Write_What_Where_Condition__listen_socket_61a.c +Label Definition File: CWE123_Write_What_Where_Condition.label.xml +Template File: sources-sink-61a.tmpl.c +*/ +/* + * @description + * CWE: 123 Write-What-Where Condition + * BadSource: listen_socket Overwrite linked list pointers using a listen socket (server side) + * GoodSource: Don't overwrite linked list pointers + * Sinks: + * BadSink : Remove element from list + * Flow Variant: 61 Data flow: data returned from one function to another in different source files + * + * */ + +#include "std_testcase.h" + +typedef struct _linkedList +{ + struct _linkedList *next; + struct _linkedList *prev; +} linkedList; + +typedef struct _badStruct +{ + linkedList list; +} badStruct; + +static linkedList *linkedListPrev, *linkedListNext; + +#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 + +#ifndef OMITBAD + +/* bad function declaration */ +badStruct CWE123_Write_What_Where_Condition__listen_socket_61b_badSource(badStruct data); + +void CWE123_Write_What_Where_Condition__listen_socket_61_bad() +{ + badStruct data; + linkedList head = { &head, &head }; + /* This simulates a Microsoft-style linked list insertion */ + data.list.next = head.next; + data.list.prev = head.prev; + head.next = &data.list; + head.prev = &data.list; + data = CWE123_Write_What_Where_Condition__listen_socket_61b_badSource(data); + /* POTENTIAL FLAW: The following removes 'a' from the list. Because of the possible overflow this + * causes a "write-what-where" aka "write4". It does another write as + * well. But this is the prototypical "write-what-where" at least from + * the Windows perspective. + * + * linkedListPrev = a->list->prev WHAT + * linkedListNext = a->list->next WHERE + * linkedListPrev->next = linkedListNext "at the address that prev/WHERE points, write + * next/WHAT" + * aka "write-what-where" + * linkedListNext->prev = linkedListPrev "at the address that next/WHAT points plus 4 + * (because prev is the second field in 'list' hence + * 4 bytes away on 32b machines), write prev/WHERE" + */ + linkedListPrev = data.list.prev; + linkedListNext = data.list.next; + linkedListPrev->next = linkedListNext; + linkedListNext->prev = linkedListPrev; +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +badStruct CWE123_Write_What_Where_Condition__listen_socket_61b_goodG2BSource(badStruct data); + +static void goodG2B() +{ + badStruct data; + linkedList head = { &head, &head }; + /* This simulates a Microsoft-style linked list insertion */ + data.list.next = head.next; + data.list.prev = head.prev; + head.next = &data.list; + head.prev = &data.list; + data = CWE123_Write_What_Where_Condition__listen_socket_61b_goodG2BSource(data); + /* POTENTIAL FLAW: The following removes 'a' from the list. Because of the possible overflow this + * causes a "write-what-where" aka "write4". It does another write as + * well. But this is the prototypical "write-what-where" at least from + * the Windows perspective. + * + * linkedListPrev = a->list->prev WHAT + * linkedListNext = a->list->next WHERE + * linkedListPrev->next = linkedListNext "at the address that prev/WHERE points, write + * next/WHAT" + * aka "write-what-where" + * linkedListNext->prev = linkedListPrev "at the address that next/WHAT points plus 4 + * (because prev is the second field in 'list' hence + * 4 bytes away on 32b machines), write prev/WHERE" + */ + linkedListPrev = data.list.prev; + linkedListNext = data.list.next; + linkedListPrev->next = linkedListNext; + linkedListNext->prev = linkedListPrev; +} + +void CWE123_Write_What_Where_Condition__listen_socket_61_good() +{ + goodG2B(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + * its own for testing or for building a binary to use in testing binary + * analysis tools. It is not used when compiling all the testcases as one + * application, which is how source code analysis tools are tested. + */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE123_Write_What_Where_Condition__listen_socket_61_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE123_Write_What_Where_Condition__listen_socket_61_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard000/C/0014127_dmesg_log.c b/pool/shard000/C/0014127_dmesg_log.c new file mode 100644 index 0000000000000000000000000000000000000000..6b681c3737d628ea815883c89074354d3ad9f807 --- /dev/null +++ b/pool/shard000/C/0014127_dmesg_log.c @@ -0,0 +1,42 @@ +#include +#include +#include +#include +#include + +static int pk_write(struct file *file, const char *buffer, unsigned long count, void *data) +{ + char string[256]; + count = count < 255 ? count : 255; + + if(copy_from_user(string, buffer, count)) + return -EFAULT; + + string[count] = '\0'; + printk(string); + return count; +} + + +static int __init printk_init(void) +{ + struct proc_dir_entry *pk_file; + + pk_file = create_proc_entry("printk", 0222, NULL); + if(pk_file == NULL) + return -ENOMEM; + + pk_file->write_proc = pk_write; + pk_file->owner = THIS_MODULE; + + return 0; +} + +static void __exit printk_cleanup(void) +{ + remove_proc_entry("printk", NULL); +} + +module_init(printk_init); +module_exit(printk_cleanup); +MODULE_LICENSE("GPL"); \ No newline at end of file diff --git a/pool/shard000/C/0014142_dcb.c b/pool/shard000/C/0014142_dcb.c new file mode 100644 index 0000000000000000000000000000000000000000..2d9b9d7a7992111cc1d4bd0ff3e60254bf52dcb5 --- /dev/null +++ b/pool/shard000/C/0014142_dcb.c @@ -0,0 +1,204 @@ +/* + * Copyright 2012 Red Hat Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) 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. + * + * Authors: Ben Skeggs + */ + +#include "core/device.h" + +#include "subdev/bios.h" +#include "subdev/bios/dcb.h" + +u16 +dcb_table(struct nouveau_bios *bios, u8 *ver, u8 *hdr, u8 *cnt, u8 *len) +{ + struct nouveau_device *device = nv_device(bios); + u16 dcb = 0x0000; + + if (device->card_type > NV_04) + dcb = nv_ro16(bios, 0x36); + if (!dcb) { + nv_warn(bios, "DCB table not found\n"); + return dcb; + } + + *ver = nv_ro08(bios, dcb); + + if (*ver >= 0x41) { + nv_warn(bios, "DCB version 0x%02x unknown\n", *ver); + return 0x0000; + } else + if (*ver >= 0x30) { + if (nv_ro32(bios, dcb + 6) == 0x4edcbdcb) { + *hdr = nv_ro08(bios, dcb + 1); + *cnt = nv_ro08(bios, dcb + 2); + *len = nv_ro08(bios, dcb + 3); + return dcb; + } + } else + if (*ver >= 0x20) { + if (nv_ro32(bios, dcb + 4) == 0x4edcbdcb) { + u16 i2c = nv_ro16(bios, dcb + 2); + *hdr = 8; + *cnt = (i2c - dcb) / 8; + *len = 8; + return dcb; + } + } else + if (*ver >= 0x15) { + if (!nv_memcmp(bios, dcb - 7, "DEV_REC", 7)) { + u16 i2c = nv_ro16(bios, dcb + 2); + *hdr = 4; + *cnt = (i2c - dcb) / 10; + *len = 10; + return dcb; + } + } else { + /* + * v1.4 (some NV15/16, NV11+) seems the same as v1.5, but + * always has the same single (crt) entry, even when tv-out + * present, so the conclusion is this version cannot really + * be used. + * + * v1.2 tables (some NV6/10, and NV15+) normally have the + * same 5 entries, which are not specific to the card and so + * no use. + * + * v1.2 does have an I2C table that read_dcb_i2c_table can + * handle, but cards exist (nv11 in #14821) with a bad i2c + * table pointer, so use the indices parsed in + * parse_bmp_structure. + * + * v1.1 (NV5+, maybe some NV4) is entirely unhelpful + */ + nv_warn(bios, "DCB contains no useful data\n"); + return 0x0000; + } + + nv_warn(bios, "DCB header validation failed\n"); + return 0x0000; +} + +u16 +dcb_outp(struct nouveau_bios *bios, u8 idx, u8 *ver, u8 *len) +{ + u8 hdr, cnt; + u16 dcb = dcb_table(bios, ver, &hdr, &cnt, len); + if (dcb && idx < cnt) + return dcb + hdr + (idx * *len); + return 0x0000; +} + +static inline u16 +dcb_outp_hasht(struct dcb_output *outp) +{ + return (outp->extdev << 8) | (outp->location << 4) | outp->type; +} + +static inline u16 +dcb_outp_hashm(struct dcb_output *outp) +{ + return (outp->heads << 8) | (outp->link << 6) | outp->or; +} + +u16 +dcb_outp_parse(struct nouveau_bios *bios, u8 idx, u8 *ver, u8 *len, + struct dcb_output *outp) +{ + u16 dcb = dcb_outp(bios, idx, ver, len); + if (dcb) { + if (*ver >= 0x20) { + u32 conn = nv_ro32(bios, dcb + 0x00); + outp->or = (conn & 0x0f000000) >> 24; + outp->location = (conn & 0x00300000) >> 20; + outp->bus = (conn & 0x000f0000) >> 16; + outp->connector = (conn & 0x0000f000) >> 12; + outp->heads = (conn & 0x00000f00) >> 8; + outp->i2c_index = (conn & 0x000000f0) >> 4; + outp->type = (conn & 0x0000000f); + outp->link = 0; + } else { + dcb = 0x0000; + } + + if (*ver >= 0x40) { + u32 conf = nv_ro32(bios, dcb + 0x04); + switch (outp->type) { + case DCB_OUTPUT_TMDS: + case DCB_OUTPUT_LVDS: + case DCB_OUTPUT_DP: + outp->link = (conf & 0x00000030) >> 4; + outp->sorconf.link = outp->link; /*XXX*/ + outp->extdev = 0x00; + if (outp->location != 0) + outp->extdev = (conf & 0x0000ff00) >> 8; + break; + default: + break; + } + } + + outp->hasht = dcb_outp_hasht(outp); + outp->hashm = dcb_outp_hashm(outp); + } + return dcb; +} + +u16 +dcb_outp_match(struct nouveau_bios *bios, u16 type, u16 mask, + u8 *ver, u8 *len, struct dcb_output *outp) +{ + u16 dcb, idx = 0; + while ((dcb = dcb_outp_parse(bios, idx++, ver, len, outp))) { + if ((dcb_outp_hasht(outp) & 0x00ff) == (type & 0x00ff)) { + if ((dcb_outp_hashm(outp) & mask) == mask) + break; + } + } + return dcb; +} + +int +dcb_outp_foreach(struct nouveau_bios *bios, void *data, + int (*exec)(struct nouveau_bios *, void *, int, u16)) +{ + int ret, idx = -1; + u8 ver, len; + u16 outp; + + while ((outp = dcb_outp(bios, ++idx, &ver, &len))) { + if (nv_ro32(bios, outp) == 0x00000000) + break; /* seen on an NV11 with DCB v1.5 */ + if (nv_ro32(bios, outp) == 0xffffffff) + break; /* seen on an NV17 with DCB v2.0 */ + + if (nv_ro08(bios, outp) == DCB_OUTPUT_UNUSED) + continue; + if (nv_ro08(bios, outp) == DCB_OUTPUT_EOL) + break; + + ret = exec(bios, data, idx, outp); + if (ret) + return ret; + } + + return 0; +} diff --git a/pool/shard000/C/0014148_os-linux.c b/pool/shard000/C/0014148_os-linux.c new file mode 100644 index 0000000000000000000000000000000000000000..91017fc3f8e6c769ab6b882976a6cb222b6e4d6a --- /dev/null +++ b/pool/shard000/C/0014148_os-linux.c @@ -0,0 +1,58 @@ +#include "master.h" + +/* Snarfed from SBCL linux-so.c. You must free() this yourself. */ +const char *vm_executable_path(void) +{ + char *path = safe_malloc(PATH_MAX + 1); + + int size = readlink("/proc/self/exe", path, PATH_MAX); + if (size < 0) + { + fatal_error("Cannot read /proc/self/exe",0); + return NULL; + } + else + { + path[size] = '\0'; + return safe_strdup(path); + } +} + +#ifdef SYS_inotify_init + +int inotify_init(void) +{ + return syscall(SYS_inotify_init); +} + +int inotify_add_watch(int fd, const char *name, u32 mask) +{ + return syscall(SYS_inotify_add_watch, fd, name, mask); +} + +int inotify_rm_watch(int fd, u32 wd) +{ + return syscall(SYS_inotify_rm_watch, fd, wd); +} + +#else + +int inotify_init(void) +{ + not_implemented_error(); + return -1; +} + +int inotify_add_watch(int fd, const char *name, u32 mask) +{ + not_implemented_error(); + return -1; +} + +int inotify_rm_watch(int fd, u32 wd) +{ + not_implemented_error(); + return -1; +} + +#endif diff --git a/pool/shard000/C/0014179_role-tests.c b/pool/shard000/C/0014179_role-tests.c new file mode 100644 index 0000000000000000000000000000000000000000..3aee3235412e31687e6c9a42b42d92ebe563860a --- /dev/null +++ b/pool/shard000/C/0014179_role-tests.c @@ -0,0 +1,154 @@ +/** + * @file + * + * Test the role queries. + * + * @author Jeremy A. Mowery jmowery@tresys.com + * @author Jason Tang jtang@tresys.com + * + * Copyright (C) 2007 Tresys Technology, LLC + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include + +#include +#include +#include +#include +#include + +#define SOURCE_POLICY TEST_POLICIES "/setools/apol/role_dom.conf" + +static apol_policy_t *sp = NULL; +static qpol_policy_t *qp = NULL; + +static void role_basic(void) +{ + apol_role_query_t *q = apol_role_query_create(); + CU_ASSERT_PTR_NOT_NULL_FATAL(q); + + apol_vector_t *v = NULL; + CU_ASSERT(apol_role_get_by_query(sp, q, &v) == 0); + CU_ASSERT(v != NULL && apol_vector_get_size(v) == 26); + apol_vector_destroy(&v); + + apol_role_query_set_role(sp, q, "sh"); + CU_ASSERT(apol_role_get_by_query(sp, q, &v) == 0); + CU_ASSERT(v != NULL && apol_vector_get_size(v) == 0); + apol_vector_destroy(&v); + + apol_role_query_set_role(sp, q, NULL); + apol_role_query_set_type(sp, q, "silly_t"); + CU_ASSERT(apol_role_get_by_query(sp, q, &v) == 0); + CU_ASSERT(v != NULL && apol_vector_get_size(v) == 2); + bool found_silly = false, found_object = false; + for (size_t i = 0; i < apol_vector_get_size(v); i++) { + qpol_role_t *r = (qpol_role_t *) apol_vector_get_element(v, i); + const char *name; + qpol_role_get_name(qp, r, &name); + if (strcmp(name, "silly_r") == 0) { + found_silly = true; + } else if (strcmp(name, "object_r") == 0) { + found_object = true; + } else { + CU_ASSERT(0); + } + } + CU_ASSERT(found_silly && found_object); + apol_vector_destroy(&v); + + apol_role_query_set_type(sp, q, "not_in_the_policy_t"); + CU_ASSERT(apol_role_get_by_query(sp, q, &v) == 0); + CU_ASSERT(v != NULL && apol_vector_get_size(v) == 0); + apol_vector_destroy(&v); + + apol_role_query_destroy(&q); +} + +static void role_regex(void) +{ + apol_role_query_t *q = apol_role_query_create(); + CU_ASSERT_PTR_NOT_NULL_FATAL(q); + apol_role_query_set_regex(sp, q, 1); + + apol_role_query_set_role(sp, q, "*"); + apol_vector_t *v = NULL; + CU_ASSERT(apol_role_get_by_query(sp, q, &v) < 0 && v == NULL); + + apol_role_query_set_role(sp, q, "^sh"); + CU_ASSERT(apol_role_get_by_query(sp, q, &v) == 0); + CU_ASSERT(v != NULL && apol_vector_get_size(v) == 2); + bool found_shirt = false, found_shoe = false; + for (size_t i = 0; i < apol_vector_get_size(v); i++) { + qpol_role_t *r = (qpol_role_t *) apol_vector_get_element(v, i); + const char *name; + qpol_role_get_name(qp, r, &name); + if (strcmp(name, "shirt_r") == 0) { + found_shirt = true; + } else if (strcmp(name, "shoe_r") == 0) { + found_shoe = true; + } else { + CU_ASSERT(0); + } + } + CU_ASSERT(found_shirt && found_shoe); + apol_vector_destroy(&v); + + apol_role_query_set_role(sp, q, NULL); + apol_role_query_set_type(sp, q, "file"); + CU_ASSERT(apol_role_get_by_query(sp, q, &v) == 0); + CU_ASSERT(v != NULL && apol_vector_get_size(v) == 1); + qpol_role_t *r = (qpol_role_t *) apol_vector_get_element(v, 0); + const char *name; + qpol_role_get_name(qp, r, &name); + CU_ASSERT_STRING_EQUAL(name, "object_r"); + apol_vector_destroy(&v); + + apol_role_query_destroy(&q); +} + +CU_TestInfo role_tests[] = { + {"basic query", role_basic} + , + {"regex query", role_regex} + , + CU_TEST_INFO_NULL +}; + +int role_init() +{ + apol_policy_path_t *ppath = apol_policy_path_create(APOL_POLICY_PATH_TYPE_MONOLITHIC, SOURCE_POLICY, NULL); + if (ppath == NULL) { + return 1; + } + + if ((sp = apol_policy_create_from_policy_path(ppath, 0, NULL, NULL)) == NULL) { + apol_policy_path_destroy(&ppath); + return 1; + } + apol_policy_path_destroy(&ppath); + + qp = apol_policy_get_qpol(sp); + + return 0; +} + +int role_cleanup() +{ + apol_policy_destroy(&sp); + return 0; +} diff --git a/pool/shard000/C/0014187_suite.c b/pool/shard000/C/0014187_suite.c new file mode 100644 index 0000000000000000000000000000000000000000..7f4d1402c810643d334d39c5098d97baf1fa38eb --- /dev/null +++ b/pool/shard000/C/0014187_suite.c @@ -0,0 +1,33 @@ +#include "internal.h" + +test_result_t suite_run( const suite_t* suite ) { + suite_status_t status = SUITE_STATUS_INIT(suite); + listener_t* listener = listener_progress(); + + return suite_status_run( &status, listener ); +} + +test_result_t suite_status_run( suite_status_t* status, + listener_t* listener ) { + const suite_t* suite = status->suite; + int i; + + listener_suite_start( listener, status ); + + for( i=0; suite->tests[i] != NULL; i++ ) { + test_status_t test = TEST_STATUS_INIT(suite->tests[i]); + + test_status_run( &test, listener ); + + status->ms += test.ms; + status->result = WORST_RESULT(status->ms, test.ms); + status->count[ test.result ] += 1; + + listener_suite_step( listener, status ); + } + + listener_suite_end( listener, status ); + + return status->result; +} + diff --git a/pool/shard000/C/0014232_platform_driver.c b/pool/shard000/C/0014232_platform_driver.c new file mode 100644 index 0000000000000000000000000000000000000000..dc54354c5bc42e0657f19ee9c53f89e7b93ea1fd --- /dev/null +++ b/pool/shard000/C/0014232_platform_driver.c @@ -0,0 +1,66 @@ +#include +#include + +#include +#define DRIVER_NAME "Sample_Pldrv" + +MODULE_LICENSE("GPL"); + +/**************/ +static int sample_drv_probe(struct platform_device *pdev) { + struct resource *res1, *res2; + printk("Platform Driver Probe called\n"); + res1 = platform_get_resource(pdev, IORESOURCE_MEM, 1); + if (!res1) { + pr_err(" Specified Resource Not Available... 1\n"); + return -1; + } + printk(KERN_ALERT "\n Memory Area1\n"); + printk(KERN_ALERT "Start:%lx, End:%lx Size:%d\n", (unsigned long)res1->start, + (unsigned long)res1->end, resource_size(res1)); + res2 = platform_get_resource(pdev, IORESOURCE_MEM, 1); + if ((!res2)) { + pr_err(" Specified Resource Not Available... 2\n"); + return -1; + } + printk(KERN_ALERT "\n Memory Area2\n"); + printk(KERN_ALERT "Start:%lx, End:%lx, size:%d\n", (unsigned long)res2->start, + (unsigned long)res2->end, resource_size(res2)); + printk(KERN_ALERT "\n IRQ Number of Device :%d\n", platform_get_irq(pdev, 0)); + return 0; +} +static int sample_drv_remove(struct platform_device *pdev){ + return 0; +} + +static struct platform_driver sample_pldriver = { + .probe = sample_drv_probe, + .remove = sample_drv_remove, + .driver = { + .name = DRIVER_NAME, + }, +}; +/**************/ + +int ourinitmodule(void) +{ + printk(KERN_ALERT "\n Welcome to sample Platform driver.... \n"); + + /* Registering with Kernel */ + platform_driver_register(&sample_pldriver); + + return 0; +} + +void ourcleanupmodule(void) +{ + printk(KERN_ALERT "\n Thanks....Exiting sample Platform driver... \n"); + + /* Unregistering from Kernel */ + platform_driver_unregister(&sample_pldriver); + + return; +} + +module_init(ourinitmodule); +module_exit(ourcleanupmodule); diff --git a/pool/shard000/C/0014243_setpwnam.c b/pool/shard000/C/0014243_setpwnam.c new file mode 100644 index 0000000000000000000000000000000000000000..589b9bebad87d121157741af9d1514e75f8c03b0 --- /dev/null +++ b/pool/shard000/C/0014243_setpwnam.c @@ -0,0 +1,227 @@ +/* + * setpwnam.c -- + * edit an entry in a password database. + * + * (c) 1994 Salvatore Valente + * This file 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. + * + * Edited 11/10/96 (DD/MM/YY ;-) by Nicolai Langfeldt (janl@math.uio.no) + * to read /etc/passwd directly so that passwd, chsh and chfn can work + * on machines that run NIS (né YP). Changes will not be made to + * usernames starting with +. + * + * This file is distributed with no warranty. + * + * Usage: + * 1) get a struct passwd * from getpwnam(). + * You should assume a struct passwd has an infinite number of fields, + * so you should not try to create one from scratch. + * 2) edit the fields you want to edit. + * 3) call setpwnam() with the edited struct passwd. + * + * A _normal user_ program should never directly manipulate + * /etc/passwd but use getpwnam() and (family, as well as) + * setpwnam(). + * + * But, setpwnam was made to _edit_ the password file. For use by + * chfn, chsh and passwd. _I_ _HAVE_ to read and write /etc/passwd + * directly. Let those who say nay be forever silent and think about + * how getpwnam (and family) works on a machine running YP. + * + * Added checks for failure of malloc() and removed error reporting + * to stderr, this is a library function and should not print on the + * screen, but return appropriate error codes. + * 27-Jan-97 - poe@daimi.aau.dk + * + * Thanks to "two guys named Ian". + * + * $Author: poer $ + * $Revision: 1.13 $ + * $Date: 1997/06/23 08:26:29 $ + * + */ + +#undef DEBUG + +/* because I use getpwent(), putpwent(), etc... */ +#define _SVID_SOURCE + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "setpwnam.h" + +#define false 0 +#define true 1 + +typedef int boolean; + +static void pw_init(void); + +/* + * setpwnam () -- + * takes a struct passwd in which every field is filled in and valid. + * If the given username exists in the passwd file, the entry is + * replaced with the given entry. + */ +int +setpwnam (struct passwd *pwd) +{ + FILE *fp = NULL, *pwf = NULL; + int x, save_errno, fd, ret; + boolean found; + int oldumask; + int namelen; + int buflen = 256; + int contlen; + char *linebuf = malloc(buflen); + + if (!linebuf) return -1; + + oldumask = umask(0); /* Create with exact permissions */ + + pw_init(); + + /* sanity check */ + for (x = 0; x < 3; x++) { + if (x > 0) sleep(1); + fd = open(PTMPTMP_FILE, O_WRONLY|O_CREAT|O_EXCL, 0644); + if (fd == -1) { + umask(oldumask); + return -1; + } + ret = link(PTMPTMP_FILE, PTMP_FILE); + unlink(PTMPTMP_FILE); + if (ret == -1) + close(fd); + else + break; + } + umask(oldumask); + if (ret == -1) return -1; + + /* ptmp should be owned by root.root or root.wheel */ + if (chown(PTMP_FILE, (uid_t) 0, (gid_t) 0) < 0) return -1; + + /* open ptmp for writing and passwd for reading */ + fp = fdopen(fd, "w"); + if (!fp) goto fail; + + pwf = fopen(PASSWD_FILE, "r"); + if (!pwf) goto fail; + + namelen = strlen(pwd->pw_name); + + /* parse the passwd file */ + found = false; + /* Do you wonder why I don't use getpwent? Read comments at top of file */ + while (fgets(linebuf, buflen, pwf) != NULL) { + contlen = strlen(linebuf); + while (linebuf[contlen-1] != '\n' && !feof(pwf)) { + /* Extend input buffer if it failed getting the whole line */ + + /* So now we double the buffer size */ + buflen *= 2; + + linebuf = realloc(linebuf, buflen); + if (linebuf == NULL) goto fail; + + /* And fill the rest of the buffer */ + if (fgets(&linebuf[contlen], buflen/2, pwf) == NULL) break; + contlen = strlen(linebuf); + + /* That was a lot of work for nothing. Gimme perl! */ + } + + /* Is this the username we were sent to change? */ + if (!found && linebuf[namelen] == ':' && + !strncmp(linebuf, pwd->pw_name, namelen)) { + /* Yes! So go forth in the name of the Lord and change it! */ + if (putpwent(pwd, fp) < 0) goto fail; + found = true; + continue; + } + /* Nothing in particular happened, copy input to output */ + fputs(linebuf, fp); + } + + if (fclose(fp) < 0) goto fail; + fp = NULL; + close (fd); + fd = -1; + fclose (pwf); /* I don't think I want to know if this failed */ + pwf = NULL; + + if (!found) { + errno = ENOENT; /* give me something better */ + goto fail; + } + + /* we don't care if we can't remove the backup file */ + unlink(PASSWD_FILE".OLD"); + /* we don't care if we can't create the backup file */ + link(PASSWD_FILE, PASSWD_FILE".OLD"); + /* we DO care if we can't rename to the passwd file */ + if(rename(PTMP_FILE, PASSWD_FILE) < 0) + goto fail; + /* finally: success */ + return 0; + +fail: + save_errno = errno; + if (fp != NULL) fclose (fp); + if (pwf != NULL) fclose(pwf); + if (fd >= 0) close (fd); + if (linebuf != NULL) free(linebuf); + unlink(PTMP_FILE); + errno = save_errno; + return -1; +} + +/* Set up the limits so that we're not foiled */ + +static void +pw_init() +{ + struct rlimit rlim; + + /* Unlimited resource limits. */ + rlim.rlim_cur = rlim.rlim_max = RLIM_INFINITY; + setrlimit(RLIMIT_CPU, &rlim); + setrlimit(RLIMIT_FSIZE, &rlim); + setrlimit(RLIMIT_STACK, &rlim); + setrlimit(RLIMIT_DATA, &rlim); + setrlimit(RLIMIT_RSS, &rlim); + +#ifndef DEBUG + /* Don't drop core (not really necessary, but GP's). */ + rlim.rlim_cur = rlim.rlim_max = 0; + setrlimit(RLIMIT_CORE, &rlim); +#endif + + /* Turn off signals. */ + signal(SIGALRM, SIG_IGN); + signal(SIGHUP, SIG_IGN); + signal(SIGINT, SIG_IGN); + signal(SIGPIPE, SIG_IGN); + signal(SIGQUIT, SIG_IGN); + signal(SIGTERM, SIG_IGN); + signal(SIGTSTP, SIG_IGN); + signal(SIGTTOU, SIG_IGN); + + /* Create with exact permissions. */ + umask(0); +} diff --git a/pool/shard000/C/0014244_test-mu-msg-fields.c b/pool/shard000/C/0014244_test-mu-msg-fields.c new file mode 100644 index 0000000000000000000000000000000000000000..27864d8d012e8be5772d7fdd454769331542f6e7 --- /dev/null +++ b/pool/shard000/C/0014244_test-mu-msg-fields.c @@ -0,0 +1,134 @@ +/* +** Copyright (C) 2008-2013 Dirk-Jan C. Binnema +** +** 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, 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. +** +*/ + +#if HAVE_CONFIG_H +#include "config.h" +#endif /*HAVE_CONFIG_H*/ + +#include +#include +#include +#include + +#include + +#include "test-mu-common.h" +#include "mu-msg-fields.h" + +static void +test_mu_msg_field_body (void) +{ + MuMsgFieldId field; + + field = MU_MSG_FIELD_ID_BODY_TEXT; + + g_assert_cmpstr (mu_msg_field_name(field),==, "body"); + g_assert_cmpuint (mu_msg_field_shortcut(field),==, 'b'); + g_assert_cmpuint (mu_msg_field_xapian_prefix(field),==, 'B'); + + g_assert_cmpuint (mu_msg_field_is_numeric(field), ==, FALSE); +} + +static void +test_mu_msg_field_subject (void) +{ + MuMsgFieldId field; + + field = MU_MSG_FIELD_ID_SUBJECT; + + g_assert_cmpstr (mu_msg_field_name(field),==, "subject"); + g_assert_cmpuint (mu_msg_field_shortcut(field),==, 's'); + g_assert_cmpuint (mu_msg_field_xapian_prefix(field),==, 'S'); + + g_assert_cmpuint (mu_msg_field_is_numeric(field), ==,FALSE); +} + +static void +test_mu_msg_field_to (void) +{ + MuMsgFieldId field; + + field = MU_MSG_FIELD_ID_TO; + + g_assert_cmpstr (mu_msg_field_name(field),==, "to"); + g_assert_cmpuint (mu_msg_field_shortcut(field),==, 't'); + g_assert_cmpuint (mu_msg_field_xapian_prefix(field),==, 'T'); + + g_assert_cmpuint (mu_msg_field_is_numeric(field), ==, FALSE); +} + + +static void +test_mu_msg_field_prio (void) +{ + MuMsgFieldId field; + + field = MU_MSG_FIELD_ID_PRIO; + + g_assert_cmpstr (mu_msg_field_name(field),==, "prio"); + g_assert_cmpuint (mu_msg_field_shortcut(field),==, 'p'); + g_assert_cmpuint (mu_msg_field_xapian_prefix(field),==, 'P'); + + g_assert_cmpuint (mu_msg_field_is_numeric(field), ==, TRUE); +} + +static void +test_mu_msg_field_flags (void) +{ + MuMsgFieldId field; + + field = MU_MSG_FIELD_ID_FLAGS; + + g_assert_cmpstr (mu_msg_field_name(field),==, "flag"); + g_assert_cmpuint (mu_msg_field_shortcut(field),==, 'g'); + g_assert_cmpuint (mu_msg_field_xapian_prefix(field),==, 'G'); + + g_assert_cmpuint (mu_msg_field_is_numeric(field),==, TRUE); +} + + + + +int +main (int argc, char *argv[]) +{ + g_test_init (&argc, &argv, NULL); + + /* mu_msg_str_date */ + g_test_add_func ("/mu-msg-fields/mu-msg-field-body", + test_mu_msg_field_body); + g_test_add_func ("/mu-msg-fields/mu-msg-field-subject", + test_mu_msg_field_subject); + g_test_add_func ("/mu-msg-fields/mu-msg-field-to", + test_mu_msg_field_to); + g_test_add_func ("/mu-msg-fields/mu-msg-field-prio", + test_mu_msg_field_prio); + g_test_add_func ("/mu-msg-fields/mu-msg-field-flags", + test_mu_msg_field_flags); + + /* FIXME: add tests for mu_msg_str_flags; but note the + * function simply calls mu_msg_field_str */ + + g_log_set_handler (NULL, + G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL | + G_LOG_FLAG_RECURSION, + (GLogFunc)black_hole, NULL); + + return g_test_run (); +} diff --git a/pool/shard000/C/0014250_mem-break.c b/pool/shard000/C/0014250_mem-break.c new file mode 100644 index 0000000000000000000000000000000000000000..ba7dc242e5ea3dd56c10e3c1b66e1a245e945d9f --- /dev/null +++ b/pool/shard000/C/0014250_mem-break.c @@ -0,0 +1,91 @@ +/* Simulate breakpoints by patching locations in the target system, for GDB. + + Copyright (C) 1990, 1991, 1992, 1993, 1995, 1997, 1998, 1999, 2000, 2002, + 2007, 2008, 2009, 2010, 2011 Free Software Foundation, Inc. + + Contributed by Cygnus Support. Written by John Gilmore. + + 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" + +/* This file is only useful if BREAKPOINT_FROM_PC is set. If not, we + punt. */ + +#include "symtab.h" +#include "breakpoint.h" +#include "inferior.h" +#include "target.h" + + +/* Insert a breakpoint on targets that don't have any better + breakpoint support. We read the contents of the target location + and stash it, then overwrite it with a breakpoint instruction. + BP_TGT->placed_address is the target location in the target + machine. BP_TGT->shadow_contents is some memory allocated for + saving the target contents. It is guaranteed by the caller to be + long enough to save BREAKPOINT_LEN bytes (this is accomplished via + BREAKPOINT_MAX). */ + +int +default_memory_insert_breakpoint (struct gdbarch *gdbarch, + struct bp_target_info *bp_tgt) +{ + int val; + const unsigned char *bp; + + /* Determine appropriate breakpoint contents and size for this address. */ + bp = gdbarch_breakpoint_from_pc + (gdbarch, &bp_tgt->placed_address, &bp_tgt->placed_size); + if (bp == NULL) + error (_("Software breakpoints not implemented for this target.")); + + /* Save the memory contents. */ + bp_tgt->shadow_len = bp_tgt->placed_size; + val = target_read_memory (bp_tgt->placed_address, bp_tgt->shadow_contents, + bp_tgt->placed_size); + + /* Write the breakpoint. */ + if (val == 0) + val = target_write_memory (bp_tgt->placed_address, bp, + bp_tgt->placed_size); + + return val; +} + + +int +default_memory_remove_breakpoint (struct gdbarch *gdbarch, + struct bp_target_info *bp_tgt) +{ + return target_write_memory (bp_tgt->placed_address, bp_tgt->shadow_contents, + bp_tgt->placed_size); +} + + +int +memory_insert_breakpoint (struct gdbarch *gdbarch, + struct bp_target_info *bp_tgt) +{ + return gdbarch_memory_insert_breakpoint (gdbarch, bp_tgt); +} + +int +memory_remove_breakpoint (struct gdbarch *gdbarch, + struct bp_target_info *bp_tgt) +{ + return gdbarch_memory_remove_breakpoint (gdbarch, bp_tgt); +} diff --git a/pool/shard000/C/0014259_BaseGun.c b/pool/shard000/C/0014259_BaseGun.c new file mode 100644 index 0000000000000000000000000000000000000000..5f39d06419b39daf2792830fc254b03155ff45b9 --- /dev/null +++ b/pool/shard000/C/0014259_BaseGun.c @@ -0,0 +1,198 @@ +/* +FreeCS Project +Copyright (C) 2016, 2017 Marco "eukara" Hladik + +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. +*/ + +weaponinfo_t wptTable[ CS_WEAPON_COUNT ] = { + { 0, 0, 0, 0, 240, 0, 0, 0, 0, 0.0, 0.0, 0, 0.0, 0.0, iAmmo_9MM, iAmmo_9MM, 0.0, 0.0, 0.0, 0, 0 }, + wptKNIFE, + wptUSP45, + wptGLOCK18, + wptDEAGLE, + wptP228, + wptELITES, + wptFIVESEVEN, + wptM3, + wptXM1014, + wptMP5, + wptP90, + wptUMP45, + wptMAC10, + wptTMP, + wptAK47, + wptSG552, + wptM4A1, + wptAUG, + wptSCOUT, + wptAWP, + wptG3SG1, + wptSG550, + wptPARA, + wptC4BOMB, + wptFLASHBANG, + wptHEGRENADE, + wptSMOKEGRENADE +}; + +#ifdef SSQC +.int iShotMultiplier; +.float fDecreaseShotTime; +//.int iOldShotMultiplier; +#endif + +/* +==================== +BaseGun_ShotMultiplierHandle +==================== +*/ +void BaseGun_ShotMultiplierHandle( float fShots ) { +#ifdef SSQC + if ( self.iShotMultiplier > 12 ) { + self.iShotMultiplier = 12; + } else { + self.iShotMultiplier += fShots; + } + self.fDecreaseShotTime = time + 0.2; +#else + vector vPunch; + if ( pSeat->iShotMultiplier > 12 ) { + pSeat->iShotMultiplier = 12; + } else { + pSeat->iShotMultiplier += fShots; + } + + vPunch_x = -2 * ( pSeat->iShotMultiplier / 6 ); + vPunch_y = random( -1, 1 ); + View_AddPunchAngle( vPunch ); +#endif +} + +#ifdef SSQC +/* +==================== +BaseGun_ShotMultiplierUpdate + +This is being triggered in PlayerPreThink after the input +==================== +*/ +void BaseGun_ShotMultiplierUpdate( void ) { + if ( ( self.iShotMultiplier > 0 ) && ( self.fDecreaseShotTime < time ) ) { + self.fDecreaseShotTime = time + wptTable[ self.weapon ].fAttackFinished + 0.01; + self.iShotMultiplier--; + } +} + +/* +==================== +BaseGun_Draw +==================== +*/ +void BaseGun_Draw( void ) { + self.iCurrentMag = self.(wptTable[ self.weapon ].iMagfld); + self.iCurrentCaliber = self.(wptTable[ self.weapon ].iCaliberfld); + Client_SendEvent( self, EV_WEAPON_DRAW ); +} + +/* +==================== +BaseGun_AccuracyCalc +==================== +*/ +void BaseGun_AccuracyCalc( void ) { + if ( wptTable[ self.weapon ].fAccuracyDivisor == -1 ) { + if ( self.viewzoom < 1.0f ) { + self.fAccuracy = 0.0f; + } else { + self.fAccuracy = 0.05f; + } + } else { + self.fAccuracy = ( self.iShotMultiplier / wptTable[ self.weapon ].fAccuracyDivisor ); + } +} + +/* +==================== +BaseGun_PrimaryFire + +Returns whether or not to play an animation +==================== +*/ +float BaseGun_PrimaryFire( void ) { + // Nothing in the clip anymore? Don't even attempt + if ( ( self.(wptTable[ self.weapon ].iMagfld) - 1 ) < 0 ) { + if ( autocvar_mp_autoreload == TRUE ) { + Weapon_Reload( self.weapon ); + } + return FALSE; + } + + // Responsible for semi-automatic switch + if ( wptTable[ self.weapon ].fWeaponType == TYPE_SEMI ) { + self.flags = self.flags - ( self.flags & FL_SEMI_TOGGLED ); + } + + BaseGun_ShotMultiplierHandle( wptTable[ self.weapon ].iBullets ); + BaseGun_AccuracyCalc(); + TraceAttack_FireBullets( wptTable[ self.weapon ].iBullets, ( self.origin + self.view_ofs ) ); + Animation_ShootWeapon( self ); + + self.(wptTable[ self.weapon ].iMagfld) -= 1; + self.fAttackFinished = time + wptTable[ self.weapon ].fAttackFinished; + Client_SendEvent( self, EV_WEAPON_PRIMARYATTACK ); + return TRUE; +} + +/* +==================== +BaseGun_Reload +==================== +*/ +float BaseGun_Reload( void ) { + static void BaseGun_FinishReload( void ) { + // What if we've got less in our caliberfield than we need + if ( self.(wptTable[ self.weapon ].iCaliberfld) < wptTable[ self.weapon ].iMagSize ) { + self.(wptTable[ self.weapon ].iMagfld) = self.(wptTable[ self.weapon ].iCaliberfld); + self.(wptTable[ self.weapon ].iCaliberfld) = 0; + } else { + self.(wptTable[ self.weapon ].iCaliberfld) -= ( wptTable[ self.weapon ].iMagSize - self.(wptTable[ self.weapon ].iMagfld) ); + self.(wptTable[ self.weapon ].iMagfld) = wptTable[ self.weapon ].iMagSize; + } + + Weapon_UpdateCurrents(); + } + + // Don't bother reloading the gun when full + if ( self.(wptTable[ self.weapon ].iMagfld) == wptTable[ self.weapon ].iMagSize ) { + return FALSE; + } + + // Also don't bother reloading the gun if you've got nothing to reload it with + if ( self.(wptTable[ self.weapon ].iCaliberfld) <= 0 ) { + return FALSE; + } + + + self.think = BaseGun_FinishReload; + self.nextthink = time + wptTable[ self.weapon ].fReloadFinished; + self.fAttackFinished = self.nextthink; + + Animation_ReloadWeapon( self ); + Client_SendEvent( self, EV_WEAPON_RELOAD ); + return TRUE; +} +#endif diff --git a/pool/shard000/C/0014276_ui_node_abstractvalue.c b/pool/shard000/C/0014276_ui_node_abstractvalue.c new file mode 100644 index 0000000000000000000000000000000000000000..128f43410a5f89b6e2dd27ba25d79f4b9e9e0999 --- /dev/null +++ b/pool/shard000/C/0014276_ui_node_abstractvalue.c @@ -0,0 +1,131 @@ +/** + * @file ui_node_abstractvalue.c + * @brief The abstractvalue node is an abstract node (we can't instanciate it). + * It provide common properties to concrete nodes, to manage a value in a range. + */ + +/* +Copyright (C) 2002-2010 UFO: Alien Invasion. + +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 "../ui_nodes.h" +#include "../ui_parse.h" +#include "../ui_internal.h" +#include "ui_node_abstractvalue.h" + +#define EXTRADATA_TYPE abstractValueExtraData_t +#define EXTRADATA(node) UI_EXTRADATA(node, EXTRADATA_TYPE) +#define EXTRADATACONST(node) UI_EXTRADATACONST(node, EXTRADATA_TYPE) + +static const uiBehaviour_t const *localBehaviour; + +static inline void UI_InitCvarOrFloat (float** adress, float defaultValue) +{ + if (*adress == NULL) { + *adress = UI_AllocStaticFloat(1); + **adress = defaultValue; + } +} + +static void UI_AbstractValueLoaded (uiNode_t * node) +{ + UI_InitCvarOrFloat((float**)&EXTRADATA(node).value, 0); + UI_InitCvarOrFloat((float**)&EXTRADATA(node).delta, 1); + UI_InitCvarOrFloat((float**)&EXTRADATA(node).max, 0); + UI_InitCvarOrFloat((float**)&EXTRADATA(node).min, 0); +} + +static void UI_AbstractValueNew (uiNode_t * node) +{ + EXTRADATA(node).value = Mem_PoolAlloc(sizeof(float), ui_dynPool, 0); + EXTRADATA(node).delta = Mem_PoolAlloc(sizeof(float), ui_dynPool, 0); + EXTRADATA(node).max = Mem_PoolAlloc(sizeof(float), ui_dynPool, 0); + EXTRADATA(node).min = Mem_PoolAlloc(sizeof(float), ui_dynPool, 0); +} + +static void UI_AbstractValueDelete (uiNode_t * node) +{ + Mem_Free(EXTRADATA(node).value); + Mem_Free(EXTRADATA(node).delta); + Mem_Free(EXTRADATA(node).max); + Mem_Free(EXTRADATA(node).min); + EXTRADATA(node).value = NULL; + EXTRADATA(node).delta = NULL; + EXTRADATA(node).max = NULL; + EXTRADATA(node).min = NULL; +} + +static void UI_CloneCvarOrFloat (const uiNode_t *source, uiNode_t *clone, const float*const* sourceData, float** cloneData) +{ + /* dont update cvar */ + if (Q_strstart(*(const char*const*)sourceData, "*cvar")) { + /* thats anyway a const string */ + assert(!source->dynamic); + if (clone->dynamic) + Mem_Free(*(char**)cloneData); + *(const char**)cloneData = *(const char*const*)sourceData; + } else { + /* clone float */ + if (!clone->dynamic) + *cloneData = UI_AllocStaticFloat(1); + **cloneData = **sourceData; + } +} + +/** + * @brief Call to update a cloned node + */ +static void UI_AbstractValueClone (const uiNode_t *source, uiNode_t *clone) +{ + localBehaviour->super->clone(source, clone); + UI_CloneCvarOrFloat(source, clone, (const float*const*)&EXTRADATACONST(source).value, (float**)&EXTRADATA(clone).value); + UI_CloneCvarOrFloat(source, clone, (const float*const*)&EXTRADATACONST(source).delta, (float**)&EXTRADATA(clone).delta); + UI_CloneCvarOrFloat(source, clone, (const float*const*)&EXTRADATACONST(source).max, (float**)&EXTRADATA(clone).max); + UI_CloneCvarOrFloat(source, clone, (const float*const*)&EXTRADATACONST(source).min, (float**)&EXTRADATA(clone).min); +} + +static const value_t properties[] = { + /* Current value of the node. It should be a cvar */ + {"current", V_CVAR_OR_FLOAT, UI_EXTRADATA_OFFSETOF(abstractValueExtraData_t, value), 0}, + /* Value of a positive step. Must be bigger than 1. */ + {"delta", V_CVAR_OR_FLOAT, UI_EXTRADATA_OFFSETOF(abstractValueExtraData_t, delta), 0}, + /* Maximum value we can set to the node. It can be a cvar. Default value is 0. */ + {"max", V_CVAR_OR_FLOAT, UI_EXTRADATA_OFFSETOF(abstractValueExtraData_t, max), 0}, + /* Minimum value we can set to the node. It can be a cvar. Default value is 1. */ + {"min", V_CVAR_OR_FLOAT, UI_EXTRADATA_OFFSETOF(abstractValueExtraData_t, min), 0}, + + /* Callback value set when before calling onChange. It is used to know the change apply by the user + * @Deprecated + */ + {"lastdiff", V_FLOAT, UI_EXTRADATA_OFFSETOF(abstractValueExtraData_t, lastdiff), MEMBER_SIZEOF(abstractValueExtraData_t, lastdiff)}, + {NULL, V_NULL, 0, 0} +}; + +void UI_RegisterAbstractValueNode (uiBehaviour_t *behaviour) +{ + localBehaviour = behaviour; + behaviour->name = "abstractvalue"; + behaviour->loaded = UI_AbstractValueLoaded; + behaviour->clone = UI_AbstractValueClone; + behaviour->newNode = UI_AbstractValueNew; + behaviour->deleteNode = UI_AbstractValueDelete; + behaviour->isAbstract = qtrue; + behaviour->properties = properties; + behaviour->extraDataSize = sizeof(EXTRADATA_TYPE); +} diff --git a/pool/shard000/C/0014281_convert.c b/pool/shard000/C/0014281_convert.c new file mode 100644 index 0000000000000000000000000000000000000000..2ab4205639201b27eee0580fb60a9e88bf224e14 --- /dev/null +++ b/pool/shard000/C/0014281_convert.c @@ -0,0 +1,170 @@ +/* Test conversion using mpz_get_str and mpz_set_str. + +Copyright 1993, 1994, 1996, 1999, 2000, 2001, 2002, 2006, 2007 Free Software +Foundation, Inc. + +This file is part of the GNU MP Library. + +The GNU MP 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 MP 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 MP Library. If not, see http://www.gnu.org/licenses/. */ + +#include +#include +#include /* for strlen */ + +#include "gmp.h" +#include "gmp-impl.h" +#include "tests.h" + +void debug_mp __GMP_PROTO ((mpz_t, int)); + + +void +string_urandomb (char *bp, size_t len, int base, gmp_randstate_ptr rands) +{ + mpz_t bs; + unsigned long bsi; + int d, l; + char *collseq = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + + mpz_init (bs); + + mpz_urandomb (bs, rands, 32); + bsi = mpz_get_ui (bs); + d = bsi % base; + while (len != 0) + { + l = (bsi >> 16) % 20; + l = MIN (l, len); + + memset (bp, collseq[d], l); + + len -= l; + bp += l; + + mpz_urandomb (bs, rands, 32); + bsi = mpz_get_ui (bs); + d = bsi & 0xfff; + if (d >= base) + d = 0; + } + + bp[0] = '\0'; + mpz_clear (bs); +} + +int +main (int argc, char **argv) +{ + mpz_t op1, op2; + mp_size_t size; + int i; + int reps = 2000; + char *str, *buf, *bp; + int base; + gmp_randstate_ptr rands; + mpz_t bs; + unsigned long bsi, size_range; + size_t len; + + tests_start (); + TESTS_REPS (reps, argv, argc); + + rands = RANDS; + + mpz_init (bs); + + mpz_init (op1); + mpz_init (op2); + + for (i = 0; i < reps; i++) + { + /* 1. Generate random mpz_t and convert to a string and back to mpz_t + again. */ + mpz_urandomb (bs, rands, 32); + size_range = mpz_get_ui (bs) % 17 + 2; /* 2..18 */ + mpz_urandomb (bs, rands, size_range); /* 3..262144 bits */ + size = mpz_get_ui (bs); + mpz_rrandomb (op1, rands, size); + + mpz_urandomb (bs, rands, 1); + bsi = mpz_get_ui (bs); + if ((bsi & 1) != 0) + mpz_neg (op1, op1); + + mpz_urandomb (bs, rands, 32); + bsi = mpz_get_ui (bs); + base = bsi % 62 + 1; + if (base == 1) + base = 0; + + str = mpz_get_str ((char *) 0, base, op1); + mpz_set_str_or_abort (op2, str, base); + + if (mpz_cmp (op1, op2)) + { + fprintf (stderr, "ERROR, op1 and op2 different in test %d\n", i); + fprintf (stderr, "str = %s\n", str); + fprintf (stderr, "base = %d\n", base); + fprintf (stderr, "op1 = "); debug_mp (op1, -16); + fprintf (stderr, "op2 = "); debug_mp (op2, -16); + abort (); + } + + (*__gmp_free_func) (str, strlen (str) + 1); + + /* 2. Generate random string and convert to mpz_t and back to a string + again. */ + mpz_urandomb (bs, rands, 32); + size_range = mpz_get_ui (bs) % 16 + 1; /* 1..16 */ + mpz_urandomb (bs, rands, size_range); /* 1..65536 digits */ + len = mpz_get_ui (bs) + 1; + buf = (*__gmp_allocate_func) (len + 1); + if (base == 0) + base = 10; + string_urandomb (buf, len, base, rands); + + mpz_set_str_or_abort (op1, buf, base); + str = mpz_get_str ((char *) 0, base, op1); + + /* Skip over leading zeros, but don't leave the string at zero length. */ + for (bp = buf; bp[0] == '0' && bp[1] != '\0'; bp++) + ; + + if (strcasecmp (str, bp) != 0) + { + fprintf (stderr, "ERROR, str and buf different in test %d\n", i); + fprintf (stderr, "str = %s\n", str); + fprintf (stderr, "buf = %s\n", buf); + fprintf (stderr, "base = %d\n", base); + fprintf (stderr, "op1 = "); debug_mp (op1, -16); + abort (); + } + + (*__gmp_free_func) (buf, len + 1); + (*__gmp_free_func) (str, strlen (str) + 1); + } + + mpz_clear (bs); + mpz_clear (op1); + mpz_clear (op2); + + tests_end (); + exit (0); +} + +void +debug_mp (mpz_t x, int base) +{ + mpz_out_str (stderr, base, x); fputc ('\n', stderr); +} diff --git a/pool/shard000/C/0014286_arm_biquad_cascade_df1_init_q15.c b/pool/shard000/C/0014286_arm_biquad_cascade_df1_init_q15.c new file mode 100644 index 0000000000000000000000000000000000000000..c2e542c43df8840fdfc1350a2bd32a2c701bc51f --- /dev/null +++ b/pool/shard000/C/0014286_arm_biquad_cascade_df1_init_q15.c @@ -0,0 +1,96 @@ +/* ---------------------------------------------------------------------- + * Project: CMSIS DSP Library + * Title: arm_biquad_cascade_df1_init_q15.c + * Description: Q15 Biquad cascade DirectFormI(DF1) filter initialization function + * + * $Date: 18. March 2019 + * $Revision: V1.6.0 + * + * Target Processor: Cortex-M cores + * -------------------------------------------------------------------- */ +/* + * Copyright (C) 2010-2019 ARM Limited or its affiliates. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * 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 + * + * 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 "arm_math.h" + +/** + @ingroup groupFilters + */ + +/** + @addtogroup BiquadCascadeDF1 + @{ + */ + +/** + @brief Initialization function for the Q15 Biquad cascade filter. + @param[in,out] S points to an instance of the Q15 Biquad cascade structure. + @param[in] numStages number of 2nd order stages in the filter. + @param[in] pCoeffs points to the filter coefficients. + @param[in] pState points to the state buffer. + @param[in] postShift Shift to be applied to the accumulator result. Varies according to the coefficients format + @return none + + @par Coefficient and State Ordering + The coefficients are stored in the array pCoeffs in the following order: +
+      {b10, 0, b11, b12, a11, a12, b20, 0, b21, b22, a21, a22, ...}
+  
+ @par + where b1x and a1x are the coefficients for the first stage, + b2x and a2x are the coefficients for the second stage, + and so on. The pCoeffs array contains a total of 6*numStages values. + The zero coefficient between b1 and b2 facilities use of 16-bit SIMD instructions on the Cortex-M4. + @par + The state variables are stored in the array pState. + Each Biquad stage has 4 state variables x[n-1], x[n-2], y[n-1], and y[n-2]. + The state variables are arranged in the pState array as: +
+      {x[n-1], x[n-2], y[n-1], y[n-2]}
+  
+ The 4 state variables for stage 1 are first, then the 4 state variables for stage 2, and so on. + The state array has a total length of 4*numStages values. + The state variables are updated after each block of data is processed; the coefficients are untouched. + */ + +void arm_biquad_cascade_df1_init_q15( + arm_biquad_casd_df1_inst_q15 * S, + uint8_t numStages, + const q15_t * pCoeffs, + q15_t * pState, + int8_t postShift) +{ + /* Assign filter stages */ + S->numStages = numStages; + + /* Assign postShift to be applied to the output */ + S->postShift = postShift; + + /* Assign coefficient pointer */ + S->pCoeffs = pCoeffs; + + /* Clear state buffer and size is always 4 * numStages */ + memset(pState, 0, (4U * (uint32_t) numStages) * sizeof(q15_t)); + + /* Assign state pointer */ + S->pState = pState; +} + +/** + @} end of BiquadCascadeDF1 group + */ diff --git a/pool/shard000/C/0014290_ci_hdrc_pci.c b/pool/shard000/C/0014290_ci_hdrc_pci.c new file mode 100644 index 0000000000000000000000000000000000000000..49a61549cee678324429aca80433a5f07a68e156 --- /dev/null +++ b/pool/shard000/C/0014290_ci_hdrc_pci.c @@ -0,0 +1,170 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * ci_hdrc_pci.c - MIPS USB IP core family device controller + * + * Copyright (C) 2008 Chipidea - MIPS Technologies, Inc. All rights reserved. + * + * Author: David Lopo + */ + +#include +#include +#include +#include +#include +#include +#include + +/* driver name */ +#define UDC_DRIVER_NAME "ci_hdrc_pci" + +struct ci_hdrc_pci { + struct platform_device *ci; + struct platform_device *phy; +}; + +/****************************************************************************** + * PCI block + *****************************************************************************/ +static struct ci_hdrc_platform_data pci_platdata = { + .name = UDC_DRIVER_NAME, + .capoffset = DEF_CAPOFFSET, +}; + +static struct ci_hdrc_platform_data langwell_pci_platdata = { + .name = UDC_DRIVER_NAME, + .capoffset = 0, +}; + +static struct ci_hdrc_platform_data penwell_pci_platdata = { + .name = UDC_DRIVER_NAME, + .capoffset = 0, + .power_budget = 200, +}; + +/** + * ci_hdrc_pci_probe: PCI probe + * @pdev: USB device controller being probed + * @id: PCI hotplug ID connecting controller to UDC framework + * + * This function returns an error code + * Allocates basic PCI resources for this USB device controller, and then + * invokes the udc_probe() method to start the UDC associated with it + */ +static int ci_hdrc_pci_probe(struct pci_dev *pdev, + const struct pci_device_id *id) +{ + struct ci_hdrc_platform_data *platdata = (void *)id->driver_data; + struct ci_hdrc_pci *ci; + struct resource res[3]; + int retval = 0, nres = 2; + + if (!platdata) { + dev_err(&pdev->dev, "device doesn't provide driver data\n"); + return -ENODEV; + } + + ci = devm_kzalloc(&pdev->dev, sizeof(*ci), GFP_KERNEL); + if (!ci) + return -ENOMEM; + + retval = pcim_enable_device(pdev); + if (retval) + return retval; + + if (!pdev->irq) { + dev_err(&pdev->dev, "No IRQ, check BIOS/PCI setup!"); + return -ENODEV; + } + + pci_set_master(pdev); + pci_try_set_mwi(pdev); + + /* register a nop PHY */ + ci->phy = usb_phy_generic_register(); + if (IS_ERR(ci->phy)) + return PTR_ERR(ci->phy); + + memset(res, 0, sizeof(res)); + res[0].start = pci_resource_start(pdev, 0); + res[0].end = pci_resource_end(pdev, 0); + res[0].flags = IORESOURCE_MEM; + res[1].start = pdev->irq; + res[1].flags = IORESOURCE_IRQ; + + ci->ci = ci_hdrc_add_device(&pdev->dev, res, nres, platdata); + if (IS_ERR(ci->ci)) { + dev_err(&pdev->dev, "ci_hdrc_add_device failed!\n"); + usb_phy_generic_unregister(ci->phy); + return PTR_ERR(ci->ci); + } + + pci_set_drvdata(pdev, ci); + + return 0; +} + +/** + * ci_hdrc_pci_remove: PCI remove + * @pdev: USB Device Controller being removed + * + * Reverses the effect of ci_hdrc_pci_probe(), + * first invoking the udc_remove() and then releases + * all PCI resources allocated for this USB device controller + */ +static void ci_hdrc_pci_remove(struct pci_dev *pdev) +{ + struct ci_hdrc_pci *ci = pci_get_drvdata(pdev); + + ci_hdrc_remove_device(ci->ci); + usb_phy_generic_unregister(ci->phy); +} + +/** + * PCI device table + * PCI device structure + * + * Check "pci.h" for details + * + * Note: ehci-pci driver may try to probe the device first. You have to add an + * ID to the bypass_pci_id_table in ehci-pci driver to prevent this. + */ +static const struct pci_device_id ci_hdrc_pci_id_table[] = { + { + PCI_DEVICE(0x153F, 0x1004), + .driver_data = (kernel_ulong_t)&pci_platdata, + }, + { + PCI_DEVICE(0x153F, 0x1006), + .driver_data = (kernel_ulong_t)&pci_platdata, + }, + { + PCI_VDEVICE(INTEL, 0x0811), + .driver_data = (kernel_ulong_t)&langwell_pci_platdata, + }, + { + PCI_VDEVICE(INTEL, 0x0829), + .driver_data = (kernel_ulong_t)&penwell_pci_platdata, + }, + { + /* Intel Clovertrail */ + PCI_VDEVICE(INTEL, 0xe006), + .driver_data = (kernel_ulong_t)&penwell_pci_platdata, + }, + { 0 } /* end: all zeroes */ +}; +MODULE_DEVICE_TABLE(pci, ci_hdrc_pci_id_table); + +static struct pci_driver ci_hdrc_pci_driver = { + .name = UDC_DRIVER_NAME, + .id_table = ci_hdrc_pci_id_table, + .probe = ci_hdrc_pci_probe, + .remove = ci_hdrc_pci_remove, +}; + +module_pci_driver(ci_hdrc_pci_driver); + +MODULE_AUTHOR("MIPS - David Lopo "); +MODULE_DESCRIPTION("MIPS CI13XXX USB Peripheral Controller"); +MODULE_LICENSE("GPL"); +MODULE_ALIAS("platform:ci13xxx_pci"); diff --git a/pool/shard000/C/0014306_breakpoints.c b/pool/shard000/C/0014306_breakpoints.c new file mode 100644 index 0000000000000000000000000000000000000000..5462195e7ac04e4b7c18b38b42260bf254552a8f --- /dev/null +++ b/pool/shard000/C/0014306_breakpoints.c @@ -0,0 +1,21 @@ +#include +#include +#include +#include + +void set_breakpoints(uint8_t *old_buf, uint8_t *new_buf, size_t sz) { +new_buf[0] = 0xcc; + ud_t ud; +ud_init(&ud); +ud_set_mode(&ud, 64); +ud_set_pc(&ud, 0); +ud_set_input_buffer(&ud, old_buf, sz); +ud_set_syntax(&ud, NULL); +while(ud_disassemble(&ud)) { +if(ud_insn_mnemonic(&ud) == UD_Iret) { +uint64_t offset = ud_insn_off(&ud); +debug_printf("Setting break point at offset %llu\n", offset); +new_buf[offset] = 0xcc; +} +} +} diff --git a/pool/shard000/C/0014320_madvise03.c b/pool/shard000/C/0014320_madvise03.c new file mode 100644 index 0000000000000000000000000000000000000000..49f0c30422fe1c3bf8620a541b1be6608758d759 --- /dev/null +++ b/pool/shard000/C/0014320_madvise03.c @@ -0,0 +1,263 @@ +/*************************************************************************** + * madvise03 .c + * + * Fri Nov 23 15:00:59 2007 + * Copyright (c) International Business Machines Corp., 2004 + * Email : pavan@in.ibm.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. + * + * 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 Library 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. + */ + +/********************************************************** + * TEST CASES + * + * 1.) madvise(2) advices...(See Description) + * + * INPUT SPECIFICATIONS + * The standard options for system call tests are accepted. + * (See the parse_opts(3) man page). + * + * OUTPUT SPECIFICATIONS + * Output describing whether test cases passed or failed. + * + * ENVIRONMENTAL NEEDS + * None + * + * SPECIAL PROCEDURAL REQUIREMENTS + * None + * + * DETAILED DESCRIPTION + * This is a test case for madvise(2) system call. + * It tests madvise(2) with combinations of advice values. + * No error should be returned. + * + * Total 3 Test Cases :- + * (1) Test Case for MADV_REMOVE + * (2) Test Case for MADV_DONTFORK + * (3) Test Case for MADV_DOFORK + * + * Setup: + * Setup signal handling. + * Pause for SIGUSR1 if option specified. + * + * Test: + * Loop if the proper options are given. + * Execute system call + * Check return code, if system call failed (return=-1) + * Log the errno and Issue a FAIL message. + * Otherwise, Issue a PASS message. + * + * Cleanup: + * Print errno log and/or timing stats if options given + * + * + *#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#**/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "test.h" +#include "usctest.h" + +char *TCID = "madvise03"; + +#ifdef MADV_REMOVE + +/* Uncomment the following line in DEBUG mode */ +//#define MM_DEBUG 1 + +int TST_TOTAL = 3; + +#define BUFFER_SIZE 256 + +static void setup(void); +static void cleanup(void); +static void check_and_print(char *advice); +static long get_shmmax(void); + +static int shmid1; + +int main(int argc, char *argv[]) +{ + int lc, fd; + int i; + char *file = NULL; + struct stat stat; + void *addr1; + long shm_size = 0; + + char *msg = NULL; + char filename[64]; + char *progname = NULL; + char *str_for_file = "abcdefghijklmnopqrstuvwxyz12345\n"; + + msg = parse_opts(argc, argv, NULL, NULL); + if (msg) + tst_brkm(TBROK, NULL, "OPTION PARSING ERROR - %s", msg); + + setup(); + + progname = *argv; + sprintf(filename, "%s-out.%d", progname, getpid()); + + for (lc = 0; TEST_LOOPING(lc); lc++) { + Tst_count = 0; + + fd = open(filename, O_RDWR | O_CREAT, 0664); + if (fd < 0) + tst_brkm(TBROK, cleanup, "open failed"); +#ifdef MM_DEBUG + tst_resm(TINFO, "filename = %s opened successfully", filename); +#endif + + /* Writing 40 KB of random data into this file + [32 * 1280 = 40960] */ + for (i = 0; i < 1280; i++) + if (write(fd, str_for_file, strlen(str_for_file)) == -1) + tst_brkm(TBROK|TERRNO, cleanup, "write failed"); + + if (fstat(fd, &stat) == -1) + tst_brkm(TBROK, cleanup, "fstat failed"); + + file = mmap(NULL, stat.st_size, PROT_READ, MAP_SHARED, fd, 0); + if (file == MAP_FAILED) + tst_brkm(TBROK|TERRNO, cleanup, "mmap failed"); + + /* Allocate shared memory segment */ + shm_size = get_shmmax(); + +#define min(a, b) ((a) < (b) ? (a) : (b)) + shmid1 = shmget(IPC_PRIVATE, min(1024*1024, shm_size), + IPC_CREAT|IPC_EXCL|0701); + if (shmid1 == -1) + tst_brkm(TBROK, cleanup, "shmget failed"); + + /* Attach shared memory segment to an address selected by the system */ + addr1 = shmat(shmid1, NULL, 0); + if (addr1 == (void *) -1) + tst_brkm(TBROK, cleanup, "shmat error"); + + /* (1) Test case for MADV_REMOVE */ + TEST(madvise(addr1, 4096, MADV_REMOVE)); + check_and_print("MADV_REMOVE"); + + /* (2) Test case for MADV_DONTFORK */ + TEST(madvise(file, (stat.st_size / 2), MADV_DONTFORK)); + check_and_print("MADV_DONTFORK"); + + /* (3) Test case for MADV_DOFORK */ + TEST(madvise(file, (stat.st_size / 2), MADV_DOFORK)); + check_and_print("MADV_DOFORK"); + + /* Finally Unmapping the whole file */ + if (munmap(file, stat.st_size) < 0) + tst_brkm(TBROK|TERRNO, cleanup, "munmap failed"); + + close(fd); + } + + cleanup(); + tst_exit(); +} + +static void setup(void) +{ + + tst_sig(NOFORK, DEF_HANDLER, cleanup); + + TEST_PAUSE; + + tst_tmpdir(); +} + +static void cleanup(void) +{ + if (shmid1 != -1) + if (shmctl(shmid1, IPC_RMID, 0) < 0) + tst_resm(TBROK|TERRNO, + "shmctl(.., IPC_RMID, ..) failed"); + + TEST_CLEANUP; + + tst_rmdir(); + +} + +/*************************************************************** + * check_and_print(advice) - checks the return value + * of the previous madvise call + * and based on the advice value + * prints the appropriate messages. + ***************************************************************/ +static void check_and_print(char *advice) +{ + if (TEST_RETURN == -1) { + tst_resm(TFAIL, + "madvise test for %s failed with " + "return = %ld, errno = %d : %s", + advice, TEST_RETURN, TEST_ERRNO, strerror(TEST_ERRNO)); + } else if (STD_FUNCTIONAL_TEST) { + tst_resm(TPASS, "madvise test for %s PASSED", advice); + } +} + +/*************************************************************** + * get_shmmax() - Reads the size of share memory size + * from /proc/sys/kernel/shmmax + ***************************************************************/ +static long get_shmmax(void) +{ + long maxsize; + FILE *f; + int retcode = 0; + char buff[BUFFER_SIZE]; + + f = fopen("/proc/sys/kernel/shmmax", "r"); + if (!f) + tst_brkm(TFAIL, cleanup, + "Could not open /proc/sys/kernel/shmmax for reading"); + + while (fgets(buff, BUFFER_SIZE, f) != NULL) { + retcode = sscanf(buff, "%ld ", &maxsize); + if (retcode == 1) + break; + } + + if (retcode != 1) { + fclose(f); + tst_brkm(TFAIL, cleanup, "Failed reading size of huge page."); + } + fclose(f); + return maxsize; +} +#else +int +main(void) +{ + /* "Requires 2.6.16+" were the original comments */ + tst_brkm(TCONF, NULL, + "this system doesn't have required madvise support"); +} +#endif diff --git a/pool/shard000/C/0014321_cpu_init.c b/pool/shard000/C/0014321_cpu_init.c new file mode 100644 index 0000000000000000000000000000000000000000..11154c63a83e649dcdfbab56c01a035d48a66381 --- /dev/null +++ b/pool/shard000/C/0014321_cpu_init.c @@ -0,0 +1,132 @@ +/* + * + * (C) Copyright 2000-2003 + * Wolfgang Denk, DENX Software Engineering, wd@denx.de. + * + * (C) Copyright 2007 Freescale Semiconductor, Inc. + * TsiChung Liew (Tsi-Chung.Liew@freescale.com) + * + * See file CREDITS for list of people who contributed to this + * project. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of + * the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, + * MA 02111-1307 USA + */ + +#include +#include +#include + +/* + * Breath some life into the CPU... + * + * Set up the memory map, + * initialize a bunch of registers, + * initialize the UPM's + */ +void cpu_init_f(void) +{ + volatile gpio_t *gpio = (gpio_t *) MMAP_GPIO; + volatile fbcs_t *fbcs = (fbcs_t *) MMAP_FBCS; + volatile xlbarb_t *xlbarb = (volatile xlbarb_t *) MMAP_XARB; + + xlbarb->adrto = 0x2000; + xlbarb->datto = 0x2000; + xlbarb->busto = 0x3000; + + xlbarb->cfg = XARB_SR_AT | XARB_SR_DT; + + /* Master Priority Enable */ + xlbarb->pri = 0; + xlbarb->prien = 0xff; + +#if (defined(CFG_CS0_BASE) && defined(CFG_CS0_MASK) && defined(CFG_CS0_CTRL)) + fbcs->csar0 = CFG_CS0_BASE; + fbcs->cscr0 = CFG_CS0_CTRL; + fbcs->csmr0 = CFG_CS0_MASK; +#endif + +#if (defined(CFG_CS1_BASE) && defined(CFG_CS1_MASK) && defined(CFG_CS1_CTRL)) + fbcs->csar1 = CFG_CS1_BASE; + fbcs->cscr1 = CFG_CS1_CTRL; + fbcs->csmr1 = CFG_CS1_MASK; +#endif + +#if (defined(CFG_CS2_BASE) && defined(CFG_CS2_MASK) && defined(CFG_CS2_CTRL)) + fbcs->csar2 = CFG_CS2_BASE; + fbcs->cscr2 = CFG_CS2_CTRL; + fbcs->csmr2 = CFG_CS2_MASK; +#endif + +#if (defined(CFG_CS3_BASE) && defined(CFG_CS3_MASK) && defined(CFG_CS3_CTRL)) + fbcs->csar3 = CFG_CS3_BASE; + fbcs->cscr3 = CFG_CS3_CTRL; + fbcs->csmr3 = CFG_CS3_MASK; +#endif + +#if (defined(CFG_CS4_BASE) && defined(CFG_CS4_MASK) && defined(CFG_CS4_CTRL)) + fbcs->csar4 = CFG_CS4_BASE; + fbcs->cscr4 = CFG_CS4_CTRL; + fbcs->csmr4 = CFG_CS4_MASK; +#endif + +#if (defined(CFG_CS5_BASE) && defined(CFG_CS5_MASK) && defined(CFG_CS5_CTRL)) + fbcs->csar5 = CFG_CS5_BASE; + fbcs->cscr5 = CFG_CS5_CTRL; + fbcs->csmr5 = CFG_CS5_MASK; +#endif + +#ifdef CONFIG_FSL_I2C + gpio->par_feci2cirq = GPIO_PAR_FECI2CIRQ_SCL | GPIO_PAR_FECI2CIRQ_SDA; +#endif + + icache_enable(); +} + +/* + * initialize higher level parts of CPU like timers + */ +int cpu_init_r(void) +{ +#if defined(CONFIG_CMD_NET) && defined(CONFIG_FSLDMAFEC) + MCD_initDma((dmaRegs *) (MMAP_MCDMA), (void *)(MMAP_SRAM + 512), + MCD_RELOC_TASKS); +#endif + return (0); +} + +void uart_port_conf(void) +{ + volatile gpio_t *gpio = (gpio_t *) MMAP_GPIO; + volatile u8 *pscsicr = (u8 *) (CFG_UART_BASE + 0x40); + + /* Setup Ports: */ + switch (CFG_UART_PORT) { + case 0: + gpio->par_psc0 = (GPIO_PAR_PSC0_TXD0 | GPIO_PAR_PSC0_RXD0); + break; + case 1: + gpio->par_psc1 = (GPIO_PAR_PSC1_TXD1 | GPIO_PAR_PSC1_RXD1); + break; + case 2: + gpio->par_psc2 = (GPIO_PAR_PSC2_TXD2 | GPIO_PAR_PSC2_RXD2); + break; + case 3: + gpio->par_psc3 = (GPIO_PAR_PSC3_TXD3 | GPIO_PAR_PSC3_RXD3); + break; + } + + *pscsicr &= 0xF8; +} diff --git a/pool/shard000/C/0014351_s5j_mct.c b/pool/shard000/C/0014351_s5j_mct.c new file mode 100644 index 0000000000000000000000000000000000000000..95162ca02e1fbcee8455ae5896b2607b5f351445 --- /dev/null +++ b/pool/shard000/C/0014351_s5j_mct.c @@ -0,0 +1,288 @@ +/**************************************************************************** + * + * Copyright 2017 Samsung Electronics 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. + * + ****************************************************************************/ +/**************************************************************************** + * arch/arm/src/s5j/s5j_mct.c + * + * Copyright (C) 2013-2014 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * 3. Neither the name NuttX nor the names of its contributors may be + * used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include + +#include "chip.h" +#include "up_internal.h" +#include "up_arch.h" + +#include "chip/s5jt200_mct.h" +#include "s5j_mct.h" + +/**************************************************************************** + * Pre-processor Definitions + ****************************************************************************/ + +/**************************************************************************** + * Private Types + ****************************************************************************/ +struct s5j_mct_priv_s { + /* mct base address */ + uint32_t base_addr; + int irq_id; +}; + +/**************************************************************************** + * Private Functions + ****************************************************************************/ +static unsigned int s5j_mct_getoscclock(void) +{ + /* TODO: get TCLKB from CLK DRIVER */ + return 26000000; +} + +static uint32_t mct_getreg32(FAR struct s5j_mct_priv_s *priv, uint32_t offset) +{ + return getreg32(priv->base_addr + offset); +} + +static void mct_putreg32(FAR struct s5j_mct_priv_s *priv, uint32_t offset, + uint32_t value) +{ + putreg32(value, priv->base_addr + offset); +} + +static int s5j_mct_setclock(uint32_t freq) +{ + uint32_t tclkb = s5j_mct_getoscclock(); + uint32_t cfg = getreg32(S5J_MCT_CFG) & 0xFFFFF800; + uint32_t prescaler = (tclkb / freq - 1); + + if (prescaler > 0xFF) { + return -EPERM; + } + + /* set value what are divide(1), and prescaler */ + putreg32(prescaler | cfg, S5J_MCT_CFG); + + return OK; +} + +static void s5j_mct_wait_wstat(uint32_t base, uint32_t bitmask) +{ + uint32_t reg = base + S5J_MCT_WSTAT_OFFSET; + + while ((getreg32(reg) & bitmask) == 0) { + /* poll */ + } + + putreg32(bitmask, reg); +} + +/**************************************************************************** + * Private Data + ****************************************************************************/ +#ifdef CONFIG_S5J_TIMER0 +static FAR struct s5j_mct_priv_s s5j_mct0_priv = { + .base_addr = (S5J_MCT_BASE + 0x300), + .irq_id = IRQ_MCT_L0, +}; +#endif + +#ifdef CONFIG_S5J_TIMER1 +static FAR struct s5j_mct_priv_s s5j_mct1_priv = { + .base_addr = (S5J_MCT_BASE + 0x400), + .irq_id = IRQ_MCT_L1, +}; +#endif + +#ifdef CONFIG_S5J_TIMER2 +static FAR struct s5j_mct_priv_s s5j_mct2_priv = { + .base_addr = (S5J_MCT_BASE + 0x500), + .irq_id = IRQ_MCT_L2, +}; +#endif + +#ifdef CONFIG_S5J_TIMER3 +static FAR struct s5j_mct_priv_s s5j_mct3_priv = { + .base_addr = (S5J_MCT_BASE + 0x600), + .irq_id = IRQ_MCT_L3, +}; +#endif + +static bool g_mct_initialized; + +/**************************************************************************** + * Pubic Functions + ****************************************************************************/ +void s5j_mct_ack_irq(FAR struct s5j_mct_priv_s *priv) +{ + unsigned int cstat = S5J_MCT_INT_CSTAT_FRC | S5J_MCT_INT_CSTAT_ICNT; + + mct_putreg32(priv, S5J_MCT_INT_CSTAT_OFFSET, cstat); +} + +void s5j_mct_setmode(FAR struct s5j_mct_priv_s *priv, bool oneshot) +{ + unsigned int value = mct_getreg32(priv, S5J_MCT_TCON_OFFSET); + + if (oneshot) { + mct_putreg32(priv, S5J_MCT_TCON_OFFSET, value & ~S5J_MCT_TCON_INTERVAL_MODE); + } else { + mct_putreg32(priv, S5J_MCT_TCON_OFFSET, value | S5J_MCT_TCON_INTERVAL_MODE); + } + + s5j_mct_wait_wstat(priv->base_addr, S5J_MCT_WSTAT_TCON); +} + +void s5j_mct_enable(FAR struct s5j_mct_priv_s *priv) +{ + unsigned int value; + + /* Start timer and enable interrupt */ + value = mct_getreg32(priv, S5J_MCT_TCON_OFFSET); + value |= S5J_MCT_TCON_INT_START | S5J_MCT_TCON_TIMER_START; + mct_putreg32(priv, S5J_MCT_TCON_OFFSET, value); + s5j_mct_wait_wstat(priv->base_addr, S5J_MCT_WSTAT_TCON); +} + +void s5j_mct_disable(FAR struct s5j_mct_priv_s *priv) +{ + unsigned int value; + + /* Stop timer and disable interrupt */ + value = mct_getreg32(priv, S5J_MCT_TCON_OFFSET); + value &= ~(S5J_MCT_TCON_TIMER_START | S5J_MCT_TCON_INT_START); + mct_putreg32(priv, S5J_MCT_TCON_OFFSET, value); + s5j_mct_wait_wstat(priv->base_addr, S5J_MCT_WSTAT_TCON); +} + +int s5j_mct_setisr(FAR struct s5j_mct_priv_s *priv, xcpt_t handler, void *arg) +{ + irq_attach(priv->irq_id, handler, arg); + + /* Enable SysTick interrupts */ + up_enable_irq(priv->irq_id); + + return OK; +} + +void s5j_mct_setperiod(FAR struct s5j_mct_priv_s *priv, uint32_t period) +{ + /* Write the appropriate values to TCNTB SFR to set the tick counter. */ + mct_putreg32(priv, S5J_MCT_TCNTB_OFFSET, period); + s5j_mct_wait_wstat(priv->base_addr, S5J_MCT_WSTAT_TCNTB); + + /* + * Write ICNTB SFR with ICNTB[31] = 1 to + * update the 31-bit internal interrupt counter. + */ + mct_putreg32(priv, S5J_MCT_ICNTB_OFFSET, 1 << 31); + s5j_mct_wait_wstat(priv->base_addr, S5J_MCT_WSTAT_ICNTB); +} + +void s5j_mct_enableint(FAR struct s5j_mct_priv_s *priv) +{ + mct_putreg32(priv, S5J_MCT_INT_ENB_OFFSET, S5J_MCT_INTR_ICNT); +} + +void s5j_mct_disableint(FAR struct s5j_mct_priv_s *priv) +{ + mct_putreg32(priv, S5J_MCT_INT_ENB_OFFSET, 0); +} + +FAR struct s5j_mct_priv_s *s5j_mct_init(int timer) +{ + FAR struct s5j_mct_priv_s *priv = NULL; + + DEBUGASSERT(timer < CONFIG_S5J_MCT_NUM); + + switch (timer) { +#ifdef CONFIG_S5J_TIMER0 + case S5J_MCT_CHANNEL0: + priv = &s5j_mct0_priv; + break; +#endif + +#ifdef CONFIG_S5J_TIMER1 + case S5J_MCT_CHANNEL1: + priv = &s5j_mct1_priv; + break; +#endif + +#ifdef CONFIG_S5J_TIMER2 + case S5J_MCT_CHANNEL2: + priv = &s5j_mct2_priv; + break; +#endif + +#ifdef CONFIG_S5J_TIMER3 + case S5J_MCT_CHANNEL3: + priv = &s5j_mct3_priv; + break; +#endif + } + + if (!g_mct_initialized && priv) { + s5j_mct_setclock(USEC_PER_SEC); + g_mct_initialized = true; + } + + return priv; +} diff --git a/pool/shard000/C/0014357_UART.c b/pool/shard000/C/0014357_UART.c new file mode 100644 index 0000000000000000000000000000000000000000..44c2aeeb832f1ab75732e1df63cb789d111afd9c --- /dev/null +++ b/pool/shard000/C/0014357_UART.c @@ -0,0 +1,31 @@ +#include "UART.h" + +void UARTInit(u16 baudrate) +{ + // Set BaudRate + REGVALUE(UBRR0L) = BAUDRATE(baudrate); + REGVALUE(UBRR0H) = BAUDRATE(baudrate) >> 8; + + // Frame Format: 8 bit, no parity, 1 stop bit + REGVALUE(UCSR0C) |= ((1<dir = Str_Clone(dir); + ivars->entry = NULL; + ABSTRACT_CLASS_CHECK(self, DIRHANDLE); + return self; +} + +void +DH_Destroy_IMP(DirHandle *self) { + DirHandleIVARS *const ivars = DH_IVARS(self); + DH_Close(self); + DECREF(ivars->dir); + DECREF(ivars->entry); + SUPER_DESTROY(self, DIRHANDLE); +} + +String* +DH_Get_Dir_IMP(DirHandle *self) { + return DH_IVARS(self)->dir; +} + +String* +DH_Get_Entry_IMP(DirHandle *self) { + String *entry = DH_IVARS(self)->entry; + return (String*)INCREF(entry); +} + + diff --git a/pool/shard000/C/0014370_gpio_backlight.c b/pool/shard000/C/0014370_gpio_backlight.c new file mode 100644 index 0000000000000000000000000000000000000000..81fb12770c2a259f1ff2a3cc45103b6bc85b5d8a --- /dev/null +++ b/pool/shard000/C/0014370_gpio_backlight.c @@ -0,0 +1,126 @@ +/* + * gpio_backlight.c - Simple GPIO-controlled backlight + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct gpio_backlight { + struct device *dev; + struct device *fbdev; + + int gpio; + int active; +}; + +static int gpio_backlight_update_status(struct backlight_device *bl) +{ + struct gpio_backlight *gbl = bl_get_data(bl); + int brightness = bl->props.brightness; + + if (bl->props.power != FB_BLANK_UNBLANK || + bl->props.fb_blank != FB_BLANK_UNBLANK || + bl->props.state & (BL_CORE_SUSPENDED | BL_CORE_FBBLANK)) + brightness = 0; + + gpio_set_value(gbl->gpio, brightness ? gbl->active : !gbl->active); + + return 0; +} + +static int gpio_backlight_get_brightness(struct backlight_device *bl) +{ + return bl->props.brightness; +} + +static int gpio_backlight_check_fb(struct backlight_device *bl, + struct fb_info *info) +{ + struct gpio_backlight *gbl = bl_get_data(bl); + + return gbl->fbdev == NULL || gbl->fbdev == info->dev; +} + +static const struct backlight_ops gpio_backlight_ops = { + .options = BL_CORE_SUSPENDRESUME, + .update_status = gpio_backlight_update_status, + .get_brightness = gpio_backlight_get_brightness, + .check_fb = gpio_backlight_check_fb, +}; + +static int gpio_backlight_probe(struct platform_device *pdev) +{ + struct gpio_backlight_platform_data *pdata = + dev_get_platdata(&pdev->dev); + struct backlight_properties props; + struct backlight_device *bl; + struct gpio_backlight *gbl; + int ret; + + if (!pdata) { + dev_err(&pdev->dev, "failed to find platform data\n"); + return -ENODEV; + } + + gbl = devm_kzalloc(&pdev->dev, sizeof(*gbl), GFP_KERNEL); + if (gbl == NULL) + return -ENOMEM; + + gbl->dev = &pdev->dev; + gbl->fbdev = pdata->fbdev; + gbl->gpio = pdata->gpio; + gbl->active = pdata->active_low ? 0 : 1; + + ret = devm_gpio_request_one(gbl->dev, gbl->gpio, GPIOF_DIR_OUT | + (gbl->active ? GPIOF_INIT_LOW + : GPIOF_INIT_HIGH), + pdata->name); + if (ret < 0) { + dev_err(&pdev->dev, "unable to request GPIO\n"); + return ret; + } + + memset(&props, 0, sizeof(props)); + props.type = BACKLIGHT_RAW; + props.max_brightness = 1; + bl = devm_backlight_device_register(&pdev->dev, dev_name(&pdev->dev), + &pdev->dev, gbl, &gpio_backlight_ops, + &props); + if (IS_ERR(bl)) { + dev_err(&pdev->dev, "failed to register backlight\n"); + return PTR_ERR(bl); + } + + bl->props.brightness = pdata->def_value; + backlight_update_status(bl); + + platform_set_drvdata(pdev, bl); + return 0; +} + +static struct platform_driver gpio_backlight_driver = { + .driver = { + .name = "gpio-backlight", + .owner = THIS_MODULE, + }, + .probe = gpio_backlight_probe, +}; + +module_platform_driver(gpio_backlight_driver); + +MODULE_AUTHOR("Laurent Pinchart "); +MODULE_DESCRIPTION("GPIO-based Backlight Driver"); +MODULE_LICENSE("GPL"); +MODULE_ALIAS("platform:gpio-backlight"); diff --git a/pool/shard000/C/0014407_lower.c b/pool/shard000/C/0014407_lower.c new file mode 100644 index 0000000000000000000000000000000000000000..2e7fe1151240b75f5939c2c464cb90650f6748b1 --- /dev/null +++ b/pool/shard000/C/0014407_lower.c @@ -0,0 +1,29 @@ +/* + * $Id: lower.c,v 1.4 2008/07/15 07:40:54 bnv Exp $ + * $Log: lower.c,v $ + * Revision 1.4 2008/07/15 07:40:54 bnv + * #include changed from <> to "" + * + * Revision 1.3 2002/06/11 12:37:15 bnv + * Added: CDECL + * + * Revision 1.2 2001/06/25 18:49:48 bnv + * Header changed to Id + * + * Revision 1.1 1998/07/02 17:18:00 bnv + * Initial Version + * + */ + +#include "lstring.h" + +/* --------------- Llower ----------------- */ +void __CDECL +Llower( const PLstr s ) +{ + size_t i; + + L2STR(s); + for (i=0; i + +#include "base/memento/memento.h" + +#include "base/errors.h" + +#include "datastruct/hash.h" + +#include "impl.h" + +error hash__walk_internal(const hash_t *hash, + hash__walk_internal_callback *cb, + void *opaque) +{ + error err; + int i; + + if (hash == NULL) + return error_OK; + + for (i = 0; i < hash->nbins; i++) + { + int j; + hash__node_t *n; + hash__node_t *next; + + j = 0; + for (n = hash->bins[i]; n != NULL; n = next) + { + next = n->next; + + err = cb(n, i, j, opaque); + if (err) + return err; + + j++; + } + } + + return error_OK; +} diff --git a/pool/shard000/C/0014414_stream.c b/pool/shard000/C/0014414_stream.c new file mode 100644 index 0000000000000000000000000000000000000000..e569645c15f0e84dfb9f7c61357c050e1e5035b8 --- /dev/null +++ b/pool/shard000/C/0014414_stream.c @@ -0,0 +1,174 @@ +/* + +----------------------------------------------------------------------+ + | Swoole | + +----------------------------------------------------------------------+ + | This source file is subject to version 2.0 of the Apache license, | + | that is bundled with this package in the file LICENSE, and is | + | available through the world-wide-web at the following url: | + | http://www.apache.org/licenses/LICENSE-2.0.html | + | If you did not receive a copy of the Apache2.0 license and are unable| + | to obtain it through the world-wide-web, please send a note to | + | license@swoole.com so we can mail you a copy immediately. | + +----------------------------------------------------------------------+ + | Author: Tianfeng Han | + +----------------------------------------------------------------------+ + */ + +#include "swoole.h" +#include "client.h" + +static void swStream_free(swStream *stream); + +static void swStream_onConnect(swClient *cli) +{ + swStream *stream = (swStream*) cli->object; + if (stream->cancel) + { + cli->close(cli); + } + *((uint32_t *) stream->buffer->str) = ntohl(stream->buffer->length - 4); + if (cli->send(cli, stream->buffer->str, stream->buffer->length, 0) < 0) + { + cli->close(cli); + } + else + { + swString_free(stream->buffer); + stream->buffer = NULL; + } +} + +static void swStream_onError(swClient *cli) +{ + swoole_error_log(SW_LOG_WARNING, SW_ERROR_SERVER_CONNECT_FAIL, + " connect() failed (%d: %s) while connecting to worker process", errno, strerror(errno)); + swStream_free(cli->object); +} + +static void swStream_onReceive(swClient *cli, char *data, uint32_t length) +{ + swStream *stream = (swStream*) cli->object; + if (length == 4) + { + cli->socket->close_wait = 1; + } + else + { + stream->response(stream, data + 4, length - 4); + } +} + +static void swStream_onClose(swClient *cli) +{ + swStream_free(cli->object); +} + +static void swStream_free(swStream *stream) +{ + if (stream->buffer) + { + swString_free(stream->buffer); + } + sw_free(stream); +} + +swStream* swStream_new(char *dst_host, int dst_port, int type) +{ + swStream *stream = (swStream*) sw_malloc(sizeof(swStream)); + if (!stream) + { + return NULL; + } + bzero(stream, sizeof(swStream)); + + swClient *cli = &stream->client; + if (swClient_create(cli, type, 1) < 0) + { + swStream_free(stream); + return NULL; + } + + cli->onConnect = swStream_onConnect; + cli->onReceive = swStream_onReceive; + cli->onError = swStream_onError; + cli->onClose = swStream_onClose; + cli->object = stream; + + cli->open_length_check = 1; + swStream_set_protocol(&cli->protocol); + + if (cli->connect(cli, dst_host, dst_port, -1, 0) < 0) + { + swSysWarn("failed to connect to [%s:%d]", dst_host, dst_port); + return NULL; + } + else + { + return stream; + } +} + +/** + * Stream Protocol: Length(32bit/Network Byte Order) + Body + */ +void swStream_set_protocol(swProtocol *protocol) +{ + protocol->get_package_length = swProtocol_get_package_length; + protocol->package_length_size = 4; + protocol->package_length_type = 'N'; + protocol->package_body_offset = 4; + protocol->package_length_offset = 0; +} + +void swStream_set_max_length(swStream *stream, uint32_t max_length) +{ + stream->client.protocol.package_max_length = max_length; +} + +int swStream_send(swStream *stream, char *data, size_t length) +{ + if (stream->buffer == NULL) + { + stream->buffer = swString_new(swoole_size_align(length + 4, SwooleG.pagesize)); + if (stream->buffer == NULL) + { + return SW_ERR; + } + stream->buffer->length = 4; + } + if (swString_append_ptr(stream->buffer, data, length) < 0) + { + return SW_ERR; + } + return SW_OK; +} + +int swStream_recv_blocking(int fd, void *__buf, size_t __len) +{ + int tmp = 0; + int ret = swSocket_recv_blocking(fd, &tmp, sizeof(tmp), MSG_WAITALL); + + if (ret <= 0) + { + return SW_CLOSE; + } + int length = ntohl(tmp); + if (length <= 0) + { + return SW_CLOSE; + } + else if (length > __len) + { + return SW_CLOSE; + } + + ret = swSocket_recv_blocking(fd, __buf, length, MSG_WAITALL); + if (ret <= 0) + { + return SW_CLOSE; + } + else + { + return SW_READY; + } +} diff --git a/pool/shard000/C/0014420_fast_synth.c b/pool/shard000/C/0014420_fast_synth.c new file mode 100644 index 0000000000000000000000000000000000000000..72c7a1cf749a25b35c6fe84a81a358c365c80bd7 --- /dev/null +++ b/pool/shard000/C/0014420_fast_synth.c @@ -0,0 +1,185 @@ +/*************************************************************************** +* +* W phase source inversion package +* ------------- +* +* Main authors: Zacharie Duputel, Luis Rivera and Hiroo Kanamori +* +* (c) California Institute of Technology and Universite de Strasbourg / CNRS +* April 2013 +* +* Neither the name of the California Institute of Technology (Caltech) +* nor the names of its contributors may be used to endorse or promote +* products derived from this software without specific prior written +* permission +* +* 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 "rwsacs.h" +#include "proto_alloc.h" +#include "read_i_files.h" +#include "travel_times.h" + +#define YES 1 +#define NON 0 + + +/* External routines */ +int read_stats(char* file, char*** stats, char*** nets, float** stlats, + float** stlons); + +void init_tapering(int nh, int nd, double h, double **dv, double **tv); + +void taper_syn(double *R, double *T, double *P, int *npts, float *dt, float *d, + double *tv, double *dv, int nd); + +void distaz(double cmt_lat, double cmt_lon, float* stlats, float* stlons, + int nstat, float* dists, float* azs, float* bazs, float* xdegs, + long int* nerr); + +void save_sac(char *stnm, char *netwk, char *chan, float *lat, float *lon, + sachdr *hdr, double* depval); + +void fast_synth_sub(double az, double baz, double xdeg, double *tv, double *dv, int nd, + str_quake_params *eq, sachdr *hdr, double **GFs, double *Z, double *TH, double *PH); + + +int main(int argc, char **argv) +{ + int j ; + /* CMT variables */ + char stat_file[FSIZE] ; + double *M1_cmt, *M2_cmt ; + str_quake_params eq ; + /* Stations variables */ + char **stats, **nets ; + float *stlats,*stlons ; + float *dists, *azs, *bazs, *xdegs ; + int jstat, nstat ; + /* Sac header variables */ + long int nerr ; + sachdr hdr ; + /* Seismograms */ + double **GFs ; + double *Z, *TH, *PH ; + /* Tapering */ + int tapering = NON, ierror = 1 ; + int nh=NDEPTHS, nd=NDISTAS ; + double *tv, *dv ; + + /* Input parameters */ + if(argc != 3 && argc != 4) + { + fprintf(stderr,"Error: syntax: fast_synth cmt_file stats_file [-t]\n") ; + exit(1) ; + } + + /* Double allocations */ + GFs = double_alloc2(10,__LEN_SIG__);/* GFs: Rrr, Rtt, Rpp, Rrt */ + Z = double_alloc(__LEN_SIG__) ; /* Vertical components */ + TH = double_alloc(__LEN_SIG__) ; /* Radial components */ + PH = double_alloc(__LEN_SIG__) ; /* Transverse components */ + M1_cmt = double_alloc(6) ; /* Moment tensor */ + M2_cmt = double_alloc(6) ; /* Rotated moment tensor */ + eq.vm = double_alloc2p(2) ; + eq.vm[1] = &M1_cmt[0] ; /* eq.vm[1] is extracted from cmtfile */ + eq.vm[0] = &M2_cmt[0] ; + tv = double_alloc(nd); /* travel times */ + dv = double_alloc(nd); /* distances */ + + /* Sac header allocation */ + hdr_init(&hdr) ; /* header for synthetics */ + + /* Tapering before the P arrival */ + if(argc == 4) + { + if (strcmp(argv[3], "-t") == 0) + { + fprintf(stdout, "Tapering between Origin and P_arrival times\n"); + tapering = YES; + } + else + fprintf(stdout, "WARNING: ignoring unknown option: %s\n", argv[3]); + } + + /* Reading the CMT file */ + strcpy(eq.cmtfile, argv[1]); + get_cmtf(&eq, 2) ; + + /* Set travel time table for depth = dep */ + trav_time_init(nh,nd,eq.evdp,dv,tv,&ierror); + + /* Reading the stations file */ + strncpy(stat_file, argv[2], FSIZE); + nstat = read_stats(stat_file, &stats, &nets, &stlats, &stlons); + + /* Float allocations */ + dists = float_calloc(nstat); + azs = float_calloc(nstat); + bazs = float_calloc(nstat); + xdegs = float_calloc(nstat); + + /* Distance, azimuth, back-azimuth, etc */ + distaz(eq.evla, eq.evlo, stlats, stlons, nstat, dists, azs, bazs, xdegs, &nerr); + hdr.o = 0.; /* otime */ + + /* Treating each station */ + for(jstat=0;jstat< nstat;jstat++) + { + printf("%-5s", stats[jstat]) ; + fast_synth_sub(azs[jstat], bazs[jstat], xdegs[jstat], tv, dv, nd, &eq, &hdr, GFs, Z, TH, PH); + if (tapering == YES) + taper_syn(Z,TH,PH,&hdr.npts,&hdr.delta,&(xdegs[jstat]),tv,dv,nd) ; + + save_sac(stats[jstat], nets[jstat], "LHZ", &stlats[jstat] , &stlons[jstat], &hdr, Z) ; + save_sac(stats[jstat], nets[jstat], "LHL", &stlats[jstat] , &stlons[jstat], &hdr,TH) ; + save_sac(stats[jstat], nets[jstat], "LHT", &stlats[jstat] , &stlons[jstat], &hdr,PH) ; + } + + /* Freeing memory */ + free((void *) Z) ; + free((void *) PH) ; + free((void *) TH) ; + for(j=0; j<10; j++) + free((void *)GFs[j]); + free((void**)GFs) ; + free((void *)M1_cmt) ; + free((void *)M2_cmt) ; + free((void**)eq.vm) ; + free((void *)dists) ; + free((void *)azs) ; + free((void *)bazs) ; + free((void *)xdegs) ; + for (j=0;j< nstat;j++) + { + free((void *) stats[j]) ; + free((void *) nets[j]) ; + } + free((void **) stats) ; + free((void **) nets) ; + free((void *) stlats) ; + free((void *) stlons) ; + if(tapering == YES) + { + free((void *) tv); + free((void *) dv); + } + printf("\n"); + exit(0); +} diff --git a/pool/shard000/C/0014448_gss-8064.c b/pool/shard000/C/0014448_gss-8064.c new file mode 100644 index 0000000000000000000000000000000000000000..7b77a2a2244715b73fb62ade951a54c1220a7890 --- /dev/null +++ b/pool/shard000/C/0014448_gss-8064.c @@ -0,0 +1,271 @@ +/* Copyright (c) 2012, The Linux Foundation. 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 version 2 and + * only 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. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "smd_private.h" +#include "modem_notifier.h" +#include "ramdump.h" +#ifdef CONFIG_RAMDUMP_TAGS +#include +#endif + +static struct gss_8064_data { + struct miscdevice gss_dev; + void *pil_handle; + void *gss_ramdump_dev; + void *smem_ramdump_dev; +} gss_data; + +static int crash_shutdown; + +static struct subsys_device *gss_8064_dev; + +#define MAX_SSR_REASON_LEN 81U + +static void log_gss_sfr(void) +{ + u32 size; + char *smem_reason, reason[MAX_SSR_REASON_LEN]; + + smem_reason = smem_get_entry(SMEM_SSR_REASON_MSS0, &size); + if (!smem_reason || !size) { + pr_err("GSS subsystem failure reason: (unknown, smem_get_entry failed).\n"); + return; + } + if (!smem_reason[0]) { + pr_err("GSS subsystem failure reason: (unknown, init string found).\n"); + return; + } + + size = min(size, MAX_SSR_REASON_LEN-1); + memcpy(reason, smem_reason, size); + reason[size] = '\0'; + pr_err("GSS subsystem failure reason: %s.\n", reason); +#ifdef CONFIG_RAMDUMP_TAGS + rdtags_add_tag("ssr_reason", reason, strnlen(reason, MAX_SSR_REASON_LEN - 1) + 1); +#endif + + smem_reason[0] = '\0'; + wmb(); +} + +static void restart_gss(void) +{ + log_gss_sfr(); + subsystem_restart_dev(gss_8064_dev); +} + +static void smsm_state_cb(void *data, uint32_t old_state, uint32_t new_state) +{ + /* Ignore if we're the one that set SMSM_RESET */ + if (crash_shutdown) + return; + + if (new_state & SMSM_RESET) { + pr_err("GSS SMSM state changed to SMSM_RESET.\n" + "Probable err_fatal on the GSS. " + "Calling subsystem restart...\n"); + restart_gss(); + } +} + +#define Q6_FW_WDOG_ENABLE 0x08882024 +#define Q6_SW_WDOG_ENABLE 0x08982024 +static int gss_shutdown(const struct subsys_desc *desc) +{ + pil_force_shutdown("gss"); + disable_irq_nosync(GSS_A5_WDOG_EXPIRED); + + return 0; +} + +static int gss_powerup(const struct subsys_desc *desc) +{ + pil_force_boot("gss"); + enable_irq(GSS_A5_WDOG_EXPIRED); + return 0; +} + +void gss_crash_shutdown(const struct subsys_desc *desc) +{ + crash_shutdown = 1; + smsm_reset_modem(SMSM_RESET); +} + +/* FIXME: Get address, size from PIL */ +static struct ramdump_segment gss_segments[] = { + {0x89000000, 0x00D00000} +}; + +static struct ramdump_segment smem_segments[] = { + {0x80000000, 0x00200000}, +}; + +static int gss_ramdump(int enable, + const struct subsys_desc *crashed_subsys) +{ + int ret = 0; + + if (enable) { + ret = do_ramdump(gss_data.gss_ramdump_dev, gss_segments, + ARRAY_SIZE(gss_segments)); + + if (ret < 0) { + pr_err("Unable to dump gss memory (rc = %d).\n", + ret); + goto out; + } + + ret = do_ramdump(gss_data.smem_ramdump_dev, smem_segments, + ARRAY_SIZE(smem_segments)); + + if (ret < 0) { + pr_err("Unable to dump smem memory (rc = %d).\n", ret); + goto out; + } + } + +out: + return ret; +} + +static irqreturn_t gss_wdog_bite_irq(int irq, void *dev_id) +{ + pr_err("Watchdog bite received from GSS!\n"); + restart_gss(); + + return IRQ_HANDLED; +} + +static struct subsys_desc gss_8064 = { + .name = "gss", + .shutdown = gss_shutdown, + .powerup = gss_powerup, + .ramdump = gss_ramdump, + .crash_shutdown = gss_crash_shutdown +}; + +static int gss_subsystem_restart_init(void) +{ + gss_8064_dev = subsys_register(&gss_8064); + if (IS_ERR(gss_8064_dev)) + return PTR_ERR(gss_8064_dev); + return 0; +} + +static int gss_open(struct inode *inode, struct file *filep) +{ + void *ret; + gss_data.pil_handle = ret = pil_get("gss"); + if (!ret) + pr_debug("%s - pil_get returned NULL\n", __func__); + return 0; +} + +static int gss_release(struct inode *inode, struct file *filep) +{ + pil_put(gss_data.pil_handle); + pr_debug("%s pil_put called on GSS\n", __func__); + return 0; +} + +const struct file_operations gss_file_ops = { + .open = gss_open, + .release = gss_release, +}; + +static int __init gss_8064_init(void) +{ + int ret; + + if (!(soc_class_is_apq8064())) + return -ENODEV; + + ret = smsm_state_cb_register(SMSM_MODEM_STATE, SMSM_RESET, + smsm_state_cb, 0); + + if (ret < 0) + pr_err("%s: Unable to register SMSM callback! (%d)\n", + __func__, ret); + + ret = request_irq(GSS_A5_WDOG_EXPIRED, gss_wdog_bite_irq, + IRQF_TRIGGER_RISING, "gss_a5_wdog", NULL); + + if (ret < 0) { + pr_err("%s: Unable to request gss watchdog IRQ. (%d)\n", + __func__, ret); + disable_irq_nosync(GSS_A5_WDOG_EXPIRED); + goto out; + } + + ret = gss_subsystem_restart_init(); + + if (ret < 0) { + pr_err("%s: Unable to reg with subsystem restart. (%d)\n", + __func__, ret); + goto out; + } + + gss_data.gss_dev.minor = MISC_DYNAMIC_MINOR; + gss_data.gss_dev.name = "gss"; + gss_data.gss_dev.fops = &gss_file_ops; + ret = misc_register(&gss_data.gss_dev); + + if (ret) { + pr_err("%s: misc_registers failed for %s (%d)", __func__, + gss_data.gss_dev.name, ret); + goto out; + } + + gss_data.gss_ramdump_dev = create_ramdump_device("gss"); + + if (!gss_data.gss_ramdump_dev) { + pr_err("%s: Unable to create gss ramdump device. (%d)\n", + __func__, -ENOMEM); + ret = -ENOMEM; + goto out; + } + + gss_data.smem_ramdump_dev = create_ramdump_device("smem-gss"); + + if (!gss_data.smem_ramdump_dev) { + pr_err("%s: Unable to create smem ramdump device. (%d)\n", + __func__, -ENOMEM); + ret = -ENOMEM; + goto out; + } + + pr_info("%s: gss fatal driver init'ed.\n", __func__); +out: + return ret; +} + +module_init(gss_8064_init); diff --git a/pool/shard000/C/0014481_CWE195_Signed_to_Unsigned_Conversion_Error__connect_socket_malloc_31.c b/pool/shard000/C/0014481_CWE195_Signed_to_Unsigned_Conversion_Error__connect_socket_malloc_31.c new file mode 100644 index 0000000000000000000000000000000000000000..d7ef6205a34463336ab26f46243cf62300a14993 --- /dev/null +++ b/pool/shard000/C/0014481_CWE195_Signed_to_Unsigned_Conversion_Error__connect_socket_malloc_31.c @@ -0,0 +1,183 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE195_Signed_to_Unsigned_Conversion_Error__connect_socket_malloc_31.c +Label Definition File: CWE195_Signed_to_Unsigned_Conversion_Error.label.xml +Template File: sources-sink-31.tmpl.c +*/ +/* + * @description + * CWE: 195 Signed to Unsigned Conversion Error + * BadSource: connect_socket Read data using a connect socket (client side) + * GoodSource: Positive integer + * Sinks: malloc + * BadSink : Allocate memory using malloc() with the size of data + * Flow Variant: 31 Data flow using a copy of data within the same function + * + * */ + +#include "std_testcase.h" + +#ifdef _WIN32 +#include +#include +#include +#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */ +#define CLOSE_SOCKET closesocket +#else /* NOT _WIN32 */ +#include +#include +#include +#include +#include +#define INVALID_SOCKET -1 +#define SOCKET_ERROR -1 +#define CLOSE_SOCKET close +#define SOCKET int +#endif + +#define TCP_PORT 27015 +#define IP_ADDRESS "127.0.0.1" +#define CHAR_ARRAY_SIZE (3 * sizeof(data) + 2) + +#ifndef OMITBAD + +void CWE195_Signed_to_Unsigned_Conversion_Error__connect_socket_malloc_31_bad() +{ + int data; + /* Initialize data */ + data = -1; + { +#ifdef _WIN32 + WSADATA wsaData; + int wsaDataInit = 0; +#endif + int recvResult; + struct sockaddr_in service; + SOCKET connectSocket = INVALID_SOCKET; + char inputBuffer[CHAR_ARRAY_SIZE]; + do + { +#ifdef _WIN32 + if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) + { + break; + } + wsaDataInit = 1; +#endif + /* POTENTIAL FLAW: Read data using a connect socket */ + connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (connectSocket == INVALID_SOCKET) + { + break; + } + memset(&service, 0, sizeof(service)); + service.sin_family = AF_INET; + service.sin_addr.s_addr = inet_addr(IP_ADDRESS); + service.sin_port = htons(TCP_PORT); + if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) + { + break; + } + /* Abort on error or the connection was closed, make sure to recv one + * less char than is in the recv_buf in order to append a terminator */ + recvResult = recv(connectSocket, inputBuffer, CHAR_ARRAY_SIZE - 1, 0); + if (recvResult == SOCKET_ERROR || recvResult == 0) + { + break; + } + /* NUL-terminate the string */ + inputBuffer[recvResult] = '\0'; + /* Convert to int */ + data = atoi(inputBuffer); + } + while (0); + if (connectSocket != INVALID_SOCKET) + { + CLOSE_SOCKET(connectSocket); + } +#ifdef _WIN32 + if (wsaDataInit) + { + WSACleanup(); + } +#endif + } + { + int dataCopy = data; + int data = dataCopy; + /* Assume we want to allocate a relatively small buffer */ + if (data < 100) + { + /* POTENTIAL FLAW: malloc() takes a size_t (unsigned int) as input and therefore if it is negative, + * the conversion will cause malloc() to allocate a very large amount of data or fail */ + char * dataBuffer = (char *)malloc(data); + /* Do something with dataBuffer */ + memset(dataBuffer, 'A', data-1); + dataBuffer[data-1] = '\0'; + printLine(dataBuffer); + free(dataBuffer); + } + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B() uses the GoodSource with the BadSink */ +static void goodG2B() +{ + int data; + /* Initialize data */ + data = -1; + /* FIX: Use a positive integer less than &InitialDataSize&*/ + data = 100-1; + { + int dataCopy = data; + int data = dataCopy; + /* Assume we want to allocate a relatively small buffer */ + if (data < 100) + { + /* POTENTIAL FLAW: malloc() takes a size_t (unsigned int) as input and therefore if it is negative, + * the conversion will cause malloc() to allocate a very large amount of data or fail */ + char * dataBuffer = (char *)malloc(data); + /* Do something with dataBuffer */ + memset(dataBuffer, 'A', data-1); + dataBuffer[data-1] = '\0'; + printLine(dataBuffer); + free(dataBuffer); + } + } +} + +void CWE195_Signed_to_Unsigned_Conversion_Error__connect_socket_malloc_31_good() +{ + goodG2B(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + * its own for testing or for building a binary to use in testing binary + * analysis tools. It is not used when compiling all the testcases as one + * application, which is how source code analysis tools are tested. + */ +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE195_Signed_to_Unsigned_Conversion_Error__connect_socket_malloc_31_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE195_Signed_to_Unsigned_Conversion_Error__connect_socket_malloc_31_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard000/C/0014486_CWE78_OS_Command_Injection__wchar_t_console_w32_execvp_41.c b/pool/shard000/C/0014486_CWE78_OS_Command_Injection__wchar_t_console_w32_execvp_41.c new file mode 100644 index 0000000000000000000000000000000000000000..74f4eda8590151b164b95e11a484b0055b3dd02b --- /dev/null +++ b/pool/shard000/C/0014486_CWE78_OS_Command_Injection__wchar_t_console_w32_execvp_41.c @@ -0,0 +1,143 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE78_OS_Command_Injection__wchar_t_console_w32_execvp_41.c +Label Definition File: CWE78_OS_Command_Injection.strings.label.xml +Template File: sources-sink-41.tmpl.c +*/ +/* + * @description + * CWE: 78 OS Command Injection + * BadSource: console Read input from the console + * GoodSource: Fixed string + * Sink: w32_execvp + * BadSink : execute command with wexecvp + * Flow Variant: 41 Data flow: data passed as an argument from one function to another in the same source file + * + * */ + +#include "std_testcase.h" + +#include + +#ifdef _WIN32 +#define COMMAND_INT_PATH L"%WINDIR%\\system32\\cmd.exe" +#define COMMAND_INT L"cmd.exe" +#define COMMAND_ARG1 L"/c" +#define COMMAND_ARG2 L"dir " +#define COMMAND_ARG3 data +#else /* NOT _WIN32 */ +#include +#define COMMAND_INT_PATH L"/bin/sh" +#define COMMAND_INT L"sh" +#define COMMAND_ARG1 L"-c" +#define COMMAND_ARG2 L"ls " +#define COMMAND_ARG3 data +#endif + +#include +#define EXECVP _wexecvp + +#ifndef OMITBAD + +void CWE78_OS_Command_Injection__wchar_t_console_w32_execvp_41_badSink(wchar_t * data) +{ + { + wchar_t *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG3, NULL}; + /* wexecvp - searches for the location of the command among + * the directories specified by the PATH environment variable */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + EXECVP(COMMAND_INT, args); + } +} + +void CWE78_OS_Command_Injection__wchar_t_console_w32_execvp_41_bad() +{ + wchar_t * data; + wchar_t dataBuffer[100] = COMMAND_ARG2; + data = dataBuffer; + { + /* Read input from the console */ + size_t dataLen = wcslen(data); + /* if there is room in data, read into it from the console */ + if (100-dataLen > 1) + { + /* POTENTIAL FLAW: Read data from the console */ + if (fgetws(data+dataLen, (int)(100-dataLen), stdin) != NULL) + { + /* The next few lines remove the carriage return from the string that is + * inserted by fgetws() */ + dataLen = wcslen(data); + if (dataLen > 0 && data[dataLen-1] == L'\n') + { + data[dataLen-1] = L'\0'; + } + } + else + { + printLine("fgetws() failed"); + /* Restore NUL terminator if fgetws fails */ + data[dataLen] = L'\0'; + } + } + } + CWE78_OS_Command_Injection__wchar_t_console_w32_execvp_41_badSink(data); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +void CWE78_OS_Command_Injection__wchar_t_console_w32_execvp_41_goodG2BSink(wchar_t * data) +{ + { + wchar_t *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG3, NULL}; + /* wexecvp - searches for the location of the command among + * the directories specified by the PATH environment variable */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + EXECVP(COMMAND_INT, args); + } +} + +/* goodG2B uses the GoodSource with the BadSink */ +static void goodG2B() +{ + wchar_t * data; + wchar_t dataBuffer[100] = COMMAND_ARG2; + data = dataBuffer; + /* FIX: Append a fixed string to data (not user / external input) */ + wcscat(data, L"*.*"); + CWE78_OS_Command_Injection__wchar_t_console_w32_execvp_41_goodG2BSink(data); +} + +void CWE78_OS_Command_Injection__wchar_t_console_w32_execvp_41_good() +{ + goodG2B(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + * its own for testing or for building a binary to use in testing binary + * analysis tools. It is not used when compiling all the testcases as one + * application, which is how source code analysis tools are tested. + */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE78_OS_Command_Injection__wchar_t_console_w32_execvp_41_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE78_OS_Command_Injection__wchar_t_console_w32_execvp_41_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard000/C/0014500_rapl_plot.c b/pool/shard000/C/0014500_rapl_plot.c new file mode 100644 index 0000000000000000000000000000000000000000..a6ec01092ae2a99ec3776d73e4281713f540d18a --- /dev/null +++ b/pool/shard000/C/0014500_rapl_plot.c @@ -0,0 +1,146 @@ +/** + * @author Vince Weaver + */ + +#include +#include +#include +#include + +#include "papi.h" + +#define NUM_EVENTS 6 + +char events[NUM_EVENTS][BUFSIZ]={ + "PACKAGE_ENERGY:PACKAGE0", + "PACKAGE_ENERGY:PACKAGE1", + "DRAM_ENERGY:PACKAGE0", + "DRAM_ENERGY:PACKAGE1", + "PP0_ENERGY:PACKAGE0", + "PP0_ENERGY:PACKAGE1", +}; + +char filenames[NUM_EVENTS][BUFSIZ]={ + "results.PACKAGE_ENERGY_PACKAGE0", + "results.PACKAGE_ENERGY_PACKAGE1", + "results.DRAM_ENERGY_PACKAGE0", + "results.DRAM_ENERGY_PACKAGE1", + "results.PP0_ENERGY_PACKAGE0", + "results.PP0_ENERGY_PACKAGE1", +}; + +FILE *fff[NUM_EVENTS]; + + +int main (int argc, char **argv) +{ + + int retval,cid,rapl_cid=-1,numcmp; + int EventSet = PAPI_NULL; + long long values[NUM_EVENTS]; + int i; + const PAPI_component_info_t *cmpinfo = NULL; + long long start_time,before_time,after_time; + double elapsed_time,total_time; + + + + /* PAPI Initialization */ + retval = PAPI_library_init( PAPI_VER_CURRENT ); + if ( retval != PAPI_VER_CURRENT ) { + fprintf(stderr,"PAPI_library_init failed\n"); + exit(1); + } + + numcmp = PAPI_num_components(); + + for(cid=0; cidname,"linux-rapl")) { + rapl_cid=cid; + printf("Found rapl component at cid %d\n", rapl_cid); + + if (cmpinfo->num_native_events==0) { + fprintf(stderr,"No rapl events found\n"); + exit(1); + } + break; + } + } + + /* Component not found */ + if (cid==numcmp) { + fprintf(stderr,"No rapl component found\n"); + exit(1); + } + + + /* Open output files */ + for(i=0;i + * + * based on + * Allwinner SoCs Reset Controller driver + * + * Copyright 2013 Maxime Ripard + * + * Maxime Ripard + * + * 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 + +#define NR_BANKS 4 + +struct socfpga_reset_data { + spinlock_t lock; + void __iomem *membase; + u32 modrst_offset; + struct reset_controller_dev rcdev; +}; + +static int socfpga_reset_assert(struct reset_controller_dev *rcdev, + unsigned long id) +{ + struct socfpga_reset_data *data = container_of(rcdev, + struct socfpga_reset_data, + rcdev); + int bank = id / BITS_PER_LONG; + int offset = id % BITS_PER_LONG; + unsigned long flags; + u32 reg; + + spin_lock_irqsave(&data->lock, flags); + + reg = readl(data->membase + data->modrst_offset + (bank * NR_BANKS)); + writel(reg | BIT(offset), data->membase + data->modrst_offset + + (bank * NR_BANKS)); + spin_unlock_irqrestore(&data->lock, flags); + + return 0; +} + +static int socfpga_reset_deassert(struct reset_controller_dev *rcdev, + unsigned long id) +{ + struct socfpga_reset_data *data = container_of(rcdev, + struct socfpga_reset_data, + rcdev); + + int bank = id / BITS_PER_LONG; + int offset = id % BITS_PER_LONG; + unsigned long flags; + u32 reg; + + spin_lock_irqsave(&data->lock, flags); + + reg = readl(data->membase + data->modrst_offset + (bank * NR_BANKS)); + writel(reg & ~BIT(offset), data->membase + data->modrst_offset + + (bank * NR_BANKS)); + + spin_unlock_irqrestore(&data->lock, flags); + + return 0; +} + +static int socfpga_reset_status(struct reset_controller_dev *rcdev, + unsigned long id) +{ + struct socfpga_reset_data *data = container_of(rcdev, + struct socfpga_reset_data, rcdev); + int bank = id / BITS_PER_LONG; + int offset = id % BITS_PER_LONG; + u32 reg; + + reg = readl(data->membase + data->modrst_offset + (bank * NR_BANKS)); + + return !(reg & BIT(offset)); +} + +static const struct reset_control_ops socfpga_reset_ops = { + .assert = socfpga_reset_assert, + .deassert = socfpga_reset_deassert, + .status = socfpga_reset_status, +}; + +static int socfpga_reset_probe(struct platform_device *pdev) +{ + struct socfpga_reset_data *data; + struct resource *res; + struct device *dev = &pdev->dev; + struct device_node *np = dev->of_node; + + /* + * The binding was mainlined without the required property. + * Do not continue, when we encounter an old DT. + */ + if (!of_find_property(pdev->dev.of_node, "#reset-cells", NULL)) { + dev_err(&pdev->dev, "%s missing #reset-cells property\n", + pdev->dev.of_node->full_name); + return -EINVAL; + } + + data = devm_kzalloc(&pdev->dev, sizeof(*data), GFP_KERNEL); + if (!data) + return -ENOMEM; + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + data->membase = devm_ioremap_resource(&pdev->dev, res); + if (IS_ERR(data->membase)) + return PTR_ERR(data->membase); + + if (of_property_read_u32(np, "altr,modrst-offset", &data->modrst_offset)) { + dev_warn(dev, "missing altr,modrst-offset property, assuming 0x10!\n"); + data->modrst_offset = 0x10; + } + + spin_lock_init(&data->lock); + + data->rcdev.owner = THIS_MODULE; + data->rcdev.nr_resets = NR_BANKS * BITS_PER_LONG; + data->rcdev.ops = &socfpga_reset_ops; + data->rcdev.of_node = pdev->dev.of_node; + + return devm_reset_controller_register(dev, &data->rcdev); +} + +static const struct of_device_id socfpga_reset_dt_ids[] = { + { .compatible = "altr,rst-mgr", }, + { /* sentinel */ }, +}; + +static struct platform_driver socfpga_reset_driver = { + .probe = socfpga_reset_probe, + .driver = { + .name = "socfpga-reset", + .of_match_table = socfpga_reset_dt_ids, + }, +}; +module_platform_driver(socfpga_reset_driver); + +MODULE_AUTHOR("Steffen Trumtrar + +#define MAXLINE 1000 +#define COL_WIDTH 8 + +void detab(char from[], char to[]); +void entab(char from[], char to[]); +int my_getline(char s[], int lim); + +/* replace spaces in input with appropriate number of spaces and tabs */ +int main() +{ + int len; + char line[MAXLINE]; + char line_detabbed[MAXLINE]; + char line_entabbed[MAXLINE]; + + while ((len=my_getline(line, MAXLINE)) > 0){ + detab(line, line_detabbed); + entab(line_detabbed, line_entabbed); + printf("%s", line_entabbed); + } + return 0; +} + +int my_getline(char s[], int lim) +{ + int c, i; + + for (i=0; i 0) + to[i_to++] = ' '; + i_from++; + } + + } + to[i_to] = '\0'; +} +/* replace blank space with appropriate number of spaces and tabs + * assumes no tabs in input */ +void entab(char from[], char to[]) +{ + int i_from; + int i_to; + + i_from = 0; + i_to = 0; + + int num_white = 0; + + while(from[i_from] != '\0'){ + /* four cases: + * non-space, not leaving space - just copy and move on + * non-space, leaving space - if tab boundary, add tab + * else, put back spaces + * space, not tab boundary - increment num_white + * space, tab boundary - insert tab, reset num_white */ + if (from[i_from] != ' '){ + if (num_white != 0) { + if ((i_from % COL_WIDTH) == 0) + to[i_to++] = '\t'; + else { + while(num_white-- > 0) + to[i_to++] = ' '; + } + num_white = 0; + } + to[i_to++] = from[i_from++]; + } + else { + if ((i_from % COL_WIDTH) != (COL_WIDTH - 1)) + num_white++; + else { + to[i_to++] = '\t'; + num_white = 0; + } + i_from++; + } + } + to[i_to] = '\0'; +} diff --git a/pool/shard000/C/0014514_ccp_tick_start.c b/pool/shard000/C/0014514_ccp_tick_start.c new file mode 100644 index 0000000000000000000000000000000000000000..0ac65a1ae8dc866099b6ee31b1fee89385d9199b --- /dev/null +++ b/pool/shard000/C/0014514_ccp_tick_start.c @@ -0,0 +1,42 @@ +/**************************************************************** + * * + * Copyright 2001 Sanchez Computer Associates, Inc. * + * * + * This source code contains the intellectual property * + * of its copyright holder(s), and is made available * + * under a license. If you do not know the terms of * + * the license, please stop and do not read further. * + * * + ****************************************************************/ + +#include "mdef.h" +#include "gdsroot.h" +#include "gtm_facility.h" +#include "fileinfo.h" +#include "gdsbt.h" +#include "gdsfhead.h" +#include "ccp.h" +#include + + +/* AST routine called from ccp_exitwm_blkast, ccp_gotdrt_tick, and ccp_tick_interrupt */ + +void ccp_tick_start( ccp_db_header *db) +{ + uint4 status; + + + assert(lib$ast_in_prog()); + assert(!db->quantum_expired); + assert(db->wmexit_requested); + assert(db->segment->nl->ccp_state != CCST_WMXREQ); + + db->tick_in_progress = TRUE; + db->tick_tn = db->segment->ti->curr_tn; + + status = sys$setimr(0, &db->glob_sec->ccp_tick_interval, ccp_tick_interrupt, &db->tick_timer_id, 0); + if (status != SS$_NORMAL) + ccp_signal_cont(status); /***** Is this reasonable? *****/ + + return; +} diff --git a/pool/shard000/C/0014519_plan-dft-r2c-3d.c b/pool/shard000/C/0014519_plan-dft-r2c-3d.c new file mode 100644 index 0000000000000000000000000000000000000000..1d74be48c173a5d3d60258f482dea5f47f801ad1 --- /dev/null +++ b/pool/shard000/C/0014519_plan-dft-r2c-3d.c @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2003, 2007-8 Matteo Frigo + * Copyright (c) 2003, 2007-8 Massachusetts Institute of Technology + * + * See the file COPYING for license information. + * + */ + +#include "api.h" + +X(plan) X(plan_dft_r2c_3d)(int nx, int ny, int nz, + R *in, C *out, unsigned flags) +{ + int n[3]; + n[0] = nx; + n[1] = ny; + n[2] = nz; + return X(plan_dft_r2c)(3, n, in, out, flags); +} diff --git a/pool/shard000/C/0014524_mbedtls_threadlock.c b/pool/shard000/C/0014524_mbedtls_threadlock.c new file mode 100644 index 0000000000000000000000000000000000000000..473f5171e2c97f06113eabae920631acfa5bc59a --- /dev/null +++ b/pool/shard000/C/0014524_mbedtls_threadlock.c @@ -0,0 +1,144 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) 2013 - 2020, Daniel Stenberg, , et al. + * Copyright (C) 2010, 2011, Hoi-Ho Chan, + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ***************************************************************************/ +#include "curl_setup.h" + +#if defined(USE_MBEDTLS) && \ + ((defined(USE_THREADS_POSIX) && defined(HAVE_PTHREAD_H)) || \ + (defined(USE_THREADS_WIN32) && defined(HAVE_PROCESS_H))) + +#if defined(USE_THREADS_POSIX) && defined(HAVE_PTHREAD_H) +# include +# define MBEDTLS_MUTEX_T pthread_mutex_t +#elif defined(USE_THREADS_WIN32) && defined(HAVE_PROCESS_H) +# include +# define MBEDTLS_MUTEX_T HANDLE +#endif + +#include "mbedtls_threadlock.h" +#include "curl_printf.h" +#include "curl_memory.h" +/* The last #include file should be: */ +#include "memdebug.h" + +/* number of thread locks */ +#define NUMT 2 + +/* This array will store all of the mutexes available to Mbedtls. */ +static MBEDTLS_MUTEX_T *mutex_buf = NULL; + +int Curl_mbedtlsthreadlock_thread_setup(void) +{ + int i; + + mutex_buf = calloc(NUMT * sizeof(MBEDTLS_MUTEX_T), 1); + if(!mutex_buf) + return 0; /* error, no number of threads defined */ + + for(i = 0; i < NUMT; i++) { + int ret; +#if defined(USE_THREADS_POSIX) && defined(HAVE_PTHREAD_H) + ret = pthread_mutex_init(&mutex_buf[i], NULL); + if(ret) + return 0; /* pthread_mutex_init failed */ +#elif defined(USE_THREADS_WIN32) && defined(HAVE_PROCESS_H) + mutex_buf[i] = CreateMutex(0, FALSE, 0); + if(mutex_buf[i] == 0) + return 0; /* CreateMutex failed */ +#endif /* USE_THREADS_POSIX && HAVE_PTHREAD_H */ + } + + return 1; /* OK */ +} + +int Curl_mbedtlsthreadlock_thread_cleanup(void) +{ + int i; + + if(!mutex_buf) + return 0; /* error, no threads locks defined */ + + for(i = 0; i < NUMT; i++) { + int ret; +#if defined(USE_THREADS_POSIX) && defined(HAVE_PTHREAD_H) + ret = pthread_mutex_destroy(&mutex_buf[i]); + if(ret) + return 0; /* pthread_mutex_destroy failed */ +#elif defined(USE_THREADS_WIN32) && defined(HAVE_PROCESS_H) + ret = CloseHandle(mutex_buf[i]); + if(!ret) + return 0; /* CloseHandle failed */ +#endif /* USE_THREADS_POSIX && HAVE_PTHREAD_H */ + } + free(mutex_buf); + mutex_buf = NULL; + + return 1; /* OK */ +} + +int Curl_mbedtlsthreadlock_lock_function(int n) +{ + if(n < NUMT) { + int ret; +#if defined(USE_THREADS_POSIX) && defined(HAVE_PTHREAD_H) + ret = pthread_mutex_lock(&mutex_buf[n]); + if(ret) { + DEBUGF(fprintf(stderr, + "Error: mbedtlsthreadlock_lock_function failed\n")); + return 0; /* pthread_mutex_lock failed */ + } +#elif defined(USE_THREADS_WIN32) && defined(HAVE_PROCESS_H) + ret = (WaitForSingleObject(mutex_buf[n], INFINITE) == WAIT_FAILED?1:0); + if(ret) { + DEBUGF(fprintf(stderr, + "Error: mbedtlsthreadlock_lock_function failed\n")); + return 0; /* pthread_mutex_lock failed */ + } +#endif /* USE_THREADS_POSIX && HAVE_PTHREAD_H */ + } + return 1; /* OK */ +} + +int Curl_mbedtlsthreadlock_unlock_function(int n) +{ + if(n < NUMT) { + int ret; +#if defined(USE_THREADS_POSIX) && defined(HAVE_PTHREAD_H) + ret = pthread_mutex_unlock(&mutex_buf[n]); + if(ret) { + DEBUGF(fprintf(stderr, + "Error: mbedtlsthreadlock_unlock_function failed\n")); + return 0; /* pthread_mutex_unlock failed */ + } +#elif defined(USE_THREADS_WIN32) && defined(HAVE_PROCESS_H) + ret = ReleaseMutex(mutex_buf[n]); + if(!ret) { + DEBUGF(fprintf(stderr, + "Error: mbedtlsthreadlock_unlock_function failed\n")); + return 0; /* pthread_mutex_lock failed */ + } +#endif /* USE_THREADS_POSIX && HAVE_PTHREAD_H */ + } + return 1; /* OK */ +} + +#endif /* USE_MBEDTLS */ diff --git a/pool/shard000/C/0014530_nm-fake-rdisc.c b/pool/shard000/C/0014530_nm-fake-rdisc.c new file mode 100644 index 0000000000000000000000000000000000000000..f39c5a208c81c97edadc475d69254d05e08b2362 --- /dev/null +++ b/pool/shard000/C/0014530_nm-fake-rdisc.c @@ -0,0 +1,133 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */ +/* nm-fake-rdisc.c - Fake implementation of router discovery + * + * 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, 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. + * + * Copyright (C) 2013 Red Hat, Inc. + */ + +#include +#include + +#include "nm-fake-rdisc.h" + +#include "nm-logging.h" + +#define debug(...) nm_log_dbg (LOGD_IP6, __VA_ARGS__) +#define warning(...) nm_log_warn (LOGD_IP6, __VA_ARGS__) +#define error(...) nm_log_err (LOGD_IP6, __VA_ARGS__) + +#define NM_FAKE_RDISC_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), NM_TYPE_FAKE_RDISC, NMFakeRDiscPrivate)) + +G_DEFINE_TYPE (NMFakeRDisc, nm_fake_rdisc, NM_TYPE_RDISC) + +/******************************************************************/ + +NMRDisc * +nm_fake_rdisc_new (int ifindex, const char *ifname) +{ + NMRDisc *rdisc = g_object_new (NM_TYPE_FAKE_RDISC, NULL); + + g_assert (rdisc); + + rdisc->ifindex = ifindex; + rdisc->ifname = g_strdup (ifname); + + return rdisc; +} + +static void +delayed_start (NMRDisc *rdisc) +{ + int changed = + NM_RDISC_CONFIG_GATEWAYS | NM_RDISC_CONFIG_ADDRESSES | NM_RDISC_CONFIG_ROUTES | + NM_RDISC_CONFIG_DNS_SERVERS | NM_RDISC_CONFIG_DNS_DOMAINS; + debug ("%d", rdisc->dhcp_level); + + g_signal_emit_by_name ( + rdisc, NM_RDISC_CONFIG_CHANGED, changed); +} + +static void +start (NMRDisc *rdisc) +{ + g_idle_add ((GSourceFunc) (delayed_start), rdisc); +} + +/******************************************************************/ + +static void +nm_fake_rdisc_init (NMFakeRDisc *fake_rdisc) +{ + NMRDisc *rdisc = NM_RDISC (fake_rdisc); + NMRDiscGateway gateway; + NMRDiscAddress address; + NMRDiscRoute route; + NMRDiscDNSServer dns_server; + NMRDiscDNSDomain dns_domain; + + rdisc->dhcp_level = NM_RDISC_DHCP_LEVEL_NONE; + + memset (&gateway, 0, sizeof (gateway)); + inet_pton (AF_INET6, "fe80::1", &gateway.address); + g_array_append_val (rdisc->gateways, gateway); + inet_pton (AF_INET6, "fe80::2", &gateway.address); + g_array_append_val (rdisc->gateways, gateway); + inet_pton (AF_INET6, "fe80::3", &gateway.address); + g_array_append_val (rdisc->gateways, gateway); + + memset (&address, 0, sizeof (address)); + inet_pton (AF_INET6, "2001:db8:a:a::1", &address.address); + g_array_append_val (rdisc->addresses, address); + inet_pton (AF_INET6, "2001:db8:a:a::2", &address.address); + g_array_append_val (rdisc->addresses, address); + inet_pton (AF_INET6, "2001:db8:f:f::1", &address.address); + g_array_append_val (rdisc->addresses, address); + + memset (&route, 0, sizeof (route)); + route.plen = 64; + inet_pton (AF_INET6, "2001:db8:a:a::", &route.network); + g_array_append_val (rdisc->routes, route); + inet_pton (AF_INET6, "2001:db8:b:b::", &route.network); + g_array_append_val (rdisc->routes, route); + + memset (&dns_server, 0, sizeof (dns_server)); + inet_pton (AF_INET6, "2001:db8:c:c::1", &dns_server.address); + g_array_append_val (rdisc->dns_servers, dns_server); + inet_pton (AF_INET6, "2001:db8:c:c::2", &dns_server.address); + g_array_append_val (rdisc->dns_servers, dns_server); + inet_pton (AF_INET6, "2001:db8:c:c::3", &dns_server.address); + g_array_append_val (rdisc->dns_servers, dns_server); + inet_pton (AF_INET6, "2001:db8:c:c::4", &dns_server.address); + g_array_append_val (rdisc->dns_servers, dns_server); + inet_pton (AF_INET6, "2001:db8:c:c::5", &dns_server.address); + g_array_append_val (rdisc->dns_servers, dns_server); + + memset (&dns_domain, 0, sizeof (dns_domain)); + dns_domain.domain = g_strdup ("example.net"); + g_array_append_val (rdisc->dns_domains, dns_domain); + dns_domain.domain = g_strdup ("example.com"); + g_array_append_val (rdisc->dns_domains, dns_domain); + dns_domain.domain = g_strdup ("example.org"); + g_array_append_val (rdisc->dns_domains, dns_domain); +} + +static void +nm_fake_rdisc_class_init (NMFakeRDiscClass *klass) +{ + NMRDiscClass *rdisc_class = NM_RDISC_CLASS (klass); + + rdisc_class->start = start; +} diff --git a/pool/shard000/C/0014537_mddi_client_renesas_R61408.c b/pool/shard000/C/0014537_mddi_client_renesas_R61408.c new file mode 100644 index 0000000000000000000000000000000000000000..1e001b4f5aedef1de2cc46bddb0337ca79414e2c --- /dev/null +++ b/pool/shard000/C/0014537_mddi_client_renesas_R61408.c @@ -0,0 +1,279 @@ +/* + * Copyright (C) 2008 HTC Corporation. + * + * 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 +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static DECLARE_WAIT_QUEUE_HEAD(renesas_vsync_wait); + +struct panel_info { + struct msm_mddi_client_data *client_data; + struct platform_device pdev; + struct msm_panel_data panel_data; + struct msmfb_callback *renesas_callback; + struct wake_lock idle_lock; + int renesas_got_int; + int vsync_gpio; +}; + +static struct platform_device mddi_renesas_backlight = { + .name = "renesas_backlight", + .id = 0, +}; + +static void renesas_request_vsync(struct msm_panel_data *panel_data, + struct msmfb_callback *callback) +{ + struct panel_info *panel = container_of(panel_data, struct panel_info, + panel_data); + struct msm_mddi_client_data *client_data = panel->client_data; + + panel->renesas_callback = callback; + if (panel->renesas_got_int) { + panel->renesas_got_int = 0; + client_data->activate_link(client_data); + } +} + +static void renesas_clear_vsync(struct msm_panel_data *panel_data) +{ + struct panel_info *panel = container_of(panel_data, struct panel_info, + panel_data); + struct msm_mddi_client_data *client_data = panel->client_data; + + client_data->activate_link(client_data); +} + +static void renesas_wait_vsync(struct msm_panel_data *panel_data) +{ + struct panel_info *panel = container_of(panel_data, struct panel_info, + panel_data); + struct msm_mddi_client_data *client_data = panel->client_data; + + if (panel->renesas_got_int) { + panel->renesas_got_int = 0; + client_data->activate_link(client_data); /* clears interrupt */ + } + if (wait_event_timeout(renesas_vsync_wait, panel->renesas_got_int, + HZ/2) == 0) + PR_DISP_ERR("timeout waiting for VSYNC\n"); + panel->renesas_got_int = 0; + /* interrupt clears when screen dma starts */ +} + +static int renesas_suspend(struct msm_panel_data *panel_data) +{ + struct panel_info *panel = container_of(panel_data, struct panel_info, + panel_data); + struct msm_mddi_client_data *client_data = panel->client_data; + + struct msm_mddi_bridge_platform_data *bridge_data = + client_data->private_client_data; + int ret; + + wake_lock(&panel->idle_lock); + ret = bridge_data->uninit(bridge_data, client_data); + wake_unlock(&panel->idle_lock); + if (ret) { + PR_DISP_INFO("mddi renesas client: non zero return from " + "uninit\n"); + return ret; + } + client_data->suspend(client_data); + return 0; +} + +static int renesas_resume(struct msm_panel_data *panel_data) +{ + struct panel_info *panel = container_of(panel_data, struct panel_info, + panel_data); + struct msm_mddi_client_data *client_data = panel->client_data; + + struct msm_mddi_bridge_platform_data *bridge_data = + client_data->private_client_data; + int ret; + + wake_lock(&panel->idle_lock); + client_data->resume(client_data); + wake_unlock(&panel->idle_lock); + ret = bridge_data->init(bridge_data, client_data); + if (ret) + return ret; + return 0; +} + +static int renesas_blank(struct msm_panel_data *panel_data) +{ + struct panel_info *panel = container_of(panel_data, struct panel_info, + panel_data); + struct msm_mddi_client_data *client_data = panel->client_data; + struct msm_mddi_bridge_platform_data *bridge_data = + client_data->private_client_data; + + return bridge_data->blank(bridge_data, client_data); +} + +static int renesas_unblank(struct msm_panel_data *panel_data) +{ + struct panel_info *panel = container_of(panel_data, struct panel_info, + panel_data); + struct msm_mddi_client_data *client_data = panel->client_data; + struct msm_mddi_bridge_platform_data *bridge_data = + client_data->private_client_data; + + return bridge_data->unblank(bridge_data, client_data); +} + +static irqreturn_t renesas_vsync_interrupt(int irq, void *data) +{ + struct panel_info *panel = data; + + panel->renesas_got_int = 1; + if (panel->renesas_callback) { + panel->renesas_callback->func(panel->renesas_callback); + panel->renesas_callback = 0; + } + wake_up(&renesas_vsync_wait); + return IRQ_HANDLED; +} + +static int setup_vsync(struct panel_info *panel, + int init) +{ + int ret; + int gpio = panel->vsync_gpio; + unsigned int irq; + + if (!init) { + ret = 0; + goto uninit; + } + ret = gpio_request(gpio, "vsync"); + if (ret) + goto err_request_gpio_failed; + + ret = gpio_direction_input(gpio); + if (ret) + goto err_gpio_direction_input_failed; + + ret = irq = gpio_to_irq(gpio); + if (ret < 0) + goto err_get_irq_num_failed; + + register_gpio_int_mask(gpio, 1); + + ret = request_irq(irq, renesas_vsync_interrupt, IRQF_TRIGGER_RISING, + "vsync", panel); + if (ret) + goto err_request_irq_failed; + PR_DISP_INFO("vsync on gpio %d now %d\n", + gpio, gpio_get_value(gpio)); + return 0; + +uninit: + free_irq(gpio_to_irq(gpio), panel); +err_request_irq_failed: +err_get_irq_num_failed: +err_gpio_direction_input_failed: + gpio_free(gpio); +err_request_gpio_failed: + return ret; +} + +static int mddi_renesas_probe(struct platform_device *pdev) +{ + int ret; + struct msm_mddi_client_data *client_data = pdev->dev.platform_data; + struct msm_mddi_bridge_platform_data *bridge_data = + client_data->private_client_data; + struct panel_data *panel_data = &bridge_data->panel_conf; + struct panel_info *panel = + kzalloc(sizeof(struct panel_info), GFP_KERNEL); + + if (!panel) + return -ENOMEM; + platform_set_drvdata(pdev, panel); + + PR_DISP_DEBUG("%s\n", __func__); + + mddi_renesas_backlight.dev.platform_data = client_data; + platform_device_register(&mddi_renesas_backlight); + + if (panel_data->vsync_gpio == 0) +#if defined(CONFIG_ARCH_MSM7X30) + panel->vsync_gpio = 30; +#else + panel->vsync_gpio = 98; +#endif + else + panel->vsync_gpio = panel_data->vsync_gpio; + + ret = setup_vsync(panel, 1); + if (ret) { + dev_err(&pdev->dev, "mddi_bridge_setup_vsync failed\n"); + return ret; + } + panel->client_data = client_data; + panel->panel_data.suspend = renesas_suspend; + panel->panel_data.resume = renesas_resume; + panel->panel_data.wait_vsync = renesas_wait_vsync; + panel->panel_data.request_vsync = renesas_request_vsync; + panel->panel_data.clear_vsync = renesas_clear_vsync; + panel->panel_data.blank = renesas_blank; + panel->panel_data.unblank = renesas_unblank; + panel->panel_data.fb_data = &bridge_data->fb_data; + panel->panel_data.caps = MSMFB_CAP_PARTIAL_UPDATES; + panel->pdev.name = "msm_panel"; + panel->pdev.id = pdev->id; + panel->pdev.resource = client_data->fb_resource; + panel->pdev.num_resources = 1; + panel->pdev.dev.platform_data = &panel->panel_data; + platform_device_register(&panel->pdev); + wake_lock_init(&panel->idle_lock, WAKE_LOCK_IDLE, "renesas_idle_lock"); + + return 0; +} + +static int mddi_renesas_remove(struct platform_device *pdev) +{ + struct panel_info *panel = platform_get_drvdata(pdev); + + setup_vsync(panel, 0); + kfree(panel); + return 0; +} + +static struct platform_driver mddi_client_b9f6_61408 = { + .probe = mddi_renesas_probe, + .remove = mddi_renesas_remove, + .driver = { .name = "mddi_renesas_b9f6_61408" }, +}; + +static int __init mddi_client_renesas_init(void) +{ + platform_driver_register(&mddi_client_b9f6_61408); + return 0; +} + +module_init(mddi_client_renesas_init); + diff --git a/pool/shard000/C/0014539_res_shade.c b/pool/shard000/C/0014539_res_shade.c new file mode 100644 index 0000000000000000000000000000000000000000..b761716193777f5242d70dd25cdec32c11f3991b --- /dev/null +++ b/pool/shard000/C/0014539_res_shade.c @@ -0,0 +1,127 @@ +#include "fitz.h" + +fz_shade * +fz_keep_shade(fz_shade *shade) +{ + shade->refs ++; + return shade; +} + +void +fz_drop_shade(fz_context *ctx, fz_shade *shade) +{ + if (shade && --shade->refs == 0) + { + if (shade->colorspace) + fz_drop_colorspace(ctx, shade->colorspace); + fz_free(ctx, shade->mesh); + fz_free(ctx, shade); + } +} + +fz_rect +fz_bound_shade(fz_shade *shade, fz_matrix ctm) +{ + float *v; + fz_rect r; + fz_point p; + int i, ncomp, nvert; + + ctm = fz_concat(shade->matrix, ctm); + ncomp = shade->use_function ? 3 : 2 + shade->colorspace->n; + nvert = shade->mesh_len / ncomp; + v = shade->mesh; + + if (shade->type == FZ_LINEAR) + return fz_infinite_rect; + if (shade->type == FZ_RADIAL) + return fz_infinite_rect; + + if (nvert == 0) + return fz_empty_rect; + + p.x = v[0]; + p.y = v[1]; + v += ncomp; + p = fz_transform_point(ctm, p); + r.x0 = r.x1 = p.x; + r.y0 = r.y1 = p.y; + + for (i = 1; i < nvert; i++) + { + p.x = v[0]; + p.y = v[1]; + p = fz_transform_point(ctm, p); + v += ncomp; + if (p.x < r.x0) r.x0 = p.x; + if (p.y < r.y0) r.y0 = p.y; + if (p.x > r.x1) r.x1 = p.x; + if (p.y > r.y1) r.y1 = p.y; + } + + return r; +} + +void +fz_debug_shade(fz_shade *shade) +{ + int i, j, n; + float *vertex; + int triangle; + + printf("shading {\n"); + + switch (shade->type) + { + case FZ_LINEAR: printf("\ttype linear\n"); break; + case FZ_RADIAL: printf("\ttype radial\n"); break; + case FZ_MESH: printf("\ttype mesh\n"); break; + } + + printf("\tbbox [%g %g %g %g]\n", + shade->bbox.x0, shade->bbox.y0, + shade->bbox.x1, shade->bbox.y1); + + printf("\tcolorspace %s\n", shade->colorspace->name); + + printf("\tmatrix [%g %g %g %g %g %g]\n", + shade->matrix.a, shade->matrix.b, shade->matrix.c, + shade->matrix.d, shade->matrix.e, shade->matrix.f); + + if (shade->use_background) + { + printf("\tbackground ["); + for (i = 0; i < shade->colorspace->n; i++) + printf("%s%g", i == 0 ? "" : " ", shade->background[i]); + printf("]\n"); + } + + if (shade->use_function) + { + printf("\tfunction\n"); + n = 3; + } + else + n = 2 + shade->colorspace->n; + + printf("\tvertices: %d\n", shade->mesh_len); + + vertex = shade->mesh; + triangle = 0; + i = 0; + while (i < shade->mesh_len) + { + printf("\t%d:(%g, %g): ", triangle, vertex[0], vertex[1]); + + for (j = 2; j < n; j++) + printf("%s%g", j == 2 ? "" : " ", vertex[j]); + printf("\n"); + + vertex += n; + i++; + if (i % 3 == 0) + triangle++; + } + + printf("}\n"); +} diff --git a/pool/shard000/C/0014540_prom.c b/pool/shard000/C/0014540_prom.c new file mode 100644 index 0000000000000000000000000000000000000000..1ecc7a90a10fa215d930f4b30b16b5f66d9c5625 --- /dev/null +++ b/pool/shard000/C/0014540_prom.c @@ -0,0 +1,91 @@ +/* + * OpenRISC prom.c + * + * Linux architectural port borrowing liberally from similar works of + * others. All original copyrights apply as per the original source + * declaration. + * + * Modifications for the OpenRISC architecture: + * Copyright (C) 2010-2011 Jonas Bonn + * + * 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. + * + * Architecture specific procedures for creating, accessing and + * interpreting the device tree. + * + */ + +#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 + +extern char cmd_line[COMMAND_LINE_SIZE]; + +void __init early_init_dt_add_memory_arch(u64 base, u64 size) +{ + size &= PAGE_MASK; + memblock_add(base, size); +} + +void __init early_init_devtree(void *params) +{ + void *alloc; + + /* Setup flat device-tree pointer */ + initial_boot_params = params; + + + /* Retrieve various informations from the /chosen node of the + * device-tree, including the platform type, initrd location and + * size, TCE reserve, and more ... + */ + of_scan_flat_dt(early_init_dt_scan_chosen, cmd_line); + + /* Scan memory nodes and rebuild MEMBLOCKs */ + of_scan_flat_dt(early_init_dt_scan_root, NULL); + of_scan_flat_dt(early_init_dt_scan_memory, NULL); + + /* Save command line for /proc/cmdline and then parse parameters */ + strlcpy(boot_command_line, cmd_line, COMMAND_LINE_SIZE); + + memblock_allow_resize(); + + /* We must copy the flattend device tree from init memory to regular + * memory because the device tree references the strings in it + * directly. + */ + + alloc = __va(memblock_alloc(initial_boot_params->totalsize, PAGE_SIZE)); + + memcpy(alloc, initial_boot_params, initial_boot_params->totalsize); + + initial_boot_params = alloc; +} diff --git a/pool/shard000/C/0014546_ualarm.c b/pool/shard000/C/0014546_ualarm.c new file mode 100644 index 0000000000000000000000000000000000000000..fcf760295e5e1bf7f515fd0f149104794782362d --- /dev/null +++ b/pool/shard000/C/0014546_ualarm.c @@ -0,0 +1,112 @@ +/** + * @file + * + * @brief Schedule Alarm + * @ingroup POSIXAPI + */ + +/* + * COPYRIGHT (c) 1989-2008. + * On-Line Applications Research Corporation (OAR). + * + * The license and distribution terms for this file may be + * found in the file LICENSE in this distribution or at + * http://www.rtems.com/license/LICENSE. + */ + +#if HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include + +#include +#include +#include +#include +#include +#include + +static void _POSIX_signals_Ualarm_TSR( Objects_Id id, void *argument ); + +static Watchdog_Control _POSIX_signals_Ualarm_timer = WATCHDOG_INITIALIZER( + _POSIX_signals_Ualarm_TSR, + 0, + NULL +); + +/* + * _POSIX_signals_Ualarm_TSR + */ + +static void _POSIX_signals_Ualarm_TSR( + Objects_Id id __attribute__((unused)), + void *argument __attribute__((unused)) +) +{ + /* + * Send a SIGALRM but if there is a problem, ignore it. + * It's OK, there isn't a way this should fail. + */ + (void) kill( getpid(), SIGALRM ); + + /* + * If the reset interval is non-zero, reschedule ourselves. + */ + _Watchdog_Reset( &_POSIX_signals_Ualarm_timer ); +} + +useconds_t ualarm( + useconds_t useconds, + useconds_t interval +) +{ + useconds_t remaining = 0; + Watchdog_Control *the_timer; + Watchdog_Interval ticks; + Watchdog_States state; + struct timespec tp; + + the_timer = &_POSIX_signals_Ualarm_timer; + + _Thread_Disable_dispatch(); + + state = _Watchdog_Remove( the_timer ); + if ( (state == WATCHDOG_ACTIVE) || (state == WATCHDOG_REMOVE_IT) ) { + /* + * The stop_time and start_time fields are snapshots of ticks since + * boot. Since alarm() is dealing in seconds, we must account for + * this. + */ + + ticks = the_timer->initial; + ticks -= (the_timer->stop_time - the_timer->start_time); + /* remaining is now in ticks */ + + _Timespec_From_ticks( ticks, &tp ); + remaining = tp.tv_sec * TOD_MICROSECONDS_PER_SECOND; + remaining += tp.tv_nsec / 1000; + } + + /* + * If useconds is non-zero, then the caller wants to schedule + * the alarm repeatedly at that interval. If the interval is + * less than a single clock tick, then fudge it to a clock tick. + */ + if ( useconds ) { + Watchdog_Interval ticks; + + tp.tv_sec = useconds / TOD_MICROSECONDS_PER_SECOND; + tp.tv_nsec = (useconds % TOD_MICROSECONDS_PER_SECOND) * 1000; + ticks = _Timespec_To_ticks( &tp ); + if ( ticks == 0 ) + ticks = 1; + + _Watchdog_Insert_ticks( the_timer, _Timespec_To_ticks( &tp ) ); + } + + _Thread_Enable_dispatch(); + + return remaining; +} diff --git a/pool/shard000/C/0014552_timers.c b/pool/shard000/C/0014552_timers.c new file mode 100644 index 0000000000000000000000000000000000000000..2afd44e058845ba97b28727614578f7fb3e76994 --- /dev/null +++ b/pool/shard000/C/0014552_timers.c @@ -0,0 +1,257 @@ +// Fireclaw Copyright (C) 2003 Ian Packer +// +// 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. +// +// $Id: timers.c,v 1.24 2003/07/16 15:35:02 snazbaz Exp $ +// + +#include +#include +#include +#include +#include + +#include "main.h" + +#ifdef REPORT_UPTIME +void check_hourly(); +#endif + +struct Timer { + time_t ts; + void *function; +}; + +static struct Timer *timers; + +/* the vars above are the beginnings of a better timer system, not used yet. */ + + + + +static int timer60, timer5, timer1; +static char whobuf[BUFSIZE]; + +void init_timers() +{ + timers = NULL; +} + +void timer_skew() +{ + struct chanRec *c; + struct suser *u; + struct criminalRecord *i; + int iter; + sRelay("(!) clock skew detected. resetting timers and protection mechanisms."); + timeSkewWait = time(0) + 10; + reset_timers(); + /* lets cycle chans and ial and reset all flood protection and repeat timestamps */ + c = chans.next; + while(c) { + if(c->physical) { + c->physical->flood_last = time(0); + c->physical->flood_lines = 0; + u = c->physical->user; + while(u) { + u->flines = 0; + u->lastMsg = time(0); + u->idleMsg = time(0); + u->lastNick = time(0); + u = u->next; + } + i = c->physical->nortyusers; + while(i) { + i->lastJoin = time(0); + i->njoins = 1; + for(iter = 0; iter < REPEAT_HISTORY_SIZE; iter++) + i->trackrepeat[iter].id = 0; + i = i->next; + } + } + c = c->next; + } + /* phew! */ +} + +void reset_timers() +{ + timer5 = time(NULL); + timer1 = time(NULL); + timer60 = time(NULL); + return; +} + +void check_timers() +{ + /* someone changed the system clock backward (urgh) */ + if(timer1 > time(NULL)) + timer_skew(); + + if(timer1 < time(NULL) - 60) + { + timer1 = time(NULL); + expireBans(); + /* someone skipped the system clock forward excessive amounts? */ + if(time(NULL) - timer5 > 1000) + timer_skew(); + + checkNeedCon(); + + /******* 5 min timer ********/ + if(timer5 < time(NULL) - 300) + { + timer5 = time(NULL); + runTimer5(); + } + /******* 1 hour timer ********/ + if(timer60 < time(NULL) - 3600) + { + timer60 = time(NULL); + expireCriminals(); + } + } + return; +} + +void runTimer5() +{ + struct chanRec *i = chans.next; + + service_auth(); + start_links(); + + fprintf(out, "DEBUG: Timer5\n"); + + /* add_listen wont add multiple entries with the same ID, so we don't need to + check if there is already a listening dcc socket. */ + if(config.dcc_listenport > 0) + if(add_listen('D', 3, config.dcc_listenport, config.dcc_listenip)) + fprintf(out, "Listening for connections on %s:%d\n", config.dcc_listenip, config.dcc_listenport); + + if(config.linkport > 0) + if(add_listen('F', 4, config.linkport, config.vhost)) + fprintf(out, "Listening for connections on %s:%d\n", config.vhost, config.linkport); + + while(i != NULL) + { + if(i->physical) + { + if(chan_has_rn_bans(i) || strchr(i->flags, 'a')) + { + sprintf(whobuf, "WHO %s %%cnar", i->name); + lowMsg(whobuf); + } + if(strchr(i->flags, 'l')) + checkLimit(i->physical); + searchForMissedBans(i->physical); + checkNiceModes(i->physical); + } else + if(strchr(i->flags, 'j')) + { + sprintf(whobuf, "JOIN %s %s", i->name, i->key); + lowMsg(whobuf); + } + i = i->next; + } + + if(strcmp(cNick, config.nick)) + { + sprintf(whobuf, "NICK %s", config.nick); + highMsg(whobuf); + } + + #ifdef REPORT_UPTIME + check_hourly(); + #endif + + return; +} + +void expireCriminals() +{ + struct criminalRecord *i, *fr; + struct schan *c; + + c = ial.channel; + while(c != NULL) + { + i = c->nortyusers; + while(i) + { + if(--i->longTerm <= 0) { + fr = i; i = i->next; + nu_del(c, fr); + } else + i = i->next; + } + c = c->next; + } + + return; +} + +void checkNiceModes(struct schan *theChan) +{ + char *p1; + char yn = 0; + + sprintf(whobuf, "MODE %s ", theChan->name); + + for(p1 = theChan->modes; *p1; p1++) + { + if(strchr(theChan->record->badModes, *p1)) + { + strcat(whobuf, theChan->record->badModes); + yn = 1; + break; + } + } + + for(p1 = theChan->record->goodModes + 1; *p1; p1++) + { + if(!strchr(theChan->modes, *p1)) + { + strcat(whobuf, theChan->record->goodModes); + yn = 1; + break; + } + } + + if(yn) + lowMsg(whobuf); + + return; +} + +void checkLimit(struct schan *theChan) +{ + if(check_dependants(theChan)) + return; + if(theChan->userSize >= theChan->limit) { + theChan->tsLim = time(0); + sprintf(whobuf, "MODE %s +l %d", theChan->name, theChan->userSize + config.float_thresh); + lowMsg(whobuf); + } else + if((time(0) - theChan->tsLim) > config.float_period) { + if( (theChan->userSize > theChan->limit - config.float_step) || (theChan->userSize < theChan->limit - config.float_step4) ) + { + theChan->tsLim = time(0); + sprintf(whobuf, "MODE %s +l %d", theChan->name, theChan->userSize + config.float_thresh); + highMsg(whobuf); + } + } + return; +} diff --git a/pool/shard000/C/0014564_lib_options.c b/pool/shard000/C/0014564_lib_options.c new file mode 100644 index 0000000000000000000000000000000000000000..fc3dc42bca41710d38f39676f7a670df23ca3eec --- /dev/null +++ b/pool/shard000/C/0014564_lib_options.c @@ -0,0 +1,255 @@ +/**************************************************************************** + * Copyright (c) 1998,1999,2000 Free Software Foundation, Inc. * + * * + * Permission is hereby granted, free of charge, to any person obtaining a * + * copy of this software and associated documentation files (the * + * "Software"), to deal in the Software without restriction, including * + * without limitation the rights to use, copy, modify, merge, publish, * + * distribute, distribute with modifications, 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 ABOVE 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. * + * * + * Except as contained in this notice, the name(s) of the above copyright * + * holders shall not be used in advertising or otherwise to promote the * + * sale, use or other dealings in this Software without prior written * + * authorization. * + ****************************************************************************/ + +/**************************************************************************** + * Author: Zeyd M. Ben-Halim 1992,1995 * + * and: Eric S. Raymond * + ****************************************************************************/ + +/* +** lib_options.c +** +** The routines to handle option setting. +** +*/ + +#include + +#include + +MODULE_ID("$Id: lib_options.c,v 1.40 2000/09/02 18:02:05 tom Exp $") + +int +idlok(WINDOW *win, bool flag) +{ + T((T_CALLED("idlok(%p,%d)"), win, flag)); + + if (win) { + _nc_idlok = win->_idlok = (flag && (has_il() || change_scroll_region)); + returnCode(OK); + } else + returnCode(ERR); +} + +void +idcok(WINDOW *win, bool flag) +{ + T((T_CALLED("idcok(%p,%d)"), win, flag)); + + if (win) + _nc_idcok = win->_idcok = (flag && has_ic()); + + returnVoid; +} + +int +halfdelay(int t) +{ + T((T_CALLED("halfdelay(%d)"), t)); + + if (t < 1 || t > 255) + returnCode(ERR); + + cbreak(); + SP->_cbreak = t + 1; + returnCode(OK); +} + +int +nodelay(WINDOW *win, bool flag) +{ + T((T_CALLED("nodelay(%p,%d)"), win, flag)); + + if (win) { + if (flag == TRUE) + win->_delay = 0; + else + win->_delay = -1; + returnCode(OK); + } else + returnCode(ERR); +} + +int +notimeout(WINDOW *win, bool f) +{ + T((T_CALLED("notimout(%p,%d)"), win, f)); + + if (win) { + win->_notimeout = f; + returnCode(OK); + } else + returnCode(ERR); +} + +void +wtimeout(WINDOW *win, int delay) +{ + T((T_CALLED("wtimeout(%p,%d)"), win, delay)); + + if (win) { + win->_delay = delay; + } +} + +int +keypad(WINDOW *win, bool flag) +{ + T((T_CALLED("keypad(%p,%d)"), win, flag)); + + if (win) { + win->_use_keypad = flag; + returnCode(_nc_keypad(flag)); + } else + returnCode(ERR); +} + +int +meta(WINDOW *win GCC_UNUSED, bool flag) +{ + /* Ok, we stay relaxed and don't signal an error if win is NULL */ + T((T_CALLED("meta(%p,%d)"), win, flag)); + + SP->_use_meta = flag; + + if (flag && meta_on) { + TPUTS_TRACE("meta_on"); + putp(meta_on); + } else if (!flag && meta_off) { + TPUTS_TRACE("meta_off"); + putp(meta_off); + } + returnCode(OK); +} + +/* curs_set() moved here to narrow the kernel interface */ + +int +curs_set(int vis) +{ + int cursor = SP->_cursor; + + T((T_CALLED("curs_set(%d)"), vis)); + + if (vis < 0 || vis > 2) + returnCode(ERR); + + if (vis == cursor) + returnCode(cursor); + + switch (vis) { + case 2: + if (cursor_visible) { + TPUTS_TRACE("cursor_visible"); + putp(cursor_visible); + } else + returnCode(ERR); + break; + case 1: + if (cursor_normal) { + TPUTS_TRACE("cursor_normal"); + putp(cursor_normal); + } else + returnCode(ERR); + break; + case 0: + if (cursor_invisible) { + TPUTS_TRACE("cursor_invisible"); + putp(cursor_invisible); + } else + returnCode(ERR); + break; + } + SP->_cursor = vis; + _nc_flush(); + + returnCode(cursor == -1 ? 1 : cursor); +} + +int +typeahead(int fd) +{ + T((T_CALLED("typeahead(%d)"), fd)); + SP->_checkfd = fd; + returnCode(OK); +} + +/* +** has_key() +** +** Return TRUE if the current terminal has the given key +** +*/ + +#if NCURSES_EXT_FUNCS +static int +has_key_internal(int keycode, struct tries *tp) +{ + if (tp == 0) + return (FALSE); + else if (tp->value == keycode) + return (TRUE); + else + return (has_key_internal(keycode, tp->child) + || has_key_internal(keycode, tp->sibling)); +} + +int +has_key(int keycode) +{ + T((T_CALLED("has_key(%d)"), keycode)); + returnCode(has_key_internal(keycode, SP->_keytry)); +} +#endif /* NCURSES_EXT_FUNCS */ + +/* Turn the keypad on/off + * + * Note: we flush the output because changing this mode causes some terminals + * to emit different escape sequences for cursor and keypad keys. If we don't + * flush, then the next wgetch may get the escape sequence that corresponds to + * the terminal state _before_ switching modes. + */ +int +_nc_keypad(bool flag) +{ + if (flag && keypad_xmit) { + TPUTS_TRACE("keypad_xmit"); + putp(keypad_xmit); + _nc_flush(); + } else if (!flag && keypad_local) { + TPUTS_TRACE("keypad_local"); + putp(keypad_local); + _nc_flush(); + } + + if (flag && !SP->_tried) { + _nc_init_keytry(); + SP->_tried = TRUE; + } + return (OK); +} diff --git a/pool/shard000/C/0014566_roundrobin.c b/pool/shard000/C/0014566_roundrobin.c new file mode 100644 index 0000000000000000000000000000000000000000..b2e57350cfccc4bfea3ee095f8661f1dab0f3786 --- /dev/null +++ b/pool/shard000/C/0014566_roundrobin.c @@ -0,0 +1,146 @@ +/* + * Copyright (C) 2014 Julien Rabinow + * + * This file is part of Lab2-Scheduler. + * + * Lab2-Scheduler 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. + * + * Lab2-Scheduler 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 Lab2-Scheduler. If not, see . + */ + +#include + +static Scheduler new(const Builder bld, int quantum); +static void delete(Scheduler sched); +static Scheduler clone(const Scheduler sched); +static char *to_string(const Scheduler sched); +static unsigned readyq_size(const Scheduler sched); +static void put_event(Scheduler sched, Process proc); +static Process get_event(Scheduler sched); +static int get_quantum(const Scheduler sched); +static void set_quantum(Scheduler sched, int quantum); +static Process peek_readyq(Scheduler sched); + +static struct RR_Scheduler_LT RR_lt = { + NULL, + false, + &new, + &delete, + &clone, + &to_string, + NULL, + &readyq_size, + &get_event, + &put_event, + &peek_readyq, + NULL, + NULL, + &get_quantum, + &set_quantum +}; + +const struct Builder __RR_Scheduler__ = { + &__Scheduler__, + (Lookup_Table) &RR_lt, + sizeof(struct RR_Scheduler), + "RR" +}; + + +static Scheduler new(const Builder bld, int quantum) +{ + RR_Scheduler sched = __RR_Scheduler__.super->lt->new(bld); + +#define new(builder, ...) ((__##builder##__).lt->new((const Builder)\ + &__##builder##__, ##__VA_ARGS__)) + if(bld == &__RR_Scheduler__) + bld->lt->lt_initialized = true; + sched->ready_queue = new(FIFO); + sched->quantum = quantum; + + return (Scheduler) sched; +} + +static void delete(Scheduler sched) +{ + RR_Scheduler this = (RR_Scheduler) sched; + + this->ready_queue->lt->delete(this->ready_queue); + __RR_Scheduler__.super->lt->delete(sched); +} + +static Scheduler clone(const Scheduler sched) +{ + RR_Scheduler this = (RR_Scheduler) sched, + s = __RR_Scheduler__.super->lt->clone(sched); + + s->ready_queue = this->ready_queue->lt->clone(this->ready_queue); + + return (Scheduler) s; +} + +static char *to_string(const Scheduler sched) +{ + RR_Scheduler this = (RR_Scheduler) sched; + char *str = NULL; + + if(asprintf(&str, "%s %d", this->lt->bld->name, this->quantum) + == -1) { + perror("Error allocating memory "); + exit(EXIT_FAILURE); + } else + return str; +} + + +static unsigned readyq_size(const Scheduler sched) +{ + RR_Scheduler this = (RR_Scheduler) sched; + + return this->ready_queue->lt->size(this->ready_queue); +} + + +static Process get_event(Scheduler sched) +{ + RR_Scheduler this = (RR_Scheduler) sched; + + if(this->size > 0) + this->size--; + return (Process) this->ready_queue->lt->get(this->ready_queue);; +} + +static void put_event(Scheduler sched, Process proc) +{ + RR_Scheduler this = (RR_Scheduler) sched; + + proc->preempt_after = this->quantum; + this->ready_queue->lt->put(this->ready_queue, (Object) proc); + this->size++; +} + +static Process peek_readyq(Scheduler sched) +{ + RR_Scheduler this = (RR_Scheduler) sched; + + return (Process) this->ready_queue->lt->peek(this->ready_queue); +} + +static int get_quantum(const Scheduler this) +{ + return ((RR_Scheduler) this)->quantum; +} + +static void set_quantum(Scheduler this, int quantum) +{ + ((RR_Scheduler) this)->quantum = quantum; +} diff --git a/pool/shard000/C/0014567_ags_generic_preferences.c b/pool/shard000/C/0014567_ags_generic_preferences.c new file mode 100644 index 0000000000000000000000000000000000000000..bb82ce7b6e06628a01aa9f9e8af1f62cf5dc0be1 --- /dev/null +++ b/pool/shard000/C/0014567_ags_generic_preferences.c @@ -0,0 +1,260 @@ +/* AGS - Advanced GTK Sequencer + * Copyright (C) 2014 Joël Krähemann + * + * 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, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#include +#include + +#include +#include +#include + +#include + +#include +#include + +void ags_generic_preferences_class_init(AgsGenericPreferencesClass *generic_preferences); +void ags_generic_preferences_connectable_interface_init(AgsConnectableInterface *connectable); +void ags_generic_preferences_applicable_interface_init(AgsApplicableInterface *applicable); +void ags_generic_preferences_init(AgsGenericPreferences *generic_preferences); +void ags_generic_preferences_connect(AgsConnectable *connectable); +void ags_generic_preferences_disconnect(AgsConnectable *connectable); +void ags_generic_preferences_set_update(AgsApplicable *applicable, gboolean update); +void ags_generic_preferences_apply(AgsApplicable *applicable); +void ags_generic_preferences_reset(AgsApplicable *applicable); +static void ags_generic_preferences_finalize(GObject *gobject); +void ags_generic_preferences_show(GtkWidget *widget); + +/** + * SECTION:ags_generic_preferences + * @short_description: A composite widget to do generic related preferences + * @title: AgsGenericPreferences + * @section_id: + * @include: ags/X/ags_generic_preferences.h + * + * #AgsGenericPreferences enables you to make generic related preferences. + */ + +static gpointer ags_generic_preferences_parent_class = NULL; + +GType +ags_generic_preferences_get_type(void) +{ + static GType ags_type_generic_preferences = 0; + + if(!ags_type_generic_preferences){ + static const GTypeInfo ags_generic_preferences_info = { + sizeof (AgsGenericPreferencesClass), + NULL, /* base_init */ + NULL, /* base_finalize */ + (GClassInitFunc) ags_generic_preferences_class_init, + NULL, /* class_finalize */ + NULL, /* class_data */ + sizeof (AgsGenericPreferences), + 0, /* n_preallocs */ + (GInstanceInitFunc) ags_generic_preferences_init, + }; + + static const GInterfaceInfo ags_connectable_interface_info = { + (GInterfaceInitFunc) ags_generic_preferences_connectable_interface_init, + NULL, /* interface_finalize */ + NULL, /* interface_data */ + }; + + static const GInterfaceInfo ags_applicable_interface_info = { + (GInterfaceInitFunc) ags_generic_preferences_applicable_interface_init, + NULL, /* interface_finalize */ + NULL, /* interface_data */ + }; + + ags_type_generic_preferences = g_type_register_static(GTK_TYPE_VBOX, + "AgsGenericPreferences\0", &ags_generic_preferences_info, + 0); + + g_type_add_interface_static(ags_type_generic_preferences, + AGS_TYPE_CONNECTABLE, + &ags_connectable_interface_info); + + g_type_add_interface_static(ags_type_generic_preferences, + AGS_TYPE_APPLICABLE, + &ags_applicable_interface_info); + } + + return(ags_type_generic_preferences); +} + +void +ags_generic_preferences_class_init(AgsGenericPreferencesClass *generic_preferences) +{ + GObjectClass *gobject; + GtkWidgetClass *widget; + + ags_generic_preferences_parent_class = g_type_class_peek_parent(generic_preferences); + + /* GtkObjectClass */ + gobject = (GObjectClass *) generic_preferences; + + gobject->finalize = ags_generic_preferences_finalize; + + /* GtkWidgetClass */ + widget = (GtkWidgetClass *) generic_preferences; + + widget->show = ags_generic_preferences_show; +} + +void +ags_generic_preferences_connectable_interface_init(AgsConnectableInterface *connectable) +{ + connectable->is_ready = NULL; + connectable->is_connected = NULL; + connectable->connect = ags_generic_preferences_connect; + connectable->disconnect = ags_generic_preferences_disconnect; +} + +void +ags_generic_preferences_applicable_interface_init(AgsApplicableInterface *applicable) +{ + applicable->set_update = ags_generic_preferences_set_update; + applicable->apply = ags_generic_preferences_apply; + applicable->reset = ags_generic_preferences_reset; +} + +void +ags_generic_preferences_init(AgsGenericPreferences *generic_preferences) +{ + generic_preferences->autosave_thread = (GtkCheckButton *) gtk_check_button_new_with_label("autosave thread\0"); + gtk_box_pack_start(GTK_BOX(generic_preferences), + GTK_WIDGET(generic_preferences->autosave_thread), + FALSE, FALSE, + 0); +} + +void +ags_generic_preferences_connect(AgsConnectable *connectable) +{ + AgsGenericPreferences *generic_preferences; + + generic_preferences = AGS_GENERIC_PREFERENCES(connectable); + + // g_signal_connect_after(G_OBJECT(generic_preferences->autosave_thread), "clicked\0", + // G_CALLBACK(ags_generic_preferences_autosave_thread_clicked_callback), generic_preferences); +} + +void +ags_generic_preferences_disconnect(AgsConnectable *connectable) +{ + /* empty */ +} + +void +ags_generic_preferences_set_update(AgsApplicable *applicable, gboolean update) +{ + //TODO:JK: implement me +} + +void +ags_generic_preferences_apply(AgsApplicable *applicable) +{ + AgsPreferences *preferences; + AgsGenericPreferences *generic_preferences; + + AgsApplicationContext *application_context; + AgsConfig *config; + + generic_preferences = AGS_GENERIC_PREFERENCES(applicable); + + preferences = (AgsPreferences *) gtk_widget_get_ancestor(GTK_WIDGET(generic_preferences), + AGS_TYPE_PREFERENCES); + + application_context = AGS_WINDOW(preferences->parent)->application_context; + config = application_context->config; + + if(gtk_toggle_button_get_active(generic_preferences->autosave_thread)){ + ags_config_set_value(config, + AGS_CONFIG_GENERIC, + "autosave-thread\0", + "true\0"); + }else{ + ags_config_set_value(config, + AGS_CONFIG_GENERIC, + "autosave-thread\0", + "false\0"); + } +} + +void +ags_generic_preferences_reset(AgsApplicable *applicable) +{ + AgsPreferences *preferences; + AgsGenericPreferences *generic_preferences; + + AgsApplicationContext *application_context; + AgsConfig *config; + + generic_preferences = AGS_GENERIC_PREFERENCES(applicable); + + preferences = (AgsPreferences *) gtk_widget_get_ancestor(GTK_WIDGET(generic_preferences), + AGS_TYPE_PREFERENCES); + + application_context = AGS_WINDOW(preferences->parent)->application_context; + config = application_context->config; + + gtk_toggle_button_set_active(generic_preferences->autosave_thread, + ((!strncmp(ags_config_get_value( config, + AGS_CONFIG_GENERIC, + "autosave-thread\0"), + "true\0", + 5)) ? TRUE: FALSE)); +} + +static void +ags_generic_preferences_finalize(GObject *gobject) +{ + //TODO:JK: implement me +} + +void +ags_generic_preferences_show(GtkWidget *widget) +{ + AgsGenericPreferences *generic_preferences; + pthread_t thread; + + generic_preferences = AGS_GENERIC_PREFERENCES(widget); + + GTK_WIDGET_CLASS(ags_generic_preferences_parent_class)->show(widget); +} + +/** + * ags_generic_preferences_new: + * + * Creates an #AgsGenericPreferences + * + * Returns: a new #AgsGenericPreferences + * + * Since: 0.4 + */ +AgsGenericPreferences* +ags_generic_preferences_new() +{ + AgsGenericPreferences *generic_preferences; + + generic_preferences = (AgsGenericPreferences *) g_object_new(AGS_TYPE_GENERIC_PREFERENCES, + NULL); + + return(generic_preferences); +} diff --git a/pool/shard000/C/0014579_main.c b/pool/shard000/C/0014579_main.c new file mode 100644 index 0000000000000000000000000000000000000000..ddd661a923e0b5ab846a4e641cecbbfeb8d0badf --- /dev/null +++ b/pool/shard000/C/0014579_main.c @@ -0,0 +1,156 @@ +/* + prophyle_index main file, implements build and query commands. + Author: Kamil Salikhov + Licence: MIT + Examples: + build prophyle index for k = 20, suffix array and klcp simultaneously: + prophyle_index build -k 20 -s index.fa + query reads for k=20 using rolling window search with 10 threads, writing output in results.txt: + prophyle_index query -u -k 20 -t 10 index.fa reads.fq > results.txt +*/ + +#include +#include +#include +#include +#include +#include +#include +#include "prophyle_query.h" +#include "bwa.h" +#include "prophyle_index_build.h" +#include "bwa_utils.h" + +static int usage() +{ + fprintf(stderr, "\n"); + fprintf(stderr, "Program: prophyle_index (alignment of k-mers)\n"); + fprintf(stderr, "Contact: Kamil Salikhov \n"); + fprintf(stderr, "\n"); + fprintf(stderr, "Usage: prophyle_index command [options]\n"); + fprintf(stderr, "\n"); + fprintf(stderr, "Command: build construct index\n"); + fprintf(stderr, " query query reads against index\n"); + fprintf(stderr, "\n"); + return 1; +} + +static int usage_build(){ + fprintf(stderr, "\n"); + fprintf(stderr, "Usage: prophyle_index build \n"); + fprintf(stderr, "\n"); + fprintf(stderr, "Options: -k INT length of k-mer\n"); + fprintf(stderr, " -s construct k-LCP and SA in parallel\n"); + fprintf(stderr, " -i sampling distance for SA\n"); + fprintf(stderr, "\n"); + return 1; +} + +static int usage_debwtupdate(){ + fprintf(stderr, "\n"); + fprintf(stderr, "Usage: prophyle_index debwtupdate input.bwt output.bwt\n"); + fprintf(stderr, "\n"); + return 1; +} + +static int usage_query(int threads){ + fprintf(stderr, "\n"); + fprintf(stderr, "Usage: prophyle_index query [options] \n"); + fprintf(stderr, "\n"); + fprintf(stderr, "Options: -k INT length of k-mer\n"); + fprintf(stderr, " -u use k-LCP for querying\n"); + fprintf(stderr, " -v output set of chromosomes for every k-mer\n"); + fprintf(stderr, " -p do not check whether k-mer is on border of two contigs, and show such k-mers in output\n"); + fprintf(stderr, " -b print sequences and base qualities\n"); + fprintf(stderr, " -l STR log file name to output statistics\n"); + fprintf(stderr, " -t INT number of threads [%d]\n", threads); + fprintf(stderr, "\n"); + return 1; +} + +int prophyle_index_query(int argc, char *argv[]) +{ + int c; + prophyle_index_opt_t *opt; + char *prefix; + + opt = prophyle_index_init_opt(); + while ((c = getopt(argc, argv, "l:psuvk:bt:")) >= 0) { + switch (c) { + case 'v': { opt->output_old = 1; opt->output = 0; } break; + case 'u': opt->use_klcp = 1; break; + case 'k': opt->kmer_length = atoi(optarg); break; + case 's': opt->skip_after_fail = 1; break; + case 'p': opt->skip_positions_on_border = 0; break; + case 'l': { opt->need_log = 1; opt->log_file_name = optarg; break; } + case 'b': opt->output_read_qual = 1; break; + case 't': opt->n_threads = atoi(optarg); break; + default: return 1; + } + } + if (opt->output_old && opt->n_threads > 1) { + fprintf(stderr, "[prophyle_index:%s] -v option can be used only with one thread (-t 1)\n", __func__); + return 1; + } + + if (optind + 2 > argc) { + usage_query(opt->n_threads); + return 1; + } + if ((prefix = bwa_idx_infer_prefix(argv[optind])) == 0) { + fprintf(stderr, "[prophyle_index:%s] fail to locate the index %s\n", __func__, argv[optind]); + free(opt); + return 1; + } + query(prefix, argv[optind+1], opt); + free(opt); free(prefix); + return 0; +} + +int prophyle_index_build(int argc, char *argv[]) +{ + int c; + prophyle_index_opt_t *opt; + char *prefix; + opt = prophyle_index_init_opt(); + int sa_intv = 32; + while ((c = getopt(argc, argv, "si:k:")) >= 0) { + switch (c) { + case 'k': opt->kmer_length = atoi(optarg); break; + case 'i': sa_intv = atoi(optarg); break; + case 's': opt->construct_sa_parallel = 1; break; + default: return 1; + } + } + if (optind + 1 > argc) { + usage_build(); + return 1; + } + if ((prefix = bwa_idx_infer_prefix(argv[optind])) == 0) { + fprintf(stderr, "[prophyle_index:%s] fail to locate the index %s\n", __func__, argv[optind]); + return 1; + } + build_index(prefix, opt, sa_intv); + free(prefix); + return 0; +} + +int prophyle_debwtupdate(int argc, char *argv[]) +{ + if (argc < 2) { + return usage_debwtupdate(); + } + return debwtupdate(argv[0], argv[1]); +} + +int main(int argc, char *argv[]) +{ + int ret = 0; + if (argc < 2) return usage(); + if (strcmp(argv[1], "build") == 0) ret = prophyle_index_build(argc - 1, argv + 1); + else if (strcmp(argv[1], "query") == 0) ret = prophyle_index_query(argc - 1, argv+1); + else if (strcmp(argv[1], "debwtupdate") == 0) ret = prophyle_debwtupdate(argc - 2, argv + 2); + else return usage(); + + return ret; +} diff --git a/pool/shard000/C/0014591_devtty.c b/pool/shard000/C/0014591_devtty.c new file mode 100644 index 0000000000000000000000000000000000000000..d1583c6c981f0fff05a7ffcfc4114ab78690db93 --- /dev/null +++ b/pool/shard000/C/0014591_devtty.c @@ -0,0 +1,143 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static char tbuf1[TTYSIZ]; + +uint8_t vtattr_cap = VTA_INVERSE|VTA_FLASH|VTA_UNDERLINE; +extern uint8_t curattr; + +tcflag_t termios_mask[NUM_DEV_TTY + 1] = { + 0, + _CSYS +}; + + +struct s_queue ttyinq[NUM_DEV_TTY + 1] = { /* ttyinq[0] is never used */ + {NULL, NULL, NULL, 0, 0, 0}, + {tbuf1, tbuf1, tbuf1, TTYSIZ, 0, TTYSIZ / 2}, +}; + +/* tty1 is the screen */ + +/* Output for the system console (kprintf etc) */ +void kputchar(char c) +{ + if (c == '\n') + tty_putc(0, '\r'); + tty_putc(0, c); +} + +/* Both console and debug port are always ready */ +ttyready_t tty_writeready(uint8_t minor) +{ + minor; + return TTY_READY_NOW; +} + +void tty_putc(uint8_t minor, unsigned char c) +{ + minor; + vtoutput(&c, 1); +} + +int tty_carrier(uint8_t minor) +{ + minor; + return 1; +} + +void tty_setup(uint8_t minor, uint8_t flags) +{ + minor; +} + +void tty_sleeping(uint8_t minor) +{ + minor; +} + +void tty_data_consumed(uint8_t minor) +{ +} + + +/* This is used by the vt asm code, but needs to live in the kernel */ +uint16_t cursorpos; + +/* For now we only support 64 char mode - we should add the mode setting + logic an dother modes FIXME */ +static struct display specdisplay = { + 0, + 512, 192, + 512, 192, + 0xFF, 0xFF, + FMT_TIMEX64, + HW_UNACCEL, + GFX_VBLANK|GFX_MAPPABLE|GFX_TEXT, + 0 +}; + +static struct videomap specmap = { + 0, + 0, + 0x4000, + 14336, + 0, + 0, + 0, + MAP_FBMEM|MAP_FBMEM_SIMPLE +}; + +/* + * Graphics ioctls. Very minimal for this platform. It's a single fixed + * mode with direct memory mapping. + */ +int gfx_ioctl(uint8_t minor, uarg_t arg, char *ptr) +{ + if (minor != 1 || arg >> 8 != 0x03) + return vt_ioctl(minor, arg, ptr); + switch(arg) { + case GFXIOC_GETINFO: + return uput(&specdisplay, ptr, sizeof(struct display)); + case GFXIOC_MAP: + return uput(&specmap, ptr, sizeof(struct videomap)); + case GFXIOC_UNMAP: + return 0; + case GFXIOC_WAITVB: + /* Our system clock is vblank */ + timer_wait++; + psleep(&timer_interrupt); + timer_wait--; + chksigs(); + if (udata.u_cursig) { + udata.u_error = EINTR; + return -1; + } + return 0; + } + return -1; +} + +void vtattr_notify(void) +{ + /* Attribute byte fixups: not hard as the colours map directly + to the spectrum ones */ + if (vtattr & VTA_INVERSE) + curattr = ((vtink & 7) << 3) | (vtpaper & 7); + else + curattr = (vtink & 7) | ((vtpaper & 7) << 3); + if (vtattr & VTA_FLASH) + curattr |= 0x80; + /* How to map the bright bit - we go by either */ + if ((vtink | vtpaper) & 0x10) + curattr |= 0x40; +} diff --git a/pool/shard000/C/0014595_dwc3-haps.c b/pool/shard000/C/0014595_dwc3-haps.c new file mode 100644 index 0000000000000000000000000000000000000000..55b4a901168e8c46d5f71f3055c4690345ba29f5 --- /dev/null +++ b/pool/shard000/C/0014595_dwc3-haps.c @@ -0,0 +1,142 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * dwc3-haps.c - Synopsys HAPS PCI Specific glue layer + * + * Copyright (C) 2018 Synopsys, Inc. + * + * Authors: Thinh Nguyen , + * John Youn + */ + +#include +#include +#include +#include +#include +#include + +/** + * struct dwc3_haps - Driver private structure + * @dwc3: child dwc3 platform_device + * @pci: our link to PCI bus + */ +struct dwc3_haps { + struct platform_device *dwc3; + struct pci_dev *pci; +}; + +static const struct property_entry initial_properties[] = { + PROPERTY_ENTRY_BOOL("snps,usb3_lpm_capable"), + PROPERTY_ENTRY_BOOL("snps,has-lpm-erratum"), + PROPERTY_ENTRY_BOOL("snps,dis_enblslpm_quirk"), + PROPERTY_ENTRY_BOOL("linux,sysdev_is_parent"), + { }, +}; + +static int dwc3_haps_probe(struct pci_dev *pci, + const struct pci_device_id *id) +{ + struct dwc3_haps *dwc; + struct device *dev = &pci->dev; + struct resource res[2]; + int ret; + + ret = pcim_enable_device(pci); + if (ret) { + dev_err(dev, "failed to enable pci device\n"); + return -ENODEV; + } + + pci_set_master(pci); + + dwc = devm_kzalloc(dev, sizeof(*dwc), GFP_KERNEL); + if (!dwc) + return -ENOMEM; + + dwc->dwc3 = platform_device_alloc("dwc3", PLATFORM_DEVID_AUTO); + if (!dwc->dwc3) + return -ENOMEM; + + memset(res, 0x00, sizeof(struct resource) * ARRAY_SIZE(res)); + + res[0].start = pci_resource_start(pci, 0); + res[0].end = pci_resource_end(pci, 0); + res[0].name = "dwc_usb3"; + res[0].flags = IORESOURCE_MEM; + + res[1].start = pci->irq; + res[1].name = "dwc_usb3"; + res[1].flags = IORESOURCE_IRQ; + + ret = platform_device_add_resources(dwc->dwc3, res, ARRAY_SIZE(res)); + if (ret) { + dev_err(dev, "couldn't add resources to dwc3 device\n"); + goto err; + } + + dwc->pci = pci; + dwc->dwc3->dev.parent = dev; + + ret = platform_device_add_properties(dwc->dwc3, initial_properties); + if (ret) + goto err; + + ret = platform_device_add(dwc->dwc3); + if (ret) { + dev_err(dev, "failed to register dwc3 device\n"); + goto err; + } + + pci_set_drvdata(pci, dwc); + + return 0; +err: + platform_device_put(dwc->dwc3); + return ret; +} + +static void dwc3_haps_remove(struct pci_dev *pci) +{ + struct dwc3_haps *dwc = pci_get_drvdata(pci); + + platform_device_unregister(dwc->dwc3); +} + +static const struct pci_device_id dwc3_haps_id_table[] = { + { + PCI_DEVICE(PCI_VENDOR_ID_SYNOPSYS, + PCI_DEVICE_ID_SYNOPSYS_HAPSUSB3), + /* + * i.MX6QP and i.MX7D platform use a PCIe controller with the + * same VID and PID as this USB controller. The system may + * incorrectly match this driver to that PCIe controller. To + * workaround this, specifically use class type USB to prevent + * incorrect driver matching. + */ + .class = (PCI_CLASS_SERIAL_USB << 8), + .class_mask = 0xffff00, + }, + { + PCI_DEVICE(PCI_VENDOR_ID_SYNOPSYS, + PCI_DEVICE_ID_SYNOPSYS_HAPSUSB3_AXI), + }, + { + PCI_DEVICE(PCI_VENDOR_ID_SYNOPSYS, + PCI_DEVICE_ID_SYNOPSYS_HAPSUSB31), + }, + { } /* Terminating Entry */ +}; +MODULE_DEVICE_TABLE(pci, dwc3_haps_id_table); + +static struct pci_driver dwc3_haps_driver = { + .name = "dwc3-haps", + .id_table = dwc3_haps_id_table, + .probe = dwc3_haps_probe, + .remove = dwc3_haps_remove, +}; + +MODULE_AUTHOR("Thinh Nguyen "); +MODULE_LICENSE("GPL v2"); +MODULE_DESCRIPTION("Synopsys HAPS PCI Glue Layer"); + +module_pci_driver(dwc3_haps_driver); diff --git a/pool/shard000/C/0014598_ags_pad_callbacks.c b/pool/shard000/C/0014598_ags_pad_callbacks.c new file mode 100644 index 0000000000000000000000000000000000000000..3cdaa2f107607b02319c7820bbf7ebd5ae9c986b --- /dev/null +++ b/pool/shard000/C/0014598_ags_pad_callbacks.c @@ -0,0 +1,204 @@ +/* AGS - Advanced GTK Sequencer + * Copyright (C) 2005-2011 Joël Krähemann + * + * 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, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#include + +#include + +#include +#include + +#include +#include +#include + +#include + +#include +#include + +int +ags_pad_parent_set_callback(GtkWidget *widget, GtkObject *old_parent, AgsPad *pad) +{ + if(old_parent != NULL) + return; +} + +int +ags_pad_option_changed_callback(GtkWidget *widget, AgsPad *pad) +{ + /* empty */ + + return(0); +} + +int +ags_pad_group_clicked_callback(GtkWidget *widget, AgsPad *pad) +{ + AgsLine *line; + GtkContainer *container; + GList *list, *list_start; + + if(gtk_toggle_button_get_active(pad->group)){ + container = (GtkContainer *) pad->expander_set; + + list_start = + list = gtk_container_get_children(container); + + while(list != NULL){ + line = AGS_LINE(list->data); + + if(!gtk_toggle_button_get_active(line->group)){ + gtk_toggle_button_set_active(line->group, TRUE); + } + + list = list->next; + } + + g_list_free(list_start); + }else{ + container = (GtkContainer *) pad->expander_set; + + list_start = + list = gtk_container_get_children(container); + + while(list != NULL){ + line = AGS_LINE(list->data); + + if(!gtk_toggle_button_get_active(line->group)){ + return(0); + } + + list = list->next; + } + + g_list_free(list_start); + gtk_toggle_button_set_active(pad->group, TRUE); + } + + return(0); +} + +int +ags_pad_mute_clicked_callback(GtkWidget *widget, AgsPad *pad) +{ + AgsWindow *window; + AgsMachine *machine; + GtkContainer *container; + AgsChannel *channel; + AgsSetMuted *set_muted; + AgsThread *main_loop, *current; + AgsTaskThread *task_thread; + AgsApplicationContext *application_context; + GList *list, *list_start, *tasks; + + machine = (AgsMachine *) gtk_widget_get_ancestor((GtkWidget *) pad, + AGS_TYPE_MACHINE); + + window = gtk_widget_get_ancestor((GtkWidget *) pad, + AGS_TYPE_WINDOW); + + application_context = window->application_context; + + main_loop = application_context->main_loop; + + task_thread = NULL; + + channel = pad->channel; + tasks = NULL; + + if(gtk_toggle_button_get_active(pad->mute)){ + if(gtk_toggle_button_get_active(pad->solo)) + gtk_toggle_button_set_active(pad->solo, FALSE); + + /* mute */ + while(channel != pad->channel->next_pad){ + set_muted = ags_set_muted_new(G_OBJECT(channel), + TRUE); + tasks = g_list_prepend(tasks, set_muted); + + channel = channel->next; + } + }else{ + if((AGS_MACHINE_SOLO & (machine->flags)) != 0){ + container = (GtkContainer *) (AGS_IS_OUTPUT(pad->channel) ? machine->output: machine->input); + list_start = + list = gtk_container_get_children(container); + + while(!gtk_toggle_button_get_active(AGS_PAD(list->data)->solo)) + list = list->next; + + g_list_free(list_start); + + gtk_toggle_button_set_active(AGS_PAD(list->data)->solo, FALSE); + + machine->flags &= ~(AGS_MACHINE_SOLO); + } + + /* unmute */ + while(channel != pad->channel->next_pad){ + set_muted = ags_set_muted_new(G_OBJECT(channel), + FALSE); + tasks = g_list_prepend(tasks, set_muted); + + channel = channel->next; + } + } + + ags_task_thread_append_tasks(task_thread, + tasks); + + return(0); +} + +int +ags_pad_solo_clicked_callback(GtkWidget *widget, AgsPad *pad) +{ + AgsMachine *machine; + GtkContainer *container; + GList *list, *list_start; + + machine = (AgsMachine *) gtk_widget_get_ancestor((GtkWidget *) pad, AGS_TYPE_MACHINE); + + if(gtk_toggle_button_get_active(pad->solo)){ + container = (GtkContainer *) (AGS_IS_OUTPUT(pad->channel) ? machine->output: machine->input); + + if(gtk_toggle_button_get_active(pad->mute)) + gtk_toggle_button_set_active(pad->mute, FALSE); + + list_start = + list = gtk_container_get_children(container); + + while(list != NULL){ + if(list->data == pad){ + list = list->next; + continue; + } + + gtk_toggle_button_set_active(AGS_PAD(list->data)->mute, TRUE); + + list = list->next; + } + + g_list_free(list_start); + machine->flags |= (AGS_MACHINE_SOLO); + }else + machine->flags &= ~(AGS_MACHINE_SOLO); + + return(0); +} diff --git a/pool/shard000/C/0014616_convert_uint64_uint32.c b/pool/shard000/C/0014616_convert_uint64_uint32.c new file mode 100644 index 0000000000000000000000000000000000000000..d01edf86042da862363309fe7cb7adc5b3352b62 --- /dev/null +++ b/pool/shard000/C/0014616_convert_uint64_uint32.c @@ -0,0 +1,75 @@ +/* Copyright (C) 2008-2011 D. V. Wiebe + * + *************************************************************************** + * + * This file is part of the GetData project. + * + * GetData 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. + * + * GetData 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 GetData; if not, write to the Free Software Foundation, Inc., + * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ +/* Attempt to read UINT64 as UINT32 */ +#include "test.h" + +#include +#include +#include +#include +#include +#include +#include + +int main(void) +{ + const char *filedir = "dirfile"; + const char *format = "dirfile/format"; + const char *data = "dirfile/data"; + const char *format_data = "data RAW UINT64 8\n"; + uint64_t data_data[256]; + uint32_t c[8]; + int fd, i, n, error, r = 0; + DIRFILE *D; + + memset(c, 0, 8); + rmdirfile(); + mkdir(filedir, 0777); + + for (fd = 0; fd < 256; ++fd) + data_data[fd] = fd; + + fd = open(format, O_CREAT | O_EXCL | O_WRONLY, 0666); + write(fd, format_data, strlen(format_data)); + close(fd); + + fd = open(data, O_CREAT | O_EXCL | O_WRONLY | O_BINARY, 0666); + write(fd, data_data, 256 * sizeof(uint64_t)); + close(fd); + + D = gd_open(filedir, GD_RDONLY | GD_VERBOSE); + n = gd_getdata(D, "data", 5, 0, 1, 0, GD_UINT32, c); + + error = gd_error(D); + + gd_close(D); + + unlink(data); + unlink(format); + rmdir(filedir); + + CHECKI(error, 0); + CHECKI(n, 8); + for (i = 0; i < 8; ++i) + CHECKUi(i,c[i], 40 + (unsigned)i); + + return r; +} diff --git a/pool/shard000/C/0014628_vmifs.c b/pool/shard000/C/0014628_vmifs.c new file mode 100644 index 0000000000000000000000000000000000000000..94ea5aa1f7ab293c06a2547e121f73e3703d0c30 --- /dev/null +++ b/pool/shard000/C/0014628_vmifs.c @@ -0,0 +1,158 @@ +/* The LibVMI Library is an introspection library that simplifies access to + * memory in a target virtual machine or in a file containing a dump of + * a system's physical memory. LibVMI is based on the XenAccess Library. + * + * Author: Tamas K Lengyel 2013 (tamas.lengyel@zentific.com) + * + * This file is part of LibVMI. + * + * LibVMI 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. + * + * LibVMI 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 LibVMI. If not, see . + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static const char *mem_path = "/mem"; +vmi_instance_t vmi; + +static int vmifs_getattr(const char *path, struct stat *stbuf) +{ + int res = 0; + + memset(stbuf, 0, sizeof(struct stat)); + if(strcmp(path, "/") == 0) { + stbuf->st_mode = S_IFDIR | 0755; + stbuf->st_nlink = 2; + } + else if(strcmp(path, mem_path) == 0) { + stbuf->st_mode = S_IFREG | 0444; + stbuf->st_nlink = 1; + stbuf->st_size = vmi_get_memsize(vmi); + } + else + res = -ENOENT; + + return res; +} + +static int vmifs_readdir(const char *path, void *buf, fuse_fill_dir_t filler, + off_t offset, struct fuse_file_info *fi) +{ + (void) offset; + (void) fi; + + if(strcmp(path, "/") != 0) + return -ENOENT; + + filler(buf, ".", NULL, 0); + filler(buf, "..", NULL, 0); + filler(buf, mem_path + 1, NULL, 0); + + return 0; +} + +static int vmifs_open(const char *path, struct fuse_file_info *fi) +{ + if(strcmp(path, mem_path) != 0) + return -ENOENT; + + uint32_t accmod = O_RDONLY | O_WRONLY | O_RDWR; + if((fi->flags & accmod) != O_RDONLY) + return -EACCES; + + return 0; +} + +static int vmifs_read(const char *path, char *buf, size_t size, off_t offset, + struct fuse_file_info *fi) +{ + (void) fi; + if(strcmp(path, mem_path) != 0) + return -ENOENT; + + unsigned long memsize = vmi_get_memsize(vmi); + if(offset < memsize && size) { + if(offset + size > memsize) + size = memsize-offset; + + uint8_t *buffer = g_malloc0(sizeof(uint8_t)*size); + size_t size_read = vmi_read_pa(vmi, offset, buffer, size); + + if(size != size_read) { + g_free(buffer); + } else { + memcpy(buf, buffer, size); + g_free(buffer); + } + + } else { + return 0; + } + + return size; +} + +void vmifs_destroy() { + vmi_destroy(vmi); +} + +static struct fuse_operations vmifs_oper = { + .getattr = vmifs_getattr, + .readdir = vmifs_readdir, + .open = vmifs_open, + .read = vmifs_read, + .destroy = vmifs_destroy, +}; + +int main(int argc, char *argv[]) +{ + /* this is the VM or file that we are looking at */ + if (argc != 4) { + printf("Usage: %s name|domid \n", argv[0]); + return 1; + } + + uint64_t domid = VMI_INVALID_DOMID; + GHashTable *config = g_hash_table_new(g_str_hash, g_str_equal); + + if(strcmp(argv[1],"name")==0) { + g_hash_table_insert(config, "name", argv[2]); + } else + if(strcmp(argv[1],"domid")==0) { + domid = strtoull(argv[2], NULL, 0); + g_hash_table_insert(config, "domid", &domid); + } else { + printf("You have to specify either name or domid!\n"); + return 1; + } + + /* initialize the libvmi library */ + if (vmi_init_custom(&vmi, VMI_AUTO | VMI_INIT_PARTIAL | VMI_CONFIG_GHASHTABLE, (vmi_config_t)config) == VMI_FAILURE) { + printf("Failed to init LibVMI library.\n"); + return 1; + } + + g_hash_table_destroy(config); + + char *fuse_argv[2] = { argv[0], argv[3] }; + + return fuse_main(2, fuse_argv, &vmifs_oper); +} diff --git a/pool/shard000/C/0014632_ag71xx_mdio.c b/pool/shard000/C/0014632_ag71xx_mdio.c new file mode 100644 index 0000000000000000000000000000000000000000..552c7bfbacb07b5649e99305bb207c5aa47a4b92 --- /dev/null +++ b/pool/shard000/C/0014632_ag71xx_mdio.c @@ -0,0 +1,246 @@ +/* + * Atheros AR71xx built-in ethernet mac driver + * + * Copyright (C) 2008-2010 Gabor Juhos + * Copyright (C) 2008 Imre Kaloz + * + * Based on Atheros' AG7100 driver + * + * 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 "ag71xx.h" + +#define AG71XX_MDIO_RETRY 1000 +#define AG71XX_MDIO_DELAY 5 + +static inline void ag71xx_mdio_wr(struct ag71xx_mdio *am, unsigned reg, + u32 value) +{ + void __iomem *r; + + r = am->mdio_base + reg; + __raw_writel(value, r); + + /* flush write */ + (void) __raw_readl(r); +} + +static inline u32 ag71xx_mdio_rr(struct ag71xx_mdio *am, unsigned reg) +{ + return __raw_readl(am->mdio_base + reg); +} + +static void ag71xx_mdio_dump_regs(struct ag71xx_mdio *am) +{ + DBG("%s: mii_cfg=%08x, mii_cmd=%08x, mii_addr=%08x\n", + am->mii_bus->name, + ag71xx_mdio_rr(am, AG71XX_REG_MII_CFG), + ag71xx_mdio_rr(am, AG71XX_REG_MII_CMD), + ag71xx_mdio_rr(am, AG71XX_REG_MII_ADDR)); + DBG("%s: mii_ctrl=%08x, mii_status=%08x, mii_ind=%08x\n", + am->mii_bus->name, + ag71xx_mdio_rr(am, AG71XX_REG_MII_CTRL), + ag71xx_mdio_rr(am, AG71XX_REG_MII_STATUS), + ag71xx_mdio_rr(am, AG71XX_REG_MII_IND)); +} + +int ag71xx_mdio_mii_read(struct ag71xx_mdio *am, int addr, int reg) +{ + int ret; + int i; + + ag71xx_mdio_wr(am, AG71XX_REG_MII_CMD, MII_CMD_WRITE); + ag71xx_mdio_wr(am, AG71XX_REG_MII_ADDR, + ((addr & 0xff) << MII_ADDR_SHIFT) | (reg & 0xff)); + ag71xx_mdio_wr(am, AG71XX_REG_MII_CMD, MII_CMD_READ); + + i = AG71XX_MDIO_RETRY; + while (ag71xx_mdio_rr(am, AG71XX_REG_MII_IND) & MII_IND_BUSY) { + if (i-- == 0) { + pr_err("%s: mii_read timed out\n", am->mii_bus->name); + ret = 0xffff; + goto out; + } + udelay(AG71XX_MDIO_DELAY); + } + + ret = ag71xx_mdio_rr(am, AG71XX_REG_MII_STATUS) & 0xffff; + ag71xx_mdio_wr(am, AG71XX_REG_MII_CMD, MII_CMD_WRITE); + + DBG("mii_read: addr=%04x, reg=%04x, value=%04x\n", addr, reg, ret); + +out: + return ret; +} + +void ag71xx_mdio_mii_write(struct ag71xx_mdio *am, int addr, int reg, u16 val) +{ + int i; + + DBG("mii_write: addr=%04x, reg=%04x, value=%04x\n", addr, reg, val); + + ag71xx_mdio_wr(am, AG71XX_REG_MII_ADDR, + ((addr & 0xff) << MII_ADDR_SHIFT) | (reg & 0xff)); + ag71xx_mdio_wr(am, AG71XX_REG_MII_CTRL, val); + + i = AG71XX_MDIO_RETRY; + while (ag71xx_mdio_rr(am, AG71XX_REG_MII_IND) & MII_IND_BUSY) { + if (i-- == 0) { + pr_err("%s: mii_write timed out\n", am->mii_bus->name); + break; + } + udelay(AG71XX_MDIO_DELAY); + } +} + +static int ag71xx_mdio_reset(struct mii_bus *bus) +{ + struct ag71xx_mdio *am = bus->priv; + u32 t; + + if (am->pdata->is_ar7240) + t = MII_CFG_CLK_DIV_6; + else + t = MII_CFG_CLK_DIV_28; + + ag71xx_mdio_wr(am, AG71XX_REG_MII_CFG, t | MII_CFG_RESET); + udelay(100); + + ag71xx_mdio_wr(am, AG71XX_REG_MII_CFG, t); + udelay(100); + + return 0; +} + +static int ag71xx_mdio_read(struct mii_bus *bus, int addr, int reg) +{ + struct ag71xx_mdio *am = bus->priv; + + if (am->pdata->is_ar7240) + return ar7240sw_phy_read(bus, addr, reg); + else + return ag71xx_mdio_mii_read(am, addr, reg); +} + +static int ag71xx_mdio_write(struct mii_bus *bus, int addr, int reg, u16 val) +{ + struct ag71xx_mdio *am = bus->priv; + + if (am->pdata->is_ar7240) + ar7240sw_phy_write(bus, addr, reg, val); + else + ag71xx_mdio_mii_write(am, addr, reg, val); + return 0; +} + +static int __devinit ag71xx_mdio_probe(struct platform_device *pdev) +{ + struct ag71xx_mdio_platform_data *pdata; + struct ag71xx_mdio *am; + struct resource *res; + int i; + int err; + + pdata = pdev->dev.platform_data; + if (!pdata) { + dev_err(&pdev->dev, "no platform data specified\n"); + return -EINVAL; + } + + am = kzalloc(sizeof(*am), GFP_KERNEL); + if (!am) { + err = -ENOMEM; + goto err_out; + } + + am->pdata = pdata; + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (!res) { + dev_err(&pdev->dev, "no iomem resource found\n"); + err = -ENXIO; + goto err_out; + } + + am->mdio_base = ioremap_nocache(res->start, res->end - res->start + 1); + if (!am->mdio_base) { + dev_err(&pdev->dev, "unable to ioremap registers\n"); + err = -ENOMEM; + goto err_free_mdio; + } + + am->mii_bus = mdiobus_alloc(); + if (am->mii_bus == NULL) { + err = -ENOMEM; + goto err_iounmap; + } + + am->mii_bus->name = "ag71xx_mdio"; + am->mii_bus->read = ag71xx_mdio_read; + am->mii_bus->write = ag71xx_mdio_write; + am->mii_bus->reset = ag71xx_mdio_reset; + am->mii_bus->irq = am->mii_irq; + am->mii_bus->priv = am; + am->mii_bus->parent = &pdev->dev; + snprintf(am->mii_bus->id, MII_BUS_ID_SIZE, "%s", dev_name(&pdev->dev)); + am->mii_bus->phy_mask = pdata->phy_mask; + + for (i = 0; i < PHY_MAX_ADDR; i++) + am->mii_irq[i] = PHY_POLL; + + ag71xx_mdio_wr(am, AG71XX_REG_MAC_CFG1, 0); + + err = mdiobus_register(am->mii_bus); + if (err) + goto err_free_bus; + + ag71xx_mdio_dump_regs(am); + + platform_set_drvdata(pdev, am); + return 0; + +err_free_bus: + mdiobus_free(am->mii_bus); +err_iounmap: + iounmap(am->mdio_base); +err_free_mdio: + kfree(am); +err_out: + return err; +} + +static int __devexit ag71xx_mdio_remove(struct platform_device *pdev) +{ + struct ag71xx_mdio *am = platform_get_drvdata(pdev); + + if (am) { + mdiobus_unregister(am->mii_bus); + mdiobus_free(am->mii_bus); + iounmap(am->mdio_base); + kfree(am); + platform_set_drvdata(pdev, NULL); + } + + return 0; +} + +static struct platform_driver ag71xx_mdio_driver = { + .probe = ag71xx_mdio_probe, + .remove = __exit_p(ag71xx_mdio_remove), + .driver = { + .name = "ag71xx-mdio", + } +}; + +int __init ag71xx_mdio_driver_init(void) +{ + return platform_driver_register(&ag71xx_mdio_driver); +} + +void ag71xx_mdio_driver_exit(void) +{ + platform_driver_unregister(&ag71xx_mdio_driver); +} diff --git a/pool/shard000/C/0014644_syllables.c b/pool/shard000/C/0014644_syllables.c new file mode 100644 index 0000000000000000000000000000000000000000..8aa6486c7dd36ace7a8f0972d303de23cb447f2d --- /dev/null +++ b/pool/shard000/C/0014644_syllables.c @@ -0,0 +1,43 @@ +// + +#include +#include + +int main () +{ + char inputString[20]; + int length, k, j, syl; + char vowels[6]; + vowels[0] = 'a'; + vowels[1] = 'e'; + vowels[2] = 'i'; + vowels[3] = 'o'; + vowels[4] = 'u'; + vowels[5] = 'y'; + char temp; + + k = 0; + j = 0; + syl = 0; + + printf("Please enter a string > "); + gets(inputString); + + length = strlen(inputString); + + for(k = 0; (k < length); k++) + { + temp = inputString[k]; + for(j = 0; (j < 6); j++) + { + if(temp == vowels[j]) + { + syl = syl + 1; + j = 99; + // + } + } + } +printf("The number of syllables is %d.",syl); +return 0; +} diff --git a/pool/shard000/C/0014667_boehm.c b/pool/shard000/C/0014667_boehm.c new file mode 100644 index 0000000000000000000000000000000000000000..897f07d61250fd436dc759834a06c9fcb9d9e22e --- /dev/null +++ b/pool/shard000/C/0014667_boehm.c @@ -0,0 +1,245 @@ +/* Functions related to the Boehm garbage collector. + Copyright (C) 2000-2015 Free Software Foundation, Inc. + +This file is part of GCC. + +GCC is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 3, or (at your option) +any later version. + +GCC 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 GCC; see the file COPYING3. If not see +. + +Java and all Java-based marks are trademarks or registered trademarks +of Sun Microsystems, Inc. in the United States and other countries. +The Free Software Foundation is independent of Sun Microsystems, Inc. */ + +/* Written by Tom Tromey . */ + +#include "config.h" +#include "system.h" +#include "coretypes.h" +#include "double-int.h" +#include "tm.h" +#include "hash-set.h" +#include "machmode.h" +#include "vec.h" +#include "input.h" +#include "alias.h" +#include "symtab.h" +#include "options.h" +#include "wide-int.h" +#include "inchash.h" +#include "tree.h" +#include "java-tree.h" +#include "parse.h" +#include "diagnostic-core.h" + +static void mark_reference_fields (tree, wide_int *, unsigned int, + int *, int *, int *, HOST_WIDE_INT *); + +/* A procedure-based object descriptor. We know that our + `kind' is 0, and `env' is likewise 0, so we have a simple + computation. From the GC sources: + (((((env) << LOG_MAX_MARK_PROCS) | (proc_index)) << DS_TAG_BITS) \ + | DS_PROC) + Here DS_PROC == 2. */ +#define PROCEDURE_OBJECT_DESCRIPTOR 2 + +/* Recursively mark reference fields. */ +static void +mark_reference_fields (tree field, + wide_int *mask, + unsigned int ubit, + int *pointer_after_end, + int *all_bits_set, + int *last_set_index, + HOST_WIDE_INT *last_view_index) +{ + /* See if we have fields from our superclass. */ + if (DECL_NAME (field) == NULL_TREE) + { + mark_reference_fields (TYPE_FIELDS (TREE_TYPE (field)), + mask, ubit, + pointer_after_end, all_bits_set, + last_set_index, last_view_index); + field = DECL_CHAIN (field); + } + + for (; field != NULL_TREE; field = DECL_CHAIN (field)) + { + HOST_WIDE_INT offset; + HOST_WIDE_INT size_bytes; + + if (FIELD_STATIC (field)) + continue; + + offset = int_byte_position (field); + size_bytes = int_size_in_bytes (TREE_TYPE (field)); + + if (JREFERENCE_TYPE_P (TREE_TYPE (field)) + /* An `object' of type gnu.gcj.RawData is actually non-Java + data. */ + && TREE_TYPE (field) != rawdata_ptr_type_node) + { + unsigned int count; + unsigned int size_words; + unsigned int i; + + /* If this reference slot appears to overlay a slot we think + we already covered, then we are doomed. */ + gcc_assert (offset > *last_view_index); + + if (offset % (HOST_WIDE_INT) (POINTER_SIZE / BITS_PER_UNIT)) + { + *all_bits_set = -1; + *pointer_after_end = 1; + break; + } + + count = offset * BITS_PER_UNIT / POINTER_SIZE; + size_words = size_bytes * BITS_PER_UNIT / POINTER_SIZE; + + *last_set_index = count; + + if (count >= ubit - 2) + *pointer_after_end = 1; + else + /* First word in object corresponds to most significant byte of + bitmap. + + In the case of a multiple-word record, we set pointer + bits for all words in the record. This is conservative, but the + size_words != 1 case is impossible in regular java code. */ + for (i = 0; i < size_words; ++i) + *mask = wi::set_bit (*mask, ubit - count - i - 1); + + /* If we saw a non-reference field earlier, then we can't + use the count representation. We keep track of that in + *ALL_BITS_SET. */ + if (! *all_bits_set) + *all_bits_set = -1; + } + else if (*all_bits_set > 0) + *all_bits_set = 0; + + *last_view_index = offset; + } +} + +/* Return the marking bitmap for the class TYPE. For now this is a + single word describing the type. */ +tree +get_boehm_type_descriptor (tree type) +{ + unsigned int count, log2_size, ubit; + int bit; + int all_bits_set = 1; + int last_set_index = 0; + HOST_WIDE_INT last_view_index = -1; + int pointer_after_end = 0; + tree field, value, value_type; + + /* If the GC wasn't requested, just use a null pointer. */ + if (! flag_use_boehm_gc) + return null_pointer_node; + + value_type = java_type_for_mode (ptr_mode, 1); + wide_int mask = wi::zero (TYPE_PRECISION (value_type)); + + /* If we have a type of unknown size, use a proc. */ + if (int_size_in_bytes (type) == -1) + goto procedure_object_descriptor; + + bit = POINTER_SIZE / BITS_PER_UNIT; + /* The size of this node has to be known. And, we only support 32 + and 64 bit targets, so we need to know that the log2 is one of + our values. */ + log2_size = exact_log2 (bit); + if (bit == -1 || (log2_size != 2 && log2_size != 3)) + { + /* This means the GC isn't supported. We should probably + abort or give an error. Instead, for now, we just silently + revert. FIXME. */ + return null_pointer_node; + } + bit *= BITS_PER_UNIT; + + /* Warning avoidance. */ + ubit = (unsigned int) bit; + + if (type == class_type_node) + goto procedure_object_descriptor; + + field = TYPE_FIELDS (type); + mark_reference_fields (field, &mask, ubit, + &pointer_after_end, &all_bits_set, + &last_set_index, &last_view_index); + + /* If the object is all pointers, or if the part with pointers fits + in our bitmap, then we are ok. Otherwise we have to allocate it + a different way. */ + if (all_bits_set != -1 || (pointer_after_end && flag_reduced_reflection)) + { + /* In this case the initial part of the object is all reference + fields, and the end of the object is all non-reference + fields. We represent the mark as a count of the fields, + shifted. In the GC the computation looks something like + this: + value = DS_LENGTH | WORDS_TO_BYTES (last_set_index + 1); + DS_LENGTH is 0. + WORDS_TO_BYTES shifts by log2(bytes-per-pointer). + + In the case of flag_reduced_reflection and the bitmap would + overflow, we tell the gc that the object is all pointers so + that we don't have to emit reflection data for run time + marking. */ + count = 0; + mask = wi::zero (TYPE_PRECISION (value_type)); + ++last_set_index; + while (last_set_index) + { + if ((last_set_index & 1)) + mask = wi::set_bit (mask, log2_size + count); + last_set_index >>= 1; + ++count; + } + value = wide_int_to_tree (value_type, mask); + } + else if (! pointer_after_end) + { + /* Bottom two bits for bitmap mark type are 01. */ + mask = wi::set_bit (mask, 0); + value = wide_int_to_tree (value_type, mask); + } + else + { + procedure_object_descriptor: + value = build_int_cst (value_type, PROCEDURE_OBJECT_DESCRIPTOR); + } + + return value; +} + +/* The fourth (index of 3) element in the vtable is the GC descriptor. + A value of 2 indicates that the class uses _Jv_MarkObj. */ +bool +uses_jv_markobj_p (tree dtable) +{ + tree v; + /* FIXME: what do we return if !flag_use_boehm_gc ? */ + gcc_assert (flag_use_boehm_gc); + /* FIXME: this is wrong if TARGET_VTABLE_USES_DESCRIPTORS. However, + this function is only used with flag_reduced_reflection. No + point in asserting unless we hit the bad case. */ + gcc_assert (!flag_reduced_reflection || TARGET_VTABLE_USES_DESCRIPTORS == 0); + v = (*CONSTRUCTOR_ELTS (dtable))[3].value; + return (PROCEDURE_OBJECT_DESCRIPTOR == TREE_INT_CST_LOW (v)); +} diff --git a/pool/shard000/C/0014676_fitness.c b/pool/shard000/C/0014676_fitness.c new file mode 100644 index 0000000000000000000000000000000000000000..2411ace0d81fbf0b37b38ec1d045e2aa57d66cec --- /dev/null +++ b/pool/shard000/C/0014676_fitness.c @@ -0,0 +1,28 @@ +// Fitness function +// !!! THIS FILE MUST BE UPDATED WITH AN ACTUAL FITNESS FUNCTION !!! +// For more details: +// http://phievo.readthedocs.io/en/latest/create_new_project.html#fitness-c +// Examples of fitnesses can be found in the example projects: +// https://github.com/phievo/phievo/tree/master/Examples +// Store the results for individual trials. +static double result[NTRIES]; + +void fitness( double history[][NSTEP][NCELLTOT], int trackout[],int trial) { + // MODIFY HERE to compute a fitness from the history array + result[trial] = 1; +} + +// Combine the fitnesses obtained in the different trials. +void treatment_fitness( double history2[][NSTEP][NCELLTOT], int trackout[]){ + // MODIFY HERE to combine the fitnesses computed for the different trials. + int trial = 0; + int func = 0; + double total_fitness = 0; + for(trial=0;trial + * This is inspired by code which was identical in both + * auth_krb4.c and auth_krb5.c. This code is shared + * between the two implementations, contains protection + * against a race condition, and, when possible, uses + * Heimdal krb5's memory-only credential caches to avoid + * needless disk i/o. + */ + +/* PUBLIC DEPENDENCIES */ +#include +#include +#include +#include + +#ifdef SASLAUTHD_THREADED /* is this really used??? */ +#include +#endif /* SASLAUTHD_THREADED */ + +#include "mechanisms.h" + +#include +#include +#include +#include + +#ifdef AUTH_KRB4 +#include +#define WANT_KRBTF +#endif /* WANT_KRBTF */ + +#ifdef AUTH_KRB5 +#include +#define WANT_KRBTF +#endif /* WANT_KRBTF */ + +#ifdef WANT_KRBTF + +/* PRIVATE DEPENDENCIES */ +/* globals */ + +/* privates */ +static char tf_dir[] = PATH_SASLAUTHD_RUNDIR "/.tf"; +static char *tfn_cookie = 0; +static int tfn_cookie_len = 0; +static char pidstring[80]; +size_t pidstring_len = 0; +/* END PRIVATE DEPENDENCIES */ + +#endif /* WANT_KRBTF */ + +/* FUNCTION: krbtf_init */ + +/* SYNOPSIS + * Initialize the Kerberos IV/V ticket-file/credential-cache common code + * + * When possible, use Heimdal krb5's memory-only credential caches-- + * this saves a whole bunch of useless disk i/o's to create and destroy + * a file which we don't want anybody to see anyway. + * + * If not, this function will create a private directory for ticket + * files and cache getpid() for later use. Therefore, we must be + * called AFTER main() does whatever fork()ing it wants. + * + * END SYNOPSIS */ + +int /* R: -1 on failure, else 0 */ +krbtf_init ( + /* PARAMETERS */ + void /* no parameters */ + /* END PARAMETERS */ + ) +{ +#ifdef WANT_KRBTF + /* VARIABLES */ + int rc; /* return code holder */ + struct stat sb; /* stat() work area */ + /* END VARIABLES */ + authmech_t *authmech; + +#ifdef AUTH_KRB5 + for (authmech = mechanisms; authmech->name != NULL; authmech++ ) { + if (authmech->initialize != auth_krb5_init) continue; + /* This execution is using krb5 */ + /* Both MIT krb5 and Heimdal support MEMORY: ccaches */ + tfn_cookie = "MEMORY:0"; + tfn_cookie_len = strlen(tfn_cookie); + return 0; + } +#endif /* AUTH_KRB5 */ + + if (((rc = mkdir(tf_dir, 0700)) == 0) || (errno == EEXIST)) { + if ((rc = lstat(tf_dir, &sb)) == 0) { + if (sb.st_mode & S_IFLNK) { + syslog(LOG_ERR, "krbtf_init: %s is a symbolic link", tf_dir); + return -1; + } + } + } + + if (rc != 0) { + syslog(LOG_ERR, "krbtf_init %s: %m", tf_dir); + return -1; + } + + /* cache getpid() for use in filenames */ + if ((pidstring_len = snprintf(pidstring, sizeof (pidstring), "%d", getpid())) >= sizeof (pidstring)) { + syslog(LOG_ERR, "krbtf_init pidstring too long(!?)"); + return -1; + } + + return 0; +#else /* WANT_KRBTF */ + syslog(LOG_ERR, "krbtf_init: not compiled!"); + return -1; +#endif /* WANT_KRBTF */ +} + +/* END FUNCTION: krbtf_init */ + +/* FUNCTION: krbtf_name */ + +/* SYNOPSIS + * Spit a ticket-file/credentical-cache name into caller's array. + * + * If we can, emit the magic cookie for a memory-only krb5 ccname + * END SYNOPSIS */ + +int /* R: -1 on failure, else 0 */ +krbtf_name ( + /* PARAMETERS */ + char *tfname, /* O: where caller wants name */ + int len /* I: available length */ + /* END PARAMETERS */ + ) +{ +#ifdef WANT_KRBTF + if (tfn_cookie_len) { + if (tfn_cookie_len + 1 > len) { + syslog(LOG_ERR, "krbtf_name: cookie name (%s) too long", tfn_cookie); + return -1; + } + strcpy(tfname, tfn_cookie); + } else { + int dir_len = sizeof (tf_dir) - 1; /* don't count the null */ + int want_len = dir_len + 1 + pidstring_len + 1; + + if (want_len > len) { + syslog(LOG_ERR, "krbtf_name: need room for %d bytes, got %d", want_len, len); + return -1; + } + + strcpy(tfname, tf_dir); + tfname += dir_len; len -= dir_len; + + *tfname++ = '/'; len--; + + strcpy(tfname, pidstring); + +#ifdef SASLAUTHD_THREADED /* is this really used??? */ + tfname += pidstring_len; + len -= pidstring_len; + + if (snprintf(tfname, len, "_%d", pthread_self() >= len)) { + syslog(LOG_ERR, "krbtf_name: no room for thread id"); + return -1; + } +#endif /* SASLAUTHD_THREADED */ + } + + return 0; +#else /* WANT_KRBTF */ + syslog(LOG_ERR, "krbtf_name: not compiled!"); + return -1; +#endif /* WANT_KRBTF */ +} +/* END FUNCTION: krbtf_name */ + +/* END MODULE: krbtf */ diff --git a/pool/shard000/C/0014690_fpu.c b/pool/shard000/C/0014690_fpu.c new file mode 100644 index 0000000000000000000000000000000000000000..6243adaba23bba643c88e699c59dfbe7239b19e5 --- /dev/null +++ b/pool/shard000/C/0014690_fpu.c @@ -0,0 +1,225 @@ +/* $NetBSD: fpu.c,v 1.1 2001/06/19 00:21:16 fvdl Exp $ */ + +/*- + * Copyright (c) 1994, 1995, 1998 Charles M. Hannum. All rights reserved. + * Copyright (c) 1990 William Jolitz. + * Copyright (c) 1991 The Regents of the University of California. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)npx.c 7.2 (Berkeley) 5/12/91 + */ + +/* + * XXXfvdl update copyright notice. this started out as a stripped isa/npx.c + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include + +/* + * We do lazy initialization and switching using the TS bit in cr0 and the + * MDP_USEDFPU bit in mdproc. + * + * DNA exceptions are handled like this: + * + * 1) If there is no FPU, return and go to the emulator. + * 2) If someone else has used the FPU, save its state into that process's PCB. + * 3a) If MDP_USEDFPU is not set, set it and initialize the FPU. + * 3b) Otherwise, reload the process's previous FPU state. + * + * When a process is created or exec()s, its saved cr0 image has the TS bit + * set and the MDP_USEDFPU bit clear. The MDP_USEDFPU bit is set when the + * process first gets a DNA and the FPU is initialized. The TS bit is turned + * off when the FPU is used, and turned on again later when the process's FPU + * state is saved. + */ + +#define fninit() __asm("fninit") +#define fwait() __asm("fwait") +#define fxsave(addr) __asm("fxsave %0" : "=m" (*addr)) +#define fxrstor(addr) __asm("fxrstor %0" : : "m" (*addr)) +#define clts() __asm("clts") +#define stts() lcr0(rcr0() | CR0_TS) + +void fpudna(struct proc *); +void fpuexit(void); +static void fpusave1(void); + +struct proc *fpuproc; + +/* + * Init the FPU. + */ +void +fpuinit(void) +{ + lcr0(rcr0() & ~(CR0_EM|CR0_TS)); + fninit(); + lcr0(rcr0() | (CR0_TS)); +} + +/* + * Record the FPU state and reinitialize it all except for the control word. + * Then generate a SIGFPE. + * + * Reinitializing the state allows naive SIGFPE handlers to longjmp without + * doing any fixups. + */ +void +fputrap(frame) + struct trapframe *frame; +{ + register struct proc *p = fpuproc; + +#ifdef DIAGNOSTIC + /* + * At this point, fpuproc should be curproc. If it wasn't, the TS bit + * should be set, and we should have gotten a DNA exception. + */ + if (p != curproc) + panic("fputrap: wrong process"); +#endif + + fxsave(&p->p_addr->u_pcb.pcb_savefpu); + fninit(); + fwait(); + trapsignal(p, SIGFPE, frame->tf_err); +} + +/* + * Wrapper for the fnsave instruction. We set the TS bit in the saved CR0 for + * this process, so that it will get a DNA exception on the FPU instruction and + * force a reload. + */ +static inline void +fpusave1(void) +{ + struct proc *p = fpuproc; + + fxsave(&p->p_addr->u_pcb.pcb_savefpu); + p->p_addr->u_pcb.pcb_cr0 |= CR0_TS; +} + +/* + * Implement device not available (DNA) exception + * + * If we were the last process to use the FPU, we can simply return. + * Otherwise, we save the previous state, if necessary, and restore our last + * saved state. + */ +void +fpudna(struct proc *p) +{ + +#ifdef DIAGNOSTIC + if (cpl != 0) + panic("fpudna: masked"); +#endif + + p->p_addr->u_pcb.pcb_cr0 &= ~CR0_TS; + clts(); + + /* + * Initialize the FPU state to clear any exceptions. If someone else + * was using the FPU, save their state. + */ + if (fpuproc != 0 && fpuproc != p) + fpusave1(); + + fninit(); + fwait(); + + fpuproc = p; + + if ((p->p_md.md_flags & MDP_USEDFPU) == 0) + p->p_md.md_flags |= MDP_USEDFPU; + else + fxrstor(&p->p_addr->u_pcb.pcb_savefpu); +} + +/* + * Drop the current FPU state on the floor. + */ +void +fpudrop(void) +{ + struct proc *p = fpuproc; + + fpuproc = 0; + stts(); + p->p_addr->u_pcb.pcb_cr0 |= CR0_TS; +} + +/* + * Save fpuproc's FPU state. + * + * The FNSAVE instruction clears the FPU state. Rather than reloading the FPU + * immediately, we clear fpuproc and turn on CR0_TS to force a DNA and a reload + * of the FPU state the next time we try to use it. This routine is only + * called when forking or core dumping, so the lazy reload at worst forces us + * to trap once per fork(), and at best saves us a reload once per fork(). + */ +void +fpusave(void) +{ + +#ifdef DIAGNOSTIC + if (cpl != 0) + panic("fpusave: masked"); +#endif + clts(); + fpusave1(); + fpuproc = 0; + stts(); +} diff --git a/pool/shard000/C/0014697_sys.c b/pool/shard000/C/0014697_sys.c new file mode 100644 index 0000000000000000000000000000000000000000..1a13b018d5172ed8ca1337f4d3ee7f8d6f1d395f --- /dev/null +++ b/pool/shard000/C/0014697_sys.c @@ -0,0 +1,87 @@ +/**************************************************************************** + * + * Copyright 2016 Samsung Electronics 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. + * + ****************************************************************************/ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR 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. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ + +/** + * @file + * lwIP Operating System abstraction + * + */ + +#include + +#include +#include + +/* Most of the functions defined in sys.h must be implemented in the + * architecture-dependent file sys_arch.c */ + +#if !NO_SYS + +#ifndef sys_msleep +/** + * Sleep for some ms. Timeouts are NOT processed while sleeping. + * + * @param ms number of milliseconds to sleep + */ +void sys_msleep(u32_t ms) +{ + if (ms > 0) { + sys_sem_t delaysem; + err_t err = sys_sem_new(&delaysem, 0); + if (err == ERR_OK) { + if (ms < MSEC_PER_TICK) + ms = MSEC_PER_TICK; + sys_arch_sem_wait(&delaysem, ms); + sys_sem_free(&delaysem); + } + } +} +#endif /* sys_msleep */ + +#endif /* !NO_SYS */ diff --git a/pool/shard000/C/0014743_purge.c b/pool/shard000/C/0014743_purge.c new file mode 100644 index 0000000000000000000000000000000000000000..557bc626e1275bbacd8537ca61572af423fe5b38 --- /dev/null +++ b/pool/shard000/C/0014743_purge.c @@ -0,0 +1,115 @@ + +/** + * `test/purge.c' - libsphia + * + * Copyright (C) 2014 The libsphia Authors + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +TEST(purge_bad_instance); +TEST(purge_simple); + +static char * +temp_file(const char *filename) { + char *tmp = malloc(256); + assert(tmp); + sprintf(tmp, "%s/%s", SPHIA_TEST_DB, filename); + return tmp; +} + +static int +file_exists(const char *name) { + struct stat stats; + + char *path = temp_file(name); + assert(path); + + int rc = stat(path, &stats); + free(path); + return -1 == rc + ? 0 + : 1; +} + +static void +create_file(const char *name) { + char *path = temp_file(name); + assert(path); + + if (0 == file_exists(name)) { + FILE *fp = fopen(path, "w"); + assert(fp); + fclose(fp); + } + + free(path); +} + +TEST(purge) { + HEADER(sphia_purge); + RUN(purge_bad_instance); + RUN(purge_simple); + FOOTER(); +} + +TEST(purge_bad_instance) { + assert(-1 == sphia_purge(NULL)); + return 0; +} + +TEST(purge_simple) { + const char *files_to_remove[] = { + "incomplete.foo" + , "a.incomplete" + , "1.incomplete" + , "12345000.incomplete" + , "foo.bar" + , NULL + }; + + const char *files_to_keep[] = { + ".foo" + , ".bar" + , "1.log" + , "foo.log" + , NULL + }; + + sphia_t *sphia = sphia_new(SPHIA_TEST_DB); + assert(sphia); + + // create a bunch of mock files + + for (int i = 0; files_to_remove[i]; i++) { + create_file(files_to_remove[i]); + } + + for (int i = 0; files_to_keep[i]; i++) { + create_file(files_to_keep[i]); + } + + assert(0 == sphia_purge(sphia)); + sphia_free(sphia); + + // verify we've removed the correct + // files and kept the others + + for (int i = 0; files_to_remove[i]; i++) { + assert(0 == file_exists(files_to_remove[i])); + } + + for (int i = 0; files_to_keep[i]; i++) { + assert(1 == file_exists(files_to_keep[i])); + } + + return 0; +} + diff --git a/pool/shard000/C/0014772_table.c b/pool/shard000/C/0014772_table.c new file mode 100644 index 0000000000000000000000000000000000000000..548d8de150a03aa0640d43bb8b889a1fbe97aebe --- /dev/null +++ b/pool/shard000/C/0014772_table.c @@ -0,0 +1,130 @@ +/** + * Tempesta DB + * + * Database table handling. + * + * Copyright (C) 2015 Tempesta Technologies. + * + * 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 "tdb.h" + +#define TDB_MAXTBL 512 + +typedef struct { + char name[TDB_TBLNAME_LEN + 1]; + TDB *db; +} TdbTable; + +/* Global list of currently open tables. */ +static TdbTable tdb_tbls[TDB_MAXTBL]; +static int tbl_last; +static DEFINE_MUTEX(tbl_mtx); + +void +tdb_tbl_enumerate(TDB *db) +{ + if (atomic_read(&db->count) > 1) + return; /* already enumerated */ + + mutex_lock(&tbl_mtx); + + if (tbl_last < TDB_MAXTBL) { + strncpy(tdb_tbls[tbl_last].name, db->tbl_name, TDB_TBLNAME_LEN); + tdb_tbls[tbl_last].db = db; + ++tbl_last; + } else + TDB_WARN("Cannot enumerate %s\n", db->tbl_name); + + mutex_unlock(&tbl_mtx); +} + +void +tdb_tbl_forget(TDB *db) +{ + int i; + + BUG_ON(atomic_read(&db->count)); + + mutex_lock(&tbl_mtx); + + for (i = 0; i < tbl_last; ++i) { + if (strncmp(db->tbl_name, tdb_tbls[i].name, TDB_TBLNAME_LEN)) + continue; + if (i < TDB_MAXTBL - 1) + memmove(tdb_tbls + i, tdb_tbls + i + 1, + (tbl_last - i) * sizeof(TdbTable)); + --tbl_last; + goto forgotten; + } + TDB_WARN("Table %s was not enumerated\n", db->tbl_name); + +forgotten: + mutex_unlock(&tbl_mtx); +} + +int +tdb_tbl_print_all(char *buf, size_t len) +{ + int i, n = 0; + + mutex_lock(&tbl_mtx); + + for (i = 0; i < tbl_last; ++i) { + int r = snprintf(buf + n, len - n, "%s ", tdb_tbls[i].name); + if (r <= 0) { + TDB_WARN("Not enough space to print all tables\n"); + break; + } + n += r; + } + + mutex_unlock(&tbl_mtx); + + return n; +} + +void +tdb_tbl_foreach(void (*func)(TDB *db)) +{ + int i; + + mutex_lock(&tbl_mtx); + + for (i = 0; i < tbl_last; ++i) + func(tdb_tbls[i].db); + + mutex_unlock(&tbl_mtx); +} + +TDB * +tdb_tbl_lookup(char *table, size_t len) +{ + int i; + TDB *db = NULL; + + mutex_lock(&tbl_mtx); + + for (i = 0; i < tbl_last; ++i) { + if (!strncmp(tdb_tbls[i].name, table, len)) { + db = tdb_get(tdb_tbls[i].db); + break; + } + } + + mutex_unlock(&tbl_mtx); + + return db; +} diff --git a/pool/shard000/C/0014778_timer-darwin.c b/pool/shard000/C/0014778_timer-darwin.c new file mode 100644 index 0000000000000000000000000000000000000000..1833694015f9489504bc7482692b02cf9f72339d --- /dev/null +++ b/pool/shard000/C/0014778_timer-darwin.c @@ -0,0 +1,116 @@ +/* + * Precise timer routines using Mach timing + * + * Copyright (c) 2003-2004, Dan Villiom Podlaski Christiansen + * + * 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. + */ + +#include +#include +#include +#include +#include +#include + +#include "config.h" +#include "mp_msg.h" +#include "timer.h" + +/* global variables */ +static double relative_time; +static double timebase_ratio; + +const char *timer_name = "Darwin accurate"; + + + +/* the core sleep function, uses floats and is used in MPlayer G2 */ +static float sleep_accurate(float time_frame) +{ + uint64_t deadline = time_frame / timebase_ratio + mach_absolute_time(); + + mach_wait_until(deadline); + + return (mach_absolute_time() - deadline) * timebase_ratio; +} + +/* wrapper for MPlayer G1 */ +int usec_sleep(int usec_delay) +{ + return sleep_accurate(usec_delay / 1e6) * 1e6; +} + + +/* current time in microseconds */ +unsigned int GetTimer(void) +{ + return (unsigned int)(uint64_t)(mach_absolute_time() * timebase_ratio * 1e6); +} + +/* current time in milliseconds */ +unsigned int GetTimerMS(void) +{ + return (unsigned int)(uint64_t)(mach_absolute_time() * timebase_ratio * 1e3); +} + +/* time spent between now and last call in seconds */ +float GetRelativeTime(void) +{ + double last_time = relative_time; + + if (!relative_time) + InitTimer(); + + relative_time = mach_absolute_time() * timebase_ratio; + + return (float)(relative_time-last_time); +} + +/* initialize timer, must be called at least once at start */ +void InitTimer(void) +{ + struct mach_timebase_info timebase; + + mach_timebase_info(&timebase); + timebase_ratio = (double)timebase.numer / (double)timebase.denom + * (double)1e-9; + + relative_time = (double)(mach_absolute_time() * timebase_ratio); +} + +#if 0 +#include + +int main(void) { + int i,j, r, c = 200; + long long t = 0; + + InitTimer(); + + for (i = 0; i < c; i++) { + const int delay = rand() / (RAND_MAX / 1e5); + j = GetTimer(); +#if 1 + r = usec_sleep(delay); +#else + r = sleep_accurate(delay / 1e6) * 1e6; +#endif + j = (GetTimer() - j) - delay; + printf("sleep time:%8i %5i (%i)\n", delay, j, j - r); + t += j - r; + } + fprintf(stderr, "average error:\t%lli\n", t / c); + + return 0; +} +#endif diff --git a/pool/shard000/C/0014779_gdb_stdio.c b/pool/shard000/C/0014779_gdb_stdio.c new file mode 100644 index 0000000000000000000000000000000000000000..ef7e12a103cb6b65a0fd32830b73bbe53a060b7c --- /dev/null +++ b/pool/shard000/C/0014779_gdb_stdio.c @@ -0,0 +1,125 @@ +/*---------------------------------------------------------------------------*\ + + FILE........: gdb_stdio.c + AUTHOR......: David Rowe + DATE CREATED: April 23 2013 + + Some stdio I/O functions that perform I/O on the host using gdb. + +\*---------------------------------------------------------------------------*/ + +/* + Copyright (C) 2013 David Rowe + + All rights reserved. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License version 2.1, as + published by the Free Software Foundation. This 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 Lesser General Public License + along with this program; if not, see . +*/ + +#include +#include +#include +#include "gdb_stdio.h" + +#define MAX_STR 2048 + +/* command codes we use to signal host */ + +#define GDB_STDIO_PRINTF 1 +#define GDB_STDIO_FOPEN 2 +#define GDB_STDIO_FCLOSE 3 +#define GDB_STDIO_FWRITE 4 +#define GDB_STDIO_FREAD 5 +#define GDB_STDIO_FPRINTF 6 + +/* globals we use to communicate with host */ + +volatile int gdb_stdio_func = 0; +volatile int gdb_stdio_ret = 0; +volatile char *gdb_stdio_pstr1; +volatile char *gdb_stdio_pstr2; +volatile int gdb_stdio_strlen1; +volatile int gdb_stdio_strlen2; +volatile FILE *gdb_stdio_file; +volatile void *gdb_stdio_ptr; +volatile int gdb_stdio_size; +volatile int gdb_stdio_nmem; + +void gdb_stdio_fprintf(FILE *file, const char *format, ...) { + va_list arg; + char str[MAX_STR]; + + va_start(arg, format); + vsnprintf(str, MAX_STR, format, arg); + va_end(arg); + gdb_stdio_file = file; + gdb_stdio_pstr1 = str; + gdb_stdio_strlen1 = strlen(str); + + gdb_stdio_func = GDB_STDIO_FPRINTF; + while(gdb_stdio_func); +} + +void gdb_stdio_printf(const char *format, ...) { + va_list arg; + char str[MAX_STR]; + + va_start(arg, format); + vsnprintf(str, MAX_STR, format, arg); + va_end(arg); + gdb_stdio_pstr1 = str; + gdb_stdio_strlen1 = strlen(str); + + gdb_stdio_func = GDB_STDIO_PRINTF; + while(gdb_stdio_func); +} + +FILE *gdb_stdio_fopen(char file_name[], char mode[]) { + gdb_stdio_pstr1 = file_name; + gdb_stdio_pstr2 = mode; + gdb_stdio_strlen1 = strlen(file_name); + gdb_stdio_strlen2 = strlen(mode); + + gdb_stdio_func = GDB_STDIO_FOPEN; + while(gdb_stdio_func); + return (FILE*)gdb_stdio_ret; +} + +void gdb_stdio_fclose(FILE *file) { + gdb_stdio_file = file; + + gdb_stdio_func = GDB_STDIO_FCLOSE; + while(gdb_stdio_func); +} + +int gdb_stdio_fwrite(void *ptr, int size, int nmem, FILE *file) { + gdb_stdio_ptr = ptr; + gdb_stdio_size = size; + gdb_stdio_nmem = nmem; + gdb_stdio_file = file; + + gdb_stdio_func = GDB_STDIO_FWRITE; + while(gdb_stdio_func); + return gdb_stdio_ret; +} + +int gdb_stdio_fread(void *ptr, int size, int nmem, FILE *file) { + gdb_stdio_ptr = ptr; + gdb_stdio_size = size; + gdb_stdio_nmem = nmem; + gdb_stdio_file = file; + + gdb_stdio_func = GDB_STDIO_FREAD; + while(gdb_stdio_func); + return gdb_stdio_ret; +} + diff --git a/pool/shard000/C/0014782_mk_cache.c b/pool/shard000/C/0014782_mk_cache.c new file mode 100644 index 0000000000000000000000000000000000000000..517cf464f6b5f41310e365f9cb4df096770e8570 --- /dev/null +++ b/pool/shard000/C/0014782_mk_cache.c @@ -0,0 +1,90 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ + +/* Monkey HTTP Server + * ================== + * Copyright 2001-2015 Monkey Software 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. + */ + +#define _GNU_SOURCE + +#include +#include +#include +#include +#include +#include + +#ifndef PTHREAD_TLS +#include +#endif + +pthread_key_t mk_utils_error_key; + + +/* This function is called when a thread is created */ +void mk_cache_worker_init() +{ + char *cache_error; + mk_ptr_t *p_tmp; + + /* Cache header request -> last modified */ + p_tmp = mk_mem_malloc_z(sizeof(mk_ptr_t)); + p_tmp->data = mk_mem_malloc_z(32); + p_tmp->len = -1; + MK_TLS_SET(mk_tls_cache_header_lm, p_tmp); + + /* Cache header request -> content length */ + p_tmp = mk_mem_malloc_z(sizeof(mk_ptr_t)); + p_tmp->data = mk_mem_malloc_z(MK_UTILS_INT2MKP_BUFFER_LEN); + p_tmp->len = -1; + MK_TLS_SET(mk_tls_cache_header_cl, p_tmp); + + /* Cache gmtime buffer */ + MK_TLS_SET(mk_tls_cache_gmtime, mk_mem_malloc(sizeof(struct tm))); + + /* Cache the most used text representations of utime2gmt */ + MK_TLS_SET(mk_tls_cache_gmtext, + mk_mem_malloc_z(sizeof(struct mk_gmt_cache) * MK_GMT_CACHES)); + + /* Cache buffer for strerror_r(2) */ + cache_error = mk_mem_malloc(MK_UTILS_ERROR_SIZE); + pthread_setspecific(mk_utils_error_key, (void *) cache_error); + + /* Virtual hosts: initialize per thread-vhost data */ + mk_vhost_fdt_worker_init(); +} + +void mk_cache_worker_exit() +{ + char *cache_error; + + /* Cache header request -> last modified */ + mk_ptr_free(MK_TLS_GET(mk_tls_cache_header_lm)); + mk_mem_free(MK_TLS_GET(mk_tls_cache_header_lm)); + + /* Cache header request -> content length */ + mk_ptr_free(MK_TLS_GET(mk_tls_cache_header_cl)); + mk_mem_free(MK_TLS_GET(mk_tls_cache_header_cl)); + + /* Cache gmtime buffer */ + mk_mem_free(MK_TLS_GET(mk_tls_cache_gmtime)); + + /* Cache the most used text representations of utime2gmt */ + mk_mem_free(MK_TLS_GET(mk_tls_cache_gmtext)); + + /* Cache buffer for strerror_r(2) */ + cache_error = pthread_getspecific(mk_utils_error_key); + mk_mem_free(cache_error); +} diff --git a/pool/shard000/C/0014797_pgtable.c b/pool/shard000/C/0014797_pgtable.c new file mode 100644 index 0000000000000000000000000000000000000000..7dfa579ab24c61761db8446c11fcb63e2ab6c5b8 --- /dev/null +++ b/pool/shard000/C/0014797_pgtable.c @@ -0,0 +1,36 @@ +#include +#include +#include + +void show_mem(void) +{ +#ifndef CONFIG_NEED_MULTIPLE_NODES /* XXX(hch): later.. */ + int pfn, total = 0, reserved = 0; + int shared = 0, cached = 0; + int highmem = 0; + struct page *page; + + printk("Mem-info:\n"); + show_free_areas(); + pfn = max_mapnr; + while (pfn-- > 0) { + if (!pfn_valid(pfn)) + continue; + page = pfn_to_page(pfn); + total++; + if (PageHighMem(page)) + highmem++; + if (PageReserved(page)) + reserved++; + else if (PageSwapCache(page)) + cached++; + else if (page_count(page)) + shared += page_count(page) - 1; + } + printk("%d pages of RAM\n", total); + printk("%d pages of HIGHMEM\n", highmem); + printk("%d reserved pages\n", reserved); + printk("%d pages shared\n", shared); + printk("%d pages swap cached\n", cached); +#endif +} diff --git a/pool/shard000/C/0014798_umf_build_tuples.c b/pool/shard000/C/0014798_umf_build_tuples.c new file mode 100644 index 0000000000000000000000000000000000000000..7b243ddac97f08de1d94fdf519894844b38cb3e8 --- /dev/null +++ b/pool/shard000/C/0014798_umf_build_tuples.c @@ -0,0 +1,159 @@ +/* ========================================================================== */ +/* === UMF_build_tuples ===================================================== */ +/* ========================================================================== */ + +/* -------------------------------------------------------------------------- */ +/* Copyright (c) 2005-2012 by Timothy A. Davis, http://www.suitesparse.com. */ +/* All Rights Reserved. See ../Doc/License for License. */ +/* -------------------------------------------------------------------------- */ + +/* + Construct the tuple lists from a set of packed elements (no holes in + elements, no internal or external fragmentation, and a packed (0..Work->nel) + element name space). Assume no tuple lists are currently allocated, but + that the tuple lengths have been initialized by UMF_tuple_lengths. + + Returns TRUE if successful, FALSE if not enough memory. +*/ + +#include "umf_internal.h" +#include "umf_build_tuples.h" +#include "umf_mem_alloc_tail_block.h" + +GLOBAL Int UMF_build_tuples +( + NumericType *Numeric, + WorkType *Work +) +{ + /* ---------------------------------------------------------------------- */ + /* local variables */ + /* ---------------------------------------------------------------------- */ + + Int e, nrows, ncols, nel, *Rows, *Cols, row, col, n_row, n_col, *E, + *Row_tuples, *Row_degree, *Row_tlen, + *Col_tuples, *Col_degree, *Col_tlen, n1 ; + Element *ep ; + Unit *p ; + Tuple tuple, *tp ; + + /* ---------------------------------------------------------------------- */ + /* get parameters */ + /* ---------------------------------------------------------------------- */ + + E = Work->E ; + Col_degree = Numeric->Cperm ; /* for NON_PIVOTAL_COL macro */ + Row_degree = Numeric->Rperm ; /* for NON_PIVOTAL_ROW macro */ + Row_tuples = Numeric->Uip ; + Row_tlen = Numeric->Uilen ; + Col_tuples = Numeric->Lip ; + Col_tlen = Numeric->Lilen ; + n_row = Work->n_row ; + n_col = Work->n_col ; + nel = Work->nel ; + n1 = Work->n1 ; + + DEBUG3 (("BUILD_TUPLES: n_row "ID" n_col "ID" nel "ID"\n", + n_row, n_col, nel)) ; + + /* ---------------------------------------------------------------------- */ + /* allocate space for the tuple lists */ + /* ---------------------------------------------------------------------- */ + + /* Garbage collection and memory reallocation have already attempted to */ + /* ensure that there is enough memory for all the tuple lists. If */ + /* memory allocation fails here, then there is nothing more to be done. */ + + for (row = n1 ; row < n_row ; row++) + { + if (NON_PIVOTAL_ROW (row)) + { + Row_tuples [row] = UMF_mem_alloc_tail_block (Numeric, + UNITS (Tuple, TUPLES (Row_tlen [row]))) ; + if (!Row_tuples [row]) + { + /* :: out of memory for row tuples :: */ + DEBUGm4 (("out of memory: build row tuples\n")) ; + return (FALSE) ; /* out of memory for row tuples */ + } + Row_tlen [row] = 0 ; + } + } + + /* push on stack in reverse order, so column tuples are in the order */ + /* that they will be deleted. */ + for (col = n_col-1 ; col >= n1 ; col--) + { + if (NON_PIVOTAL_COL (col)) + { + Col_tuples [col] = UMF_mem_alloc_tail_block (Numeric, + UNITS (Tuple, TUPLES (Col_tlen [col]))) ; + if (!Col_tuples [col]) + { + /* :: out of memory for col tuples :: */ + DEBUGm4 (("out of memory: build col tuples\n")) ; + return (FALSE) ; /* out of memory for col tuples */ + } + Col_tlen [col] = 0 ; + } + } + +#ifndef NDEBUG + UMF_dump_memory (Numeric) ; +#endif + + /* ---------------------------------------------------------------------- */ + /* create the tuple lists (exclude element 0) */ + /* ---------------------------------------------------------------------- */ + + /* for all elements, in order of creation */ + for (e = 1 ; e <= nel ; e++) + { + DEBUG9 (("Adding tuples for element: "ID" at "ID"\n", e, E [e])) ; + ASSERT (E [e]) ; /* no external fragmentation */ + p = Numeric->Memory + E [e] ; + GET_ELEMENT_PATTERN (ep, p, Cols, Rows, ncols) ; + nrows = ep->nrows ; + ASSERT (e != 0) ; + ASSERT (e == 0 || nrows == ep->nrowsleft) ; + ASSERT (e == 0 || ncols == ep->ncolsleft) ; + tuple.e = e ; + for (tuple.f = 0 ; tuple.f < ncols ; tuple.f++) + { + col = Cols [tuple.f] ; + ASSERT (col >= n1 && col < n_col) ; + ASSERT (NON_PIVOTAL_COL (col)) ; + ASSERT (Col_tuples [col]) ; + tp = ((Tuple *) (Numeric->Memory + Col_tuples [col])) + + Col_tlen [col]++ ; + *tp = tuple ; +#ifndef NDEBUG + UMF_dump_rowcol (1, Numeric, Work, col, FALSE) ; +#endif + } + for (tuple.f = 0 ; tuple.f < nrows ; tuple.f++) + { + row = Rows [tuple.f] ; + ASSERT (row >= n1 && row < n_row) ; + ASSERT (NON_PIVOTAL_COL (col)) ; + ASSERT (Row_tuples [row]) ; + tp = ((Tuple *) (Numeric->Memory + Row_tuples [row])) + + Row_tlen [row]++ ; + *tp = tuple ; +#ifndef NDEBUG + UMF_dump_rowcol (0, Numeric, Work, row, FALSE) ; +#endif + } + } + + /* ---------------------------------------------------------------------- */ + /* the tuple lists are now valid, and can be scanned */ + /* ---------------------------------------------------------------------- */ + +#ifndef NDEBUG + UMF_dump_memory (Numeric) ; + UMF_dump_matrix (Numeric, Work, FALSE) ; +#endif + DEBUG3 (("BUILD_TUPLES: done\n")) ; + return (TRUE) ; +} diff --git a/pool/shard000/C/0014814_mvt.c b/pool/shard000/C/0014814_mvt.c new file mode 100644 index 0000000000000000000000000000000000000000..5861bd17deba138498d2caa24e592d234f2a8974 --- /dev/null +++ b/pool/shard000/C/0014814_mvt.c @@ -0,0 +1,148 @@ +/** + * mvt.c: This file is part of the PolyBench/GPU 1.0 test suite. + * + * + * Contact: Scott Grauer-Gray + * Louis-Noel Pouchet + * Web address: http://www.cse.ohio-state.edu/~pouchet/software/polybench/GPU + */ + +#include +#include +#include +#include +#include + +#include "../../../common/polybenchUtilFuncts.h" + +//define the error threshold for the results "not matching" +#define PERCENT_DIFF_ERROR_THRESHOLD 0.05 + +/* Problem size */ +#define N 4096 + +/* Can switch DATA_TYPE between float and double */ +typedef float DATA_TYPE; + + + +#pragma hmpp mvt codelet, target=OpenCL, args[x1,x2].io=inout +void runMvt(DATA_TYPE a[N][N], DATA_TYPE x1[N], DATA_TYPE x2[N], DATA_TYPE y1[N], DATA_TYPE y2[N]){ + + int i, j; + + #pragma hmppcg grid blocksize 32 X 8 + + for (i=0; i PERCENT_DIFF_ERROR_THRESHOLD) + { + fail++; + } + + if (percentDiff(x2[i], x2_outputFromGpu[i]) > PERCENT_DIFF_ERROR_THRESHOLD) + { + fail++; + } + } + + // Print results + printf("Non-Matching CPU-GPU Outputs Beyond Error Threshold of %4.2f Percent: %d\n", PERCENT_DIFF_ERROR_THRESHOLD, fail); + +} + + + +int main() +{ + double t_start, t_end; + + DATA_TYPE a[N][N]; + DATA_TYPE x1[N]; + DATA_TYPE x1_outputFromGpu[N]; + DATA_TYPE x2[N]; + DATA_TYPE x2_outputFromGpu[N]; + DATA_TYPE y1[N]; + DATA_TYPE y2[N]; + + + //initialize the arrays for running on the CPU and GPU + init_array(a, x1, x1_outputFromGpu, x2, x2_outputFromGpu, y1, y2); + + #pragma hmpp mvt allocate + + #pragma hmpp mvt advancedload, args[a,x1,x2,y1,y2] + + t_start = rtclock(); + + //run the algorithm on the GPU + #pragma hmpp mvt callsite, args[x1,x2].advancedload=true, asynchronous + runMvt(a, x1_outputFromGpu, x2_outputFromGpu, y1, y2); // parameters are initialized in decls.h and are initialized with init_array() + + #pragma hmpp mvt synchronize + + t_end = rtclock(); + fprintf(stderr, "GPU Runtime: %0.6lf\n", t_end - t_start); + + #pragma hmpp mvt delegatedstore, args[x1,x2] + + #pragma hmpp mvt release + + t_start = rtclock(); + + //run the algorithm on the CPU + runMvt(a, x1, x2, y1, y2); + + t_end = rtclock(); + fprintf(stderr, "CPU Runtime: %0.6lf\n", t_end - t_start); + + compareResults(x1, x1_outputFromGpu, x2, x2_outputFromGpu); + + return 0; +} diff --git a/pool/shard000/C/0014818_rb_echo.c b/pool/shard000/C/0014818_rb_echo.c new file mode 100644 index 0000000000000000000000000000000000000000..b2379ff0c527d441de4db1278d368df41f1b42d7 --- /dev/null +++ b/pool/shard000/C/0014818_rb_echo.c @@ -0,0 +1,55 @@ +/* + * Copyright 2013, 2014 Chris Rhodin + * + * 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 "librb.h" + + +/* + * rb_echo - ring-buffer echo + * + * If available, return echo byte from the ring-buffer and update the control + * structure. + * + * returns: 1 - byte returned, more available + * 0 - byte returned, no more available + * -1 - byte not returned, none available + */ +int8_t rb_echo(struct ring_buffer * const rb, volatile uint8_t * const b) +{ + uint8_t * echo; + + if (rb_is_cantecho(rb)) return -1; + + /* byte will be available for get */ + rb_clr_cantget(rb); + + /* return byte, update pointer */ + echo = rb->echo; + *b = *echo; + rb_inc_ptr(rb, echo); + rb->echo = echo; + + if (echo == rb->put) { + /* echo byte not available on exit */ + rb_set_cantecho(rb); + return 0; + } + + /* echo byte available on exit */ + return 1; +} diff --git a/pool/shard000/C/0014819_NewObjectTest.c b/pool/shard000/C/0014819_NewObjectTest.c new file mode 100644 index 0000000000000000000000000000000000000000..8512f6556705d7ab34eb31a3dc097d395c2c0676 --- /dev/null +++ b/pool/shard000/C/0014819_NewObjectTest.c @@ -0,0 +1,39 @@ +/* + Copyright 2005-2006 The Apache Software Foundation or its licensors, as applicable + + 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 + +/* + * Method: org.apache.harmony.vts.test.vm.jni.object_operations.NewObjectTest.nativeExecute(Ljava/lang/Class;I)Z + */ +JNIEXPORT jboolean JNICALL +Java_org_apache_harmony_vts_test_vm_jni_object_1operations_NewObjectTest_nativeExecute + (JNIEnv *env, jobject this_object, jclass clazz, jint value) +{ + jmethodID mID; + jobject obj; + + mID = (*env)->GetMethodID(env, clazz, "", "(I)V"); + if (NULL == mID) + return JNI_FALSE; + + obj = (*env)->NewObject(env, clazz, mID, value); + if (NULL == obj) + return JNI_FALSE; + + return JNI_TRUE; +} diff --git a/pool/shard000/C/0014833_sdhci-of-core.c b/pool/shard000/C/0014833_sdhci-of-core.c new file mode 100644 index 0000000000000000000000000000000000000000..f9b611fc773e19d9133e79681280164c9e4d8538 --- /dev/null +++ b/pool/shard000/C/0014833_sdhci-of-core.c @@ -0,0 +1,250 @@ +/* + * OpenFirmware bindings for Secure Digital Host Controller Interface. + * + * Copyright (c) 2007 Freescale Semiconductor, Inc. + * Copyright (c) 2009 MontaVista Software, Inc. + * + * Authors: Xiaobo Xie + * Anton Vorontsov + * + * 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 +#ifdef CONFIG_PPC +#include +#endif +#include "sdhci-of.h" +#include "sdhci.h" + +#ifdef CONFIG_MMC_SDHCI_BIG_ENDIAN_32BIT_BYTE_SWAPPER + +/* + * These accessors are designed for big endian hosts doing I/O to + * little endian controllers incorporating a 32-bit hardware byte swapper. + */ + +u32 sdhci_be32bs_readl(struct sdhci_host *host, int reg) +{ + return in_be32(host->ioaddr + reg); +} + +u16 sdhci_be32bs_readw(struct sdhci_host *host, int reg) +{ + return in_be16(host->ioaddr + (reg ^ 0x2)); +} + +u8 sdhci_be32bs_readb(struct sdhci_host *host, int reg) +{ + return in_8(host->ioaddr + (reg ^ 0x3)); +} + +void sdhci_be32bs_writel(struct sdhci_host *host, u32 val, int reg) +{ + out_be32(host->ioaddr + reg, val); +} + +void sdhci_be32bs_writew(struct sdhci_host *host, u16 val, int reg) +{ + struct sdhci_of_host *of_host = sdhci_priv(host); + int base = reg & ~0x3; + int shift = (reg & 0x2) * 8; + + switch (reg) { + case SDHCI_TRANSFER_MODE: + /* + * Postpone this write, we must do it together with a + * command write that is down below. + */ + of_host->xfer_mode_shadow = val; + return; + case SDHCI_COMMAND: + sdhci_be32bs_writel(host, val << 16 | of_host->xfer_mode_shadow, + SDHCI_TRANSFER_MODE); + return; + } + clrsetbits_be32(host->ioaddr + base, 0xffff << shift, val << shift); +} + +void sdhci_be32bs_writeb(struct sdhci_host *host, u8 val, int reg) +{ + int base = reg & ~0x3; + int shift = (reg & 0x3) * 8; + + clrsetbits_be32(host->ioaddr + base , 0xff << shift, val << shift); +} +#endif /* CONFIG_MMC_SDHCI_BIG_ENDIAN_32BIT_BYTE_SWAPPER */ + +#ifdef CONFIG_PM + +static int sdhci_of_suspend(struct platform_device *ofdev, pm_message_t state) +{ + struct sdhci_host *host = dev_get_drvdata(&ofdev->dev); + + return mmc_suspend_host(host->mmc); +} + +static int sdhci_of_resume(struct platform_device *ofdev) +{ + struct sdhci_host *host = dev_get_drvdata(&ofdev->dev); + + return mmc_resume_host(host->mmc); +} + +#else + +#define sdhci_of_suspend NULL +#define sdhci_of_resume NULL + +#endif + +static bool __devinit sdhci_of_wp_inverted(struct device_node *np) +{ + if (of_get_property(np, "sdhci,wp-inverted", NULL)) + return true; + + /* Old device trees don't have the wp-inverted property. */ +#ifdef CONFIG_PPC + return machine_is(mpc837x_rdb) || machine_is(mpc837x_mds); +#else + return false; +#endif +} + +static int __devinit sdhci_of_probe(struct platform_device *ofdev) +{ + struct device_node *np = ofdev->dev.of_node; + struct sdhci_of_data *sdhci_of_data; + struct sdhci_host *host; + struct sdhci_of_host *of_host; + const __be32 *clk; + int size; + int ret; + + if (!ofdev->dev.of_match) + return -EINVAL; + sdhci_of_data = ofdev->dev.of_match->data; + + if (!of_device_is_available(np)) + return -ENODEV; + + host = sdhci_alloc_host(&ofdev->dev, sizeof(*of_host)); + if (IS_ERR(host)) + return -ENOMEM; + + of_host = sdhci_priv(host); + dev_set_drvdata(&ofdev->dev, host); + + host->ioaddr = of_iomap(np, 0); + if (!host->ioaddr) { + ret = -ENOMEM; + goto err_addr_map; + } + + host->irq = irq_of_parse_and_map(np, 0); + if (!host->irq) { + ret = -EINVAL; + goto err_no_irq; + } + + host->hw_name = dev_name(&ofdev->dev); + if (sdhci_of_data) { + host->quirks = sdhci_of_data->quirks; + host->ops = &sdhci_of_data->ops; + } + + if (of_get_property(np, "sdhci,auto-cmd12", NULL)) + host->quirks |= SDHCI_QUIRK_MULTIBLOCK_READ_ACMD12; + + + if (of_get_property(np, "sdhci,1-bit-only", NULL)) + host->quirks |= SDHCI_QUIRK_FORCE_1_BIT_DATA; + + if (sdhci_of_wp_inverted(np)) + host->quirks |= SDHCI_QUIRK_INVERTED_WRITE_PROTECT; + + clk = of_get_property(np, "clock-frequency", &size); + if (clk && size == sizeof(*clk) && *clk) + of_host->clock = be32_to_cpup(clk); + + ret = sdhci_add_host(host); + if (ret) + goto err_add_host; + + return 0; + +err_add_host: + irq_dispose_mapping(host->irq); +err_no_irq: + iounmap(host->ioaddr); +err_addr_map: + sdhci_free_host(host); + return ret; +} + +static int __devexit sdhci_of_remove(struct platform_device *ofdev) +{ + struct sdhci_host *host = dev_get_drvdata(&ofdev->dev); + + sdhci_remove_host(host, 0); + sdhci_free_host(host); + irq_dispose_mapping(host->irq); + iounmap(host->ioaddr); + return 0; +} + +static const struct of_device_id sdhci_of_match[] = { +#ifdef CONFIG_MMC_SDHCI_OF_ESDHC + { .compatible = "fsl,mpc8379-esdhc", .data = &sdhci_esdhc, }, + { .compatible = "fsl,mpc8536-esdhc", .data = &sdhci_esdhc, }, + { .compatible = "fsl,esdhc", .data = &sdhci_esdhc, }, +#endif +#ifdef CONFIG_MMC_SDHCI_OF_HLWD + { .compatible = "nintendo,hollywood-sdhci", .data = &sdhci_hlwd, }, +#endif + { .compatible = "generic-sdhci", }, + {}, +}; +MODULE_DEVICE_TABLE(of, sdhci_of_match); + +static struct platform_driver sdhci_of_driver = { + .driver = { + .name = "sdhci-of", + .owner = THIS_MODULE, + .of_match_table = sdhci_of_match, + }, + .probe = sdhci_of_probe, + .remove = __devexit_p(sdhci_of_remove), + .suspend = sdhci_of_suspend, + .resume = sdhci_of_resume, +}; + +static int __init sdhci_of_init(void) +{ + return platform_driver_register(&sdhci_of_driver); +} +module_init(sdhci_of_init); + +static void __exit sdhci_of_exit(void) +{ + platform_driver_unregister(&sdhci_of_driver); +} +module_exit(sdhci_of_exit); + +MODULE_DESCRIPTION("Secure Digital Host Controller Interface OF driver"); +MODULE_AUTHOR("Xiaobo Xie , " + "Anton Vorontsov "); +MODULE_LICENSE("GPL"); diff --git a/pool/shard000/C/0014836_proxy_dhcp6ds.c b/pool/shard000/C/0014836_proxy_dhcp6ds.c new file mode 100644 index 0000000000000000000000000000000000000000..995269b00e2ffc0ecefe4797e5da1434fe22cffa --- /dev/null +++ b/pool/shard000/C/0014836_proxy_dhcp6ds.c @@ -0,0 +1,316 @@ +/* $Id: proxy_dhcp6ds.c 56300 2015-06-09 14:36:22Z vboxsync $ */ +/** @file + * NAT Network - Simple stateless DHCPv6 (RFC 3736) server. + */ + +/* + * Copyright (C) 2013-2015 Oracle Corporation + * + * This file is part of VirtualBox Open Source Edition (OSE), as + * available from http://www.virtualbox.org. This file is free software; + * you can redistribute it and/or modify it under the terms of the GNU + * General Public License (GPL) as published by the Free Software + * Foundation, in version 2 as it comes in the "COPYING" file of the + * VirtualBox OSE distribution. VirtualBox OSE is distributed in the + * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. + */ + +#define LOG_GROUP LOG_GROUP_NAT_SERVICE + +#include "winutils.h" +#include "dhcp6.h" +#include "proxy.h" + +#include + +#include "lwip/opt.h" +#include "lwip/mld6.h" +#include "lwip/udp.h" + + +static void dhcp6ds_recv(void *, struct udp_pcb *, struct pbuf *, ip6_addr_t *, u16_t); + + +/* ff02::1:2 - "All_DHCP_Relay_Agents_and_Servers" link-scoped multicast */ +static /* const */ ip6_addr_t all_dhcp_relays_and_servers = { + { PP_HTONL(0xff020000UL), 0, 0, PP_HTONL(0x00010002UL) } +}; + +/* ff05::1:3 - "All_DHCP_Servers" site-scoped multicast */ +static /* const */ ip6_addr_t all_dhcp_servers = { + { PP_HTONL(0xff050000UL), 0, 0, PP_HTONL(0x00010003UL) } +}; + + +static struct udp_pcb *dhcp6ds_pcb; + +/* prebuilt Server ID option */ +#define DUID_LL_LEN (/* duid type */ 2 + /* hw type */ 2 + /* ether addr */ 6) +static u8_t dhcp6ds_serverid[/* opt */ 2 + /* optlen */ 2 + DUID_LL_LEN]; + +/* prebuilt DNS Servers option */ +static u8_t dhcp6ds_dns[/* opt */ 2 + /* optlen */ 2 + /* IPv6 addr */ 16]; + + +/** + * Initialize DHCP6 server. + * + * Join DHCP6 multicast groups. + * Create and bind server pcb. + * Prebuild fixed parts of reply. + */ +err_t +dhcp6ds_init(struct netif *proxy_netif) +{ + ip6_addr_t *pxaddr, *pxaddr_nonlocal; + int i; + err_t error; + + LWIP_ASSERT1(proxy_netif != NULL); + LWIP_ASSERT1(proxy_netif->hwaddr_len == 6); /* ethernet */ + + pxaddr = netif_ip6_addr(proxy_netif, 0); /* link local */ + + /* + * XXX: TODO: This is a leftover from testing with IPv6 mapped + * loopback with a special IPv6->IPv4 mapping hack in pxudp.c + */ + /* advertise ourself as DNS resolver - will be proxied to host */ + pxaddr_nonlocal = NULL; + for (i = 1; i < LWIP_IPV6_NUM_ADDRESSES; ++i) { + if (ip6_addr_ispreferred(netif_ip6_addr_state(proxy_netif, i)) + && !ip6_addr_islinklocal(netif_ip6_addr(proxy_netif, i))) + { + pxaddr_nonlocal = netif_ip6_addr(proxy_netif, i); + break; + } + } + LWIP_ASSERT1(pxaddr_nonlocal != NULL); /* must be configured on the netif */ + + + error = mld6_joingroup(pxaddr, &all_dhcp_relays_and_servers); + if (error != ERR_OK) { + DPRINTF0(("%s: failed to join All_DHCP_Relay_Agents_and_Servers: %s\n", + __func__, proxy_lwip_strerr(error))); + goto err; + } + + error = mld6_joingroup(pxaddr, &all_dhcp_servers); + if (error != ERR_OK) { + DPRINTF0(("%s: failed to join All_DHCP_Servers: %s\n", + __func__, proxy_lwip_strerr(error))); + goto err1; + } + + + dhcp6ds_pcb = udp_new_ip6(); + if (dhcp6ds_pcb == NULL) { + DPRINTF0(("%s: failed to allocate PCB\n", __func__)); + error = ERR_MEM; + goto err2; + } + + udp_recv_ip6(dhcp6ds_pcb, dhcp6ds_recv, NULL); + + error = udp_bind_ip6(dhcp6ds_pcb, pxaddr, DHCP6_SERVER_PORT); + if (error != ERR_OK) { + DPRINTF0(("%s: failed to bind PCB\n", __func__)); + goto err3; + } + + +#define OPT_SET(buf, off, c) do { \ + u16_t _s = PP_HTONS(c); \ + memcpy(&(buf)[off], &_s, sizeof(u16_t)); \ + } while (0) + +#define SERVERID_SET(off, c) OPT_SET(dhcp6ds_serverid, (off), (c)) +#define DNSSRV_SET(off, c) OPT_SET(dhcp6ds_dns, (off), (c)) + + SERVERID_SET(0, DHCP6_OPTION_SERVERID); + SERVERID_SET(2, DUID_LL_LEN); + SERVERID_SET(4, DHCP6_DUID_LL); + SERVERID_SET(6, ARES_HRD_ETHERNET); + memcpy(&dhcp6ds_serverid[8], proxy_netif->hwaddr, 6); + + DNSSRV_SET(0, DHCP6_OPTION_DNS_SERVERS); + DNSSRV_SET(2, 16); /* one IPv6 address */ + /* + * XXX: TODO: This is a leftover from testing with IPv6 mapped + * loopback with a special IPv6->IPv4 mapping hack in pxudp.c + */ + memcpy(&dhcp6ds_dns[4], pxaddr_nonlocal, sizeof(ip6_addr_t)); + +#undef SERVERID_SET +#undef DNSSRV_SET + + return ERR_OK; + + + err3: + udp_remove(dhcp6ds_pcb); + dhcp6ds_pcb = NULL; + err2: + mld6_leavegroup(pxaddr, &all_dhcp_servers); + err1: + mld6_leavegroup(pxaddr, &all_dhcp_relays_and_servers); + err: + return error; +} + + +static u8_t dhcp6ds_reply_buf[1024]; + +static void +dhcp6ds_recv(void *arg, struct udp_pcb *pcb, struct pbuf *p, + ip6_addr_t *addr, u16_t port) +{ + u8_t msg_header[4]; + unsigned int msg_type, msg_tid; + int copied; + size_t roff; + struct pbuf *q; + err_t error; + + LWIP_UNUSED_ARG(arg); + LWIP_ASSERT1(p != NULL); + + copied = pbuf_copy_partial(p, msg_header, sizeof(msg_header), 0); + if (copied != sizeof(msg_header)) { + DPRINTF(("%s: message header truncated\n", __func__)); + pbuf_free(p); + return; + } + pbuf_header(p, -(s16_t)sizeof(msg_header)); + + msg_type = msg_header[0]; + msg_tid = (msg_header[1] << 16) | (msg_header[2] << 8) | msg_header[3]; + DPRINTF(("%s: type %u, tid 0x%6x\n", __func__, msg_type, msg_tid)); + if (msg_type != DHCP6_INFORMATION_REQUEST) { /* TODO:? RELAY_FORW */ + pbuf_free(p); + return; + } + + roff = 0; + + msg_header[0] = DHCP6_REPLY; + memcpy(dhcp6ds_reply_buf + roff, msg_header, sizeof(msg_header)); + roff += sizeof(msg_header); + + + /* loop over options */ + while (p->tot_len > 0) { + u16_t opt, optlen; + + /* fetch option code */ + copied = pbuf_copy_partial(p, &opt, sizeof(opt), 0); + if (copied != sizeof(opt)) { + DPRINTF(("%s: option header truncated\n", __func__)); + pbuf_free(p); + return; + } + pbuf_header(p, -(s16_t)sizeof(opt)); + opt = ntohs(opt); + + /* fetch option length */ + copied = pbuf_copy_partial(p, &optlen, sizeof(optlen), 0); + if (copied != sizeof(optlen)) { + DPRINTF(("%s: option %u length truncated\n", __func__, opt)); + pbuf_free(p); + return; + } + pbuf_header(p, -(s16_t)sizeof(optlen)); + optlen = ntohs(optlen); + + /* enough data? */ + if (optlen > p->tot_len) { + DPRINTF(("%s: option %u truncated: expect %u, got %u\n", + __func__, opt, optlen, p->tot_len)); + pbuf_free(p); + return; + } + + DPRINTF2(("%s: option %u length %u\n", __func__, opt, optlen)); + + if (opt == DHCP6_OPTION_CLIENTID) { + u16_t s; + + /* "A DUID can be no more than 128 octets long (not + including the type code)." */ + if (optlen > 130) { + DPRINTF(("%s: client DUID too long: %u\n", __func__, optlen)); + pbuf_free(p); + return; + } + + s = PP_HTONS(DHCP6_OPTION_CLIENTID); + memcpy(dhcp6ds_reply_buf + roff, &s, sizeof(s)); + roff += sizeof(s); + + s = ntohs(optlen); + memcpy(dhcp6ds_reply_buf + roff, &s, sizeof(s)); + roff += sizeof(s); + + pbuf_copy_partial(p, dhcp6ds_reply_buf + roff, optlen, 0); + roff += optlen; + } + else if (opt == DHCP6_OPTION_ORO) { + u16_t *opts; + int i, nopts; + + if (optlen % 2 != 0) { + DPRINTF2(("%s: Option Request of odd length\n", __func__)); + goto bad_oro; + } + nopts = optlen / 2; + + opts = (u16_t *)malloc(optlen); + if (opts == NULL) { + DPRINTF2(("%s: failed to allocate space for Option Request\n", + __func__)); + goto bad_oro; + } + + pbuf_copy_partial(p, opts, optlen, 0); + for (i = 0; i < nopts; ++i) { + opt = ntohs(opts[i]); + DPRINTF2(("> request option %u\n", opt)); + }; + free(opts); + + bad_oro: /* empty */; + } + + pbuf_header(p, -optlen); /* go to next option */ + } + pbuf_free(p); /* done */ + + + memcpy(dhcp6ds_reply_buf + roff, dhcp6ds_serverid, sizeof(dhcp6ds_serverid)); + roff += sizeof(dhcp6ds_serverid); + + memcpy(dhcp6ds_reply_buf + roff, dhcp6ds_dns, sizeof(dhcp6ds_dns)); + roff += sizeof(dhcp6ds_dns); + + q = pbuf_alloc(PBUF_RAW, roff, PBUF_RAM); + if (q == NULL) { + DPRINTF(("%s: pbuf_alloc(%d) failed\n", __func__, (int)roff)); + return; + } + + error = pbuf_take(q, dhcp6ds_reply_buf, roff); + if (error != ERR_OK) { + DPRINTF(("%s: pbuf_take(%d) failed: %s\n", + __func__, (int)roff, proxy_lwip_strerr(error))); + pbuf_free(q); + return; + } + + error = udp_sendto_ip6(pcb, q, addr, port); + if (error != ERR_OK) { + DPRINTF(("%s: udp_sendto failed: %s\n", + __func__, proxy_lwip_strerr(error))); + } + + pbuf_free(q); +} diff --git a/pool/shard000/C/0014854_path_join.c b/pool/shard000/C/0014854_path_join.c new file mode 100644 index 0000000000000000000000000000000000000000..b4823324abc66cf75e010b2f08cd2542f1bda617 --- /dev/null +++ b/pool/shard000/C/0014854_path_join.c @@ -0,0 +1,191 @@ +/** +* \file path_join.c +* \brief Join two or more pieces of a file system path. +* \author Copyright (c) 2002-2013 Jason Perkins and the Premake project +*/ + +#include "premake.h" +#include +#include "path_isabsolute.h" + +#define DEFERRED_JOIN_DELIMITER '|' + +char* path_join_single(char* buffer, char* ptr, const char* part, int allowDeferredJoin) +{ + int absoluteType; + size_t len = strlen(part); + /* remove leading "./" */ + while (strncmp(part, "./", 2) == 0) { + part += 2; + len -= 2; + } + + /* remove trailing slashes */ + while (len > 1 && part[len - 1] == '/') { + --len; + } + + /* ignore empty segments and "." */ + if (len == 0 || (len == 1 && part[0] == '.')) { + return ptr; + } + + absoluteType = do_absolutetype(part); + if (!allowDeferredJoin && absoluteType == JOIN_MAYBE_ABSOLUTE) + absoluteType = JOIN_RELATIVE; + + /* if I encounter an absolute path, restart my result */ + switch (absoluteType) { + case JOIN_ABSOLUTE: + ptr = buffer; + break; + case JOIN_RELATIVE: + /* if source has a .. prefix then take off last dest path part + note that this doesn't guarantee a normalized result as this + code doesn't check for .. in the mid path, however .. occurring + mid path are much more likely to occur during path joins + and its faster if we handle here as we don't have to remove + substrings from the middle of the string. */ + + while (ptr != buffer && len >= 2 && part[0] == '.' && part[1] == '.') + { + /* locate start of previous segment */ + char* start = strrchr(buffer, '/'); + if (!start) { + start = buffer; + } + else { + ++start; + } + + /* if I hit a segment I can't trim, bail out */ + if (strcmp(start, "..") == 0 /* parent dir */ + || strcmp(start, ".") == 0 /* current dir */ + || strstr(start, "**") != NULL /* recursive wildcard */ + || strchr(start, '$') != NULL) /* property expansion */ + { + break; + } + + /* otherwise trim segment and the ".." sequence */ + if (start != buffer) { + --start; + } + *start = '\0'; + ptr = start; + part += 2; + len -= 2; + if (len > 0 && part[0] == '/') { + ++part; + --len; + } + } + + /* if the path is already started, split parts */ + if (ptr != buffer && *(ptr - 1) != '/') { + *(ptr++) = '/'; + } + + break; + case JOIN_MAYBE_ABSOLUTE: + *ptr = DEFERRED_JOIN_DELIMITER; + ptr++; + break; + } + + /* append new part */ + strncpy(ptr, part, len); + ptr += len; + *ptr = '\0'; + return ptr; +} + +int path_join_internal(lua_State* L, int allowDeferredJoin) +{ + int i; + const char* part; + char buffer[0x4000]; + char* ptr = buffer; + + /* for each argument... */ + int argc = lua_gettop(L); + for (i = 1; i <= argc; ++i) { + /* if next argument is nil, skip it */ + if (lua_isnil(L, i)) { + continue; + } + + /* grab the next argument */ + part = luaL_checkstring(L, i); + ptr = path_join_single(buffer, ptr, part, allowDeferredJoin); + } + + lua_pushstring(L, buffer); + return 1; +} + + +int path_join(lua_State* L) +{ + return path_join_internal(L, 0); +} + + +int path_deferred_join(lua_State* L) +{ + return path_join_internal(L, 1); +} + + +int do_path_has_deferred_join(const char* path) +{ + return (strchr(path, DEFERRED_JOIN_DELIMITER) != NULL); +} + + +int path_has_deferred_join(lua_State* L) +{ + const char* path = luaL_checkstring(L, -1); + lua_pushboolean(L, do_path_has_deferred_join(path)); + return 1; +} + + +int path_resolve_deferred_join(lua_State* L) +{ + const char* path = luaL_checkstring(L, -1); + char inBuffer[0x4000]; + char outBuffer[0x4000]; + char* ptr = outBuffer; + char* nextPart; + size_t len = strlen(path); + int i; + int numParts = 0; + strncpy(inBuffer, path, len); + inBuffer[len] = '\0'; + char *parts[0x200]; + // break up the string into parts and index the start of each part + nextPart = strchr(inBuffer, DEFERRED_JOIN_DELIMITER); + if (nextPart == NULL) // nothing to do + { + lua_pushlstring(L, inBuffer, len); + return 1; + } + parts[numParts++] = inBuffer; + while (nextPart != NULL) + { + *nextPart = '\0'; + nextPart++; + parts[numParts++] = nextPart; + nextPart = strchr(nextPart, DEFERRED_JOIN_DELIMITER); + } + + /* for each part... */ + for (i = 0; i < numParts; ++i) { + nextPart = parts[i]; + ptr = path_join_single(outBuffer, ptr, nextPart, 0); + } + + lua_pushstring(L, outBuffer); + return 1; +} diff --git a/pool/shard000/C/0014865_ttsafe.c b/pool/shard000/C/0014865_ttsafe.c new file mode 100644 index 0000000000000000000000000000000000000000..d0ab81a3494e8b08fd942c8d326dab484ddc5ea5 --- /dev/null +++ b/pool/shard000/C/0014865_ttsafe.c @@ -0,0 +1,122 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + * Copyright by The HDF Group. * + * Copyright by the Board of Trustees of the University of Illinois. * + * All rights reserved. * + * * + * This file is part of HDF5. The full HDF5 copyright notice, including * + * terms governing use, modification, and redistribution, is contained in * + * the files COPYING and Copyright.html. COPYING can be found at the root * + * of the source code distribution tree; Copyright.html can be found at the * + * root level of an installed copy of the electronic HDF5 document set and * + * is linked from the top-level documents page. It can also be found at * + * http://hdfgroup.org/HDF5/doc/Copyright.html. If you do not have * + * access to either file, you may request a copy from help@hdfgroup.org. * + * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +/* + * FILE + * ttsafe.c - HDF5 threadsafe testing framework main file. + * + * REMARKS + * General test wrapper for HDF5 library thread safety test programs + * + * DESIGN + * Each test function should be implemented as function having no + * parameters and returning void (i.e. no return value). They should be put + * into the list of InitTest() calls in main() below. Functions which depend + * on other functionality should be placed below the InitTest() call for the + * base functionality testing. + * Each test module should include ttsafe.h and define a unique set of + * names for test files they create. + * + * BUGS/LIMITATIONS + * + * EXPORTED ROUTINES/VARIABLES: + * + */ + +#include "h5test.h" + +/* ANY new test needs to have a prototype in ttsafe.h */ +#include "ttsafe.h" + +#ifndef H5_HAVE_THREADSAFE +int main(void) +{ + printf("Test skipped because THREADSAFE not enabled\n"); + return 0; +} +#else + +#define MAX_NUM_NAME 1000 +#define NAME_OFFSET 6 /* offset for "name" */ + +/* pre-condition: num must be a non-negative number */ +static unsigned +num_digits(int num) +{ + unsigned u; + + if(num == 0) + return 1; + + for(u = 0; num > 0; u++) + num = num / 10; + + return u; +} + +/* Routine to generate attribute names for numeric values */ +char *gen_name(int value) +{ + char *temp; + unsigned length; + int i; + + length = num_digits(MAX_NUM_NAME - 1); + temp = (char *)HDmalloc(NAME_OFFSET + length + 1); + temp = HDstrcpy(temp, "attrib"); + temp[NAME_OFFSET + length] = '\0'; + + for (i = (int)(length - 1); i >= 0; i--) { + temp[NAME_OFFSET + i] = (char)((int)'0' + value % 10); + value = value / 10; + } + + return temp; +} + +int main(int argc, char *argv[]) +{ + /* Initialize testing framework */ + TestInit(argv[0], NULL, NULL); + + /* Tests are generally arranged from least to most complexity... */ + AddTest("dcreate", tts_dcreate, cleanup_dcreate, "multi-dataset creation", NULL); + AddTest("error", tts_error, cleanup_error, "per-thread error stacks", NULL); +#ifdef H5_HAVE_PTHREAD_H + /* Thread cancellability only supported with pthreads ... */ + AddTest("cancel", tts_cancel, cleanup_cancel, "thread cancellation safety test", NULL); +#endif /* H5_HAVE_PTHREAD_H */ + AddTest("acreate", tts_acreate, cleanup_acreate, "multi-attribute creation", NULL); + + /* Display testing information */ + TestInfo(argv[0]); + + /* Parse command line arguments */ + TestParseCmdLine(argc,argv); + + /* Perform requested testing */ + PerformTests(); + + /* Display test summary, if requested */ + if (GetTestSummary()) + TestSummary(); + + /* Clean up test files, if allowed */ + if (GetTestCleanup() && !getenv("HDF5_NOCLEANUP")) + TestCleanup(); + + return GetTestNumErrs(); +} /* end main() */ +#endif /*H5_HAVE_THREADSAFE*/ diff --git a/pool/shard000/C/0014885_modf.c b/pool/shard000/C/0014885_modf.c new file mode 100644 index 0000000000000000000000000000000000000000..ec53b2e72fee185ac64a6bcfed36e405341cd83b --- /dev/null +++ b/pool/shard000/C/0014885_modf.c @@ -0,0 +1,99 @@ +/* mpfr_modf -- Integral and fractional part. + +Copyright 2007-2021 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 +https://www.gnu.org/licenses/ or write to the Free Software Foundation, Inc., +51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. */ + +#include "mpfr-impl.h" + +/* Set iop to the integral part of op and fop to its fractional part */ +int +mpfr_modf (mpfr_ptr iop, mpfr_ptr fop, mpfr_srcptr op, mpfr_rnd_t rnd_mode) +{ + mpfr_exp_t ope; + mpfr_prec_t opq; + int inexi, inexf; + + MPFR_LOG_FUNC + (("op[%Pu]=%.*Rg rnd=%d", + mpfr_get_prec (op), mpfr_log_prec, op, rnd_mode), + ("iop[%Pu]=%.*Rg fop[%Pu]=%.*Rg", + mpfr_get_prec (iop), mpfr_log_prec, iop, + mpfr_get_prec (fop), mpfr_log_prec, fop)); + + MPFR_ASSERTN (iop != fop); + + if ( MPFR_UNLIKELY (MPFR_IS_SINGULAR (op)) ) + { + if (MPFR_IS_NAN (op)) + { + MPFR_SET_NAN (iop); + MPFR_SET_NAN (fop); + MPFR_RET_NAN; + } + MPFR_SET_SAME_SIGN (iop, op); + MPFR_SET_SAME_SIGN (fop, op); + if (MPFR_IS_INF (op)) + { + MPFR_SET_INF (iop); + MPFR_SET_ZERO (fop); + MPFR_RET (0); + } + else /* op is zero */ + { + MPFR_ASSERTD (MPFR_IS_ZERO (op)); + MPFR_SET_ZERO (iop); + MPFR_SET_ZERO (fop); + MPFR_RET (0); + } + } + + ope = MPFR_GET_EXP (op); + opq = MPFR_PREC (op); + + if (ope <= 0) /* 0 < |op| < 1 */ + { + inexf = (fop != op) ? mpfr_set (fop, op, rnd_mode) : 0; + MPFR_SET_SAME_SIGN (iop, op); + MPFR_SET_ZERO (iop); + MPFR_RET (INEX(0, inexf)); + } + else if (ope >= opq) /* op has no fractional part */ + { + inexi = (iop != op) ? mpfr_set (iop, op, rnd_mode) : 0; + MPFR_SET_SAME_SIGN (fop, op); + MPFR_SET_ZERO (fop); + MPFR_RET (INEX(inexi, 0)); + } + else /* op has both integral and fractional parts */ + { + if (iop != op) + { + inexi = mpfr_rint_trunc (iop, op, rnd_mode); + inexf = mpfr_frac (fop, op, rnd_mode); + } + else + { + MPFR_ASSERTN (fop != op); + inexf = mpfr_frac (fop, op, rnd_mode); + inexi = mpfr_rint_trunc (iop, op, rnd_mode); + } + MPFR_RET (INEX(inexi, inexf)); + } +} diff --git a/pool/shard000/C/0014891_EnormousInputHandler.c b/pool/shard000/C/0014891_EnormousInputHandler.c new file mode 100644 index 0000000000000000000000000000000000000000..f1add9033c9a8d4e00dc3d54c58755cfffbea686 --- /dev/null +++ b/pool/shard000/C/0014891_EnormousInputHandler.c @@ -0,0 +1,20 @@ +#include + +int main (){ + +int lines_n, divider, current, i, counter=0; + + scanf("%d%d", &lines_n, ÷r); + for(i = 0; i < lines_n; ++i) + { + scanf("%d", ¤t); + if (!(current%divider)) + ++counter; + } + printf("%d\n", counter); + return 0; +} + + + + diff --git a/pool/shard000/C/0014894_transpose_test.c b/pool/shard000/C/0014894_transpose_test.c new file mode 100644 index 0000000000000000000000000000000000000000..f9ee38c0093e4c8ac0864b5f9a29bc424638e54b --- /dev/null +++ b/pool/shard000/C/0014894_transpose_test.c @@ -0,0 +1,54 @@ +#include "lace.h" +#include "lace_tool.h" +#include +#include +#include +#include + +int +lace_builtin_transpose_main(unsigned argc, char** argv, + LaceX** inputs, LaceO** outputs); + +int +main_transpose(unsigned argc, char** argv); + +LACE_TOOL_PIPEM_NULLARY_CALLBACK(run_transpose, in_fd, out_fd) { + const char* argv[] = {"transpose", ",", NULL}; + LaceX* in = open_fd_LaceX(in_fd); + LaceO* out = open_fd_LaceO(out_fd); + int istat = lace_builtin_transpose_main(2, (char**)argv, &in, &out); + assert(istat == 0); +} + +int main() { + const char input_data[] = + "This, is, the, first, line.\n" + "This, is, the, next, line.\n" + "This, is, the, third, line.\n" + "This, is, completely, out, of, line.\n" + "Whose, line, is, it?\n" + ", , \n" + "Transpose, is, offline.\n"; + const size_t input_size = sizeof(input_data)-1; + const char expect_data[] = + " This, This, This, This, Whose, , Transpose\n" + " is, is, is, is, line, , is\n" + " the, the, the, completely, is, , offline.\n" + "first, next, third, out, it?, ,\n" + "line., line., line., of, , ,\n" + " , , , line., , ,\n"; + const size_t expect_size = sizeof(expect_data)-1; + size_t output_size; + char* output_data = NULL; + + output_size = lace_tool_pipem( + input_size, input_data, + run_transpose, NULL, + &output_data); + fputs("Got:\n", stderr); + fputs(output_data, stderr); + assert(output_size == expect_size); + assert(0 == memcmp(output_data, expect_data, expect_size)); + free(output_data); + return 0; +} diff --git a/pool/shard000/C/0014897_cmp.c b/pool/shard000/C/0014897_cmp.c new file mode 100644 index 0000000000000000000000000000000000000000..61506b6c18962d03e2d883e74d250f3c61904155 --- /dev/null +++ b/pool/shard000/C/0014897_cmp.c @@ -0,0 +1,58 @@ +/* libguestfs - the guestfsd daemon + * Copyright (C) 2009 Red Hat Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 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 + +#include +#include +#include +#include +#include + +#include "daemon.h" +#include "actions.h" + +GUESTFSD_EXT_CMD(str_cmp, cmp); + +int +do_equal (const char *file1, const char *file2) +{ + CLEANUP_FREE char *file1buf = NULL, *file2buf = NULL; + CLEANUP_FREE char *err = NULL; + int r; + + file1buf = sysroot_path (file1); + if (file1buf == NULL) { + reply_with_perror ("malloc"); + return -1; + } + + file2buf = sysroot_path (file2); + if (file2buf == NULL) { + reply_with_perror ("malloc"); + return -1; + } + + r = commandr (NULL, &err, str_cmp, "-s", file1buf, file2buf, NULL); + if (r == -1 || r > 1) { + reply_with_error ("%s", err); + return -1; + } + + return r == 0; +} diff --git a/pool/shard000/C/0014907_malloc_heap.c b/pool/shard000/C/0014907_malloc_heap.c new file mode 100644 index 0000000000000000000000000000000000000000..7aafc880ae8f6523bca3dca62836368d6a89d9fc --- /dev/null +++ b/pool/shard000/C/0014907_malloc_heap.c @@ -0,0 +1,203 @@ +/* SPDX-License-Identifier: BSD-3-Clause + * Copyright(c) 2010-2014 Intel Corporation + */ +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "malloc_elem.h" +#include "malloc_heap.h" + +static unsigned +check_hugepage_sz(unsigned flags, uint64_t hugepage_sz) +{ + unsigned check_flag = 0; + + if (!(flags & ~RTE_MEMZONE_SIZE_HINT_ONLY)) + return 1; + + switch (hugepage_sz) { + case RTE_PGSIZE_256K: + check_flag = RTE_MEMZONE_256KB; + break; + case RTE_PGSIZE_2M: + check_flag = RTE_MEMZONE_2MB; + break; + case RTE_PGSIZE_16M: + check_flag = RTE_MEMZONE_16MB; + break; + case RTE_PGSIZE_256M: + check_flag = RTE_MEMZONE_256MB; + break; + case RTE_PGSIZE_512M: + check_flag = RTE_MEMZONE_512MB; + break; + case RTE_PGSIZE_1G: + check_flag = RTE_MEMZONE_1GB; + break; + case RTE_PGSIZE_4G: + check_flag = RTE_MEMZONE_4GB; + break; + case RTE_PGSIZE_16G: + check_flag = RTE_MEMZONE_16GB; + } + + return check_flag & flags; +} + +/* + * Expand the heap with a memseg. + * This reserves the zone and sets a dummy malloc_elem header at the end + * to prevent overflow. The rest of the zone is added to free list as a single + * large free block + */ +static void +malloc_heap_add_memseg(struct malloc_heap *heap, struct rte_memseg *ms) +{ + /* allocate the memory block headers, one at end, one at start */ + struct malloc_elem *start_elem = (struct malloc_elem *)ms->addr; + struct malloc_elem *end_elem = RTE_PTR_ADD(ms->addr, + ms->len - MALLOC_ELEM_OVERHEAD); + end_elem = RTE_PTR_ALIGN_FLOOR(end_elem, RTE_CACHE_LINE_SIZE); + const size_t elem_size = (uintptr_t)end_elem - (uintptr_t)start_elem; + + malloc_elem_init(start_elem, heap, ms, elem_size); + malloc_elem_mkend(end_elem, start_elem); + malloc_elem_free_list_insert(start_elem); + + heap->total_size += elem_size; +} + +/* + * Iterates through the freelist for a heap to find a free element + * which can store data of the required size and with the requested alignment. + * If size is 0, find the biggest available elem. + * Returns null on failure, or pointer to element on success. + */ +static struct malloc_elem * +find_suitable_element(struct malloc_heap *heap, size_t size, + unsigned flags, size_t align, size_t bound) +{ + size_t idx; + struct malloc_elem *elem, *alt_elem = NULL; + + for (idx = malloc_elem_free_list_index(size); + idx < RTE_HEAP_NUM_FREELISTS; idx++) { + for (elem = LIST_FIRST(&heap->free_head[idx]); + !!elem; elem = LIST_NEXT(elem, free_list)) { + if (malloc_elem_can_hold(elem, size, align, bound)) { + if (check_hugepage_sz(flags, elem->ms->hugepage_sz)) + return elem; + if (alt_elem == NULL) + alt_elem = elem; + } + } + } + + if ((alt_elem != NULL) && (flags & RTE_MEMZONE_SIZE_HINT_ONLY)) + return alt_elem; + + return NULL; +} + +/* + * Main function to allocate a block of memory from the heap. + * It locks the free list, scans it, and adds a new memseg if the + * scan fails. Once the new memseg is added, it re-scans and should return + * the new element after releasing the lock. + */ +void * +malloc_heap_alloc(struct malloc_heap *heap, + const char *type __attribute__((unused)), size_t size, unsigned flags, + size_t align, size_t bound) +{ + struct malloc_elem *elem; + + size = RTE_CACHE_LINE_ROUNDUP(size); + align = RTE_CACHE_LINE_ROUNDUP(align); + + rte_spinlock_lock(&heap->lock); + + elem = find_suitable_element(heap, size, flags, align, bound); + if (elem != NULL) { + elem = malloc_elem_alloc(elem, size, align, bound); + /* increase heap's count of allocated elements */ + heap->alloc_count++; + } + rte_spinlock_unlock(&heap->lock); + + return elem == NULL ? NULL : (void *)(&elem[1]); +} + +/* + * Function to retrieve data for heap on given socket + */ +int +malloc_heap_get_stats(struct malloc_heap *heap, + struct rte_malloc_socket_stats *socket_stats) +{ + size_t idx; + struct malloc_elem *elem; + + rte_spinlock_lock(&heap->lock); + + /* Initialise variables for heap */ + socket_stats->free_count = 0; + socket_stats->heap_freesz_bytes = 0; + socket_stats->greatest_free_size = 0; + + /* Iterate through free list */ + for (idx = 0; idx < RTE_HEAP_NUM_FREELISTS; idx++) { + for (elem = LIST_FIRST(&heap->free_head[idx]); + !!elem; elem = LIST_NEXT(elem, free_list)) + { + socket_stats->free_count++; + socket_stats->heap_freesz_bytes += elem->size; + if (elem->size > socket_stats->greatest_free_size) + socket_stats->greatest_free_size = elem->size; + } + } + /* Get stats on overall heap and allocated memory on this heap */ + socket_stats->heap_totalsz_bytes = heap->total_size; + socket_stats->heap_allocsz_bytes = (socket_stats->heap_totalsz_bytes - + socket_stats->heap_freesz_bytes); + socket_stats->alloc_count = heap->alloc_count; + + rte_spinlock_unlock(&heap->lock); + return 0; +} + +int +rte_eal_malloc_heap_init(void) +{ + struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config; + unsigned ms_cnt; + struct rte_memseg *ms; + + if (mcfg == NULL) + return -1; + + for (ms = &mcfg->memseg[0], ms_cnt = 0; + (ms_cnt < RTE_MAX_MEMSEG) && (ms->len > 0); + ms_cnt++, ms++) { + malloc_heap_add_memseg(&mcfg->malloc_heaps[ms->socket_id], ms); + } + + return 0; +} diff --git a/pool/shard000/C/0014912_utils.c b/pool/shard000/C/0014912_utils.c new file mode 100644 index 0000000000000000000000000000000000000000..1f94d1a2628fd236f6d6c89f226fd65c56f2e0c3 --- /dev/null +++ b/pool/shard000/C/0014912_utils.c @@ -0,0 +1,193 @@ +/* + * Provman + * + * Copyright (C) 2011 Intel Corporation. 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 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 Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + * + * + * Mark Ryan + * + */ + +/*! + * @file utils.c + * + * @brief contains general utility functions + * + *****************************************************************************/ +#include "config.h" + +#include + +#include + +#include "error.h" +#include "log.h" + +#include "utils.h" + +int provman_utils_validate_key(const char *key) +{ + int err = PROVMAN_ERR_NONE; + const char *start; + const char *end; + + if (!key) { + err = PROVMAN_ERR_BAD_ARGS; + goto on_error; + } + + if (key[0] != '/') { + err = PROVMAN_ERR_BAD_ARGS; + goto on_error; + } + + start = end = key + 1; + while (*start) { + while (*end && *end != '/') { + if (!g_ascii_isprint(*end) || g_ascii_isspace(*end)) { + err = PROVMAN_ERR_BAD_ARGS; + goto on_error; + } + ++end; + } + + if (start == end) { + err = PROVMAN_ERR_BAD_ARGS; + goto on_error; + } + + if (*end) + ++end; + start = end; + } + +on_error: + + return err; +} + +int provman_utils_make_file_path(const char* fname, bool system, gchar **path) +{ + int err = PROVMAN_ERR_NONE; + + const char *home_dir; + GString *db_path = NULL; + + if (!system) { + home_dir = g_get_home_dir(); + if (!home_dir) { + err = PROVMAN_ERR_NOT_FOUND; + goto on_error; + } + db_path = g_string_new(home_dir); + db_path = g_string_append(db_path,"/"); + db_path = g_string_append(db_path, PROVMAN_SESSION_DB_PATH); + } else { + db_path = g_string_new(PROVMAN_SYSTEM_DB_PATH); + } + + (void) g_mkdir_with_parents(db_path->str, 0700); + db_path = g_string_append(db_path,"/"); + db_path = g_string_append(db_path, fname); + + *path = db_path->str; + g_string_free(db_path, FALSE); + +on_error: + + return err; +} + +gchar *provman_utils_get_context_from_key(const gchar *key, const char *root, + unsigned int root_len) +{ + gchar *context = NULL; + gchar *ptr; + + if (!strncmp(root, key, root_len)) { + context = g_strdup(key + root_len); + ptr = strchr(context, '/'); + if (ptr) + *ptr = 0; + } + + return context; +} + +GHashTable *provman_utils_get_contexts(GHashTable *settings, const char *root, + unsigned int root_len) +{ + gpointer key; + gchar *context; + GHashTableIter iter; + GHashTable *contexts = + g_hash_table_new_full(g_str_hash, g_str_equal, g_free, NULL); + + g_hash_table_iter_init(&iter, settings); + while (g_hash_table_iter_next(&iter, &key, NULL)) { + context = provman_utils_get_context_from_key(key, root, + root_len); + if (context) + g_hash_table_insert(contexts, context, NULL); + } + + return contexts; +} + +static gboolean prv_can_remove_settings(gpointer key, gpointer value, + gpointer user_data) +{ + GString *account_key = user_data; + + return ((strlen((const char*) key) > account_key->len) && + !strncmp(account_key->str, (const char*) key, + account_key->len)); +} + +void provman_utils_remove_account(GHashTable *settings, const gchar *root, + const gchar *account) +{ + GString *account_key; + + account_key = g_string_new(root); + g_string_append(account_key, account); + g_string_append(account_key, "/"); + g_hash_table_foreach_remove(settings, prv_can_remove_settings, + account_key); + (void) g_string_free(account_key, TRUE); +} + +#ifdef PROVMAN_LOGGING +void provman_utils_dump_hash_table(GHashTable* hash_table) +{ + gpointer key, value; + GList *list; + GList *ptr; + + list = g_hash_table_get_keys(hash_table); + list = g_list_sort(list, (GCompareFunc) strcmp); + ptr = list; + while (ptr) + { + key = ptr->data; + value = g_hash_table_lookup(hash_table, key); + PROVMAN_LOGF("%s = %s", key, value); + ptr = ptr->next; + } + g_list_free(list); +} +#endif diff --git a/pool/shard000/C/0014913_fsck.c b/pool/shard000/C/0014913_fsck.c new file mode 100644 index 0000000000000000000000000000000000000000..36cb3e6259db5c85d5298abaf41ee0aa2fa60a6d --- /dev/null +++ b/pool/shard000/C/0014913_fsck.c @@ -0,0 +1,147 @@ +#define _FUZIX_SOURCE + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static int error; +static int aflag; + +static void panic(char *s) +{ + fprintf(stderr, "panic: %s\n", s); + exit(1); +} + +const char *mntpoint(const char *mount) +{ + FILE *fp; + struct mntent *mnt; + const char *p; + + fp = setmntent("/etc/fstab", "r"); + if (fp) { + while (mnt = getmntent(fp)) { + p = mnt_device_path(mnt); + if (strcmp(mnt->mnt_dir, mount) == 0) { + endmntent(fp); + return p; + } + } + endmntent(fp); + } + return NULL; +} + +static void perform_fsck_exec(const char *path) +{ + if (aflag == 0) + execl("/bin/fsck-fuzix", "fsck-fuzix", path, NULL); + else + execl("/bin/fsck-fuzix", "fsck-fuzix", "-a", path, NULL); + perror("fsck-fuzix"); + exit(1); + +} + +/* Rather than exec a whole binary to do trivial checks for the usual case we + do a clean check before we run fsck.fuzix. Anything odd or hard we punt */ +static int is_clean(const char *path) +{ + static struct fuzix_filesys fs; + int fd; + + fd = open(path, O_RDONLY); + if (fd == -1) + return 0; + if (read(fd, &fs, sizeof(fs)) != sizeof(fs)) { + close(fd); + return 0; + } + if (close(fd) || fs.s_fs.s_mounted != SMOUNTED || + fs.s_fs.s_fmod != FMOD_CLEAN) + return 0; + return 1; +} + +static int perform_fsck(const char *path, uint8_t search, uint8_t only) +{ + pid_t pid; + int st; + const char *p; + if (search) { + p = mntpoint(path); + if (p) + path = p; + } + if (aflag) { + if (is_clean(path)) + return 0; + } + /* Only fsck helper we will run - so just exec it */ + if (only) + perform_fsck_exec(path); + + /* May be multiple: use fork and exec */ + fflush(stdout); + switch (pid = fork()) { + case -1: + perror("fork"); + exit(127); + case 0: + /* FIXME: one day bigger boxes will care about the fs type */ + perform_fsck_exec(path); + default: + while (waitpid(pid, &st, 0) == -1) { + if (errno == ECHILD) { + perror("waitpid"); + exit(1); + } + } + if (WIFEXITED(st)) + return WEXITSTATUS(st); + fprintf(stderr, "child process failed %d.\n", WTERMSIG(st)); + exit(1); + } +} + +int main(int argc, char *argv[]) +{ + struct mntent *mnt; + if (argc > 1 && strcmp(argv[1], "-a") == 0) { + argc--; + argv++; + aflag = 1; + } + + if (argc == 1 && aflag) { + FILE *fp = setmntent("/etc/fstab", "r"); + if (fp == NULL) { + perror("/etc/fstab"); + exit(1); + } + while ((mnt = getmntent(fp)) != NULL) { + printf("%s:\n", mnt->mnt_fsname); + if (perform_fsck(mnt->mnt_fsname, 0, 0)) + exit(error); + } + endmntent(fp); + } else { + if (argc != 2) { + fputs("syntax: fsck [-a] [devfile]\n", stderr); + return 16; + } + perform_fsck(argv[1], 1, 1); + } + puts("Done."); + exit(error); +} diff --git a/pool/shard000/C/0014919_cdc.c b/pool/shard000/C/0014919_cdc.c new file mode 100644 index 0000000000000000000000000000000000000000..c11c277c51caa735a20734d7e3f14e3b71d28769 --- /dev/null +++ b/pool/shard000/C/0014919_cdc.c @@ -0,0 +1,235 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ + +#include "common.h" + +#include "log.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "utils.h" + +#include "cdc.h" +#include "../seafile-crypt.h" + +#include "rabin-checksum.h" +#define finger rabin_checksum +#define rolling_finger rabin_rolling_checksum + +#define READ_SIZE 1024 * 4 + +#define BYTE_TO_HEX(b) (((b)>=10)?('a'+b-10):('0'+b)) + +static int default_write_chunk (CDCDescriptor *chunk_descr) +{ + char filename[NAME_MAX_SZ]; + char chksum_str[CHECKSUM_LENGTH *2 + 1]; + int fd_chunk, ret; + + memset(chksum_str, 0, sizeof(chksum_str)); + rawdata_to_hex (chunk_descr->checksum, chksum_str, CHECKSUM_LENGTH); + snprintf (filename, NAME_MAX_SZ, "./%s", chksum_str); + fd_chunk = g_open (filename, O_RDWR | O_CREAT | O_BINARY, 0644); + if (fd_chunk < 0) + return -1; + + ret = writen (fd_chunk, chunk_descr->block_buf, chunk_descr->len); + close (fd_chunk); + return ret; +} + +static int init_cdc_file_descriptor (int fd, + uint64_t file_size, + CDCFileDescriptor *file_descr) +{ + int max_block_nr = 0; + int block_min_sz = 0; + + file_descr->block_nr = 0; + + if (file_descr->block_min_sz <= 0) + file_descr->block_min_sz = BLOCK_MIN_SZ; + if (file_descr->block_max_sz <= 0) + file_descr->block_max_sz = BLOCK_MAX_SZ; + if (file_descr->block_sz <= 0) + file_descr->block_sz = BLOCK_SZ; + + if (file_descr->write_block == NULL) + file_descr->write_block = (WriteblockFunc)default_write_chunk; + + block_min_sz = file_descr->block_min_sz; + max_block_nr = ((file_size + block_min_sz - 1) / block_min_sz); + file_descr->blk_sha1s = (uint8_t *)calloc (sizeof(uint8_t), + max_block_nr * CHECKSUM_LENGTH); + file_descr->max_block_nr = max_block_nr; + + return 0; +} + +#define WRITE_CDC_BLOCK(block_sz, write_data) \ +do { \ + int _block_sz = (block_sz); \ + chunk_descr.len = _block_sz; \ + chunk_descr.offset = offset; \ + ret = file_descr->write_block (file_descr->repo_id, \ + file_descr->version, \ + &chunk_descr, \ + crypt, chunk_descr.checksum, \ + (write_data)); \ + if (ret < 0) { \ + free (buf); \ + g_warning ("CDC: failed to write chunk.\n"); \ + return -1; \ + } \ + memcpy (file_descr->blk_sha1s + \ + file_descr->block_nr * CHECKSUM_LENGTH, \ + chunk_descr.checksum, CHECKSUM_LENGTH); \ + SHA1_Update (&file_ctx, chunk_descr.checksum, 20); \ + file_descr->block_nr++; \ + offset += _block_sz; \ + \ + memmove (buf, buf + _block_sz, tail - _block_sz); \ + tail = tail - _block_sz; \ + cur = 0; \ +}while(0); + +/* content-defined chunking */ +int file_chunk_cdc(int fd_src, + CDCFileDescriptor *file_descr, + SeafileCrypt *crypt, + gboolean write_data) +{ + char *buf; + uint32_t buf_sz; + SHA_CTX file_ctx; + CDCDescriptor chunk_descr; + SHA1_Init (&file_ctx); + + SeafStat sb; + if (seaf_fstat (fd_src, &sb) < 0) { + seaf_warning ("CDC: failed to stat: %s.\n", strerror(errno)); + return -1; + } + uint64_t expected_size = sb.st_size; + + init_cdc_file_descriptor (fd_src, expected_size, file_descr); + uint32_t block_min_sz = file_descr->block_min_sz; + uint32_t block_mask = file_descr->block_sz - 1; + + int fingerprint = 0; + int offset = 0; + int ret = 0; + int tail, cur, rsize; + + buf_sz = file_descr->block_max_sz; + buf = chunk_descr.block_buf = malloc (buf_sz); + if (!buf) + return -1; + + /* buf: a fix-sized buffer. + * cur: data behind (inclusive) this offset has been scanned. + * cur + 1 is the bytes that has been scanned. + * tail: length of data loaded into memory. buf[tail] is invalid. + */ + tail = cur = 0; + while (1) { + if (tail < block_min_sz) { + rsize = block_min_sz - tail + READ_SIZE; + } else { + rsize = (buf_sz - tail < READ_SIZE) ? (buf_sz - tail) : READ_SIZE; + } + ret = readn (fd_src, buf + tail, rsize); + if (ret < 0) { + seaf_warning ("CDC: failed to read: %s.\n", strerror(errno)); + free (buf); + return -1; + } + tail += ret; + file_descr->file_size += ret; + + if (file_descr->file_size > expected_size) { + seaf_warning ("File size changed while chunking.\n"); + free (buf); + return -1; + } + + /* We've read all the data in this file. Output the block immediately + * in two cases: + * 1. The data left in the file is less than block_min_sz; + * 2. We cannot find the break value until the end of this file. + */ + if (tail < block_min_sz || cur >= tail) { + if (tail > 0) { + if (file_descr->block_nr == file_descr->max_block_nr) { + seaf_warning ("Block id array is not large enough, bail out.\n"); + free (buf); + return -1; + } + WRITE_CDC_BLOCK (tail, write_data); + } + break; + } + + /* + * A block is at least of size block_min_sz. + */ + if (cur < block_min_sz - 1) + cur = block_min_sz - 1; + + while (cur < tail) { + fingerprint = (cur == block_min_sz - 1) ? + finger(buf + cur - BLOCK_WIN_SZ + 1, BLOCK_WIN_SZ) : + rolling_finger (fingerprint, BLOCK_WIN_SZ, + *(buf+cur-BLOCK_WIN_SZ), *(buf + cur)); + + /* get a chunk, write block info to chunk file */ + if (((fingerprint & block_mask) == ((BREAK_VALUE & block_mask))) + || cur + 1 >= file_descr->block_max_sz) + { + if (file_descr->block_nr == file_descr->max_block_nr) { + seaf_warning ("Block id array is not large enough, bail out.\n"); + free (buf); + return -1; + } + + WRITE_CDC_BLOCK (cur + 1, write_data); + break; + } else { + cur ++; + } + } + } + + SHA1_Final (file_descr->file_sum, &file_ctx); + + free (buf); + + return 0; +} + +int filename_chunk_cdc(const char *filename, + CDCFileDescriptor *file_descr, + SeafileCrypt *crypt, + gboolean write_data) +{ + int fd_src = seaf_util_open (filename, O_RDONLY | O_BINARY); + if (fd_src < 0) { + seaf_warning ("CDC: failed to open %s.\n", filename); + return -1; + } + + int ret = file_chunk_cdc (fd_src, file_descr, crypt, write_data); + close (fd_src); + return ret; +} + +void cdc_init () +{ + rabin_init (BLOCK_WIN_SZ); +} diff --git a/pool/shard000/C/0014933_g2bk.c b/pool/shard000/C/0014933_g2bk.c new file mode 100644 index 0000000000000000000000000000000000000000..19bee550f86f1d36d7b644a5280a9a662f725ddf --- /dev/null +++ b/pool/shard000/C/0014933_g2bk.c @@ -0,0 +1,51 @@ +/* + * Copyright 1999-2000,2005,2016 BitMover, Inc + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "system.h" +#include "sccs.h" + +static void print_name(char *); + +/* + * _g2bk - convert gfile names to sfile names + */ +int +g2bk_main(int ac, char **av) +{ + int i; + + if ((ac > 1) && strcmp(av[ac-1], "-")) { + for (i = 1; i < ac; ++i) { + print_name(av[i]); + } + } else { + char buf[MAXPATH]; + + while (fnext(buf, stdin)) { + chop(buf); + print_name(buf); + } + } + return (0); +} + +static void +print_name(char *name) +{ + name = name2sccs(name); + printf("%s\n", name); + free(name); +} diff --git a/pool/shard000/C/0014943_hash_server_poll.c b/pool/shard000/C/0014943_hash_server_poll.c new file mode 100644 index 0000000000000000000000000000000000000000..591fa97f035de832c906f172a3b603394d566045 --- /dev/null +++ b/pool/shard000/C/0014943_hash_server_poll.c @@ -0,0 +1,210 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define MAX(a, b) ((a) > (b) ? (a) : (b)) + +typedef int (*client_func_t)(int cfd); + +struct node { + struct node *next; + int key; + char value[128]; + int v_len; +}; + +struct hashtable { + struct node **heads; + int vect_size; +}; + +struct hashtable db; + +void stampa (const char *dato, int len) { + int i; + for (i = 0; i < len; ++i) { + printf("%c", dato[i]); + } + printf("\n"); +} + +void hashtable_init (struct hashtable *self, int vect_size) { + struct node **buf; // vettore di puntatori ai nodi + buf = (struct node **)malloc(vect_size * sizeof(struct node *)); + int i; + self->vect_size = vect_size; + self->heads = buf; + for (i = 0; i < vect_size; i++){ + self->heads[i] = NULL; + } +} + +int hash (int key) { + return(key); +} + +void hashtable_insert (struct hashtable *self, int key, char *value, int value_length) { + int vect_index; + vect_index = hash(key) % self->vect_size; + struct node *node; + for (node = self->heads[vect_index]; node != NULL; node = node->next) { + if (node->key == key) { + node->v_len = value_length; + memcpy(node->value, value, value_length); + return; + } + } + node = (struct node *)malloc(sizeof(struct node)); + node->next = self->heads[vect_index]; + node->key = key; + node->v_len = value_length; + memcpy(node->value, value, value_length); + self->heads[vect_index] = node; +} + +char *hashtable_get (struct hashtable *self, int key, int *v_len) { + struct node *node; + int v_index; + v_index = hash(key) % self->vect_size; + for (node = self->heads[v_index]; node != NULL; node = node->next) { + if (node->key == key) { + *v_len = node->v_len; + return(node->value); + } + } + *v_len = 11; + return("non trovato"); +} + +int create_server (int port) { + int srv_fd; + int yep = 1; + struct sockaddr_in servaddr; + srv_fd = socket(AF_INET, SOCK_STREAM, 0); + + setsockopt(srv_fd, SOL_SOCKET, SO_REUSEADDR, &yep, sizeof(int)); + + bzero(&servaddr, sizeof(servaddr)); + servaddr.sin_family = AF_INET; + servaddr.sin_addr.s_addr = htons(INADDR_ANY); + servaddr.sin_port = htons(port); + + bind(srv_fd, (struct sockaddr *) &servaddr, sizeof(servaddr)); + listen(srv_fd, 10); + return(srv_fd); +} + +void server_loop (int srv_fd, client_func_t c_func) { + struct pollfd fds[50]; + int cfd; + int fd_count; + fd_count = 1; + fds[0].fd = srv_fd; + fds[0].events = POLLIN; + + while (1) { + printf("WAIT ON SELECT %d\n", fd_count); + if (poll(fds, fd_count, -1) < 0) { + perror("poll()"); + continue; + } + // qualcuno si e' connesso + if (fds[0].revents & POLLIN) { + int cfd = accept(srv_fd, (struct sockaddr*) NULL, NULL); + int yep = 1; + setsockopt(cfd, IPPROTO_TCP, TCP_NODELAY, &yep, sizeof(int)); + printf("Accettato il client %d\n", cfd); + fds[fd_count].fd = cfd; + fds[fd_count].events = POLLIN; + fd_count++; + } else { + + printf("SCAN FOR READ fda=%d\n", fd_count); + for (int i = 1; i < fd_count; ++i) { + int cfd = fds[i].fd; + if (!(fds[i].revents & POLLIN)) continue; + + if (c_func(cfd) < 0) { + memmove(fds + i, fds +i +1, (fd_count - i) * sizeof(struct pollfd)); + fd_count--; + continue; + } + } + } + } +} + +int client_echo (int cfd) { + char buffer[128]; + ssize_t rd; + //leggiamo quello che ha scritto un client + rd = read(cfd, buffer, sizeof(buffer)); + if (rd <= 0) { + return(-1); + } + if (memcmp(buffer, "scus", 4) == 0) { + memcpy(buffer, "figur\n", 6); + rd = 6; + } else if (memcmp(buffer, "chiudi", 6) == 0) { + return(-1); + } else if (memcmp(buffer, "put", 3) == 0) { + printf("Byte letti %d\n", rd); + + char *key, *value; + int k_len, v_len; + + key = buffer + 4; + //printf("key = %p\n", key); + + value = memchr(buffer + 4, ' ',rd - 4) + 1; + k_len = (value - key) -1; + v_len = rd - 4 - k_len - 1; + printf("key = "); + stampa(key, k_len); + printf("value = "); + stampa(value, v_len); + int i_key; + i_key = strtol(key, NULL, 10); + //printf("integer key = %d\n", i_key); + + hashtable_insert(&db, i_key, value, v_len); + memcpy(buffer, "storato\n", 8); + rd = 8; + + } else if (memcmp(buffer, "get", 3) == 0) { + char *g_key, *g_value; + int ig_key, v_len; + g_key = buffer + 4; + ig_key = strtol(g_key, NULL, 10); + + g_value = hashtable_get(&db, ig_key, &v_len); + memcpy(buffer, g_value, v_len); + memcpy(buffer + v_len, "\n", 1); + rd = v_len + 1; + //todo + } + printf(" - letto dal client %d: ", cfd); + stampa(buffer, rd); + write(cfd, buffer, rd); + return(0); +} + +int main (int argc, char **argv) { + hashtable_init(&db, 16); + int srv_fd; + srv_fd = create_server(11124); + server_loop(srv_fd, client_echo); + + close(srv_fd); + return(0); +} \ No newline at end of file diff --git a/pool/shard000/C/0014947_main.c b/pool/shard000/C/0014947_main.c new file mode 100644 index 0000000000000000000000000000000000000000..7ffb61fe66f289ec56637cbbf9d5347308f158a2 --- /dev/null +++ b/pool/shard000/C/0014947_main.c @@ -0,0 +1,96 @@ +/* + * +----------------------------------------------------------+ + * | +------------------------------------------------------+ | + * | | Quafios Launcher. | | + * | | -> main() procedure. | | + * | +------------------------------------------------------+ | + * +----------------------------------------------------------+ + * + * This file is part of Quafios 1.0.2 source code. + * Copyright (C) 2014 Mostafa Abd El-Aziz Mohamed. + * + * 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 Quafios. If not, see . + * + * Visit http://www.quafios.com/ for contact information. + * + */ + +#include +#include +#include + +void launch(int selected) { + + if (selected == 0) { + /* qonqueror */ + if (!fork()) + execve("/bin/qonqueror", NULL, NULL); + } else if (selected == 2) { + /* qonsole */ + if (!fork()) + execve("/bin/qonsole", NULL, NULL); + } else if (selected == 3) { + /* control panel */ + if (!fork()) + execve("/bin/cpanel", NULL, NULL); + } +} + +int main() { + + pixbuf_t *icon1 = parse_png("/usr/share/icons/browser48.png"); + pixbuf_t *icon2 = parse_png("/usr/share/icons/edit48.png"); + pixbuf_t *icon3 = parse_png("/usr/share/icons/qonsole48.png"); + pixbuf_t *icon4 = parse_png("/usr/share/icons/cpanel48.png"); + pixbuf_t *icon5 = parse_png("/usr/share/icons/poweroff48.png"); + window_t *win; + iconview_t *iconview; + + /* allocate a window */ + win = window_alloc("Quafios Launcher", /* title */ + 465, /* width */ + 100, /* height */ + -2, /* x (center) */ + -2, /* y (center) */ + 0xFFC0C0C0, /* bg color */ + "/usr/share/icons/launcher16.png" /* iconfile */); + + /* allocate iconview */ + iconview = iconview_alloc(5, 48, 48, + win->pixbuf->width, + win->pixbuf->height, 0); + + /* insert iconview */ + window_insert(win, iconview, 0, 0); + + /* insert icons */ + iconview_insert(iconview, icon1, "Home"); + iconview_insert(iconview, icon2, "Editor"); + iconview_insert(iconview, icon3, "Qonsole"); + iconview_insert(iconview, icon4, "Settings"); + iconview_insert(iconview, icon5, "Turn off"); + + /* initialize events */ + iconview->double_click = launch; + + /* redraw on the window */ + iconview_redraw(iconview); + + /* loop */ + gui_loop(); + + /* done */ + return 0; + +} diff --git a/pool/shard000/C/0014953_read_orde.c b/pool/shard000/C/0014953_read_orde.c new file mode 100644 index 0000000000000000000000000000000000000000..d07a2ddf435401baea9e4238a00455f239be779e --- /dev/null +++ b/pool/shard000/C/0014953_read_orde.c @@ -0,0 +1,73 @@ +/* -*- Mode: C; c-basic-offset:4 ; -*- */ +/* + * + * Copyright (C) 1997 University of Chicago. + * See COPYRIGHT notice in top-level directory. + */ + +#include "mpioimpl.h" + +#ifdef HAVE_WEAK_SYMBOLS + +#if defined(HAVE_PRAGMA_WEAK) +#pragma weak MPI_File_read_ordered_end = PMPI_File_read_ordered_end +#elif defined(HAVE_PRAGMA_HP_SEC_DEF) +#pragma _HP_SECONDARY_DEF PMPI_File_read_ordered_end MPI_File_read_ordered_end +#elif defined(HAVE_PRAGMA_CRI_DUP) +#pragma _CRI duplicate MPI_File_read_ordered_end as PMPI_File_read_ordered_end +/* end of weak pragmas */ +#endif + +/* Include mapping from MPI->PMPI */ +#define MPIO_BUILD_PROFILING +#include "mpioprof.h" +#endif + +/*@ + MPI_File_read_ordered_end - Complete a split collective read using shared file pointer + +Input Parameters: +. fh - file handle (handle) + +Output Parameters: +. buf - initial address of buffer (choice) +. status - status object (Status) + +.N fortran +@*/ +int MPI_File_read_ordered_end(MPI_File mpi_fh, void *buf, MPI_Status *status) +{ + int error_code=MPI_SUCCESS; + ADIO_File fh; + static char myname[] = "MPI_FILE_READ_ORDERED_END"; + + MPIU_UNREFERENCED_ARG(buf); + + MPIU_THREAD_CS_ENTER(ALLFUNC,); + + fh = MPIO_File_resolve(mpi_fh); + + /* --BEGIN ERROR HANDLING-- */ + MPIO_CHECK_FILE_HANDLE(fh, myname, error_code); + + if (!(fh->split_coll_count)) + { + error_code = MPIO_Err_create_code(MPI_SUCCESS, MPIR_ERR_RECOVERABLE, + myname, __LINE__, MPI_ERR_IO, + "**iosplitcollnone", 0); + error_code = MPIO_Err_return_file(fh, error_code); + goto fn_exit; + } + /* --END ERROR HANDLING-- */ + +#ifdef HAVE_STATUS_SET_BYTES + if (status != MPI_STATUS_IGNORE) + *status = fh->split_status; +#endif + fh->split_coll_count = 0; + +fn_exit: + MPIU_THREAD_CS_EXIT(ALLFUNC,); + + return error_code; +} diff --git a/pool/shard000/C/0014961_drv_pcf8574.c b/pool/shard000/C/0014961_drv_pcf8574.c new file mode 100644 index 0000000000000000000000000000000000000000..4801a92bc27b650459a78c867f7f7a8ae29cc728 --- /dev/null +++ b/pool/shard000/C/0014961_drv_pcf8574.c @@ -0,0 +1,100 @@ +/* + * File : drv_iic.c + * This file is part of RT-Thread RTOS + * COPYRIGHT (C) 2017 RT-Thread Develop Team + * + * The license and distribution terms for this file may be + * found in the file LICENSE in this distribution or at + * http://www.rt-thread.org/license/LICENSE + * + * Change Logs: + * Date Author Notes + * 2017-06-09 tanek first implementation. + */ +#include "drv_pcf8574.h" +#include +#include +#include + +//#define DEBUG + +#ifdef DEBUG +#define DEBUG_PRINTF(...) rt_kprintf(__VA_ARGS__) +#else +#define DEBUG_PRINTF(...) +#endif + +#define I2C_BUS_NAME "i2c0" +#define PCF8574_ADDR 0x20 + +static uint8_t rt_pcf8574_read_onebyte(void); +static void rt_pcf8574_write_onebyte(rt_uint8_t value); + +static struct rt_i2c_bus_device * i2c_bus; + +rt_err_t rt_pcf8574_init(void) +{ + rt_uint8_t buffer[] = { 0xFF }; + rt_off_t pos = PCF8574_ADDR; + + __HAL_RCC_GPIOB_CLK_ENABLE(); + + i2c_bus = (struct rt_i2c_bus_device *)rt_device_find(I2C_BUS_NAME); + if (i2c_bus == RT_NULL) + { + DEBUG_PRINTF("\ni2c_bus %s for PCF8574 not found!\n", I2C_BUS_NAME); + return -RT_ENOSYS; + } + + if (rt_device_open(&i2c_bus->parent, RT_NULL) != RT_EOK) + { + DEBUG_PRINTF("\ni2c_bus %s for cs43l22 opened failed!\n", I2C_BUS_NAME); + return -RT_EEMPTY; + } + + rt_device_write(&i2c_bus->parent, pos, &buffer, 1); + + return RT_EOK; +} + +static uint8_t rt_pcf8574_read_onebyte(void) +{ + rt_uint8_t value; + + rt_device_read(&i2c_bus->parent, PCF8574_ADDR, &value, 1); + + return value; +} + + +static void rt_pcf8574_write_onebyte(rt_uint8_t value) +{ + rt_device_write(&i2c_bus->parent, PCF8574_ADDR, &value, 1); +} + + +void rt_pcf8574_write_bit(rt_uint8_t bit, rt_uint8_t state) +{ + rt_uint8_t data; + data = rt_pcf8574_read_onebyte(); + + if (state == 0) + data &= ~(1 << bit); + else + data |= 1 << bit; + + rt_pcf8574_write_onebyte(data); +} + + +rt_uint8_t rt_pcf8574_read_bit(rt_uint8_t bit) +{ + rt_uint8_t data; + data = rt_pcf8574_read_onebyte(); + + if (data&(1 << bit)) + return 1; + else + return 0; +} + diff --git a/pool/shard000/C/0014962_alloc.c b/pool/shard000/C/0014962_alloc.c new file mode 100644 index 0000000000000000000000000000000000000000..96590ededf93a5e2c910fa48e79a4afa62332a36 --- /dev/null +++ b/pool/shard000/C/0014962_alloc.c @@ -0,0 +1,84 @@ +#include +#include + +static int _g = 0; + +void * _pbcM_malloc(size_t sz) { + ++ _g; + return malloc(sz); +} + +void _pbcM_free(void *p) { + if (p) { + -- _g; + free(p); + } +} + +void* _pbcM_realloc(void *p, size_t sz) { + return realloc(p,sz); +} + +void _pbcM_memory() { + printf("%d\n",_g); +} + +struct heap_page { + struct heap_page * next; +}; + +struct heap { + struct heap_page *current; + int size; + int used; +}; + +struct heap * +_pbcH_new(int pagesize) { + int cap = 1024; + while(cap < pagesize) { + cap *= 2; + } + struct heap * h = (struct heap *)_pbcM_malloc(sizeof(struct heap)); + h->current = (struct heap_page *)_pbcM_malloc(sizeof(struct heap_page) + cap); + h->size = cap; + h->used = 0; + h->current->next = NULL; + return h; +} + +void +_pbcH_delete(struct heap *h) { + struct heap_page * p = h->current; + struct heap_page * next = p->next; + for(;;) { + _pbcM_free(p); + if (next == NULL) + break; + p = next; + next = p->next; + } + _pbcM_free(h); +} + +void* +_pbcH_alloc(struct heap *h, int size) { + size = (size + 3) & ~3; + if (h->size - h->used < size) { + struct heap_page * p; + if (size < h->size) { + p = (struct heap_page *)_pbcM_malloc(sizeof(struct heap_page) + h->size); + } else { + p = (struct heap_page *)_pbcM_malloc(sizeof(struct heap_page) + size); + } + p->next = h->current; + h->current = p; + h->used = size; + return (p+1); + } else { + char * buffer = (char *)(h->current + 1); + buffer += h->used; + h->used += size; + return buffer; + } +} diff --git a/pool/shard000/C/0014972_overo.c b/pool/shard000/C/0014972_overo.c new file mode 100644 index 0000000000000000000000000000000000000000..f82ae7348ebb7f4e81a716c5b31c8944ce0fbe67 --- /dev/null +++ b/pool/shard000/C/0014972_overo.c @@ -0,0 +1,148 @@ +/* + * overo.c -- SoC audio for Gumstix Overo + * + * Author: Steve Sakoman + * + * 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 "omap-mcbsp.h" +#include "omap-pcm.h" +#include "../codecs/twl4030.h" + +static int overo_hw_params(struct snd_pcm_substream *substream, + struct snd_pcm_hw_params *params) +{ + struct snd_soc_pcm_runtime *rtd = substream->private_data; + struct snd_soc_dai *codec_dai = rtd->dai->codec_dai; + struct snd_soc_dai *cpu_dai = rtd->dai->cpu_dai; + int ret; + + /* Set codec DAI configuration */ + ret = snd_soc_dai_set_fmt(codec_dai, + SND_SOC_DAIFMT_I2S | + SND_SOC_DAIFMT_NB_NF | + SND_SOC_DAIFMT_CBM_CFM); + if (ret < 0) { + printk(KERN_ERR "can't set codec DAI configuration\n"); + return ret; + } + + /* Set cpu DAI configuration */ + ret = snd_soc_dai_set_fmt(cpu_dai, + SND_SOC_DAIFMT_I2S | + SND_SOC_DAIFMT_NB_NF | + SND_SOC_DAIFMT_CBM_CFM); + if (ret < 0) { + printk(KERN_ERR "can't set cpu DAI configuration\n"); + return ret; + } + + /* Set the codec system clock for DAC and ADC */ + ret = snd_soc_dai_set_sysclk(codec_dai, 0, 26000000, + SND_SOC_CLOCK_IN); + if (ret < 0) { + printk(KERN_ERR "can't set codec system clock\n"); + return ret; + } + + return 0; +} + +static struct snd_soc_ops overo_ops = { + .hw_params = overo_hw_params, +}; + +/* Digital audio interface glue - connects codec <--> CPU */ +static struct snd_soc_dai_link overo_dai = { + .name = "TWL4030", + .stream_name = "TWL4030", + .cpu_dai = &omap_mcbsp_dai[0], + .codec_dai = &twl4030_dai[TWL4030_DAI_HIFI], + .ops = &overo_ops, +}; + +/* Audio machine driver */ +static struct snd_soc_card snd_soc_card_overo = { + .name = "overo", + .platform = &omap_soc_platform, + .dai_link = &overo_dai, + .num_links = 1, +}; + +/* Audio subsystem */ +static struct snd_soc_device overo_snd_devdata = { + .card = &snd_soc_card_overo, + .codec_dev = &soc_codec_dev_twl4030, +}; + +static struct platform_device *overo_snd_device; + +static int __init overo_soc_init(void) +{ + int ret; + + if (!machine_is_overo()) { + pr_debug("Not Overo!\n"); + return -ENODEV; + } + printk(KERN_INFO "overo SoC init\n"); + + overo_snd_device = platform_device_alloc("soc-audio", -1); + if (!overo_snd_device) { + printk(KERN_ERR "Platform device allocation failed\n"); + return -ENOMEM; + } + + platform_set_drvdata(overo_snd_device, &overo_snd_devdata); + overo_snd_devdata.dev = &overo_snd_device->dev; + *(unsigned int *)overo_dai.cpu_dai->private_data = 1; /* McBSP2 */ + + ret = platform_device_add(overo_snd_device); + if (ret) + goto err1; + + return 0; + +err1: + printk(KERN_ERR "Unable to add platform device\n"); + platform_device_put(overo_snd_device); + + return ret; +} +module_init(overo_soc_init); + +static void __exit overo_soc_exit(void) +{ + platform_device_unregister(overo_snd_device); +} +module_exit(overo_soc_exit); + +MODULE_AUTHOR("Steve Sakoman "); +MODULE_DESCRIPTION("ALSA SoC overo"); +MODULE_LICENSE("GPL"); diff --git a/pool/shard000/C/0014985_Mips32Reset.c b/pool/shard000/C/0014985_Mips32Reset.c new file mode 100644 index 0000000000000000000000000000000000000000..03a06ed07648f04e739d1c922dbe1f3073c7ba33 --- /dev/null +++ b/pool/shard000/C/0014985_Mips32Reset.c @@ -0,0 +1,84 @@ +/*++ + +Copyright (c) 2006, Intel Corporation +All rights reserved. This program and the accompanying materials +are licensed and made available under the terms and conditions of the BSD License +which accompanies this distribution. The full text of the license may be found at +http://opensource.org/licenses/bsd-license.php + +THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, +WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. + +Module Name: + Ia32Reset.c + +Abstract: + +--*/ + +#include "Reset.h" +#include "CpuMips32.h" + +#include EFI_ARCH_PROTOCOL_DEFINITION (Reset) + +// +// The handle onto which the Reset Architectural Protocol is installed +// +EFI_HANDLE mResetHandle = NULL; + + +EFI_STATUS +EFIAPI +InitializeReset ( + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable + ) +/*++ + +Routine Description: + + Initialize the state information for the Reset Architectural Protocol + +Arguments: + + ImageHandle of the loaded driver + Pointer to the System Table + +Returns: + + Status + + EFI_SUCCESS - thread can be successfully created + EFI_OUT_OF_RESOURCES - cannot allocate protocol data structure + EFI_DEVICE_ERROR - cannot create the timer service + +--*/ +// TODO: SystemTable - add argument and description to function comment +{ + EFI_STATUS Status; + + EfiInitializeRuntimeDriverLib (ImageHandle, SystemTable, NULL); + + // + // Make sure the Reset Architectural Protocol is not already installed in the system + // + ASSERT_PROTOCOL_ALREADY_INSTALLED (NULL, &gEfiResetArchProtocolGuid); + + // + // Hook the runtime service table + // + SystemTable->RuntimeServices->ResetSystem = KbcResetSystem; + + // + // Now install the Reset RT AP on a new handle + // + Status = gBS->InstallMultipleProtocolInterfaces ( + &mResetHandle, + &gEfiResetArchProtocolGuid, + NULL, + NULL + ); + ASSERT_EFI_ERROR (Status); + + return Status; +} diff --git a/pool/shard000/C/0014991_file_test2a.c b/pool/shard000/C/0014991_file_test2a.c new file mode 100644 index 0000000000000000000000000000000000000000..e42f1abedd1555ccd4ec553b7d14eb63357926bc --- /dev/null +++ b/pool/shard000/C/0014991_file_test2a.c @@ -0,0 +1,111 @@ +/* + * dir_test.c + */ + + +#include +#include +#include + +#include"adflib.h" + + +void MyVer(char *msg) +{ + fprintf(stderr,"Verbose [%s]\n",msg); +} + + +/* + * + * + */ +int main(int argc, char *argv[]) +{ + struct Device *hd; + struct Volume *vol; + struct File *file; + unsigned char buf[600]; + long n; + FILE *out; + long len; + struct List *list; + + adfEnvInitDefault(); + +// adfSetEnvFct(0,0,MyVer,0); + + /* mount existing device : FFS */ + hd = adfMountDev( "hd.adf",FALSE ); + if (!hd) { + fprintf(stderr, "can't mount device\n"); + adfEnvCleanUp(); exit(1); + } + adfDeviceInfo(hd); + + vol = adfMount(hd, 1, FALSE); + if (!vol) { + adfUnMountDev(hd); + fprintf(stderr, "can't mount volume\n"); + adfEnvCleanUp(); exit(1); + } + + adfVolumeInfo(vol); + + + /* write one file */ + file = adfOpenFile(vol, "moon_gif","w"); + if (!file) return 1; + out = fopen("Check/MOON.GIF","rb"); + if (!out) return 1; + + len = 600; + n = fread(buf,sizeof(unsigned char),len,out); + while(!feof(out)) { + adfWriteFile(file, n, buf); + n = fread(buf,sizeof(unsigned char),len,out); + } + if (n>0) + adfWriteFile(file, n, buf); + + fclose(out); + + adfCloseFile(file); + + /* the directory */ +/* list = adfGetDirEnt(vol,vol->curDirPtr); + while(list) { + printEntry(list->content); + adfFreeEntry(list->content); + list = list->next; + } + freeList(list); +*/ + + /* re read this file */ + file = adfOpenFile(vol, "moon_gif","r"); + if (!file) return 1; + out = fopen("moon__gif","wb"); + if (!out) return 1; + + len = 300; + n = adfReadFile(file, len, buf); + while(!adfEndOfFile(file)) { + fwrite(buf,sizeof(unsigned char),n,out); + n = adfReadFile(file, len, buf); + } + if (n>0) + fwrite(buf,sizeof(unsigned char),n,out); + + fclose(out); + + adfCloseFile(file); + + adfUnMount(vol); + adfUnMountDev(hd); + + + adfEnvCleanUp(); + + return 0; +} diff --git a/pool/shard000/C/0015014_ssm2602-spi.c b/pool/shard000/C/0015014_ssm2602-spi.c new file mode 100644 index 0000000000000000000000000000000000000000..8848628571a1d18e73fc8ce648696fd0a0389747 --- /dev/null +++ b/pool/shard000/C/0015014_ssm2602-spi.c @@ -0,0 +1,40 @@ +/* + * SSM2602 SPI audio driver + * + * Copyright 2014 Analog Devices Inc. + * + * Licensed under the GPL-2. + */ + +#include +#include +#include + +#include + +#include "ssm2602.h" + +static int ssm2602_spi_probe(struct spi_device *spi) +{ + return ssm2602_probe(&spi->dev, SSM2602, + devm_regmap_init_spi(spi, &ssm2602_regmap_config)); +} + +static const struct of_device_id ssm2602_of_match[] = { + { .compatible = "adi,ssm2602", }, + { } +}; +MODULE_DEVICE_TABLE(of, ssm2602_of_match); + +static struct spi_driver ssm2602_spi_driver = { + .driver = { + .name = "ssm2602", + .of_match_table = ssm2602_of_match, + }, + .probe = ssm2602_spi_probe, +}; +module_spi_driver(ssm2602_spi_driver); + +MODULE_DESCRIPTION("ASoC SSM2602 SPI driver"); +MODULE_AUTHOR("Cliff Cai"); +MODULE_LICENSE("GPL"); diff --git a/pool/shard000/C/0015018_clock_am33xx.c b/pool/shard000/C/0015018_clock_am33xx.c new file mode 100644 index 0000000000000000000000000000000000000000..92142c893444bc63ad7e1b811172c5996d6005a0 --- /dev/null +++ b/pool/shard000/C/0015018_clock_am33xx.c @@ -0,0 +1,161 @@ +/* + * clock_am33xx.c + * + * clocks for AM33XX based boards + * + * Copyright (C) 2013, Texas Instruments, Incorporated - http://www.ti.com/ + * + * SPDX-License-Identifier: GPL-2.0+ + */ + +#include +#include +#include +#include +#include + +#define OSC (V_OSCK/1000000) + +struct cm_perpll *const cmper = (struct cm_perpll *)CM_PER; +struct cm_wkuppll *const cmwkup = (struct cm_wkuppll *)CM_WKUP; +struct cm_dpll *const cmdpll = (struct cm_dpll *)CM_DPLL; +struct cm_rtc *const cmrtc = (struct cm_rtc *)CM_RTC; + +const struct dpll_regs dpll_mpu_regs = { + .cm_clkmode_dpll = CM_WKUP + 0x88, + .cm_idlest_dpll = CM_WKUP + 0x20, + .cm_clksel_dpll = CM_WKUP + 0x2C, + .cm_div_m2_dpll = CM_WKUP + 0xA8, +}; + +const struct dpll_regs dpll_core_regs = { + .cm_clkmode_dpll = CM_WKUP + 0x90, + .cm_idlest_dpll = CM_WKUP + 0x5C, + .cm_clksel_dpll = CM_WKUP + 0x68, + .cm_div_m4_dpll = CM_WKUP + 0x80, + .cm_div_m5_dpll = CM_WKUP + 0x84, + .cm_div_m6_dpll = CM_WKUP + 0xD8, +}; + +const struct dpll_regs dpll_per_regs = { + .cm_clkmode_dpll = CM_WKUP + 0x8C, + .cm_idlest_dpll = CM_WKUP + 0x70, + .cm_clksel_dpll = CM_WKUP + 0x9C, + .cm_div_m2_dpll = CM_WKUP + 0xAC, +}; + +const struct dpll_regs dpll_ddr_regs = { + .cm_clkmode_dpll = CM_WKUP + 0x94, + .cm_idlest_dpll = CM_WKUP + 0x34, + .cm_clksel_dpll = CM_WKUP + 0x40, + .cm_div_m2_dpll = CM_WKUP + 0xA0, +}; + +struct dpll_params dpll_mpu_opp100 = { + CONFIG_SYS_MPUCLK, OSC-1, 1, -1, -1, -1, -1}; +const struct dpll_params dpll_core_opp100 = { + 1000, OSC-1, -1, -1, 10, 8, 4}; +const struct dpll_params dpll_mpu = { + MPUPLL_M_300, OSC-1, 1, -1, -1, -1, -1}; +const struct dpll_params dpll_core = { + 50, OSC-1, -1, -1, 1, 1, 1}; +const struct dpll_params dpll_per = { + 960, OSC-1, 5, -1, -1, -1, -1}; + +const struct dpll_params *get_dpll_mpu_params(void) +{ + return &dpll_mpu; +} + +const struct dpll_params *get_dpll_core_params(void) +{ + return &dpll_core; +} + +const struct dpll_params *get_dpll_per_params(void) +{ + return &dpll_per; +} + +void setup_clocks_for_console(void) +{ + clrsetbits_le32(&cmwkup->wkclkstctrl, CD_CLKCTRL_CLKTRCTRL_MASK, + CD_CLKCTRL_CLKTRCTRL_SW_WKUP << + CD_CLKCTRL_CLKTRCTRL_SHIFT); + + clrsetbits_le32(&cmper->l4hsclkstctrl, CD_CLKCTRL_CLKTRCTRL_MASK, + CD_CLKCTRL_CLKTRCTRL_SW_WKUP << + CD_CLKCTRL_CLKTRCTRL_SHIFT); + + clrsetbits_le32(&cmwkup->wkup_uart0ctrl, + MODULE_CLKCTRL_MODULEMODE_MASK, + MODULE_CLKCTRL_MODULEMODE_SW_EXPLICIT_EN << + MODULE_CLKCTRL_MODULEMODE_SHIFT); + clrsetbits_le32(&cmper->uart1clkctrl, + MODULE_CLKCTRL_MODULEMODE_MASK, + MODULE_CLKCTRL_MODULEMODE_SW_EXPLICIT_EN << + MODULE_CLKCTRL_MODULEMODE_SHIFT); + clrsetbits_le32(&cmper->uart2clkctrl, + MODULE_CLKCTRL_MODULEMODE_MASK, + MODULE_CLKCTRL_MODULEMODE_SW_EXPLICIT_EN << + MODULE_CLKCTRL_MODULEMODE_SHIFT); + clrsetbits_le32(&cmper->uart3clkctrl, + MODULE_CLKCTRL_MODULEMODE_MASK, + MODULE_CLKCTRL_MODULEMODE_SW_EXPLICIT_EN << + MODULE_CLKCTRL_MODULEMODE_SHIFT); + clrsetbits_le32(&cmper->uart4clkctrl, + MODULE_CLKCTRL_MODULEMODE_MASK, + MODULE_CLKCTRL_MODULEMODE_SW_EXPLICIT_EN << + MODULE_CLKCTRL_MODULEMODE_SHIFT); + clrsetbits_le32(&cmper->uart5clkctrl, + MODULE_CLKCTRL_MODULEMODE_MASK, + MODULE_CLKCTRL_MODULEMODE_SW_EXPLICIT_EN << + MODULE_CLKCTRL_MODULEMODE_SHIFT); +} + +void enable_basic_clocks(void) +{ + u32 *const clk_domains[] = { + &cmper->l3clkstctrl, + &cmper->l4fwclkstctrl, + &cmper->l3sclkstctrl, + &cmper->l4lsclkstctrl, + &cmwkup->wkclkstctrl, + &cmper->emiffwclkctrl, + &cmrtc->clkstctrl, + 0 + }; + + u32 *const clk_modules_explicit_en[] = { + &cmper->l3clkctrl, + &cmper->l4lsclkctrl, + &cmper->l4fwclkctrl, + &cmwkup->wkl4wkclkctrl, + &cmper->l3instrclkctrl, + &cmper->l4hsclkctrl, + &cmwkup->wkgpio0clkctrl, + &cmwkup->wkctrlclkctrl, + &cmper->timer2clkctrl, + &cmper->gpmcclkctrl, + &cmper->elmclkctrl, + &cmper->mmc0clkctrl, + &cmper->mmc1clkctrl, + &cmwkup->wkup_i2c0ctrl, + &cmper->gpio1clkctrl, + &cmper->gpio2clkctrl, + &cmper->gpio3clkctrl, + &cmper->i2c1clkctrl, + &cmper->cpgmac0clkctrl, + &cmper->spi0clkctrl, + &cmrtc->rtcclkctrl, + &cmper->usb0clkctrl, + &cmper->emiffwclkctrl, + &cmper->emifclkctrl, + 0 + }; + + do_enable_clocks(clk_domains, clk_modules_explicit_en, 1); + + /* Select the Master osc 24 MHZ as Timer2 clock source */ + writel(0x1, &cmdpll->clktimer2clk); +} diff --git a/pool/shard000/C/0015026_flood_mld6.c b/pool/shard000/C/0015026_flood_mld6.c new file mode 100644 index 0000000000000000000000000000000000000000..908a7e4c5357d9db8bebf2cf572a9e96c7c1018b --- /dev/null +++ b/pool/shard000/C/0015026_flood_mld6.c @@ -0,0 +1,103 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "thc-ipv6.h" + +void help(char *prg) { + printf("%s %s (c) 2015 by %s %s\n\n", prg, VERSION, AUTHOR, RESOURCE); + printf("Syntax: %s interface [target]\n\n", prg); + printf("Flood the local network with MLD reports.\n"); +// printf("Use -r to use raw mode.\n\n"); + exit(-1); +} + +int main(int argc, char *argv[]) { + char *interface, mac[6] = ""; + unsigned char *mac6 = mac, *ip6 = thc_resolve6("fe80::ff:fe00:0"); + unsigned char buf[6], buf2[16]; + unsigned char *dst = thc_resolve6("ff02::2"), *dstmac = thc_get_multicast_mac(dst); + int i; + unsigned char *pkt = NULL; + int pkt_len = 0; + int rawmode = 0; + int count = 0; + + if (argc < 2 || argc > 4 || strncmp(argv[1], "-h", 2) == 0) + help(argv[0]); + + if (strcmp(argv[1], "-r") == 0) { + thc_ipv6_rawmode(1); + rawmode = 1; + argv++; + argc--; + } + + srand(time(NULL) + getpid()); + setvbuf(stdout, NULL, _IONBF, 0); + + interface = argv[1]; + if (thc_get_own_mac(interface) == NULL) { + fprintf(stderr, "Error: invalid interface %s\n", interface); + exit(-1); + } + if (argc > 2) { + if ((dst = thc_resolve6(argv[2])) == NULL) { + fprintf(stderr, "Error: can not resolve %s\n", argv[2]); + exit(-1); + } + if (dst[0] >= 0x20 && dst[0] <= 0xfd) + ip6 = thc_get_own_ipv6(interface, dst, PREFER_GLOBAL); + } + + mac[0] = 0x00; + mac[1] = 0x18; + ip6[9] = mac[1]; + memset(buf, 0, sizeof(buf)); + buf[0] = 5; + buf[1] = 2; + memset(buf2, 0, sizeof(buf2)); + buf2[0] = 0xff; + buf2[1] = 0x02; + + printf("Starting to flood network with MLD reports on %s (Press Control-C to end, a dot is printed for every 1000 packets):\n", interface); + while (1) { + + for (i = 0; i < 6; i++) + buf2[10 + i] = rand() % 256; + for (i = 0; i < 4; i++) + mac[2 + i] = rand() % 256; + +// ip6[9] = mac[1]; + ip6[10] = mac[2]; + ip6[13] = mac[3]; + ip6[14] = mac[4]; + ip6[15] = mac[5]; + count++; + + if ((pkt = thc_create_ipv6_extended(interface, PREFER_LINK, &pkt_len, ip6, dst, 1, 0, 0, 0, 0)) == NULL) + return -1; + if (thc_add_hdr_hopbyhop(pkt, &pkt_len, buf, 6) < 0) + return -1; + if (thc_add_icmp6(pkt, &pkt_len, ICMP6_MLD_REPORT, 0, 0, buf2, sizeof(buf2), 0) < 0) + return -1; + if (thc_generate_and_send_pkt(interface, mac6, dstmac, pkt, &pkt_len) < 0) { +// fprintf(stderr, "Error sending packet no. %d on interface %s: ", count, interface); +// perror(""); +// return -1; + printf("!"); + } + + pkt = thc_destroy_packet(pkt); +// usleep(1); + if (count % 1000 == 0) + printf("."); + } + return 0; +} diff --git a/pool/shard000/C/0015033_CWE78_OS_Command_Injection__wchar_t_environment_w32_spawnv_53a.c b/pool/shard000/C/0015033_CWE78_OS_Command_Injection__wchar_t_environment_w32_spawnv_53a.c new file mode 100644 index 0000000000000000000000000000000000000000..f5982ee3fb0a1b87a350eec62a86185480aa1d17 --- /dev/null +++ b/pool/shard000/C/0015033_CWE78_OS_Command_Injection__wchar_t_environment_w32_spawnv_53a.c @@ -0,0 +1,120 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE78_OS_Command_Injection__wchar_t_environment_w32_spawnv_53a.c +Label Definition File: CWE78_OS_Command_Injection.strings.label.xml +Template File: sources-sink-53a.tmpl.c +*/ +/* + * @description + * CWE: 78 OS Command Injection + * BadSource: environment Read input from an environment variable + * GoodSource: Fixed string + * Sink: w32_spawnv + * BadSink : execute command with wspawnv + * Flow Variant: 53 Data flow: data passed as an argument from one function through two others to a fourth; all four functions are in different source files + * + * */ + +#include "std_testcase.h" + +#include + +#ifdef _WIN32 +#define COMMAND_INT_PATH L"%WINDIR%\\system32\\cmd.exe" +#define COMMAND_INT L"cmd.exe" +#define COMMAND_ARG1 L"/c" +#define COMMAND_ARG2 L"dir " +#define COMMAND_ARG3 data +#else /* NOT _WIN32 */ +#include +#define COMMAND_INT_PATH L"/bin/sh" +#define COMMAND_INT L"sh" +#define COMMAND_ARG1 L"-c" +#define COMMAND_ARG2 L"ls " +#define COMMAND_ARG3 data +#endif + +#define ENV_VARIABLE L"ADD" + +#ifdef _WIN32 +#define GETENV _wgetenv +#else +#define GETENV getenv +#endif + +#include + +#ifndef OMITBAD + +/* bad function declaration */ +void CWE78_OS_Command_Injection__wchar_t_environment_w32_spawnv_53b_badSink(wchar_t * data); + +void CWE78_OS_Command_Injection__wchar_t_environment_w32_spawnv_53_bad() +{ + wchar_t * data; + wchar_t dataBuffer[100] = COMMAND_ARG2; + data = dataBuffer; + { + /* Append input from an environment variable to data */ + size_t dataLen = wcslen(data); + wchar_t * environment = GETENV(ENV_VARIABLE); + /* If there is data in the environment variable */ + if (environment != NULL) + { + /* POTENTIAL FLAW: Read data from an environment variable */ + wcsncat(data+dataLen, environment, 100-dataLen-1); + } + } + CWE78_OS_Command_Injection__wchar_t_environment_w32_spawnv_53b_badSink(data); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* good function declaration */ +void CWE78_OS_Command_Injection__wchar_t_environment_w32_spawnv_53b_goodG2BSink(wchar_t * data); + +/* goodG2B uses the GoodSource with the BadSink */ +static void goodG2B() +{ + wchar_t * data; + wchar_t dataBuffer[100] = COMMAND_ARG2; + data = dataBuffer; + /* FIX: Append a fixed string to data (not user / external input) */ + wcscat(data, L"*.*"); + CWE78_OS_Command_Injection__wchar_t_environment_w32_spawnv_53b_goodG2BSink(data); +} + +void CWE78_OS_Command_Injection__wchar_t_environment_w32_spawnv_53_good() +{ + goodG2B(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + * its own for testing or for building a binary to use in testing binary + * analysis tools. It is not used when compiling all the testcases as one + * application, which is how source code analysis tools are tested. + */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE78_OS_Command_Injection__wchar_t_environment_w32_spawnv_53_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE78_OS_Command_Injection__wchar_t_environment_w32_spawnv_53_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard000/C/0015038_main.c b/pool/shard000/C/0015038_main.c new file mode 100644 index 0000000000000000000000000000000000000000..ec1073ad3699ec57504c57fe94f642c9ee9d9f6e --- /dev/null +++ b/pool/shard000/C/0015038_main.c @@ -0,0 +1,53 @@ +#include +#include + +/* Print a stopwatch value on the home screen */ +static void PrintTime(float elapsed) +{ + /* Float format for printf may be unimplemented, so go through an OS real */ + real_t elapsed_real; + + /* Max stopwatch value is (2^32 - 1) / 32768 = 131072.00, */ + /* so create a buffer with room for 9 characters plus a null terminator */ + char str[10]; + + /* If the elapsed time is small enough that the OS would print it using */ + /* scientific notation, force it down to zero before conversion */ + elapsed_real = os_FloatToReal(elapsed <= 0.001f ? 0.0f : elapsed); + + /* Convert the elapsed time real to a string */ + os_RealToStr(str, &elapsed_real, 8, 1, 2); + + /* print the string */ + os_SetCursorPos(0, 0); + os_PutStrFull(str); +} + +int main(void) +{ + /* Clear the homescreen */ + os_ClrHome(); + + /* Display an initial time of zero */ + PrintTime(0.0f); + + /* Wait for a key press */ + while (!os_GetCSC()); + + /* Record the start time */ + clock_t start = clock(); + + /* Continue running until a key is pressed */ + do + { + /* Calculate and print the elapsed time */ + clock_t now = clock(); + float elapsed = (float)(now - start) / CLOCKS_PER_SEC; + PrintTime(elapsed); + } while (!os_GetCSC()); + + /* Wait for a key */ + while (!os_GetCSC()); + + return 0; +} diff --git a/pool/shard000/C/0015046_munmap01.c b/pool/shard000/C/0015046_munmap01.c new file mode 100644 index 0000000000000000000000000000000000000000..2d9005c804da42e4909bec58a03d85783a31a989 --- /dev/null +++ b/pool/shard000/C/0015046_munmap01.c @@ -0,0 +1,276 @@ +/* + * + * Copyright (c) International Business Machines Corp., 2001 + * + * 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 + */ + +/* + * Test Name: munmap01 + * + * Test Description: + * Verify that, munmap call will succeed to unmap a mapped file or + * anonymous shared memory region from the calling process's address space + * and after successful completion of munmap, the unmapped region is no + * longer accessible. + * + * Expected Result: + * munmap call should succeed to unmap a mapped file or anonymous shared + * memory region from the process's address space and it returns with a + * value 0, further reference to the unmapped region should result in a + * segmentation fault (SIGSEGV). + * + * Algorithm: + * Setup: + * Setup signal handling. + * Create temporary directory. + * Pause for SIGUSR1 if option specified. + * + * Test: + * Loop if the proper options are given. + * Execute system call + * Check return code, if system call failed (return=-1) + * Log the errno and Issue a FAIL message. + * Otherwise, + * Verify the Functionality of system call + * if successful, + * Issue Functionality-Pass message. + * Otherwise, + * Issue Functionality-Fail message. + * Cleanup: + * Print errno log and/or timing stats if options given + * Delete the temporary directory created. + * + * Usage: + * munmap01 [-c n] [-f] [-i n] [-I x] [-P x] [-t] + * where, -c n : Run n copies concurrently. + * -f : Turn off functionality Testing. + * -i n : Execute test n times. + * -I x : Execute test for x seconds. + * -P x : Pause for x seconds between iterations. + * -t : Turn on syscall timing. + * + * HISTORY + * 07/2001 Ported by Wayne Boyer + * + * RESTRICTIONS: + * None.$ + */ +#include +#include +#include +#include +#include + +#include "test.h" +#include "usctest.h" + +#define TEMPFILE "mmapfile" + +char *TCID = "munmap01"; +int TST_TOTAL = 1; + +char *addr; /* addr of memory mapped region */ +int fildes; /* file descriptor for tempfile */ +unsigned int map_len; /* length of the region to be mapped */ + +void setup(); /* Main setup function of test */ +void cleanup(); /* cleanup function for the test */ +void sig_handler(); /* signal catching function */ + +int main(int ac, char **av) +{ + int lc; + char *msg; + + if ((msg = parse_opts(ac, av, NULL, NULL)) != NULL) + tst_brkm(TBROK, NULL, "OPTION PARSING ERROR - %s", msg); + + for (lc = 0; TEST_LOOPING(lc); lc++) { + + tst_count = 0; + + setup(); + + /* + * Call munmap to unmap the mapped region of the + * temporary file from the calling process's address space. + */ + TEST(munmap(addr, map_len)); + + /* Check for the return value of munmap() */ + if (TEST_RETURN == -1) { + tst_resm(TFAIL, "munmap() fails, errno=%d : %s", + TEST_ERRNO, strerror(TEST_ERRNO)); + continue; + } +#ifdef UCLINUX + /* + * No SIGSEGV on uClinux since + * MMU not implemented on uClinux + */ + tst_resm(TPASS, "call succedded"); +#else + /* + * Perform functional verification if test + * executed without (-f) option. + */ + if (STD_FUNCTIONAL_TEST) { + /* + * Check whether further reference is possible + * to the unmapped memory region by writing + * to the first byte of region with + * some arbitrary number. + */ + *addr = 50; + + /* This message is printed if no SIGSEGV */ + tst_resm(TFAIL, "process succeeds to refer unmapped " + "memory region"); + } else { + tst_resm(TPASS, "call succeeded"); + } +#endif + + cleanup(); + + } + tst_exit(); +} + +/* + * setup() - performs all ONE TIME setup for this test. + * + * Set up signal handler to catch SIGSEGV. + * Get system page size, create a temporary file for reading/writing, + * write one byte data into it, map the open file for the specified + * map length. + */ +void setup() +{ + size_t page_sz; /* system page size */ + + tst_sig(NOFORK, DEF_HANDLER, cleanup); + + /* call signal function to trap the signal generated */ + if (signal(SIGSEGV, sig_handler) == SIG_ERR) { + tst_brkm(TBROK, cleanup, "signal fails to catch signal"); + tst_exit(); + } + + TEST_PAUSE; + + /* Get the system page size */ + if ((page_sz = getpagesize()) < 0) { + tst_brkm(TBROK, cleanup, + "getpagesize() fails to get system page size"); + tst_exit(); + } + + /* + * Get the length of the open file to be mapped into process + * address space. + */ + map_len = 3 * page_sz; + + tst_tmpdir(); + + /* Creat a temporary file used for mapping */ + if ((fildes = open(TEMPFILE, O_RDWR | O_CREAT, 0666)) < 0) { + tst_brkm(TBROK, cleanup, "open() on %s Failed, errno=%d : %s", + TEMPFILE, errno, strerror(errno)); + tst_exit(); + } + + /* + * move the file pointer to maplength position from the beginning + * of the file. + */ + if (lseek(fildes, map_len, SEEK_SET) == -1) { + tst_brkm(TBROK, cleanup, "lseek() fails on %s, errno=%d : %s", + TEMPFILE, errno, strerror(errno)); + tst_exit(); + } + + /* Write one byte into temporary file */ + if (write(fildes, "a", 1) != 1) { + tst_brkm(TBROK, cleanup, "write() on %s Failed, errno=%d : %s", + TEMPFILE, errno, strerror(errno)); + tst_exit(); + } + + /* + * map the open file 'TEMPFILE' from its beginning up to the maplength + * into the calling process's address space at the system choosen + * with read/write permissions to the the mapped region. + */ +#ifdef UCLINUX + /* MAP_SHARED is not implemented on uClinux */ + addr = mmap(0, map_len, PROT_READ | PROT_WRITE, + MAP_FILE | MAP_PRIVATE, fildes, 0); +#else + addr = mmap(0, map_len, PROT_READ | PROT_WRITE, + MAP_FILE | MAP_SHARED, fildes, 0); +#endif + + /* check for the return value of mmap system call */ + if (addr == (char *)MAP_FAILED) { + tst_brkm(TBROK, cleanup, "mmap() Failed on %s, errno=%d : %s", + TEMPFILE, errno, strerror(errno)); + tst_exit(); + } + +} + +/* + * sig_handler() - signal catching function. + * This function is used to trap the signal generated when tried to read or + * write to the memory mapped region which is already detached from the + * calling process address space. + * this function is invoked when SIGSEGV generated and it calls test + * cleanup function and exit the program. + */ +void sig_handler() +{ + tst_resm(TPASS, "Functionality of munmap() successful"); + + /* Invoke test cleanup function and exit */ + cleanup(); + + tst_exit(); +} + +/* + * cleanup() - performs all ONE TIME cleanup for this test at + * completion or premature exit. + * Close the temporary file. + * Remove the temporary directory. + */ +void cleanup() +{ + /* + * print timing stats if that option was specified. + * print errno log if that option was specified. + */ + TEST_CLEANUP; + + /* Close the temporary file */ + if (close(fildes) < 0) { + tst_brkm(TFAIL, NULL, "close() on %s Failed, errno=%d : %s", + TEMPFILE, errno, strerror(errno)); + } + + tst_rmdir(); +} diff --git a/pool/shard000/C/0015054_cbuf.c b/pool/shard000/C/0015054_cbuf.c new file mode 100644 index 0000000000000000000000000000000000000000..61f471b16bcff16b26b05cee92da06b0fc8c2846 --- /dev/null +++ b/pool/shard000/C/0015054_cbuf.c @@ -0,0 +1,199 @@ +/* + * cbuf.c: Buffer handling infra + * Copyright (C) 2012, Dipjyoti Saikia + * + * 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 +#include +#include +#include "cbuf.h" + +void +cbuf_list_head_init(struct cbuf_head *head) +{ + head->next = NULL; + head->len = 0; +} + +void +cbuf_list_queue_tail(struct cbuf_head *head, + struct cbuf *buf) +{ + struct cbuf *curr; + struct cbuf **prev = &head->next; + + while ((curr = *prev)) { + prev = &curr->next; + } + + buf->next = NULL; + *prev = buf; + head->len++; +} + +void +cbuf_list_queue(struct cbuf_head *head, + struct cbuf *buf) +{ + buf->next = head->next; + head->next = buf; + head->len++; +} + +struct cbuf * +cbuf_list_dequeue(struct cbuf_head *head) +{ + struct cbuf *curr; + struct cbuf **prev = &head->next; + + if ((curr = *prev)) { + *prev = curr->next; + head->len--; + } + + return curr; +} + +void +cbuf_list_purge(struct cbuf_head *head) +{ + struct cbuf *curr = head->next; + struct cbuf *prev = NULL; + + while (curr) { + prev = curr; + curr = curr->next; + head->len--; + free(prev); + } + + head->next = NULL; + +} + +struct cbuf * +alloc_cbuf(size_t len) +{ + struct cbuf *b; + size_t alloc_len = CBUF_ALIGN_SZ(len + CBUF_SZ); + + b = malloc(alloc_len); + assert(b); + + b->data = (unsigned char *)(b + 1); + b->tail = b->data; + b->end = (unsigned char *)b + alloc_len; + b->len = 0; + b->dpid = 0; + + return b; +} + +void * +cbuf_put(struct cbuf *b, size_t len) +{ + void *tmp = b->tail; + + assert(b->tail+len <= b->end); + + b->tail += len; + b->len += len; + + return tmp; +} + +void * +cbuf_pull(struct cbuf *b, size_t len) +{ + assert(b->data + len <= b->end); + + b->data += len; + b->len -= len; + + return (void *)(b->data); +} + +void * +cbuf_push(struct cbuf *b, size_t len) +{ + assert(cbuf_headroom(b) >= len); + + b->data -= len; + b->len += len; + + return (void *)(b->data); +} + +size_t +cbuf_headroom(struct cbuf *b) +{ + int room; + + assert(b && b->data); + + room = (b->data - (unsigned char *)b) + CBUF_SZ; + if (room < 0) return 0; + + return room; +} + +size_t +cbuf_tailroom(struct cbuf *b) +{ + return b->end - b->tail; +} + +struct cbuf * +cbuf_realloc_tailroom(struct cbuf *b, size_t room, int do_free) +{ + struct cbuf *old = b; + + if (room < cbuf_tailroom(b)) { + b = alloc_cbuf(old->len + room); + cbuf_put(b, old->len); + memcpy(b->data, old->data, old->len); + if (do_free) + free(old); + } + + return b; +} + +struct cbuf * +cbuf_realloc_headroom(struct cbuf *b, size_t room, int do_free) +{ + struct cbuf *old = b; + + if (1 /*room < cbuf_headroom(b)*/) { + b = alloc_cbuf(old->len + room); + cbuf_put(b, old->len + room); + cbuf_pull(b, room); + memcpy(b->data, old->data, old->len); + //printf(" b %p b->data %p b->tail %p b->end %p\n", b, b->data, b->tail, b->end); + if (do_free) + free(old); + } + + return b; +} + +void +free_cbuf(struct cbuf *b) +{ + free(b); +} diff --git a/pool/shard000/C/0015059_of_mdio.c b/pool/shard000/C/0015059_of_mdio.c new file mode 100644 index 0000000000000000000000000000000000000000..42a6715f8e84287ed2eef40382dc7bc89e181fbf --- /dev/null +++ b/pool/shard000/C/0015059_of_mdio.c @@ -0,0 +1,182 @@ +/* + * OF helpers for the MDIO (Ethernet PHY) API + * + * Copyright (c) 2009 Secret Lab Technologies, Ltd. + * + * This file is released under the GPLv2 + * + * This file provides helper functions for extracting PHY device information + * out of the OpenFirmware device tree and using it to populate an mii_bus. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +MODULE_AUTHOR("Grant Likely "); +MODULE_LICENSE("GPL"); + +/** + * of_mdiobus_register - Register mii_bus and create PHYs from the device tree + * @mdio: pointer to mii_bus structure + * @np: pointer to device_node of MDIO bus. + * + * This function registers the mii_bus structure and registers a phy_device + * for each child node of @np. + */ +int of_mdiobus_register(struct mii_bus *mdio, struct device_node *np) +{ + struct phy_device *phy; + struct device_node *child; + int rc, i; + + /* Mask out all PHYs from auto probing. Instead the PHYs listed in + * the device tree are populated after the bus has been registered */ + mdio->phy_mask = ~0; + + /* Clear all the IRQ properties */ + if (mdio->irq) + for (i=0; iirq[i] = PHY_POLL; + + /* Register the MDIO bus */ + rc = mdiobus_register(mdio); + if (rc) + return rc; + + /* Loop over the child nodes and register a phy_device for each one */ + for_each_child_of_node(np, child) { + const __be32 *addr; + int len; + + /* A PHY must have a reg property in the range [0-31] */ + addr = of_get_property(child, "reg", &len); + if (!addr || len < sizeof(*addr) || *addr >= 32 || *addr < 0) { + dev_err(&mdio->dev, "%s has invalid PHY address\n", + child->full_name); + continue; + } + + if (mdio->irq) { + mdio->irq[*addr] = irq_of_parse_and_map(child, 0); + if (!mdio->irq[*addr]) + mdio->irq[*addr] = PHY_POLL; + } + + phy = get_phy_device(mdio, be32_to_cpup(addr)); + if (!phy || IS_ERR(phy)) { + dev_err(&mdio->dev, "error probing PHY at address %i\n", + *addr); + continue; + } + phy_scan_fixups(phy); + + /* Associate the OF node with the device structure so it + * can be looked up later */ + of_node_get(child); + phy->dev.of_node = child; + + /* All data is now stored in the phy struct; register it */ + rc = phy_device_register(phy); + if (rc) { + phy_device_free(phy); + of_node_put(child); + continue; + } + + dev_dbg(&mdio->dev, "registered phy %s at address %i\n", + child->name, *addr); + } + + return 0; +} +EXPORT_SYMBOL(of_mdiobus_register); + +/* Helper function for of_phy_find_device */ +static int of_phy_match(struct device *dev, void *phy_np) +{ + return dev->of_node == phy_np; +} + +/** + * of_phy_find_device - Give a PHY node, find the phy_device + * @phy_np: Pointer to the phy's device tree node + * + * Returns a pointer to the phy_device. + */ +struct phy_device *of_phy_find_device(struct device_node *phy_np) +{ + struct device *d; + if (!phy_np) + return NULL; + + d = bus_find_device(&mdio_bus_type, NULL, phy_np, of_phy_match); + return d ? to_phy_device(d) : NULL; +} +EXPORT_SYMBOL(of_phy_find_device); + +/** + * of_phy_connect - Connect to the phy described in the device tree + * @dev: pointer to net_device claiming the phy + * @phy_np: Pointer to device tree node for the PHY + * @hndlr: Link state callback for the network device + * @iface: PHY data interface type + * + * Returns a pointer to the phy_device if successfull. NULL otherwise + */ +struct phy_device *of_phy_connect(struct net_device *dev, + struct device_node *phy_np, + void (*hndlr)(struct net_device *), u32 flags, + phy_interface_t iface) +{ + struct phy_device *phy = of_phy_find_device(phy_np); + + if (!phy) + return NULL; + + return phy_connect_direct(dev, phy, hndlr, flags, iface) ? NULL : phy; +} +EXPORT_SYMBOL(of_phy_connect); + +/** + * of_phy_connect_fixed_link - Parse fixed-link property and return a dummy phy + * @dev: pointer to net_device claiming the phy + * @hndlr: Link state callback for the network device + * @iface: PHY data interface type + * + * This function is a temporary stop-gap and will be removed soon. It is + * only to support the fs_enet, ucc_geth and gianfar Ethernet drivers. Do + * not call this function from new drivers. + */ +struct phy_device *of_phy_connect_fixed_link(struct net_device *dev, + void (*hndlr)(struct net_device *), + phy_interface_t iface) +{ + struct device_node *net_np; + char bus_id[MII_BUS_ID_SIZE + 3]; + struct phy_device *phy; + const __be32 *phy_id; + int sz; + + if (!dev->dev.parent) + return NULL; + + net_np = dev->dev.parent->of_node; + if (!net_np) + return NULL; + + phy_id = of_get_property(net_np, "fixed-link", &sz); + if (!phy_id || sz < sizeof(*phy_id)) + return NULL; + + sprintf(bus_id, PHY_ID_FMT, "0", be32_to_cpu(phy_id[0])); + + phy = phy_connect(dev, bus_id, hndlr, 0, iface); + return IS_ERR(phy) ? NULL : phy; +} +EXPORT_SYMBOL(of_phy_connect_fixed_link); diff --git a/pool/shard000/C/0015073_vdelay.c b/pool/shard000/C/0015073_vdelay.c new file mode 100644 index 0000000000000000000000000000000000000000..fab70ed034a574632217dd395746ba2e652b6732 --- /dev/null +++ b/pool/shard000/C/0015073_vdelay.c @@ -0,0 +1,75 @@ +#include +#include "plumber.h" + +typedef struct { + sp_vdelay *vdelay; + SPFLOAT prev; +} sporth_vdelay_d; + +int sporth_vdelay(sporth_stack *stack, void *ud) +{ + plumber_data *pd = ud; + SPFLOAT in; + SPFLOAT out; + SPFLOAT maxdel; + SPFLOAT feedback; + SPFLOAT del; + sporth_vdelay_d *vd; + + switch(pd->mode) { + case PLUMBER_CREATE: + +#ifdef DEBUG_MODE + fprintf(stderr, "vdelay: Creating\n"); +#endif + vd = malloc(sizeof(sporth_vdelay_d)); + sp_vdelay_create(&vd->vdelay); + plumber_add_module(pd, SPORTH_VDELAY, sizeof(sporth_vdelay_d), vd); + break; + case PLUMBER_INIT: + +#ifdef DEBUG_MODE + fprintf(stderr, "vdelay: Initialising\n"); +#endif + + if(sporth_check_args(stack, "ffff") != SPORTH_OK) { + fprintf(stderr,"Not enough arguments for vdelay\n"); + stack->error++; + return PLUMBER_NOTOK; + } + maxdel = sporth_stack_pop_float(stack); + del = sporth_stack_pop_float(stack); + feedback = sporth_stack_pop_float(stack); + in = sporth_stack_pop_float(stack); + vd= pd->last->ud; + sp_vdelay_init(pd->sp, vd->vdelay, maxdel); + sporth_stack_push_float(stack, 0); + break; + case PLUMBER_COMPUTE: + if(sporth_check_args(stack, "ffff") != SPORTH_OK) { + fprintf(stderr,"Not enough arguments for vdelay\n"); + stack->error++; + return PLUMBER_NOTOK; + } + vd = pd->last->ud; + maxdel = sporth_stack_pop_float(stack); + del = sporth_stack_pop_float(stack); + feedback = sporth_stack_pop_float(stack); + in = sporth_stack_pop_float(stack); + in += vd->prev * feedback; + vd->vdelay->del = del; + sp_vdelay_compute(pd->sp, vd->vdelay, &in, &out); + sporth_stack_push_float(stack, out); + vd->prev = out; + break; + case PLUMBER_DESTROY: + vd= pd->last->ud; + sp_vdelay_destroy(&vd->vdelay); + free(vd); + break; + default: + fprintf(stderr, "vdelay: Uknown mode!\n"); + break; + } + return PLUMBER_OK; +} diff --git a/pool/shard000/C/0015086_ft_lstnew.c b/pool/shard000/C/0015086_ft_lstnew.c new file mode 100644 index 0000000000000000000000000000000000000000..2e0265bc81bea51ca23bdb1985cebe2f460adc3a --- /dev/null +++ b/pool/shard000/C/0015086_ft_lstnew.c @@ -0,0 +1,36 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* ft_lstnew.c :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: ncoden +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2014/11/06 15:38:29 by ncoden #+# #+# */ +/* Updated: 2014/11/08 13:34:39 by ncoden ### ########.fr */ +/* */ +/* ************************************************************************** */ + +#include "libft.h" + +t_list *ft_lstnew(void const *content, size_t content_size) +{ + t_list *lst; + + lst = (t_list *)ft_memalloc(sizeof(t_list)); + if (lst != NULL) + { + if (content != NULL) + { + lst->content = ft_memalloc(content_size); + ft_memcpy(lst->content, content, content_size); + lst->content_size = content_size; + } + else + { + lst->content = NULL; + lst->content_size = 0; + } + lst->next = NULL; + } + return (lst); +} diff --git a/pool/shard000/C/0015104_wait_q.c b/pool/shard000/C/0015104_wait_q.c new file mode 100644 index 0000000000000000000000000000000000000000..c50bb6922fc372ca5affb84f966988c89b352870 --- /dev/null +++ b/pool/shard000/C/0015104_wait_q.c @@ -0,0 +1,51 @@ +/* wait queue for multiple fibers on nanokernel objects */ + +/* + * Copyright (c) 2015 Wind River Systems, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +#include + + +/* + * Remove first fiber from a wait queue and put it on the ready queue, knowing + * that the wait queue is not empty. + */ + +static struct tcs *_nano_wait_q_remove_no_check(struct _nano_queue *wait_q) +{ + struct tcs *tcs = wait_q->head; + + if (wait_q->tail == wait_q->head) { + _nano_wait_q_reset(wait_q); + } else { + wait_q->head = tcs->link; + } + tcs->link = 0; + + _nano_fiber_ready(tcs); + return tcs; +} + +/* + * Remove first fiber from a wait queue and put it on the ready queue. + * Abort and return NULL if the wait queue is empty. + */ +struct tcs *_nano_wait_q_remove(struct _nano_queue *wait_q) +{ + return wait_q->head ? _nano_wait_q_remove_no_check(wait_q) : NULL; +} diff --git a/pool/shard000/C/0015111_e_cosh.c b/pool/shard000/C/0015111_e_cosh.c new file mode 100644 index 0000000000000000000000000000000000000000..030b6b4d9a1c67af0b7ebf547c96256936dad47f --- /dev/null +++ b/pool/shard000/C/0015111_e_cosh.c @@ -0,0 +1,95 @@ +/* @(#)e_cosh.c 5.1 93/09/24 */ +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunPro, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ + +/* LINTLIBRARY */ + +/* cosh(x) + * Method : + * mathematically cosh(x) if defined to be (exp(x)+exp(-x))/2 + * 1. Replace x by |x| (cosh(x) = cosh(-x)). + * 2. + * [ exp(x) - 1 ]^2 + * 0 <= x <= ln2/2 : cosh(x) := 1 + ------------------- + * 2*exp(x) + * + * exp(x) + 1/exp(x) + * ln2/2 <= x <= 22 : cosh(x) := ------------------- + * 2 + * 22 <= x <= lnovft : cosh(x) := exp(x)/2 + * lnovft <= x <= ln2ovft: cosh(x) := exp(x/2)/2 * exp(x/2) + * ln2ovft < x : cosh(x) := huge*huge (overflow) + * + * Special cases: + * cosh(x) is |x| if x is +INF, -INF, or NaN. + * only cosh(0)=1 is exact for finite x. + */ + +#include +#include +#include + +#include "math_private.h" + +static const double one = 1.0, half=0.5, huge = 1.0e300; + +double +cosh(double x) +{ + double t,w; + int32_t ix; + u_int32_t lx; + + /* High word of |x|. */ + GET_HIGH_WORD(ix,x); + ix &= 0x7fffffff; + + /* x is INF or NaN */ + if(ix>=0x7ff00000) return x*x; + + /* |x| in [0,0.5*ln2], return 1+expm1(|x|)^2/(2*exp(|x|)) */ + if(ix<0x3fd62e43) { + t = expm1(fabs(x)); + w = one+t; + if (ix<0x3c800000) return w; /* cosh(tiny) = 1 */ + return one+(t*t)/(w+w); + } + + /* |x| in [0.5*ln2,22], return (exp(|x|)+1/exp(|x|)/2; */ + if (ix < 0x40360000) { + t = exp(fabs(x)); + return half*t+half/t; + } + + /* |x| in [22, log(maxdouble)] return half*exp(|x|) */ + if (ix < 0x40862E42) return half*exp(fabs(x)); + + /* |x| in [log(maxdouble), overflowthresold] */ + GET_LOW_WORD(lx,x); + if (ix<0x408633CE || + ((ix==0x408633ce)&&(lx<=(u_int32_t)0x8fb9f87d))) { + w = exp(half*fabs(x)); + t = half*w; + return t*w; + } + + /* |x| > overflowthresold, cosh(x) overflow */ + return huge*huge; +} + +#if LDBL_MANT_DIG == 53 +#ifdef lint +/* PROTOLIB1 */ +long double coshl(long double); +#else /* lint */ +__weak_alias(coshl, cosh); +#endif /* lint */ +#endif /* LDBL_MANT_DIG == 53 */ diff --git a/pool/shard000/C/0015115_env_ubi.c b/pool/shard000/C/0015115_env_ubi.c new file mode 100644 index 0000000000000000000000000000000000000000..1ed8b02e86ee7099d94836b4a88e73082f7f4f11 --- /dev/null +++ b/pool/shard000/C/0015115_env_ubi.c @@ -0,0 +1,220 @@ +/* + * (c) Copyright 2012 by National Instruments, + * Joe Hershberger + * + * See file CREDITS for list of people who contributed to this + * project. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of + * the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, + * MA 02111-1307 USA + */ + +#include + +#include +#include +#include +#include +#include +#include +#undef crc32 + +char *env_name_spec = "UBI"; + +env_t *env_ptr; + +DECLARE_GLOBAL_DATA_PTR; + +int env_init(void) +{ + /* use default */ + gd->env_addr = (ulong)&default_environment[0]; + gd->env_valid = 1; + + return 0; +} + +#ifdef CONFIG_CMD_SAVEENV +#ifdef CONFIG_SYS_REDUNDAND_ENVIRONMENT +static unsigned char env_flags; + +int saveenv(void) +{ + ALLOC_CACHE_ALIGN_BUFFER(env_t, env_new, 1); + ssize_t len; + char *res; + + res = (char *)&env_new->data; + len = hexport_r(&env_htab, '\0', 0, &res, ENV_SIZE, 0, NULL); + if (len < 0) { + error("Cannot export environment: errno = %d\n", errno); + return 1; + } + + if (ubi_part(CONFIG_ENV_UBI_PART, NULL)) { + printf("\n** Cannot find mtd partition \"%s\"\n", + CONFIG_ENV_UBI_PART); + return 1; + } + + env_new->crc = crc32(0, env_new->data, ENV_SIZE); + env_new->flags = ++env_flags; /* increase the serial */ + + if (gd->env_valid == 1) { + puts("Writing to redundant UBI... "); + if (ubi_volume_write(CONFIG_ENV_UBI_VOLUME_REDUND, + (void *)env_new, CONFIG_ENV_SIZE)) { + printf("\n** Unable to write env to %s:%s **\n", + CONFIG_ENV_UBI_PART, + CONFIG_ENV_UBI_VOLUME_REDUND); + return 1; + } + } else { + puts("Writing to UBI... "); + if (ubi_volume_write(CONFIG_ENV_UBI_VOLUME, + (void *)env_new, CONFIG_ENV_SIZE)) { + printf("\n** Unable to write env to %s:%s **\n", + CONFIG_ENV_UBI_PART, + CONFIG_ENV_UBI_VOLUME); + return 1; + } + } + + puts("done\n"); + + gd->env_valid = gd->env_valid == 2 ? 1 : 2; + + return 0; +} +#else /* ! CONFIG_SYS_REDUNDAND_ENVIRONMENT */ +int saveenv(void) +{ + ALLOC_CACHE_ALIGN_BUFFER(env_t, env_new, 1); + ssize_t len; + char *res; + + res = (char *)&env_new->data; + len = hexport_r(&env_htab, '\0', 0, &res, ENV_SIZE, 0, NULL); + if (len < 0) { + error("Cannot export environment: errno = %d\n", errno); + return 1; + } + + if (ubi_part(CONFIG_ENV_UBI_PART, NULL)) { + printf("\n** Cannot find mtd partition \"%s\"\n", + CONFIG_ENV_UBI_PART); + return 1; + } + + env_new->crc = crc32(0, env_new->data, ENV_SIZE); + + if (ubi_volume_write(CONFIG_ENV_UBI_VOLUME, (void *)env_new, + CONFIG_ENV_SIZE)) { + printf("\n** Unable to write env to %s:%s **\n", + CONFIG_ENV_UBI_PART, CONFIG_ENV_UBI_VOLUME); + return 1; + } + + puts("done\n"); + return 0; +} +#endif /* CONFIG_SYS_REDUNDAND_ENVIRONMENT */ +#endif /* CONFIG_CMD_SAVEENV */ + +#ifdef CONFIG_SYS_REDUNDAND_ENVIRONMENT +void env_relocate_spec(void) +{ + ALLOC_CACHE_ALIGN_BUFFER(char, env1_buf, CONFIG_ENV_SIZE); + ALLOC_CACHE_ALIGN_BUFFER(char, env2_buf, CONFIG_ENV_SIZE); + int crc1_ok = 0, crc2_ok = 0; + env_t *ep, *tmp_env1, *tmp_env2; + + tmp_env1 = (env_t *)env1_buf; + tmp_env2 = (env_t *)env2_buf; + + if (ubi_part(CONFIG_ENV_UBI_PART, NULL)) { + printf("\n** Cannot find mtd partition \"%s\"\n", + CONFIG_ENV_UBI_PART); + set_default_env(NULL); + return; + } + + if (ubi_volume_read(CONFIG_ENV_UBI_VOLUME, (void *)tmp_env1, + CONFIG_ENV_SIZE)) { + printf("\n** Unable to read env from %s:%s **\n", + CONFIG_ENV_UBI_PART, CONFIG_ENV_UBI_VOLUME); + } + + if (ubi_volume_read(CONFIG_ENV_UBI_VOLUME_REDUND, (void *)tmp_env2, + CONFIG_ENV_SIZE)) { + printf("\n** Unable to read redundant env from %s:%s **\n", + CONFIG_ENV_UBI_PART, CONFIG_ENV_UBI_VOLUME_REDUND); + } + + crc1_ok = crc32(0, tmp_env1->data, ENV_SIZE) == tmp_env1->crc; + crc2_ok = crc32(0, tmp_env2->data, ENV_SIZE) == tmp_env2->crc; + + if (!crc1_ok && !crc2_ok) { + set_default_env("!bad CRC"); + return; + } else if (crc1_ok && !crc2_ok) { + gd->env_valid = 1; + } else if (!crc1_ok && crc2_ok) { + gd->env_valid = 2; + } else { + /* both ok - check serial */ + if (tmp_env1->flags == 255 && tmp_env2->flags == 0) + gd->env_valid = 2; + else if (tmp_env2->flags == 255 && tmp_env1->flags == 0) + gd->env_valid = 1; + else if (tmp_env1->flags > tmp_env2->flags) + gd->env_valid = 1; + else if (tmp_env2->flags > tmp_env1->flags) + gd->env_valid = 2; + else /* flags are equal - almost impossible */ + gd->env_valid = 1; + } + + if (gd->env_valid == 1) + ep = tmp_env1; + else + ep = tmp_env2; + + env_flags = ep->flags; + env_import((char *)ep, 0); +} +#else /* ! CONFIG_SYS_REDUNDAND_ENVIRONMENT */ +void env_relocate_spec(void) +{ + ALLOC_CACHE_ALIGN_BUFFER(char, buf, CONFIG_ENV_SIZE); + + if (ubi_part(CONFIG_ENV_UBI_PART, NULL)) { + printf("\n** Cannot find mtd partition \"%s\"\n", + CONFIG_ENV_UBI_PART); + set_default_env(NULL); + return; + } + + if (ubi_volume_read(CONFIG_ENV_UBI_VOLUME, (void *)&buf, + CONFIG_ENV_SIZE)) { + printf("\n** Unable to read env from %s:%s **\n", + CONFIG_ENV_UBI_PART, CONFIG_ENV_UBI_VOLUME); + set_default_env(NULL); + return; + } + + env_import(buf, 1); +} +#endif /* CONFIG_SYS_REDUNDAND_ENVIRONMENT */ diff --git a/pool/shard000/C/0015120_4-9.c b/pool/shard000/C/0015120_4-9.c new file mode 100644 index 0000000000000000000000000000000000000000..ace6fead1b5b8d5cd6f25e4ae00fa1706c305642 --- /dev/null +++ b/pool/shard000/C/0015120_4-9.c @@ -0,0 +1,19 @@ +/* Since EOF is defined to be -1, it is an integer type. Therefore, to handle a pushed-back EOF correctly, buf should be of int data type. */ + +#define BUFSIZE 100 + +int buf[BUFSIZE]; /* buffer for ungetch */ +int bufp = 0; /* next free position in buf */ + +int getch(void) /* get a (possibly pushed back) character */ +{ + return (bufp > 0) ? buf[--bufp] : getchar(); +} + +void ungetch(int c) /* push character back on input */ +{ + if (bufp >= BUFSIZE) + printf("ungetch: too many characters\n"); + else + buf[bufp++] = c; +} diff --git a/pool/shard000/C/0015123_test.c b/pool/shard000/C/0015123_test.c new file mode 100644 index 0000000000000000000000000000000000000000..859090d019274797cf35424613029de39998f2a8 --- /dev/null +++ b/pool/shard000/C/0015123_test.c @@ -0,0 +1,195 @@ + +#include +#include +#include "CUnit/Basic.h" +#include "inc/PriorityQueue.h" + + + + + +PQueue * pq = NULL; +int init_suite1(void) // 0 Success. ? - Falha +{ + pq = NewPQueue(); + return 0; +} + +/* The suite cleanup function. + * + * Returns zero on success, non-zero otherwise. + */ +int clean_suite1(void) +{ + CleanPQueue(pq); + return 0; +} + +/* Simple test of fprintf(). + * Writes test data to the temporary file and checks + * whether the expected number of bytes were written. + */ +void testFPRINTF(void) +{ + int i1 = 10; + +// if (NULL != temp_file) { + // CU_ASSERT(0 == fprintf(temp_file, "")); + // CU_ASSERT(2 == fprintf(temp_file, "Q\n")); + // CU_ASSERT(7 == fprintf(temp_file, "i1 = %d", i1)); + // } +} + +/* Simple test of fread(). + * Reads the data previously written by testFPRINTF() + * and checks whether the expected characters are present. + * Must be run after testFPRINTF(). + */ +void testFREAD(void) +{ + unsigned char buffer[20]; + + // if (NULL != temp_file) { + // rewind(temp_file); + // CU_ASSERT(9 == fread(buffer, sizeof(unsigned char), 20, temp_file)); + // CU_ASSERT(0 == strncmp(buffer, "Q\ni1 = 10", 9)); + //} +} + +/* The main() function for setting up and running the tests. + * Returns a CUE_SUCCESS on successful running, another + * CUnit error code on failure. + */ + + +void testeinsercoes_simples(void) +{ + CU_ASSERT_EQUAL(Enqueue(pq,1,1), 0); + CU_ASSERT_EQUAL(Enqueue(pq,2,4), 1); + CU_ASSERT_EQUAL(Enqueue(pq,3,3), 2); +} +void testeremocoes_simples(void) +{ + CU_ASSERT_EQUAL(Dequeue(pq),2); + CU_ASSERT_EQUAL(Dequeue(pq),3); + CU_ASSERT_EQUAL(Dequeue(pq),1); + CleanPQueue(pq); + CU_ASSERT_EQUAL(GetPQueueSize(pq),0); +} + +void teste2insercoes_simples(void) +{ + CU_ASSERT_EQUAL(Enqueue(pq,1,1), 0); + CU_ASSERT_EQUAL(Enqueue(pq,2,4), 1); + CU_ASSERT_EQUAL(Enqueue(pq,3,3), 2); +} + +void remocoesvazias(void) +{ + Dequeue(pq); + Dequeue(pq); + CU_ASSERT_EQUAL(GetPQueueSize(pq),0); +} +void insercaocomeco(void) +{ + Enqueue(pq, 10, 10); + CU_ASSERT_EQUAL(Dequeue(pq),10); + Enqueue(pq, 10, 10); + Enqueue(pq,15,10); + CU_ASSERT_EQUAL(Dequeue(pq),10); + CleanPQueue(pq); +} + +void insercaomeio(void){ + Enqueue(pq, 10,15); + Enqueue(pq, 20, 30); + CU_ASSERT_EQUAL(Enqueue(pq,30, 20),2); + CU_ASSERT_EQUAL(Dequeue(pq),20); + CleanPQueue(pq); +} + +void insercaofim(void) +{ + Enqueue(pq, 10, 100); + Enqueue(pq, 20, 90); + CU_ASSERT_EQUAL(Enqueue(pq,30,80),2); + Enqueue(pq,40,80); + Dequeue(pq); + Dequeue(pq); + CU_ASSERT_EQUAL(Dequeue(pq),30); + CleanPQueue(pq); +} + + +void testeAbsurdo(void) +{ + Enqueue(pq,10,-10); + Enqueue(pq,50,50); + Enqueue(pq,20,300); + CU_ASSERT_EQUAL(Dequeue(pq),20); + CU_ASSERT_EQUAL(Dequeue(pq),50); + CU_ASSERT_EQUAL(Dequeue(pq),10); +} + + + +int main() +{ + CU_pSuite pSuite = NULL; + + /* initialize the CUnit test registry */ + if (CUE_SUCCESS != CU_initialize_registry()) + return CU_get_error(); + + /* add a suite to the registry */ + pSuite = CU_add_suite("Suite_1 Simples", init_suite1, clean_suite1); + if (NULL == pSuite) { + CU_cleanup_registry(); + return CU_get_error(); + } + + + /* add the tests to the suite */ + /* NOTE - ORDER IS IMPORTANT - MUST TEST fread() AFTER fprintf() */ + if ( + (NULL == CU_add_test(pSuite, "Teste de Insercoes Simples()", testeinsercoes_simples) ) + || + (NULL == CU_add_test(pSuite, "Teste de Remocoes Simples()", testeremocoes_simples) ) + || + (NULL == CU_add_test(pSuite, "Teste de Insercoes pos limpo()", teste2insercoes_simples) ) + ) + { + CU_cleanup_registry(); + return CU_get_error(); + } + + + CU_pSuite pSuite2 = NULL; + pSuite2 = CU_add_suite("Suite_2 Casos Estranhos", init_suite1, clean_suite1); + if (NULL == pSuite2) { + CU_cleanup_registry(); + return CU_get_error(); + } + + if ((NULL == CU_add_test(pSuite2, "Texte de Insercoes Comeco()", insercaocomeco) ) + || + (NULL == CU_add_test(pSuite2, "Texte de Insercoes Meio()", insercaomeio) + ) + || + (NULL == CU_add_test(pSuite2, "Texte de Insercoes Fins()",insercaofim)) + || + ((NULL == CU_add_test(pSuite2, "Texte absurdo()",testeAbsurdo)) + ) + ) + { + CU_cleanup_registry(); + return CU_get_error(); + } + + + /* Run all tests using the CUnit Basic interface */ + CU_basic_set_mode(CU_BRM_VERBOSE); + CU_basic_run_tests(); + CU_cleanup_registry(); + return CU_get_error(); +} diff --git a/pool/shard000/C/0015125_highmem.c b/pool/shard000/C/0015125_highmem.c new file mode 100644 index 0000000000000000000000000000000000000000..8c535318ef9bf9cdf92115f35ba2a9f4f15726e3 --- /dev/null +++ b/pool/shard000/C/0015125_highmem.c @@ -0,0 +1,132 @@ +#include +#include +#include +#include +#include +#include + +static pte_t *kmap_pte; + +unsigned long highstart_pfn, highend_pfn; + +void *__kmap(struct page *page) +{ + void *addr; + + might_sleep(); + if (!PageHighMem(page)) + return page_address(page); + addr = kmap_high(page); + flush_tlb_one((unsigned long)addr); + + return addr; +} +EXPORT_SYMBOL(__kmap); + +void __kunmap(struct page *page) +{ + BUG_ON(in_interrupt()); + if (!PageHighMem(page)) + return; + kunmap_high(page); +} +EXPORT_SYMBOL(__kunmap); + +/* + * kmap_atomic/kunmap_atomic is significantly faster than kmap/kunmap because + * no global lock is needed and because the kmap code must perform a global TLB + * invalidation when the kmap pool wraps. + * + * However when holding an atomic kmap is is not legal to sleep, so atomic + * kmaps are appropriate for short, tight code paths only. + */ + +void *__kmap_atomic(struct page *page, enum km_type type) +{ + enum fixed_addresses idx; + unsigned long vaddr; + + /* even !CONFIG_PREEMPT needs this, for in_atomic in do_page_fault */ + pagefault_disable(); + if (!PageHighMem(page)) + return page_address(page); + + debug_kmap_atomic(type); + idx = type + KM_TYPE_NR*smp_processor_id(); + vaddr = __fix_to_virt(FIX_KMAP_BEGIN + idx); +#ifdef CONFIG_DEBUG_HIGHMEM + BUG_ON(!pte_none(*(kmap_pte - idx))); +#endif + set_pte(kmap_pte-idx, mk_pte(page, PAGE_KERNEL)); + local_flush_tlb_one((unsigned long)vaddr); + + return (void*) vaddr; +} +EXPORT_SYMBOL(__kmap_atomic); + +void __kunmap_atomic_notypecheck(void *kvaddr, enum km_type type) +{ +#ifdef CONFIG_DEBUG_HIGHMEM + unsigned long vaddr = (unsigned long) kvaddr & PAGE_MASK; + enum fixed_addresses idx = type + KM_TYPE_NR*smp_processor_id(); + + if (vaddr < FIXADDR_START) { + pagefault_enable(); + return; + } + + BUG_ON(vaddr != __fix_to_virt(FIX_KMAP_BEGIN + idx)); + + /* + * force other mappings to Oops if they'll try to access + * this pte without first remap it + */ + pte_clear(&init_mm, vaddr, kmap_pte-idx); + local_flush_tlb_one(vaddr); +#endif + + pagefault_enable(); +} +EXPORT_SYMBOL(__kunmap_atomic_notypecheck); + +/* + * This is the same as kmap_atomic() but can map memory that doesn't + * have a struct page associated with it. + */ +void *kmap_atomic_pfn(unsigned long pfn, enum km_type type) +{ + enum fixed_addresses idx; + unsigned long vaddr; + + pagefault_disable(); + + debug_kmap_atomic(type); + idx = type + KM_TYPE_NR*smp_processor_id(); + vaddr = __fix_to_virt(FIX_KMAP_BEGIN + idx); + set_pte(kmap_pte-idx, pfn_pte(pfn, PAGE_KERNEL)); + flush_tlb_one(vaddr); + + return (void*) vaddr; +} + +struct page *__kmap_atomic_to_page(void *ptr) +{ + unsigned long idx, vaddr = (unsigned long)ptr; + pte_t *pte; + + if (vaddr < FIXADDR_START) + return virt_to_page(ptr); + + idx = virt_to_fix(vaddr); + pte = kmap_pte - (idx - FIX_KMAP_BEGIN); + return pte_page(*pte); +} + +void __init kmap_init(void) +{ + unsigned long kmap_vstart; + + /* cache the first kmap pte */ + kmap_vstart = __fix_to_virt(FIX_KMAP_BEGIN); + kmap_pte = kmap_get_fixmap_pte(kmap_vstart); +} diff --git a/pool/shard000/C/0015128_main.c b/pool/shard000/C/0015128_main.c new file mode 100644 index 0000000000000000000000000000000000000000..d8cf787112a6dc27132ccae22b6ea86f313790ab --- /dev/null +++ b/pool/shard000/C/0015128_main.c @@ -0,0 +1,207 @@ +/** + ****************************************************************************** + * @file TIM/PWM_Output/main.c + * @author MCD Application Team + * @version V3.1.2 + * @date 09/28/2009 + * @brief Main program body + ****************************************************************************** + * @copy + * + * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS + * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE + * TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY + * DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING + * FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE + * CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. + * + *

© COPYRIGHT 2009 STMicroelectronics

+ */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f10x.h" + +/** @addtogroup STM32F10x_StdPeriph_Examples + * @{ + */ + +/** @addtogroup TIM_PWM_Output + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure; +TIM_OCInitTypeDef TIM_OCInitStructure; +uint16_t CCR1_Val = 500; +uint16_t CCR2_Val = 375; +uint16_t CCR3_Val = 250; +uint16_t CCR4_Val = 125; +ErrorStatus HSEStartUpStatus; + +/* Private function prototypes -----------------------------------------------*/ +void RCC_Configuration(void); +void GPIO_Configuration(void); + +/* Private functions ---------------------------------------------------------*/ + +/** + * @brief Main program + * @param None + * @retval None + */ +int main(void) +{ + /* System Clocks Configuration */ + RCC_Configuration(); + + /* GPIO Configuration */ + GPIO_Configuration(); + + /* ----------------------------------------------------------------------- + TIM3 Configuration: generate 4 PWM signals with 4 different duty cycles: + TIM3CLK = 36 MHz, Prescaler = 0x0, TIM3 counter clock = 36 MHz + TIM3 ARR Register = 999 => TIM3 Frequency = TIM3 counter clock/(ARR + 1) + TIM3 Frequency = 36 KHz. + TIM3 Channel1 duty cycle = (TIM3_CCR1/ TIM3_ARR)* 100 = 50% + TIM3 Channel2 duty cycle = (TIM3_CCR2/ TIM3_ARR)* 100 = 37.5% + TIM3 Channel3 duty cycle = (TIM3_CCR3/ TIM3_ARR)* 100 = 25% + TIM3 Channel4 duty cycle = (TIM3_CCR4/ TIM3_ARR)* 100 = 12.5% + ----------------------------------------------------------------------- */ + + /* Time base configuration */ + TIM_TimeBaseStructure.TIM_Period = 999; + TIM_TimeBaseStructure.TIM_Prescaler = 0; + TIM_TimeBaseStructure.TIM_ClockDivision = 0; + TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; + + TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure); + + /* PWM1 Mode configuration: Channel1 */ + TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1; + TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; + TIM_OCInitStructure.TIM_Pulse = CCR1_Val; + TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High; + + TIM_OC1Init(TIM3, &TIM_OCInitStructure); + + TIM_OC1PreloadConfig(TIM3, TIM_OCPreload_Enable); + + /* PWM1 Mode configuration: Channel2 */ + TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; + TIM_OCInitStructure.TIM_Pulse = CCR2_Val; + + TIM_OC2Init(TIM3, &TIM_OCInitStructure); + + TIM_OC2PreloadConfig(TIM3, TIM_OCPreload_Enable); + + /* PWM1 Mode configuration: Channel3 */ + TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; + TIM_OCInitStructure.TIM_Pulse = CCR3_Val; + + TIM_OC3Init(TIM3, &TIM_OCInitStructure); + + TIM_OC3PreloadConfig(TIM3, TIM_OCPreload_Enable); + + /* PWM1 Mode configuration: Channel4 */ + TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; + TIM_OCInitStructure.TIM_Pulse = CCR4_Val; + + TIM_OC4Init(TIM3, &TIM_OCInitStructure); + + TIM_OC4PreloadConfig(TIM3, TIM_OCPreload_Enable); + + TIM_ARRPreloadConfig(TIM3, ENABLE); + + /* TIM3 enable counter */ + TIM_Cmd(TIM3, ENABLE); + + while (1) + {} +} + +/** + * @brief Configures the different system clocks. + * @param None + * @retval None + */ +void RCC_Configuration(void) +{ + /* Setup the microcontroller system. Initialize the Embedded Flash Interface, + initialize the PLL and update the SystemFrequency variable. */ + SystemInit(); + + /* PCLK1 = HCLK/4 */ + RCC_PCLK1Config(RCC_HCLK_Div4); + + /* TIM3 clock enable */ + RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE); + + /* GPIOA and GPIOB clock enable */ + RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOB | + RCC_APB2Periph_GPIOC | RCC_APB2Periph_AFIO, ENABLE); + +} + +/** + * @brief Configure the TIM3 Ouput Channels. + * @param None + * @retval None + */ +void GPIO_Configuration(void) +{ + GPIO_InitTypeDef GPIO_InitStructure; + +#ifdef STM32F10X_CL + /*GPIOB Configuration: TIM3 channel1, 2, 3 and 4 */ + GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7 | GPIO_Pin_8 | GPIO_Pin_9; + GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; + GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; + + GPIO_Init(GPIOC, &GPIO_InitStructure); + + GPIO_PinRemapConfig(GPIO_FullRemap_TIM3, ENABLE); + +#else + /* GPIOA Configuration:TIM3 Channel1, 2, 3 and 4 as alternate function push-pull */ + GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7; + GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; + GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; + + GPIO_Init(GPIOA, &GPIO_InitStructure); + + GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1; + GPIO_Init(GPIOB, &GPIO_InitStructure); +#endif +} + +#ifdef USE_FULL_ASSERT + +/** + * @brief Reports the name of the source file and the source line number + * where the assert_param error has occurred. + * @param file: pointer to the source file name + * @param line: assert_param error line source number + * @retval None + */ +void assert_failed(uint8_t* file, uint32_t line) +{ + /* User can add his own implementation to report the file name and line number, + ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ + + while (1) + {} +} +#endif + +/** + * @} + */ + +/** + * @} + */ + +/******************* (C) COPYRIGHT 2009 STMicroelectronics *****END OF FILE****/ diff --git a/pool/shard000/C/0015153_derpspan.c b/pool/shard000/C/0015153_derpspan.c new file mode 100644 index 0000000000000000000000000000000000000000..b9fb36264af7be477b40f62273fb99d0b82009ec --- /dev/null +++ b/pool/shard000/C/0015153_derpspan.c @@ -0,0 +1,48 @@ +// gcc -O2 -o derspan derspan.c -lpcap -std=gnu99 -Wall + +#include +#include +#include +#include +#include + +int rawsock; + +void my_callback(u_char *user, const struct pcap_pkthdr *h, const u_char *bytes) +{ + int len = h->caplen; + if (len < 40) { + //printf("skipped short packet\n"); + return; + } + if (bytes[14] != 0x88 || bytes[15] != 0xbe) { + //printf("skipped non-ethernet packet\n"); + return; + } + if (bytes[36] != 0x08 || bytes[37] != 0x00) { + //printf("skipped non-IPv4 packet\n"); + return; + } + + struct sockaddr_in self; + self.sin_family = AF_INET; + self.sin_addr.s_addr = htonl(0x7f000001); // localhost + self.sin_port = htons(1337); + + sendto(rawsock, bytes + 38, len - 38, 0, (struct sockaddr *)&self, sizeof(self)); +} + +int main(int argc, char **argv) +{ + rawsock = socket(AF_INET, SOCK_RAW, IPPROTO_RAW); + if (rawsock == -1) { + perror("socket"); + exit(0); + } + + pcap_t *pcap = pcap_open_live(argv[1], 1500, 1, 1000, NULL); + pcap_activate(pcap); + pcap_loop(pcap, -1, my_callback, NULL); + return 0; +} + diff --git a/pool/shard000/C/0015164_lge_uei_irrc.c b/pool/shard000/C/0015164_lge_uei_irrc.c new file mode 100644 index 0000000000000000000000000000000000000000..62d6fecfce7f607b4501e4f5c4c327ccdf6a0131 --- /dev/null +++ b/pool/shard000/C/0015164_lge_uei_irrc.c @@ -0,0 +1,166 @@ +/* +UEI_IRRC_DRIVER_FOR_MSM9860 +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +//#include +#include +#include +#include + +static int uei_irrc_probe(struct platform_device *pdev) +{ + struct uei_irrc_pdata_type *pdata = pdev->dev.platform_data; +#if defined(CONFIG_MACH_APQ8064_GVKT) + int rc = 0; +#endif + if(!pdata) + return -EINVAL; + + printk("%s\n", __FUNCTION__); +#if 0 + static struct regulator *IrRC_3v; + rc = -EINVAL; + + IrRC_3v = regulator_get(NULL, "8921_l10"); /* +3V0_IrRC */ + if (IS_ERR(IrRC_3v)) + { + pr_err("%s: regulator get of 8921_l10 failed (%ld)\n", __func__, PTR_ERR(IrRC_3v)); + rc = PTR_ERR(IrRC_3v); + } + + rc = regulator_set_voltage(IrRC_3v, 3000000, 3000000); + + if(rc) + { + pr_err("%s: regulator set of 8921_l10 failed (%ld)\n", __func__, PTR_ERR(IrRC_3v)); + } + + rc = regulator_enable(IrRC_3v); + + if(rc) + { + pr_err("%s: regulator enable of 8921_l10 failed (%ld)\n", __func__, PTR_ERR(IrRC_3v)); + } + + + gpio_request(pdata->en_gpio, "RC_LEVEL_EN"); + gpio_tlmm_config(GPIO_CFG(pdata->en_gpio, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), GPIO_CFG_ENABLE); + gpio_set_value(pdata->en_gpio,1); +#else +#if defined(CONFIG_MACH_APQ8064_GVDCM) + gpio_set_value_cansleep(VREG_3P0_IRDA_EN,1); + gpio_set_value_cansleep(GPIO_IRDA_PWDN, GPIO_IRDA_PWDN_DISABLE); +#endif + gpio_set_value(pdata->en_gpio,1); +#endif + +#if defined(CONFIG_MACH_APQ8064_GVKT) + if(lge_get_board_revno() == HW_REV_C ) { + rc = gpio_request(GPIO_IRDA_PORT_TX, "RC_IRDA_TX_EN"); + if(rc) + pr_err("%s: This port is busy (%d)\n", __func__, GPIO_IRDA_PORT_TX); + else { + gpio_tlmm_config(GPIO_CFG(GPIO_IRDA_PORT_TX, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), GPIO_CFG_ENABLE); + gpio_set_value(GPIO_IRDA_PORT_TX,0); + } + } +#endif + return 0; +} + +static int uei_irrc_remove(struct platform_device *pdev) +{ + + struct uei_irrc_pdata_type *pdata = platform_get_drvdata(pdev); + + printk(KERN_ERR "[UEI IrRC] remove (err:%d)\n", 104); + + pdata = NULL; + + return 0; +} + +static int uei_irrc_suspend(struct platform_device *pdev, pm_message_t state) +{ +#if defined(CONFIG_MACH_APQ8064_GVDCM) + struct uei_irrc_pdata_type *pdata = pdev->dev.platform_data; + + if(!pdata) + return -EINVAL; +#endif + printk("%s\n", __FUNCTION__); +#if defined(CONFIG_MACH_APQ8064_GVDCM) + gpio_set_value_cansleep(VREG_3P0_IRDA_EN,0); + gpio_set_value_cansleep(GPIO_IRDA_PWDN, GPIO_IRDA_PWDN_ENABLE); + gpio_set_value(pdata->en_gpio,0); +#endif + return 0; +} + +static int uei_irrc_resume(struct platform_device *pdev) +{ +#if defined(CONFIG_MACH_APQ8064_GVDCM) + struct uei_irrc_pdata_type *pdata = pdev->dev.platform_data; + + if(!pdata) + return -EINVAL; +#endif + printk("%s\n", __FUNCTION__); +#if defined(CONFIG_MACH_APQ8064_GVDCM) + gpio_set_value_cansleep(VREG_3P0_IRDA_EN,1); + gpio_set_value_cansleep(GPIO_IRDA_PWDN, GPIO_IRDA_PWDN_DISABLE); + gpio_set_value(pdata->en_gpio,1); +#endif + return 0; +} + +static struct platform_driver uei_irrc_driver = { + .probe = uei_irrc_probe, + .remove = uei_irrc_remove, + .suspend = uei_irrc_suspend, + .resume = uei_irrc_resume, + .driver = { + .name = UEI_IRRC_NAME, + .owner = THIS_MODULE, + }, +}; + +static int __init uei_irrc_init(void) +{ + int ret=0; + printk("%s\n", __FUNCTION__); + + ret = platform_driver_register(&uei_irrc_driver); + + if(ret) + printk("%s : init fail\n" ,__FUNCTION__); + + return ret; +} + +static void __exit uei_irrc_exit(void) +{ + printk("%s\n", __FUNCTION__); + + platform_driver_unregister(&uei_irrc_driver); +} + +module_init(uei_irrc_init); +module_exit(uei_irrc_exit); + +MODULE_AUTHOR("LG Electronics"); +MODULE_DESCRIPTION("UEI IrRC Driver"); +MODULE_LICENSE("GPL"); diff --git a/pool/shard000/C/0015168_pxa168.c b/pool/shard000/C/0015168_pxa168.c new file mode 100644 index 0000000000000000000000000000000000000000..7bc17eaa12eba3835392554aa893aff71641fdac --- /dev/null +++ b/pool/shard000/C/0015168_pxa168.c @@ -0,0 +1,225 @@ +/* + * linux/arch/arm/mach-mmp/pxa168.c + * + * Code specific to PXA168 + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + */ +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "common.h" +#include "clock.h" + +#define MFPR_VIRT_BASE (APB_VIRT_BASE + 0x1e000) + +static struct mfp_addr_map pxa168_mfp_addr_map[] __initdata = +{ + MFP_ADDR_X(GPIO0, GPIO36, 0x04c), + MFP_ADDR_X(GPIO37, GPIO55, 0x000), + MFP_ADDR_X(GPIO56, GPIO123, 0x0e0), + MFP_ADDR_X(GPIO124, GPIO127, 0x0f4), + + MFP_ADDR_END, +}; + +void __init pxa168_init_irq(void) +{ + icu_init_irq(); +} + +/* APB peripheral clocks */ +static APBC_CLK(uart1, PXA168_UART1, 1, 14745600); +static APBC_CLK(uart2, PXA168_UART2, 1, 14745600); +static APBC_CLK(uart3, PXA168_UART3, 1, 14745600); +static APBC_CLK(twsi0, PXA168_TWSI0, 1, 33000000); +static APBC_CLK(twsi1, PXA168_TWSI1, 1, 33000000); +static APBC_CLK(pwm1, PXA168_PWM1, 1, 13000000); +static APBC_CLK(pwm2, PXA168_PWM2, 1, 13000000); +static APBC_CLK(pwm3, PXA168_PWM3, 1, 13000000); +static APBC_CLK(pwm4, PXA168_PWM4, 1, 13000000); +static APBC_CLK(ssp1, PXA168_SSP1, 4, 0); +static APBC_CLK(ssp2, PXA168_SSP2, 4, 0); +static APBC_CLK(ssp3, PXA168_SSP3, 4, 0); +static APBC_CLK(ssp4, PXA168_SSP4, 4, 0); +static APBC_CLK(ssp5, PXA168_SSP5, 4, 0); +static APBC_CLK(gpio, PXA168_GPIO, 0, 13000000); +static APBC_CLK(keypad, PXA168_KPC, 0, 32000); + +static APMU_CLK(nand, NAND, 0x19b, 156000000); +static APMU_CLK(lcd, LCD, 0x7f, 312000000); +static APMU_CLK(eth, ETH, 0x09, 0); +static APMU_CLK(usb, USB, 0x12, 0); + +/* device and clock bindings */ +static struct clk_lookup pxa168_clkregs[] = { + INIT_CLKREG(&clk_uart1, "pxa2xx-uart.0", NULL), + INIT_CLKREG(&clk_uart2, "pxa2xx-uart.1", NULL), + INIT_CLKREG(&clk_uart3, "pxa2xx-uart.2", NULL), + INIT_CLKREG(&clk_twsi0, "pxa2xx-i2c.0", NULL), + INIT_CLKREG(&clk_twsi1, "pxa2xx-i2c.1", NULL), + INIT_CLKREG(&clk_pwm1, "pxa168-pwm.0", NULL), + INIT_CLKREG(&clk_pwm2, "pxa168-pwm.1", NULL), + INIT_CLKREG(&clk_pwm3, "pxa168-pwm.2", NULL), + INIT_CLKREG(&clk_pwm4, "pxa168-pwm.3", NULL), + INIT_CLKREG(&clk_ssp1, "pxa168-ssp.0", NULL), + INIT_CLKREG(&clk_ssp2, "pxa168-ssp.1", NULL), + INIT_CLKREG(&clk_ssp3, "pxa168-ssp.2", NULL), + INIT_CLKREG(&clk_ssp4, "pxa168-ssp.3", NULL), + INIT_CLKREG(&clk_ssp5, "pxa168-ssp.4", NULL), + INIT_CLKREG(&clk_nand, "pxa3xx-nand", NULL), + INIT_CLKREG(&clk_lcd, "pxa168-fb", NULL), + INIT_CLKREG(&clk_gpio, "pxa-gpio", NULL), + INIT_CLKREG(&clk_keypad, "pxa27x-keypad", NULL), + INIT_CLKREG(&clk_eth, "pxa168-eth", "MFUCLK"), + INIT_CLKREG(&clk_usb, "pxa168-ehci", "PXA168-USBCLK"), +}; + +static int __init pxa168_init(void) +{ + if (cpu_is_pxa168()) { + mfp_init_base(MFPR_VIRT_BASE); + mfp_init_addr(pxa168_mfp_addr_map); + pxa_init_dma(IRQ_PXA168_DMA_INT0, 32); + clkdev_add_table(ARRAY_AND_SIZE(pxa168_clkregs)); + } + + return 0; +} +postcore_initcall(pxa168_init); + +/* system timer - clock enabled, 3.25MHz */ +#define TIMER_CLK_RST (APBC_APBCLK | APBC_FNCLK | APBC_FNCLKSEL(3)) + +static void __init pxa168_timer_init(void) +{ + /* this is early, we have to initialize the CCU registers by + * ourselves instead of using clk_* API. Clock rate is defined + * by APBC_TIMERS_CLK_RST (3.25MHz) and enabled free-running + */ + __raw_writel(APBC_APBCLK | APBC_RST, APBC_PXA168_TIMERS); + + /* 3.25MHz, bus/functional clock enabled, release reset */ + __raw_writel(TIMER_CLK_RST, APBC_PXA168_TIMERS); + + timer_init(IRQ_PXA168_TIMER1); +} + +struct sys_timer pxa168_timer = { + .init = pxa168_timer_init, +}; + +void pxa168_clear_keypad_wakeup(void) +{ + uint32_t val; + uint32_t mask = APMU_PXA168_KP_WAKE_CLR; + + /* wake event clear is needed in order to clear keypad interrupt */ + val = __raw_readl(APMU_WAKE_CLR); + __raw_writel(val | mask, APMU_WAKE_CLR); +} + +/* on-chip devices */ +PXA168_DEVICE(uart1, "pxa2xx-uart", 0, UART1, 0xd4017000, 0x30, 21, 22); +PXA168_DEVICE(uart2, "pxa2xx-uart", 1, UART2, 0xd4018000, 0x30, 23, 24); +PXA168_DEVICE(uart3, "pxa2xx-uart", 2, UART3, 0xd4026000, 0x30, 23, 24); +PXA168_DEVICE(twsi0, "pxa2xx-i2c", 0, TWSI0, 0xd4011000, 0x28); +PXA168_DEVICE(twsi1, "pxa2xx-i2c", 1, TWSI1, 0xd4025000, 0x28); +PXA168_DEVICE(pwm1, "pxa168-pwm", 0, NONE, 0xd401a000, 0x10); +PXA168_DEVICE(pwm2, "pxa168-pwm", 1, NONE, 0xd401a400, 0x10); +PXA168_DEVICE(pwm3, "pxa168-pwm", 2, NONE, 0xd401a800, 0x10); +PXA168_DEVICE(pwm4, "pxa168-pwm", 3, NONE, 0xd401ac00, 0x10); +PXA168_DEVICE(nand, "pxa3xx-nand", -1, NAND, 0xd4283000, 0x80, 97, 99); +PXA168_DEVICE(ssp1, "pxa168-ssp", 0, SSP1, 0xd401b000, 0x40, 52, 53); +PXA168_DEVICE(ssp2, "pxa168-ssp", 1, SSP2, 0xd401c000, 0x40, 54, 55); +PXA168_DEVICE(ssp3, "pxa168-ssp", 2, SSP3, 0xd401f000, 0x40, 56, 57); +PXA168_DEVICE(ssp4, "pxa168-ssp", 3, SSP4, 0xd4020000, 0x40, 58, 59); +PXA168_DEVICE(ssp5, "pxa168-ssp", 4, SSP5, 0xd4021000, 0x40, 60, 61); +PXA168_DEVICE(fb, "pxa168-fb", -1, LCD, 0xd420b000, 0x1c8); +PXA168_DEVICE(keypad, "pxa27x-keypad", -1, KEYPAD, 0xd4012000, 0x4c); +PXA168_DEVICE(eth, "pxa168-eth", -1, MFU, 0xc0800000, 0x0fff); + +struct resource pxa168_resource_gpio[] = { + { + .start = 0xd4019000, + .end = 0xd4019fff, + .flags = IORESOURCE_MEM, + }, { + .start = IRQ_PXA168_GPIOX, + .end = IRQ_PXA168_GPIOX, + .flags = IORESOURCE_IRQ, + }, +}; + +struct platform_device pxa168_device_gpio = { + .name = "pxa-gpio", + .id = -1, + .num_resources = ARRAY_SIZE(pxa168_resource_gpio), + .resource = pxa168_resource_gpio, +}; + +struct resource pxa168_usb_host_resources[] = { + /* USB Host conroller register base */ + [0] = { + .start = 0xd4209000, + .end = 0xd4209000 + 0x200, + .flags = IORESOURCE_MEM, + .name = "pxa168-usb-host", + }, + /* USB PHY register base */ + [1] = { + .start = 0xd4206000, + .end = 0xd4206000 + 0xff, + .flags = IORESOURCE_MEM, + .name = "pxa168-usb-phy", + }, + [2] = { + .start = IRQ_PXA168_USB2, + .end = IRQ_PXA168_USB2, + .flags = IORESOURCE_IRQ, + }, +}; + +static u64 pxa168_usb_host_dmamask = DMA_BIT_MASK(32); +struct platform_device pxa168_device_usb_host = { + .name = "pxa168-ehci", + .id = -1, + .dev = { + .dma_mask = &pxa168_usb_host_dmamask, + .coherent_dma_mask = DMA_BIT_MASK(32), + }, + + .num_resources = ARRAY_SIZE(pxa168_usb_host_resources), + .resource = pxa168_usb_host_resources, +}; + +int __init pxa168_add_usb_host(struct pxa168_usb_pdata *pdata) +{ + pxa168_device_usb_host.dev.platform_data = pdata; + return platform_device_register(&pxa168_device_usb_host); +} + +void pxa168_restart(char mode, const char *cmd) +{ + soft_restart(0xffff0000); +} diff --git a/pool/shard000/C/0015177_string_compression.c b/pool/shard000/C/0015177_string_compression.c new file mode 100644 index 0000000000000000000000000000000000000000..6c9fdff016d557294a810841fa9ba28ea25c6329 --- /dev/null +++ b/pool/shard000/C/0015177_string_compression.c @@ -0,0 +1,295 @@ +/* + * This program compresses the string in the following manner:- + * string "aaabbbbcccaaa" -> "a3b4c3a3" + * string "abcdeeeeeeeee" -> "a1b1c1d1e9" + * If the compresses string's length is greater than the original + * string, then the program returns the string itself. + */ +#include +#include +#include +#include + +/* + * This function returns the number of digits in a number + * which is greater than or equal to zero. If the number is + * less than zero, this function returns zero. + */ +int count_digits (int num) +{ + int count = 0; + + if (num < 0) { + return(0); + } + + /* + * While number is not zero, continue counting the + * the digits + */ + while (num) { + num = num/10; + ++count; + } + + return(count); +} + +/* + * This function converts an integer number which is greater than + * or equal to zero to a string. If the number is less than zero, + * then this function returns NULL. The caller of this function + * is responsible to free the memory allocated by this function. + */ +char* ntoa (int num) +{ + char* ch; + int digits, rem; + int i; + + /* + * If the number is less than, return NULL + */ + if (num < 0) { + return(NULL); + } + + /* + * Count the number of digits in the number + */ + digits = count_digits(num); + + /* + * If the number of digits in the number are zero, then return + * NULL. + */ + if (digits == 0) { + return(NULL); + } + + /* + * Allocate a character array to store the string converted + * number. + */ + ch = (char*)malloc(sizeof(char) * (digits + 1)); + + /* + * If the allocation fails, then return NULL + */ + if (!ch) { + return(NULL); + } + + memset(ch, 0, sizeof(char) * (digits + 1)); + + /* + * Iterate until the number is zero and add the character + * digits into the array + */ + i = digits - 1; + while (i >= 0) { + + rem = num % 10; + num /= 10; + + ch[i] = '0' + rem; + --i; + } + + /* + * Return the string version of the number. + */ + return(ch); +} + +/* + * This function compresses a given character string and returns the + * compressed string. The time complexity of this function is O(n), + * where 'n' is the number of characters in the character string. + */ +char* string_compression (char* ch) +{ + char* result = NULL, len; + int i, count, j, k; + char* count_to_str; + + /* + * If the character string is NULL or its length is zero, then + * Return NULL + */ + if (!ch || !strlen(ch)) { + return(NULL); + } + + len = strlen(ch); + + /* + * The length of the compressed string can be twice as long the + * input string. So allocate a separate memory for the compressed + * string + */ + result = (char*)malloc(sizeof(char) * (2 * len + 1)); + + /* + * If the string allocation fail, then return NULL. + */ + if (!result) { + return(NULL); + } + + memset(result, 0, sizeof(char) * (2 * len + 1)); + + /* + * Iterate through the string and do the following:- + * Compare the current character with the next character + * If both are same, then increment the 'count'. Otherwise + * add the current character into the buffer and convert the + * 'count' into a string and add the numbered string into the + * buffer. + */ + i = 0; + count = 1; + j = 0; + while (i < (len - 1)) { + if (ch[i] == ch[i+1]) { + /* + * Since the current character and the next character are + * same, so increment 'count'. + */ + ++count; + } else { + /* + * Add the current character into the return buffer + */ + result[j] = ch[i]; + ++j; + + /* + * Convert the 'count' into string + */ + count_to_str = ntoa(count); + + /* + * Add the numbered string to the return buffer. + */ + if (count_to_str) { + k = 0; + while (count_to_str[k]) { + result[j] = count_to_str[k]; + ++j; ++k; + } + + /* + * Free the numbered string + */ + free(count_to_str); + } + + /* + * Reset count to maintain loop invariance + */ + count = 1; + } + + /* + * Increment the index into the character string + */ + ++i; + } + + /* + * Since we iterated through the second last character in the + * string, add the last character and its count to the return + * buffer. + */ + result[j] = ch[i]; + ++j; + + count_to_str = ntoa(count); + + if (count_to_str) { + k = 0; + while (count_to_str[k]) { + result[j] = count_to_str[k]; + ++j; ++k; + } + free(count_to_str); + } + + /* + * If the length of the input string is less than the return + * string, then return the pointer to the input string. + */ + if (strlen(ch) <= strlen(result)) { + free(result); + return(ch); + } + + /* + * Return the compressed string + */ + return(result); +} + +int main () +{ + /* + * Test 1: Test a string which can be compressed + */ + char* str1 = "aaaabbbcccd"; + char* expected_str1 = "a4b3c3d1"; + char* actual_str1 = string_compression(str1); + assert(0 == strcmp(expected_str1, actual_str1)); + + /* + * Test 2: Test a string which has only one character + */ + char* str2 = "aaaaaaaaaa"; + char* expected_str2 = "a10"; + char* actual_str2 = string_compression(str2); + assert(0 == strcmp(expected_str2, actual_str2)); + + /* + * Test 3: Test a string for which compression will give + * string larger than the original string + */ + char* str3 = "abcde"; + char* expected_str3 = "abcde"; + char* actual_str3 = string_compression(str3); + assert(0 == strcmp(expected_str3, actual_str3)); + + /* + * Test 4: Test a string which is NULL + */ + char* str4 = NULL; + char* expected_str4 = NULL; + char* actual_str4 = string_compression(str4); + assert(expected_str4 == actual_str4); + + /* + * Test 5: Test a string which has only one character + */ + char* str5 = "a"; + char* expected_str5 = "a"; + char* actual_str5 = string_compression(str5); + assert(0 == strcmp(expected_str5, actual_str5)); + + /* + * Test 6: Test a string whose length is zero + */ + char* str6 = ""; + char* expected_str6 = NULL; + char* actual_str6 = string_compression(str6); + assert(expected_str6 == actual_str6); + + /* + * Test 7: Test a case in which all characters have same + * number of contigous characters + */ + char* str7 = "aaaa....,,,,yyyy////$$$$))))"; + char* expected_str7 = "a4.4,4y4/4$4)4"; + char* actual_str7 = string_compression(str7); + assert(0 == strcmp(expected_str7, actual_str7)); + + return(0); +} diff --git a/pool/shard000/C/0015180_time_test.c b/pool/shard000/C/0015180_time_test.c new file mode 100644 index 0000000000000000000000000000000000000000..8e6567ba0e47c5c67798bd8b40620b06fdd28876 --- /dev/null +++ b/pool/shard000/C/0015180_time_test.c @@ -0,0 +1,54 @@ + +#define ZT_WITH_UNIT +#include + +static void +basic_tests(struct zt_unit_test *test, void *data UNUSED) +{ +#ifndef WIN32 + struct timeval tv1; + struct timeval tv2; + struct timeval tv_zero = { 0, 0 }; /* 0 second diff time */ + struct timeval tv4 = { 2, 0 }; /* 2 second diff time */ + struct timeval tgt; + + + gettimeofday(&tv1, NULL); + gettimeofday(&tv2, NULL); + + ZT_UNIT_ASSERT(test, zt_cmp_time(&tv1, &tv2) <= 0); + + zt_diff_time(&tgt, &tv1, &tv2); + ZT_UNIT_ASSERT(test, zt_cmp_time(&tv4, &tgt) > 0); + + zt_sub_time(&tgt, &tv1, &tv1); + ZT_UNIT_ASSERT(test, zt_cmp_time(&tgt, &tv_zero) == 0); + + zt_add_time(&tgt, &tv1, &tv1); + ZT_UNIT_ASSERT(test, zt_cmp_time(&tgt, &tv1) > 0); + + /* + * { + * struct time_result tr; + * + * void *test_fn(void * f) { + * sleep(1); + * return NULL; + * } + * + * zt_time(1, &tr, test_fn, NULL); + * zt_time_print_result(&tr, "test_fn", 1); + * } + */ +#endif /* WIN32 */ +} + +int +register_time_suite(struct zt_unit *unit) +{ + struct zt_unit_suite * suite; + + suite = zt_unit_register_suite(unit, "time tests", NULL, NULL, NULL); + zt_unit_register_test(suite, "basic", basic_tests); + return 0; +} diff --git a/pool/shard000/C/0015182_shell_makeargs.c b/pool/shard000/C/0015182_shell_makeargs.c new file mode 100644 index 0000000000000000000000000000000000000000..97163f351f62656d12a09fce4e2b63febde44112 --- /dev/null +++ b/pool/shard000/C/0015182_shell_makeargs.c @@ -0,0 +1,67 @@ +/* + * Split string into argc/argv style argument list + * + * COPYRIGHT (c) 1989-2008. + * On-Line Applications Research Corporation (OAR). + * + * The license and distribution terms for this file may be + * found in the file LICENSE in this distribution or at + * http://www.rtems.com/license/LICENSE. + */ + +#if HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include +#include + +int rtems_shell_make_args( + char *commandLine, + int *argc_p, + char **argv_p, + int max_args +) +{ + int argc; + char *ch; + int status = 0; + + argc = 0; + ch = commandLine; + + while ( *ch ) { + + while ( isspace((unsigned char)*ch) ) ch++; + + if ( *ch == '\0' ) + break; + + if ( *ch == '"' ) { + argv_p[ argc ] = ++ch; + while ( ( *ch != '\0' ) && ( *ch != '"' ) ) ch++; + } else { + argv_p[ argc ] = ch; + while ( ( *ch != '\0' ) && ( !isspace((unsigned char)*ch) ) ) ch++; + } + + argc++; + + if ( *ch == '\0' ) + break; + + *ch++ = '\0'; + + if ( argc == (max_args-1) ) { + status = -1; + break; + } + + + } + argv_p[ argc ] = NULL; + *argc_p = argc; + return status; +} + diff --git a/pool/shard000/C/0015183_hash_file.c b/pool/shard000/C/0015183_hash_file.c new file mode 100644 index 0000000000000000000000000000000000000000..70656441611b16245adc6e1b1fa34f598d7ff7e5 --- /dev/null +++ b/pool/shard000/C/0015183_hash_file.c @@ -0,0 +1,57 @@ +/* LibTomCrypt, modular cryptographic library -- Tom St Denis + * + * LibTomCrypt is a library that provides various cryptographic + * algorithms in a highly modular and flexible manner. + * + * The library is free for all purposes without any express + * guarantee it works. + * + * Tom St Denis, tomstdenis@gmail.com, http://libtomcrypt.com + */ +#include "tomcrypt.h" + +/** + @file hash_file.c + Hash a file, Tom St Denis +*/ + +/** + @param hash The index of the hash desired + @param fname The name of the file you wish to hash + @param out [out] The destination of the digest + @param outlen [in/out] The max size and resulting size of the message digest + @result CRYPT_OK if successful +*/ +int hash_file(int hash, const char *fname, unsigned char *out, unsigned long *outlen) +{ +#ifdef LTC_NO_FILE + return CRYPT_NOP; +#else + FILE *in; + int err; + LTC_ARGCHK(fname != NULL); + LTC_ARGCHK(out != NULL); + LTC_ARGCHK(outlen != NULL); + + if ((err = hash_is_valid(hash)) != CRYPT_OK) { + return err; + } + + in = fopen(fname, "rb"); + if (in == NULL) { + return CRYPT_FILE_NOTFOUND; + } + + err = hash_fd(hash, fileno(in), out, outlen); + if (fclose(in) != 0) { + return CRYPT_ERROR; + } + + return err; +#endif +} + + +/* $Source: /cvs/libtom/libtomcrypt/src/hashes/helper/hash_file.c,v $ */ +/* $Revision: 1.4 $ */ +/* $Date: 2006/03/31 14:15:35 $ */ diff --git a/pool/shard000/C/0015187_rzinterp.c b/pool/shard000/C/0015187_rzinterp.c new file mode 100644 index 0000000000000000000000000000000000000000..33d162cf070e62224d39518995c0a1f2f921a939 --- /dev/null +++ b/pool/shard000/C/0015187_rzinterp.c @@ -0,0 +1,236 @@ +#include "presto.h" + +fcomplex **corr_rz_plane(fcomplex * data, int numdata, int numbetween, + int startbin, double zlo, double zhi, + int numz, int fftlen, + presto_interp_acc accuracy, int *nextbin) + /* This routine uses the correlation method to do Fourier */ + /* complex interpolations of the f-fdot plane. */ + /* Arguments: */ + /* 'data' is a complex array of the data to be interpolated. */ + /* 'numdata' is the number of complex points (bins) in data. */ + /* 'numbetween' is the number of points to interpolate per bin. */ + /* 'startbin' is the first bin to use in data for interpolation. */ + /* 'zlo' is the lowest fdot to use (z=f-dot*T^2) */ + /* 'zhi' is the highest fdot to use (z=f-dot*T^2) */ + /* 'numz' is the number of z values to use to make the plane */ + /* 'fftlen' is the # of complex pts in kernel and result. */ + /* 'accuracy' is either HIGHACC or LOWACC. */ + /* 'nextbin' will contain the bin number of the first bin not */ + /* interpolated in data. */ +{ + double maxz, dz, dtmp; + int ii, kern_half_width, numkern, numgoodbins, numgoodbins2; + static int firsttime = 1, old_numbetween; + static int old_kern_half_width, old_fftlen, old_numz; + static double old_zlo, old_zhi; + static fcomplex **kernel = NULL, **result, *response; + static presto_interp_acc old_accuracy; + presto_datainf datainf; + + /* Make sure our z's are in the correct order */ + + if (zlo > zhi) { + dtmp = zlo; + zlo = zhi; + zhi = dtmp; + } + + /* Determine some required parameters */ + + if (numz == 1) + dz = 0.0; + else + dz = (zhi - zlo) / (numz - 1); + maxz = (fabs(zlo) < fabs(zhi)) ? zhi : zlo; + kern_half_width = z_resp_halfwidth(maxz, accuracy); + numkern = 2 * numbetween * kern_half_width; + + /* If this is our first time or the parameters have changed, */ + /* set up and FFT the correlation kernel array */ + + if (firsttime + || numbetween != old_numbetween + || kern_half_width != old_kern_half_width + || fftlen != old_fftlen + || fabs(zlo - old_zlo) > 1.0E-5 + || fabs(zhi - old_zhi) > 1.0E-5 + || numz != old_numz || accuracy != old_accuracy) { + + /* Cleanup old data if we need to */ + + if (kernel) { + vect_free(kernel[0]); + vect_free(kernel); + } + kernel = gen_cmatrix(numz, fftlen); + + /* Generate the new responses and the kernel matrix */ + + for (ii = 0; ii < numz; ii++) { + response = gen_z_response(0.0, numbetween, zlo + ii * dz, numkern); + place_complex_kernel(response, numkern, kernel[ii], fftlen); + vect_free(response); + COMPLEXFFT(kernel[ii], fftlen, -1); + } + + /* Set the old_ variables equal to the new variables */ + + old_numbetween = numbetween; + old_kern_half_width = kern_half_width; + old_zlo = zlo; + old_zhi = zhi; + old_numz = numz; + old_fftlen = fftlen; + old_accuracy = accuracy; + firsttime = 0; + } + + /* Allocate the result matrix */ + + numgoodbins = fftlen - 2 * kern_half_width * numbetween; + if (numgoodbins % numbetween) { + while (numgoodbins % numbetween) + numgoodbins--; + } + *nextbin = startbin + numgoodbins / numbetween; + result = gen_cmatrix(numz, numgoodbins); + + /* Perform the correlations. */ + + datainf = RAW; + for (ii = 0; ii < numz; ii++) { + numgoodbins2 = corr_complex(data, numdata, datainf, + kernel[ii], fftlen, FFT, + result[ii], numgoodbins, startbin, + numbetween, kern_half_width, CORR); + if (numgoodbins != numgoodbins2) { + printf("\n Calculated 'numgoodbins' = %d, does not equal\n", + numgoodbins); + printf("\n returned 'numgoodbins' = %d. Exiting.\n\n", numgoodbins2); + } + datainf = SAME; + } + return result; +} + + +fcomplex *corr_rz_interp(fcomplex * data, int numdata, int numbetween, + int startbin, double z, int fftlen, + presto_interp_acc accuracy, int *nextbin) + /* This routine uses the correlation method to do a Fourier */ + /* complex interpolation of a slice of the f-fdot plane. */ + /* Arguments: */ + /* 'data' is a complex array of the data to be interpolated. */ + /* 'numdata' is the number of complex points (bins) in data. */ + /* 'numbetween' is the number of points to interpolate per bin. */ + /* 'startbin' is the first bin to use in data for interpolation. */ + /* 'z' is the fdot to use (z=f-dot*T^2). */ + /* 'fftlen' is the # of complex pts in kernel and result. */ + /* 'accuracy' is either HIGHACC or LOWACC. */ + /* 'nextbin' will contain the bin number of the first bin not */ + /* interpolated in data. */ +{ + fcomplex **result, *tempreturn; + + result = corr_rz_plane(data, numdata, numbetween, startbin, z, z, 1, + fftlen, accuracy, nextbin); + tempreturn = result[0]; + vect_free(result); + return tempreturn; +} + + +void rz_interp(fcomplex * data, int numdata, double r, double z, + int kern_half_width, fcomplex * ans) + /* This routine uses the correlation method to do a Fourier */ + /* complex interpolation at a single point in the f-fdot plane. */ + /* It does the correlations manually. (i.e. no FFTs) */ + /* Arguments: */ + /* 'data' is a complex array of the data to be interpolated. */ + /* 'numdata' is the number of complex points (bins) in data. */ + /* 'r' is the Fourier frequency in data that we want to */ + /* interpolate. This can (and should) be fractional. */ + /* 'z' is the fdot to use (z=f-dot*T^2 (T is integration time)). */ + /* 'kern_half_width' is the half-width of the kernel in bins. */ + /* 'ans' is the complex answer. */ +{ + float *dataptr, *respptr; + int ii, numkern, nsum, intfreq, lodata, hidata, loresp, hiresp; + double fracfreq, dintfreq, tmpd, tmpr; + fcomplex *response; + + /* Check 'r' and return 0.0 + 0.0i if out of bounds. */ + /* Should this return an error and exit instead? */ + + if (r > numdata - 1.0 || r < 0.0) { + ans->r = 0.0; + ans->i = 0.0; + return; + } + + /* Split 'r' into integer and fractional parts */ + + fracfreq = modf(r, &dintfreq); + intfreq = (int) dintfreq; + + /* Return immediately if 'r' is close to an */ + /* integer frequency and z is very close to zero */ + + if (fabs(z) < 1E-4) { + if (fracfreq < 1E-5) { + ans->r = data[intfreq].r; + ans->i = data[intfreq].i; + return; + } + if ((1.0 - fracfreq) < 1E-5) { + ans->r = data[intfreq + 1].r; + ans->i = data[intfreq + 1].i; + return; + } + } + + /* Generate the response function */ + + numkern = 2 * kern_half_width; + response = gen_z_response(fracfreq, 1, z, numkern); + + /* Determine the summation boundaries */ + + lodata = intfreq - kern_half_width; + if (lodata < 0) { + loresp = abs(lodata); + lodata = 0; + } else { + loresp = 0; + } + hidata = intfreq + kern_half_width - 1; + if (hidata > numdata - 1) { + hiresp = numkern - hidata + numdata - 1; + } else { + hiresp = numkern; + } + nsum = hiresp - loresp; + + /* Set up our pointers */ + + dataptr = (float *) (data + lodata); + respptr = (float *) (response + loresp); + + /* Do the summation */ + + ans->r = 0.0; + ans->i = 0.0; + + for (ii = 0; ii < nsum; ii++) { + tmpd = *(dataptr++); + tmpr = *(respptr++); + ans->r += tmpd * tmpr + (*dataptr) * (*respptr); + ans->i += (*dataptr) * tmpr - (*respptr) * tmpd; + dataptr++; + respptr++; + } + + vect_free(response); + return; +} diff --git a/pool/shard000/C/0015192_bootblock.c b/pool/shard000/C/0015192_bootblock.c new file mode 100644 index 0000000000000000000000000000000000000000..c0f26d9a72c865a2e303fb86a7e1014e1e76de9a --- /dev/null +++ b/pool/shard000/C/0015192_bootblock.c @@ -0,0 +1,53 @@ +/* + * This file is part of the coreboot project. + * + * Copyright (C) 2016 Intel Corporation. + * + * 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. + */ + +#include +#include +#include + +static void fill_temp_ram_init_params(FSP_TEMP_RAM_INIT_PARAMS *params) +{ + params->MicrocodeRegionBase = CONFIG_CPU_MICROCODE_CBFS_LOC; + params->MicrocodeRegionLength = CONFIG_CPU_MICROCODE_CBFS_LEN; + params->CodeRegionBase = 0xFFFFFFFF - CONFIG_ROM_SIZE + 1; + params->CodeRegionLength = CONFIG_ROM_SIZE; +} + +void bootblock_fsp_temp_ram_init(void) +{ + FSP_TEMP_RAM_INIT fsp_temp_ram_init; + FSP_TEMP_RAM_INIT_PARAMS temp_ram_init_params; + FSP_INFO_HEADER *fih; + EFI_STATUS status; + + /* Locate the FSP header */ + fih = find_fsp(CONFIG_FSP_LOC); + /* Check the FSP header */ + if (fih == NULL) + die("FSP_INFO_HEADER not set!\n"); + + fill_temp_ram_init_params(&temp_ram_init_params); + + /* Perform Temp RAM Init */ + printk(BIOS_DEBUG, "Calling FspTempRamInit\n"); + post_code(POST_FSP_TEMP_RAM_INIT); + fsp_temp_ram_init = (FSP_TEMP_RAM_INIT)(fih->ImageBase + + fih->TempRamInitEntryOffset); + status = fsp_temp_ram_init(&temp_ram_init_params); + if (status != FSP_SUCCESS) + die("FspTempRamInit failed. Giving up."); + + printk(BIOS_DEBUG, "FspTempRamInit returned 0x%08x\n", status); +} diff --git a/pool/shard000/C/0015193_2.33.c b/pool/shard000/C/0015193_2.33.c new file mode 100644 index 0000000000000000000000000000000000000000..271dc2a568d22dbc56ee6b32e3f61d53b04f9846 --- /dev/null +++ b/pool/shard000/C/0015193_2.33.c @@ -0,0 +1,104 @@ +#include +#include +#include +#include +#define LIST_INT_SIZE 100 +#define LISTINCREMENT 10 +#define INFEASIBLE -1//参数不合法 +#define OK 1 +#define ERROR 0 +typedef char ElemType; +typedef int Status;//函数状态 +typedef struct LNode{ + ElemType data; + struct LNode *next; +}LNode,*LinkList;//线性链表类型 +//创建带头结点的单链表 +LinkList createLinkList(){ + LinkList head=(LinkList)malloc(sizeof(LNode)); + head->next=NULL; + return head; +} +//创建带头结点的单循环链表 +LinkList createclLinkList(){ + LinkList head=(LinkList)malloc(sizeof(LNode)); + head->next=head; + return head; +} + +//用尾插法插入单链表 +void insertend(LinkList list){ + LinkList rear=list,newptr=NULL; + while(rear->next)rear=rear->next; + int n; + printf("press n\n"); + + scanf("%d",&n); + setbuf(stdin, NULL);//清空输入缓存 + char c; + for(int i=0;idata=c; + newptr->next=NULL; + rear->next=newptr; + rear=newptr; + } + + +} + +void print(LinkList l){ + l=l->next; + if(!l)return; + while(l->next){ + printf("%c ",l->data); + l=l->next; + } + printf("%c\n",l->data); +} + +void printcl(LinkList list){ + if(!list)return; + LinkList p=list->next; + if(p==list)return; + while(p!=list){ + printf("%c ",p->data); + p=p->next; + } + printf("\n"); +} + +Status fun3_33(LinkList list,LinkList cla,LinkList clb,LinkList clc){ + if(!list)return ERROR; + LinkList pre=list,p=pre->next; + while(p){ + pre->next=p->next; + if(isalpha(p->data)){ + p->next=cla->next; + cla->next=p; + }else if(isdigit(p->data)){ + p->next=clb->next; + clb->next=p; + }else{ + p->next=clc->next; + clc->next=p; + } + p=pre->next; + } +list->next=NULL; + +} +int main(){ + LinkList list=createLinkList(); + LinkList cla=createclLinkList(); + LinkList clb=createclLinkList(); + LinkList clc=createclLinkList(); + insertend(list); + print(list); + fun3_33(list,cla,clb,clc); + printcl(cla); + printcl(clb); + printcl(clc); + return 0; +} \ No newline at end of file diff --git a/pool/shard000/C/0015206_ooaofooa_E_CEA_class.c b/pool/shard000/C/0015206_ooaofooa_E_CEA_class.c new file mode 100644 index 0000000000000000000000000000000000000000..eda5ca7123c5acc344fdaec611bdd9cfddebfc09 --- /dev/null +++ b/pool/shard000/C/0015206_ooaofooa_E_CEA_class.c @@ -0,0 +1,96 @@ +/*---------------------------------------------------------------------------- + * File: ooaofooa_E_CEA_class.c + * + * Class: Create Event to Class (E_CEA) + * Component: ooaofooa + * + * your copyright statement can go here (from te_copyright.body) + *--------------------------------------------------------------------------*/ + +#include "sys_sys_types.h" +#include "LOG_bridge.h" +#include "POP_bridge.h" +#include "T_bridge.h" +#include "ooaofooa_classes.h" + +/* + * Instance Loader (from string data). + */ +Escher_iHandle_t +ooaofooa_E_CEA_instanceloader( Escher_iHandle_t instance, const c_t * avlstring[] ) +{ + Escher_iHandle_t return_identifier = 0; + ooaofooa_E_CEA * self = (ooaofooa_E_CEA *) instance; + /* Initialize application analysis class attributes. */ + self->Statement_ID = (Escher_iHandle_t) Escher_atoi( avlstring[ 1 ] ); + return return_identifier; +} + +/* + * Select any where using referential/identifying attribute set. + * If not_empty, relate this instance to the selected instance. + */ +void ooaofooa_E_CEA_batch_relate( Escher_iHandle_t instance ) +{ + ooaofooa_E_CEA * ooaofooa_E_CEA_instance = (ooaofooa_E_CEA *) instance; + ooaofooa_E_CSME * ooaofooa_E_CSMErelated_instance1 = ooaofooa_E_CSME_AnyWhere1( ooaofooa_E_CEA_instance->Statement_ID ); + if ( ooaofooa_E_CSMErelated_instance1 ) { + ooaofooa_E_CEA_R704_Link( ooaofooa_E_CSMErelated_instance1, ooaofooa_E_CEA_instance ); + } +} + + +/* + * RELATE E_CSME TO E_CEA ACROSS R704 + */ +void +ooaofooa_E_CEA_R704_Link( ooaofooa_E_CSME * supertype, ooaofooa_E_CEA * subtype ) +{ + /* Use TagEmptyHandleDetectionOn() to detect empty handle references. */ + subtype->Statement_ID = supertype->Statement_ID; + /* Optimized linkage for E_CEA->E_CSME[R704] */ + subtype->E_CSME_R704 = supertype; + /* Optimized linkage for E_CSME->E_CEA[R704] */ + supertype->R704_subtype = subtype; + supertype->R704_object_id = ooaofooa_E_CEA_CLASS_NUMBER; +} + + +/* + * UNRELATE E_CSME FROM E_CEA ACROSS R704 + */ +void +ooaofooa_E_CEA_R704_Unlink( ooaofooa_E_CSME * supertype, ooaofooa_E_CEA * subtype ) +{ + /* Use TagEmptyHandleDetectionOn() to detect empty handle references. */ + subtype->E_CSME_R704 = 0; + supertype->R704_subtype = 0; + supertype->R704_object_id = 0; +} + + +/* + * Dump instances in SQL format. + */ +void +ooaofooa_E_CEA_instancedumper( Escher_iHandle_t instance ) +{ + ooaofooa_E_CEA * self = (ooaofooa_E_CEA *) instance; + printf( "INSERT INTO E_CEA VALUES ( %ld );\n", + ((long)self->Statement_ID & ESCHER_IDDUMP_MASK) ); +} +/* + * Statically allocate space for the instance population for this class. + * Allocate space for the class instance and its attribute values. + * Depending upon the collection scheme, allocate containoids (collection + * nodes) for gathering instances into free and active extents. + */ +static Escher_SetElement_s ooaofooa_E_CEA_container[ ooaofooa_E_CEA_MAX_EXTENT_SIZE ]; +static ooaofooa_E_CEA ooaofooa_E_CEA_instances[ ooaofooa_E_CEA_MAX_EXTENT_SIZE ]; +Escher_Extent_t pG_ooaofooa_E_CEA_extent = { + {0,0}, {0,0}, &ooaofooa_E_CEA_container[ 0 ], + (Escher_iHandle_t) &ooaofooa_E_CEA_instances, + sizeof( ooaofooa_E_CEA ), 0, ooaofooa_E_CEA_MAX_EXTENT_SIZE + }; + + diff --git a/pool/shard000/C/0015207_cache.c b/pool/shard000/C/0015207_cache.c new file mode 100644 index 0000000000000000000000000000000000000000..1eb7c71e3d6adfe25916070e180ae87e0b3eedbf --- /dev/null +++ b/pool/shard000/C/0015207_cache.c @@ -0,0 +1,194 @@ +/* + * This file is subject to the terms and conditions of the GNU General Public + * License. See the file "COPYING" in the main directory of this archive + * for more details. + * + * Copyright (C) 1994 - 2003, 06, 07 by Ralf Baechle (ralf@linux-mips.org) + * Copyright (C) 2007 MIPS Technologies, Inc. + */ +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +/* Cache operations. */ +void (*flush_cache_all)(void); +void (*__flush_cache_all)(void); +void (*flush_cache_mm)(struct mm_struct *mm); +void (*flush_cache_range)(struct vm_area_struct *vma, unsigned long start, + unsigned long end); +void (*flush_cache_page)(struct vm_area_struct *vma, unsigned long page, + unsigned long pfn); +void (*flush_icache_range)(unsigned long start, unsigned long end); +void (*local_flush_icache_range)(unsigned long start, unsigned long end); + +void (*__flush_cache_vmap)(void); +void (*__flush_cache_vunmap)(void); + +/* MIPS specific cache operations */ +void (*flush_cache_sigtramp)(unsigned long addr); +void (*local_flush_data_cache_page)(void * addr); +void (*flush_data_cache_page)(unsigned long addr); +void (*flush_icache_all)(void); + +EXPORT_SYMBOL_GPL(local_flush_data_cache_page); +EXPORT_SYMBOL(flush_data_cache_page); + +#ifdef CONFIG_DMA_NONCOHERENT + +/* DMA cache operations. */ +void (*_dma_cache_wback_inv)(unsigned long start, unsigned long size); +void (*_dma_cache_wback)(unsigned long start, unsigned long size); +void (*_dma_cache_inv)(unsigned long start, unsigned long size); + +EXPORT_SYMBOL(_dma_cache_wback_inv); + +#endif /* CONFIG_DMA_NONCOHERENT */ + +/* + * We could optimize the case where the cache argument is not BCACHE but + * that seems very atypical use ... + */ +asmlinkage int sys_cacheflush(unsigned long addr, + unsigned long bytes, unsigned int cache) +{ + if (bytes == 0) + return 0; + if (!access_ok(VERIFY_WRITE, (void __user *) addr, bytes)) + return -EFAULT; + + flush_icache_range(addr, addr + bytes); + + return 0; +} + +void __flush_dcache_page(struct page *page) +{ + struct address_space *mapping = page_mapping(page); + unsigned long addr; + + if (PageHighMem(page)) + return; + if (mapping && !mapping_mapped(mapping)) { + SetPageDcacheDirty(page); + return; + } + + /* + * We could delay the flush for the !page_mapping case too. But that + * case is for exec env/arg pages and those are %99 certainly going to + * get faulted into the tlb (and thus flushed) anyways. + */ + addr = (unsigned long) page_address(page); + flush_data_cache_page(addr); +} + +EXPORT_SYMBOL(__flush_dcache_page); + +void __flush_anon_page(struct page *page, unsigned long vmaddr) +{ + unsigned long addr = (unsigned long) page_address(page); + + if (pages_do_alias(addr, vmaddr)) { + if (page_mapped(page) && !Page_dcache_dirty(page)) { + void *kaddr; + + kaddr = kmap_coherent(page, vmaddr); + flush_data_cache_page((unsigned long)kaddr); + kunmap_coherent(); + } else + flush_data_cache_page(addr); + } +} + +EXPORT_SYMBOL(__flush_anon_page); + +void __update_cache(struct vm_area_struct *vma, unsigned long address, + pte_t pte) +{ + struct page *page; + unsigned long pfn, addr; + int exec = (vma->vm_flags & VM_EXEC) && !cpu_has_ic_fills_f_dc; + + pfn = pte_pfn(pte); + if (unlikely(!pfn_valid(pfn))) + return; + page = pfn_to_page(pfn); + if (page_mapping(page) && Page_dcache_dirty(page)) { + addr = (unsigned long) page_address(page); + if (exec || pages_do_alias(addr, address & PAGE_MASK)) + flush_data_cache_page(addr); + ClearPageDcacheDirty(page); + } +} + +unsigned long _page_cachable_default; +EXPORT_SYMBOL_GPL(_page_cachable_default); + +static inline void setup_protection_map(void) +{ + protection_map[0] = PAGE_NONE; + protection_map[1] = PAGE_READONLY; + protection_map[2] = PAGE_COPY; + protection_map[3] = PAGE_COPY; + protection_map[4] = PAGE_READONLY; + protection_map[5] = PAGE_READONLY; + protection_map[6] = PAGE_COPY; + protection_map[7] = PAGE_COPY; + protection_map[8] = PAGE_NONE; + protection_map[9] = PAGE_READONLY; + protection_map[10] = PAGE_SHARED; + protection_map[11] = PAGE_SHARED; + protection_map[12] = PAGE_READONLY; + protection_map[13] = PAGE_READONLY; + protection_map[14] = PAGE_SHARED; + protection_map[15] = PAGE_SHARED; +} + +void __devinit cpu_cache_init(void) +{ + if (cpu_has_3k_cache) { + extern void __weak r3k_cache_init(void); + + r3k_cache_init(); + } + if (cpu_has_6k_cache) { + extern void __weak r6k_cache_init(void); + + r6k_cache_init(); + } + if (cpu_has_4k_cache) { + extern void __weak r4k_cache_init(void); + + r4k_cache_init(); + } + if (cpu_has_8k_cache) { + extern void __weak r8k_cache_init(void); + + r8k_cache_init(); + } + if (cpu_has_tx39_cache) { + extern void __weak tx39_cache_init(void); + + tx39_cache_init(); + } + + setup_protection_map(); +} + +int __weak __uncached_access(struct file *file, unsigned long addr) +{ + if (file->f_flags & O_SYNC) + return 1; + + return addr >= __pa(high_memory); +} diff --git a/pool/shard000/C/0015217_motionblur.c b/pool/shard000/C/0015217_motionblur.c new file mode 100644 index 0000000000000000000000000000000000000000..2ac9f647c6a1ec6bbe76490746e798ff08bc5c9c --- /dev/null +++ b/pool/shard000/C/0015217_motionblur.c @@ -0,0 +1,222 @@ +/***************************************************************************** + * motion_blur.c : motion blur filter for vlc + ***************************************************************************** + * Copyright (C) 2000, 2001, 2002, 2003 the VideoLAN team + * $Id$ + * + * Authors: Sigmund Augdal Helberg + * Antoine Cellerier + * + * 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. + *****************************************************************************/ + +/***************************************************************************** + * Preamble + *****************************************************************************/ + +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif + +#include +#include +#include +#include +#include "filter_picture.h" + +/***************************************************************************** + * Local protypes + *****************************************************************************/ +static int Create ( vlc_object_t * ); +static void Destroy ( vlc_object_t * ); +static picture_t *Filter ( filter_t *, picture_t * ); +static void RenderBlur ( filter_sys_t *, picture_t *, picture_t * ); +static int MotionBlurCallback( vlc_object_t *, char const *, + vlc_value_t, vlc_value_t, void * ); + +/***************************************************************************** + * Module descriptor + *****************************************************************************/ +#define FACTOR_TEXT N_("Blur factor (1-127)") +#define FACTOR_LONGTEXT N_("The degree of blurring from 1 to 127.") + +#define FILTER_PREFIX "blur-" + +vlc_module_begin () + set_shortname( N_("Motion blur") ) + set_description( N_("Motion blur filter") ) + set_capability( "video filter2", 0 ) + set_category( CAT_VIDEO ) + set_subcategory( SUBCAT_VIDEO_VFILTER ) + + add_integer_with_range( FILTER_PREFIX "factor", 80, 1, 127, + FACTOR_TEXT, FACTOR_LONGTEXT, false ) + + add_shortcut( "blur" ) + + set_callbacks( Create, Destroy ) +vlc_module_end () + +static const char *const ppsz_filter_options[] = { + "factor", NULL +}; + +/***************************************************************************** + * filter_sys_t + *****************************************************************************/ +struct filter_sys_t +{ + picture_t *p_tmp; + bool b_first; + + vlc_spinlock_t lock; + int i_factor; +}; + +/***************************************************************************** + * Create + *****************************************************************************/ +static int Create( vlc_object_t *p_this ) +{ + filter_t *p_filter = (filter_t *)p_this; + + /* Allocate structure */ + p_filter->p_sys = malloc( sizeof( filter_sys_t ) ); + if( p_filter->p_sys == NULL ) + return VLC_ENOMEM; + + p_filter->p_sys->p_tmp = picture_NewFromFormat( &p_filter->fmt_in.video ); + if( !p_filter->p_sys->p_tmp ) + { + free( p_filter->p_sys ); + return VLC_ENOMEM; + } + p_filter->p_sys->b_first = true; + + p_filter->pf_video_filter = Filter; + + config_ChainParse( p_filter, FILTER_PREFIX, ppsz_filter_options, + p_filter->p_cfg ); + + p_filter->p_sys->i_factor = + var_CreateGetIntegerCommand( p_filter, FILTER_PREFIX "factor" ); + vlc_spin_init( &p_filter->p_sys->lock ); + var_AddCallback( p_filter, FILTER_PREFIX "factor", + MotionBlurCallback, p_filter->p_sys ); + + + return VLC_SUCCESS; +} + +/***************************************************************************** + * Destroy + *****************************************************************************/ +static void Destroy( vlc_object_t *p_this ) +{ + filter_t *p_filter = (filter_t *)p_this; + + var_DelCallback( p_filter, FILTER_PREFIX "factor", + MotionBlurCallback, p_filter->p_sys ); + vlc_spin_destroy( &p_filter->p_sys->lock ); + + picture_Release( p_filter->p_sys->p_tmp ); + free( p_filter->p_sys ); +} + +/***************************************************************************** + * Filter + *****************************************************************************/ +static picture_t *Filter( filter_t *p_filter, picture_t *p_pic ) +{ + picture_t * p_outpic; + filter_sys_t *p_sys = p_filter->p_sys; + + if( !p_pic ) return NULL; + + p_outpic = filter_NewPicture( p_filter ); + if( !p_outpic ) + { + picture_Release( p_pic ); + return NULL; + } + + if( p_sys->b_first ) + { + picture_CopyPixels( p_sys->p_tmp, p_pic ); + p_sys->b_first = false; + } + + /* Get a new picture */ + RenderBlur( p_sys, p_pic, p_outpic ); + + picture_CopyPixels( p_sys->p_tmp, p_outpic ); + + return CopyInfoAndRelease( p_outpic, p_pic ); +} + +/***************************************************************************** + * RenderBlur: renders a blurred picture + *****************************************************************************/ +static void RenderBlur( filter_sys_t *p_sys, picture_t *p_newpic, + picture_t *p_outpic ) +{ + int i_plane; + vlc_spin_lock( &p_sys->lock ); + const int i_oldfactor = p_sys->i_factor; + vlc_spin_unlock( &p_sys->lock ); + int i_newfactor = 128 - i_oldfactor; + + for( i_plane = 0; i_plane < p_outpic->i_planes; i_plane++ ) + { + uint8_t *p_old, *p_new, *p_out, *p_out_end, *p_out_line_end; + const int i_visible_pitch = p_outpic->p[i_plane].i_visible_pitch; + const int i_visible_lines = p_outpic->p[i_plane].i_visible_lines; + + p_out = p_outpic->p[i_plane].p_pixels; + p_new = p_newpic->p[i_plane].p_pixels; + p_old = p_sys->p_tmp->p[i_plane].p_pixels; + p_out_end = p_out + p_outpic->p[i_plane].i_pitch * i_visible_lines; + while ( p_out < p_out_end ) + { + p_out_line_end = p_out + i_visible_pitch; + + while ( p_out < p_out_line_end ) + { + *p_out++ = (((*p_old++) * i_oldfactor) + + ((*p_new++) * i_newfactor)) >> 7; + } + + p_old += p_sys->p_tmp->p[i_plane].i_pitch - i_visible_pitch; + p_new += p_newpic->p[i_plane].i_pitch - i_visible_pitch; + p_out += p_outpic->p[i_plane].i_pitch - i_visible_pitch; + } + } +} + +static int MotionBlurCallback( vlc_object_t *p_this, char const *psz_var, + vlc_value_t oldval, vlc_value_t newval, + void *p_data ) +{ + VLC_UNUSED(p_this); VLC_UNUSED(oldval); + filter_sys_t *p_sys = (filter_sys_t *)p_data; + + if( !strcmp( psz_var, FILTER_PREFIX "factor" ) ) + { + vlc_spin_lock( &p_sys->lock ); + p_sys->i_factor = VLC_CLIP( newval.i_int, 1, 127 ); + vlc_spin_unlock( &p_sys->lock ); + } + return VLC_SUCCESS; +} diff --git a/pool/shard000/C/0015219_xbeeframe.c b/pool/shard000/C/0015219_xbeeframe.c new file mode 100644 index 0000000000000000000000000000000000000000..9c09db4ccd52c1e97647e5b6d26ab9206c585ec4 --- /dev/null +++ b/pool/shard000/C/0015219_xbeeframe.c @@ -0,0 +1,75 @@ +/* xbeeframe.c - Xbee frame driver */ + +#include +#include "xbeeframe.h" + +XbeeFrame_strings http_strings = { + .post = "POST", + .ld = "ld/", + .tx = "tx/", + .rx = "rx/", + .crlf = "\r\n", + .version = "HTTP/1.1 ", + .ok = "200 OK", + .notfound = "404 ERROR" +}; + +/** + * XbeeFrame_start - initializes and starts native assembly driver in a cog. + * @param init is the initialization structure + * @param mailbox is the mailbox structure + * @param rxpin is pin number for receive input + * @param txpin is pin number for transmit output + * @param mode is interface mode. see header XBEEFRAME_MODE_... + * @param baudrate is frequency of bits ... 115200, 57600, etc... + * @returns COG ID on success and -1 on failure + */ +int XbeeFrame_start(XbeeFrameInit_t *init, XbeeFrame_t *mailbox, int rxpin, int txpin, int mode, int baudrate) +{ + use_cog_driver(xbeeframe_driver); + + init->mailbox = mailbox; // mailbox + init->rx_pin = rxpin; // receive pin + init->tx_pin = txpin; // transmit pin + init->mode = mode; // interface mode + init->ticks = _clkfreq / baudrate; // baud + init->rxlength = XBEEFRAME_RXSIZE; // receive buffer length + init->buffers = mailbox->buffers; // receive buffers + init->strings = &http_strings; // http strings + + memset(mailbox, 0, sizeof(XbeeFrame_t)); + mailbox->cogId = load_cog_driver(xbeeframe_driver, init); + + return mailbox->cogId; +} + +/** + * XbeeFrame_sendframe - sends a frame to the Xbee module + */ +void XbeeFrame_sendframe(XbeeFrame_t *mailbox, uint8_t *frame, int length) +{ + while (mailbox->txstatus != XBEEFRAME_STATUS_IDLE) + ; + mailbox->txframe = frame; + mailbox->txlength = length; + mailbox->txstatus = XBEEFRAME_STATUS_BUSY; +} + +/** + * XbeeFrame_recvframe - receives a frame from the Xbee module + */ +uint8_t *XbeeFrame_recvframe(XbeeFrame_t *mailbox, int *plength) +{ + if (mailbox->rxstatus == XBEEFRAME_STATUS_IDLE) + return NULL; + *plength = (int)mailbox->rxlength; + return (uint8_t *)mailbox->rxframe; +} + +/** + * XbeeFrame_release - releases a frame received from the Xbee module + */ +void XbeeFrame_release(XbeeFrame_t *mailbox) +{ + mailbox->rxstatus = XBEEFRAME_STATUS_IDLE; +} diff --git a/pool/shard000/C/0015223_tbutils.c b/pool/shard000/C/0015223_tbutils.c new file mode 100644 index 0000000000000000000000000000000000000000..209a401801e3aba9ad3715247c9efe0cc58ca59c --- /dev/null +++ b/pool/shard000/C/0015223_tbutils.c @@ -0,0 +1,342 @@ +/****************************************************************************** + * + * Module Name: tbutils - Table manipulation utilities + * + *****************************************************************************/ + +/* + * Copyright (C) 2000 - 2006, R. Byron Moore + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions, and the following disclaimer, + * without modification. + * 2. Redistributions in binary form must reproduce at minimum a disclaimer + * substantially similar to the "NO WARRANTY" disclaimer below + * ("Disclaimer") and any redistribution must be conditioned upon + * including a substantially similar Disclaimer requirement for further + * binary redistribution. + * 3. Neither the names of the above-listed copyright holders nor the names + * of any contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * Alternatively, this software may be distributed under the terms of the + * GNU General Public License ("GPL") version 2 as published by the Free + * Software Foundation. + * + * NO WARRANTY + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGES. + */ + +#include +#include + +#define _COMPONENT ACPI_TABLES +ACPI_MODULE_NAME("tbutils") + +/* Local prototypes */ +#ifdef ACPI_OBSOLETE_FUNCTIONS +acpi_status +acpi_tb_handle_to_object(u16 table_id, struct acpi_table_desc **table_desc); +#endif + +/******************************************************************************* + * + * FUNCTION: acpi_tb_is_table_installed + * + * PARAMETERS: new_table_desc - Descriptor for new table being installed + * + * RETURN: Status - AE_ALREADY_EXISTS if the table is already installed + * + * DESCRIPTION: Determine if an ACPI table is already installed + * + * MUTEX: Table data structures should be locked + * + ******************************************************************************/ + +acpi_status acpi_tb_is_table_installed(struct acpi_table_desc *new_table_desc) +{ + struct acpi_table_desc *table_desc; + + ACPI_FUNCTION_TRACE(tb_is_table_installed); + + /* Get the list descriptor and first table descriptor */ + + table_desc = acpi_gbl_table_lists[new_table_desc->type].next; + + /* Examine all installed tables of this type */ + + while (table_desc) { + /* + * If the table lengths match, perform a full bytewise compare. This + * means that we will allow tables with duplicate oem_table_id(s), as + * long as the tables are different in some way. + * + * Checking if the table has been loaded into the namespace means that + * we don't check for duplicate tables during the initial installation + * of tables within the RSDT/XSDT. + */ + if ((table_desc->loaded_into_namespace) && + (table_desc->pointer->length == + new_table_desc->pointer->length) + && + (!ACPI_MEMCMP + (table_desc->pointer, new_table_desc->pointer, + new_table_desc->pointer->length))) { + + /* Match: this table is already installed */ + + ACPI_DEBUG_PRINT((ACPI_DB_TABLES, + "Table [%4.4s] already installed: Rev %X OemTableId [%8.8s]\n", + new_table_desc->pointer->signature, + new_table_desc->pointer->revision, + new_table_desc->pointer-> + oem_table_id)); + + new_table_desc->owner_id = table_desc->owner_id; + new_table_desc->installed_desc = table_desc; + + return_ACPI_STATUS(AE_ALREADY_EXISTS); + } + + /* Get next table on the list */ + + table_desc = table_desc->next; + } + + return_ACPI_STATUS(AE_OK); +} + +/******************************************************************************* + * + * FUNCTION: acpi_tb_validate_table_header + * + * PARAMETERS: table_header - Logical pointer to the table + * + * RETURN: Status + * + * DESCRIPTION: Check an ACPI table header for validity + * + * NOTE: Table pointers are validated as follows: + * 1) Table pointer must point to valid physical memory + * 2) Signature must be 4 ASCII chars, even if we don't recognize the + * name + * 3) Table must be readable for length specified in the header + * 4) Table checksum must be valid (with the exception of the FACS + * which has no checksum because it contains variable fields) + * + ******************************************************************************/ + +acpi_status +acpi_tb_validate_table_header(struct acpi_table_header *table_header) +{ + acpi_name signature; + + ACPI_FUNCTION_ENTRY(); + + /* Verify that this is a valid address */ + + if (!acpi_os_readable(table_header, sizeof(struct acpi_table_header))) { + ACPI_ERROR((AE_INFO, + "Cannot read table header at %p", table_header)); + + return (AE_BAD_ADDRESS); + } + + /* Ensure that the signature is 4 ASCII characters */ + + ACPI_MOVE_32_TO_32(&signature, table_header->signature); + if (!acpi_ut_valid_acpi_name(signature)) { + ACPI_ERROR((AE_INFO, "Invalid table signature 0x%8.8X", + signature)); + + ACPI_DUMP_BUFFER(table_header, + sizeof(struct acpi_table_header)); + return (AE_BAD_SIGNATURE); + } + + /* Validate the table length */ + + if (table_header->length < sizeof(struct acpi_table_header)) { + ACPI_ERROR((AE_INFO, + "Invalid length 0x%X in table with signature %4.4s", + (u32) table_header->length, + ACPI_CAST_PTR(char, &signature))); + + ACPI_DUMP_BUFFER(table_header, + sizeof(struct acpi_table_header)); + return (AE_BAD_HEADER); + } + + return (AE_OK); +} + +/******************************************************************************* + * + * FUNCTION: acpi_tb_sum_table + * + * PARAMETERS: Buffer - Buffer to sum + * Length - Size of the buffer + * + * RETURN: 8 bit sum of buffer + * + * DESCRIPTION: Computes an 8 bit sum of the buffer(length) and returns it. + * + ******************************************************************************/ + +u8 acpi_tb_sum_table(void *buffer, u32 length) +{ + acpi_native_uint i; + u8 sum = 0; + + if (!buffer || !length) { + return (0); + } + + for (i = 0; i < length; i++) { + sum = (u8) (sum + ((u8 *) buffer)[i]); + } + return (sum); +} + +/******************************************************************************* + * + * FUNCTION: acpi_tb_generate_checksum + * + * PARAMETERS: Table - Pointer to a valid ACPI table (with a + * standard ACPI header) + * + * RETURN: 8 bit checksum of buffer + * + * DESCRIPTION: Computes an 8 bit checksum of the table. + * + ******************************************************************************/ + +u8 acpi_tb_generate_checksum(struct acpi_table_header * table) +{ + u8 checksum; + + /* Sum the entire table as-is */ + + checksum = acpi_tb_sum_table(table, table->length); + + /* Subtract off the existing checksum value in the table */ + + checksum = (u8) (checksum - table->checksum); + + /* Compute the final checksum */ + + checksum = (u8) (0 - checksum); + return (checksum); +} + +/******************************************************************************* + * + * FUNCTION: acpi_tb_set_checksum + * + * PARAMETERS: Table - Pointer to a valid ACPI table (with a + * standard ACPI header) + * + * RETURN: None. Sets the table checksum field + * + * DESCRIPTION: Computes an 8 bit checksum of the table and inserts the + * checksum into the table header. + * + ******************************************************************************/ + +void acpi_tb_set_checksum(struct acpi_table_header *table) +{ + + table->checksum = acpi_tb_generate_checksum(table); +} + +/******************************************************************************* + * + * FUNCTION: acpi_tb_verify_table_checksum + * + * PARAMETERS: *table_header - ACPI table to verify + * + * RETURN: 8 bit checksum of table + * + * DESCRIPTION: Generates an 8 bit checksum of table and returns and compares + * it to the existing checksum value. + * + ******************************************************************************/ + +acpi_status +acpi_tb_verify_table_checksum(struct acpi_table_header *table_header) +{ + u8 checksum; + + ACPI_FUNCTION_TRACE(tb_verify_table_checksum); + + /* Compute the checksum on the table */ + + checksum = acpi_tb_generate_checksum(table_header); + + /* Checksum ok? */ + + if (checksum == table_header->checksum) { + return_ACPI_STATUS(AE_OK); + } + + ACPI_WARNING((AE_INFO, + "Incorrect checksum in table [%4.4s] - is %2.2X, should be %2.2X", + table_header->signature, table_header->checksum, + checksum)); + + return_ACPI_STATUS(AE_BAD_CHECKSUM); +} + +#ifdef ACPI_OBSOLETE_FUNCTIONS +/******************************************************************************* + * + * FUNCTION: acpi_tb_handle_to_object + * + * PARAMETERS: table_id - Id for which the function is searching + * table_desc - Pointer to return the matching table + * descriptor. + * + * RETURN: Search the tables to find one with a matching table_id and + * return a pointer to that table descriptor. + * + ******************************************************************************/ + +acpi_status +acpi_tb_handle_to_object(u16 table_id, + struct acpi_table_desc **return_table_desc) +{ + u32 i; + struct acpi_table_desc *table_desc; + + ACPI_FUNCTION_NAME(tb_handle_to_object); + + for (i = 0; i < ACPI_TABLE_MAX; i++) { + table_desc = acpi_gbl_table_lists[i].next; + while (table_desc) { + if (table_desc->table_id == table_id) { + *return_table_desc = table_desc; + return (AE_OK); + } + + table_desc = table_desc->next; + } + } + + ACPI_ERROR((AE_INFO, "TableId=%X does not exist", table_id)); + return (AE_BAD_PARAMETER); +} +#endif diff --git a/pool/shard000/C/0015228_refresh.c b/pool/shard000/C/0015228_refresh.c new file mode 100644 index 0000000000000000000000000000000000000000..11fcf95ae218bcea782c720ede634950c257e08a --- /dev/null +++ b/pool/shard000/C/0015228_refresh.c @@ -0,0 +1,186 @@ +/* Hey EMACS -*- linux-c -*- */ +/* $Id: refresh.c 2349 2007-02-09 11:21:47Z kevinkofler $ */ + +/* TiEmu - Tiemu Is an EMUlator + * + * Copyright (c) 2000-2001, Thomas Corvazier, Romain Lievin + * Copyright (c) 2001-2003, Romain Lievin + * Copyright (c) 2003, Julien Blache + * Copyright (c) 2004, Romain Liévin + * Copyright (c) 2005, Romain Liévin + * Copyright (c) 2007, Kevin Kofler + * + * 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 +#include + +#include "intl.h" +#include "dboxes.h" +#include "tilibs.h" +#include "refresh.h" +#include "pbars.h" + +extern CalcUpdate calc_update; + +static void gt_start(void) +{ + calc_update.cnt1 = calc_update.max1 = 0; + calc_update.cnt2 = calc_update.max2 = 0; + calc_update.cnt3 = calc_update.max3 = 0; +} + +static void gt_stop(void) +{ + calc_update.cnt1 = calc_update.max1 = 0; + calc_update.cnt2 = calc_update.max2 = 0; + calc_update.cnt3 = calc_update.max3 = 0; +} + +static void filter_shift(void); +static gfloat filter_compute(gfloat input); + +static void refresh_pbar1(void) +{ + gchar buffer[32]; + gfloat rate, avg; + + if (p_win.pbar1 != NULL) + { + if(calc_update.cnt1 > calc_update.max1) + calc_update.cnt1 = calc_update.max1; + + if(calc_update.max1 != 0) + gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(p_win.pbar1), + (gdouble)calc_update.cnt1 / calc_update.max1); + + if(p_win.label_rate != NULL) + { + rate = calc_update.rate; + filter_shift(); + avg = filter_compute(rate); + + g_snprintf(buffer, 32, "Rate: %1.1f Kbytes/s", avg); + gtk_label_set_text(GTK_LABEL(p_win.label_rate), buffer); + } + GTK_REFRESH(); + } +} + +static void refresh_pbar2(void) +{ + if (p_win.pbar2 != NULL) + { + if(calc_update.cnt2 > calc_update.max2) + calc_update.cnt2 = calc_update.max2; + + if(calc_update.max2 != 0) + gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(p_win.pbar2), + (gdouble)calc_update.cnt2 / calc_update.max2); + + GTK_REFRESH(); + } +} + +static void refresh_pbar3(void) +{ + if(p_win.label_part != NULL) + { + gchar *str; + + str = g_strdup_printf("%i/%i: ", calc_update.cnt3, calc_update.max3); + gtk_label_set_text(GTK_LABEL(p_win.label_part), str); + + GTK_REFRESH(); + } +} + +static void gt_pbar(void) +{ + refresh_pbar1(); + refresh_pbar2(); + refresh_pbar3(); +} + +static void gt_label(void) +{ + if (p_win.label == NULL) + return; + + gtk_label_set_text(GTK_LABEL(p_win.label), calc_update.text); + + GTK_REFRESH(); +} + +static void gt_refresh(void) +{ + GTK_REFRESH(); +} + +CalcUpdate calc_update = +{ + "", 0, 0.0, + 0, 0, 0, 0, 0, 0, + 0, 0, + gt_start, + gt_stop, + gt_refresh, + gt_pbar, + gt_label, +}; + +void tiemu_update_set_gtk(void) +{ + extern CalcHandle *calc_handle; // defined in dbus.c + + ticalcs_update_set(calc_handle, &calc_update); +} + +///// misc + +static gfloat filter[8] = { 0 }; + +static void filter_shift(void) +{ + int i; + + for(i=7; i>0; i--) + filter[i] = filter[i-1]; +} + +static gfloat filter_compute(gfloat input) +{ + int i; + gfloat avg, min, max; + + avg = min = max = 0.0; + + filter[0] = input; + for(i=0; i<7; i++) { + if(filter[i] < min) min = filter[i]; + if(filter[i] > max) max = filter[i]; + + avg += filter[i]; + } + + avg -= min; + avg -= max; + + return (avg / 6); +} + + + + + diff --git a/pool/shard000/C/0015233_CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_memmove_68a.c b/pool/shard000/C/0015233_CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_memmove_68a.c new file mode 100644 index 0000000000000000000000000000000000000000..12c4b514b4f3bc3966b5ad0fcf69f2a66a752a19 --- /dev/null +++ b/pool/shard000/C/0015233_CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_memmove_68a.c @@ -0,0 +1,91 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_memmove_68a.c +Label Definition File: CWE122_Heap_Based_Buffer_Overflow__c_CWE806.label.xml +Template File: sources-sink-68a.tmpl.c +*/ +/* + * @description + * CWE: 122 Heap Based Buffer Overflow + * BadSource: Initialize data as a large string + * GoodSource: Initialize data as a small string + * Sink: memmove + * BadSink : Copy data to string using memmove + * Flow Variant: 68 Data flow: data passed as a global variable from one function to another in different source files + * + * */ + +#include "std_testcase.h" + +#include + +wchar_t * CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_memmove_68_badData; +wchar_t * CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_memmove_68_goodG2BData; + +#ifndef OMITBAD + +/* bad function declaration */ +void CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_memmove_68b_badSink(); + +void CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_memmove_68_bad() +{ + wchar_t * data; + data = (wchar_t *)malloc(100*sizeof(wchar_t)); + /* FLAW: Initialize data as a large buffer that is larger than the small buffer used in the sink */ + wmemset(data, L'A', 100-1); /* fill with L'A's */ + data[100-1] = L'\0'; /* null terminate */ + CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_memmove_68_badData = data; + CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_memmove_68b_badSink(); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* good function declarations */ +void CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_memmove_68b_goodG2BSink(); + +/* goodG2B uses the GoodSource with the BadSink */ +static void goodG2B() +{ + wchar_t * data; + data = (wchar_t *)malloc(100*sizeof(wchar_t)); + /* FIX: Initialize data as a small buffer that as small or smaller than the small buffer used in the sink */ + wmemset(data, L'A', 50-1); /* fill with L'A's */ + data[50-1] = L'\0'; /* null terminate */ + CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_memmove_68_goodG2BData = data; + CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_memmove_68b_goodG2BSink(); +} + +void CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_memmove_68_good() +{ + goodG2B(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + * its own for testing or for building a binary to use in testing binary + * analysis tools. It is not used when compiling all the testcases as one + * application, which is how source code analysis tools are tested. + */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_memmove_68_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_memmove_68_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard000/C/0015241_array_linked_list_u64_extended.c b/pool/shard000/C/0015241_array_linked_list_u64_extended.c new file mode 100644 index 0000000000000000000000000000000000000000..09b9b40a7b9f5700b80f1c2ae77db24f811ba746 --- /dev/null +++ b/pool/shard000/C/0015241_array_linked_list_u64_extended.c @@ -0,0 +1,102 @@ +/* +Autogenerated file by running: +scripts/autogenerator.sh -f source-generation/array_linked_list.gen.h -r TYPE=u8 -r TYPE=u16 -r TYPE=u32 -r TYPE=u64 + +Don't edit. +*/ +/* AUTOGENERATE: src/bl/base/generated/alnls/array_linked_list_u64_extended.c */ +/*---------------------------------------------------------------------------*/ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +static void bl_alnls_u64_find_two_previous_nodes( + bl_alnls_u64* l, + bl_alnls_u64_it* prev, + bl_alnls_u64_it* prev2, + bl_alnls_u64_it val + ) +{ + bl_assert (!bl_alnls_u64_is_empty (l)); + *prev2 = bl_alnls_u64_it_end (l); + *prev = bl_alnls_u64_it_end (l); + bl_alnls_u64_it now = bl_alnls_u64_it_begin (l); + + while (now != val) { + *prev2 = *prev; + *prev = now; + now = bl_alnls_u64_it_next (l, now); + } +} +/* TODO: regular insert ? */ +/*---------------------------------------------------------------------------*/ +BL_EXPORT void bl_alnls_u64_insert_tail( + bl_alnls_u64* l, bl_alnls_u64_it n + ) +{ + bl_assert (bl_alnls_u64_it_next (l, n) == bl_alnls_u64_it_end (l)); + if (!bl_alnls_u64_is_empty (l)) { + bl_alnls_u64_it tail, subtail; + bl_alnls_u64_find_two_previous_nodes( + l, &tail, &subtail, bl_alnls_u64_it_end (l) + ); + l->nodes[tail] = n; + bl_assert (bl_alnls_u64_it_next (l, tail) == n); /* overflow check */ + } + else { + l->head = n; + bl_assert (bl_alnls_u64_it_begin (l) == n); /* overflow check */ + } + ++l->size; +} +/*---------------------------------------------------------------------------*/ +BL_EXPORT bl_alnls_u64_it + bl_alnls_u64_drop (bl_alnls_u64* l, bl_alnls_u64_it n) +{ + bl_assert (bl_alnls_u64_it_in_range( l, n)); + bl_assert (!bl_alnls_u64_node_is_free (l, n)); + + if (bl_alnls_u64_is_empty (l)) { + return bl_alnls_u64_it_end (l); + } + bl_alnls_u64_it should_be_n, prev, find; + find = bl_alnls_u64_it_next (l, n); + bl_alnls_u64_find_two_previous_nodes (l, &should_be_n, &prev, find); + bl_assert (should_be_n == n); + if (prev != bl_alnls_u64_it_end (l)) { + l->nodes[prev] = find; + } + else { + l->head = bl_alnls_u64_it_end (l); + } + l->nodes[n] = bl_alnls_u64_it_end (l); + --l->size; + return prev; +} +/*---------------------------------------------------------------------------*/ +BL_EXPORT bl_alnls_u64_it + bl_alnls_u64_drop_tail (bl_alnls_u64* l) +{ + if (bl_alnls_u64_is_empty (l)) { + return bl_alnls_u64_it_end (l); + } + bl_alnls_u64_it tail, subtail; + bl_alnls_u64_find_two_previous_nodes( + l, &tail, &subtail, bl_alnls_u64_it_end (l) + ); + if (subtail != bl_alnls_u64_it_end (l)) { + l->nodes[subtail] = bl_alnls_u64_it_end (l); + } + else { + l->head = bl_alnls_u64_it_end (l); + } + --l->size; + return tail; +} +/*---------------------------------------------------------------------------*/ +#ifdef __cplusplus +} /*extern "C" {*/ +#endif diff --git a/pool/shard000/C/0015252_actuator.c b/pool/shard000/C/0015252_actuator.c new file mode 100644 index 0000000000000000000000000000000000000000..92ee8d51b96306af8400b6ac76151c9dfb96e914 --- /dev/null +++ b/pool/shard000/C/0015252_actuator.c @@ -0,0 +1,422 @@ +/***************************************************************************** + * + * \file + * + * \brief AVR32 UC3 Control Panel actuators interface module. + * + * This module acts as an interface to all actuators. + * + * + * The example is written for UC3 and EVK1100. + * + * + * Copyright (c) 2009-2014 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + * + *****************************************************************************/ + +/* + * Brief description of the module: + * This module acts as an interface to all actuators. + * + * Detailed description of the module: + * TODO + */ + /** + * Support and FAQ: visit Atmel Support + */ + +#include + +#include "compiler.h" +#include "FreeRTOS.h" + +#include "shell.h" +#include "datalog.h" +#include "cpled.h" +#include "lcd.h" + +#include "tracedump.h" +#include "cptime.h" +#include "actuator.h" + +//_____ M A C R O S ________________________________________________________ + +/*! Max number of actuators. */ +#define ACTUATOR_MAXNB_ACTUATORS (DATALOG_ID_LCD - DATALOG_ID_LEDB1 +1) + +#define ACTUATOR_LIST "{ledb1,ledb2,ledm1,ledm2,lcd}" + +//_____ D E F I N I T I O N S ______________________________________________ + +/*! An actuator register cell structure. */ +typedef struct ActuatorReg { + // Fct ptr to the actual actuator get value function. + bool (*pfGetActuatorValue)( xLogDef *pxLog ); + // Fct ptr to the actual actuator set value function. + eExecStatus (*pfSetActuatorValue)( eModId xModId, int ac, signed portCHAR *av[], + signed portCHAR **ppcStringReply ); +}xActuatorReg; + +xActuatorReg axActuatorsRegistry[ACTUATOR_MAXNB_ACTUATORS] = { + { b_ledb1_get_value, e_ledb1_set_value } , + { b_ledb2_get_value, e_ledb2_set_value } , + { b_ledm1_get_value, e_ledm1_set_value } , + { b_ledm2_get_value, e_ledm2_set_value } , + { b_lcd_get_value, e_lcd_set_value } +}; + +/*! + * The params given to an actuator scheduled command. + */ +typedef struct st_scheduled_param { + int ac; + signed portCHAR *av[4]; +}Scheduled_Cmd_Params; + +const signed portCHAR *const ACTUATOR_MSG_HELP = (signed portCHAR *)"\ +"CRLF"set_actuator_value actuator={ledb1,ledb2} green=value red=value [time=date]"CRLF"\ +set_actuator_value actuator={ledm1,ledm2} state={on,off} [time=date]"CRLF"\ +set_actuator_value actuator=lcd usrmsg=\"string\" [time=date]"CRLF"\ +get_actuator_value actuator="ACTUATOR_LIST" : display the current value of an actuator"CRLF; + +/*! Error msg upon get_actuator_value syntax error. */ +const signed portCHAR *const ACTUATOR_ERRMSG_GETVAL_SYNTAXERROR = (signed portCHAR *)"Error"CRLF"Usage: get_actuator_value actuator=actuatorname"CRLF; + +/*! Error msg upon unreferenced actuator error. */ +const signed portCHAR *const ACTUATOR_ERRMSG_UNREFACTUATOR = (signed portCHAR *)"Error"CRLF"Unreferenced actuator name"CRLF; + +/*! Error msg upon get_actuator_value actuator error. */ +const signed portCHAR *const ACTUATOR_ERRMSG_GETVAL_FAIL = (signed portCHAR *)"Error"CRLF"Actuator failed to deliver a value."CRLF; + +/*! Error msg upon set_actuator_value syntax error. */ +const signed portCHAR *const ACTUATOR_ERRMSG_SETVAL_SYNTAXERROR = (signed portCHAR *)"Error"CRLF"Usage: set_actuator_value actuator=actuatorname fields..."CRLF; + +//_____ D E C L A R A T I O N S ____________________________________________ + +/* \brief The get actuator value command: get value(s) from an actuator. + * Format: get_actuator_value actuator=actuatorname + * + * \note This function must be of the type pfShellCmd defined by the shell module. + * + * \param xModId Input. The module that is calling this function. + * \param FsNavId Ignored. + * \param ac Input. The argument counter. For this command, should be 2. + * \param av Input. The argument vector. + * \param ppcStringReply Input/Output. The response string. + * If Input is NULL, no response string will be output. + * Else a malloc for the response string is performed here; + * the caller must free this string. + * + * \return the status of the command execution. + */ +eExecStatus e_actuator_cmd_get_value( eModId xModId, signed short FsNavId, + int ac, signed portCHAR *av[], + signed portCHAR **ppcStringReply ) +{ + int i; + xLogDef *pxLog; + + + /* 0) If the way to reply is unavailable, it's no use to continue. */ + if( ppcStringReply == NULL ) + return( SHELL_EXECSTATUS_KO ); + + /* 1) Check the input. */ + // i) Two arguments exactly. + if( 2 != ac ) + { // Syntax error. + *ppcStringReply = (signed portCHAR *)ACTUATOR_ERRMSG_GETVAL_SYNTAXERROR; + return( SHELL_EXECSTATUS_KO ); + } + // No need to check that av[0] == actuator. We actually use the "actuator=name" + // format just to comply with the cgi calls rules. + + // ii) Identify the actuator. + for( i=DATALOG_ID_LEDB1; + i<=DATALOG_ID_LCD && strcmp( (char *)av[1], acLogSourceName[i] ); + i++ ); + i -= DATALOG_ID_LEDB1; // Scale the index to fit for the actuator only array. + + if( ACTUATOR_MAXNB_ACTUATORS == i ) + { // Unreferenced actuator. + *ppcStringReply = (signed portCHAR *)ACTUATOR_ERRMSG_UNREFACTUATOR; + return( SHELL_EXECSTATUS_KO ); + } + + /* 3) Perform the command. */ + // Alloc and init a log. + pxLog = pxdatalog_log_alloc_init( DATALOG_ALLOC_DYNAMIC ); + if( NULL == pxLog ) + { + *ppcStringReply = (signed portCHAR *)SHELL_ERRMSG_MEMALLOC; + return( SHELL_EXECSTATUS_KO ); + } + + // Init the id field of the log. + pxLog->id = i+DATALOG_ID_LEDB1; + + // Get the value. + if( false == axActuatorsRegistry[i].pfGetActuatorValue( pxLog ) ) + { + vdatalog_log_free( pxLog ); + *ppcStringReply = (signed portCHAR *)ACTUATOR_ERRMSG_GETVAL_FAIL; + return( SHELL_EXECSTATUS_KO ); + } + + /* 4) Build the reply. */ + // Alloc space for the reply. + *ppcStringReply = (signed portCHAR *)pvPortMalloc( DATALOG_LOG_MAXSIZE ); + if( NULL == *ppcStringReply ) + { + vdatalog_log_free( pxLog ); + *ppcStringReply = (signed portCHAR *)SHELL_ERRMSG_MEMALLOC; + return( SHELL_EXECSTATUS_KO ); + } + + // Build the string. + vdatalog_make_logstring( pxLog, *ppcStringReply ); + + // Free the log. + vdatalog_log_free( pxLog ); + + return( SHELL_EXECSTATUS_OK ); +} + + +/* \brief The set actuator value command: set the value(s) or state(s) of an actuator. + * Takes up to eight parameters + * The first parameter is the cte actuator indicator, the second is the actuator's name, + * the third parameter is a field name, the fourth parameter is its value, the fifth is + * another field name(optional), the sixth is its value(optional), + * the seventh is the time parameter(optional), the eighth is the time value(optional). + * Format: set_actuator_value actuator=actuatorname field1=value [field2=value] [time=date] + * + * \note This function must be of the type pfShellCmd defined by the shell module. + * + * \param xModId Input. The module that is calling this function. + * \param FsNavId Ignored. + * \param ac Input. The argument counter. For this command, should be + * at least 4, at most 8. + * \param av Input. The argument vector. + * \param ppcStringReply Input/Output. The response string. + * If Input is NULL, no response string will be output. + * Else a malloc for the response string is performed here; + * the caller must free this string. + * + * \return the status of the command execution. + */ +eExecStatus e_actuator_cmd_set_value( eModId xModId, signed short FsNavId, + int ac, signed portCHAR *av[], + signed portCHAR **ppcStringReply ) +{ + int i; + + + /* 0) If the way to reply is unavailable, it's no use to continue. */ + if( ppcStringReply == NULL ) + return( SHELL_EXECSTATUS_KO ); + + /* 1) Check the input. */ + // i) Arguments: at least 4, at most 8. + if( ( 4 > ac ) || ( 8 < ac ) ) + { // Syntax error. + *ppcStringReply = (signed portCHAR *)ACTUATOR_ERRMSG_SETVAL_SYNTAXERROR; + return( SHELL_EXECSTATUS_KO ); + } + // No need to check that av[0] == actuator. We actually use the "actuator=name" + // format just to comply with the cgi calls rules. + + // ii) Identify the actuator. + for( i=DATALOG_ID_LEDB1; + i<=DATALOG_ID_LCD && strcmp( (char *)av[1], acLogSourceName[i] ); + i++ ); + i -= DATALOG_ID_LEDB1; // Scale the index to fit for the actuator only array. + + if( ACTUATOR_MAXNB_ACTUATORS == i ) + { + *ppcStringReply = (signed portCHAR *)ACTUATOR_ERRMSG_UNREFACTUATOR; + return( SHELL_EXECSTATUS_KO ); + } + + /* 3) Perform the command. */ + return( axActuatorsRegistry[i].pfSetActuatorValue( xModId, ac-2, &(av[2]), ppcStringReply ) ); +} + + +/*! + * \brief Execute a scheduled command. + * + * \param CmdId Input. The set cmd identifier. + * \param pxCmdParams Input. The parameters (ac,*av[]) for the cmd. + */ +void vExecScheduledSet( int CmdId, void *pxCmdParams ) +{ + Scheduled_Cmd_Params *pxActuatorCmdParams; + int i; + + + // Cast pxCmdParams to the appropriate struct. + pxActuatorCmdParams = (Scheduled_Cmd_Params *)pxCmdParams; + switch( CmdId ) + { + case CPTIME_SCHEDCMDID_SETLEDM1VAL: + e_ledm1_set_value( SYS_MODID_NONE, pxActuatorCmdParams->ac, pxActuatorCmdParams->av, NULL ); + break; + + case CPTIME_SCHEDCMDID_SETLEDM2VAL: + e_ledm2_set_value( SYS_MODID_NONE, pxActuatorCmdParams->ac, pxActuatorCmdParams->av, NULL ); + break; + + case CPTIME_SCHEDCMDID_SETLEDB1VAL: + e_ledb1_set_value( SYS_MODID_NONE, pxActuatorCmdParams->ac, pxActuatorCmdParams->av, NULL ); + break; + + case CPTIME_SCHEDCMDID_SETLEDB2VAL: + e_ledb2_set_value( SYS_MODID_NONE, pxActuatorCmdParams->ac, pxActuatorCmdParams->av, NULL ); + break; + + case CPTIME_SCHEDCMDID_SETLCDVAL: + e_lcd_set_value( SYS_MODID_NONE, pxActuatorCmdParams->ac, pxActuatorCmdParams->av, NULL ); + break; + } + // Free the string params and the params struct. + for( i=0; iac; i++ ) + { + vPortFree( pxActuatorCmdParams->av[i] ); + } + vPortFree( pxActuatorCmdParams ); +} + + +/*! + * \brief Schedule an actuator set for later. + * + * \param CmdId Input. The set actuator cmd identifier. + * \param ac Input. The argument counter. + * \param av Input. The argument vector. + * \param ppcStringReply Input/Output. The response string. + * If Input is NULL, no response string will be output. + * If the action is successful, no response string is output. + * If the action failed, a response string is output. + * + * \return the status of the command execution. + */ +eExecStatus e_actuator_ScheduleCmdSet( eSchedCmdId CmdId, + int ac, signed portCHAR *av[], + signed portCHAR **ppcStringReply ) +{ + int i,j; + Scheduled_Cmd_Params *pxCmdParams; + + + // Check that the before-last param is "time". + if( strcmp( (char *)av[ac-2], "time" ) ) + { + *ppcStringReply = (signed portCHAR *)ACTUATOR_ERRMSG_SETVAL_SYNTAXERROR; + return( SHELL_EXECSTATUS_KO ); + } + + // Alloc and fill a param structure that contains the parameters that will + // be given to the scheduled function when it will execute. + pxCmdParams = pvPortMalloc( sizeof(Scheduled_Cmd_Params) ); + if( NULL == pxCmdParams ) + { + *ppcStringReply = (signed portCHAR *)SHELL_ERRMSG_MEMALLOC; + return( SHELL_EXECSTATUS_KO ); + } + + // Alloc the params. + pxCmdParams->ac = ac-2; + for( i=0; iac; i++ ) + { + pxCmdParams->av[i] = pvPortMalloc( strlen( (char *)av[i] ) +1 ); + if( NULL == pxCmdParams->av[i] ) + { // An alloc failed => free previous alloc. + for(j=0; jav[j] ); + } + vPortFree( pxCmdParams ); + *ppcStringReply = (signed portCHAR *)SHELL_ERRMSG_MEMALLOC; + return( SHELL_EXECSTATUS_KO ); + } + } + + // Copy the params. + for( i=0; iac; i++ ) + { + strcpy( (char *)pxCmdParams->av[i], (char *)av[i] ); + } + + // Record the cmd. + return( e_cptime_RecordScheduledCmd( (char *)av[ac-1], + CmdId, + vExecScheduledSet, + pxCmdParams, + ppcStringReply) ); +} + + +/* \brief The actuator command: display the actuators available shell commands. + * Format: help + * + * \note This function must be of the type pfShellCmd defined by the shell module. + * + * \param xModId Input. The module that is calling this function. + * \param FsNavId Ignored. + * \param ac Ignored. + * \param av Ignored. + * \param ppcStringReply Input/Output. The response string. + * If Input is NULL, no response string will be output. + * Else a malloc for the response string is performed here; + * the caller must free this string. + * + * \return the status of the command execution. + */ +eExecStatus e_actuator_help( eModId xModId, signed short FsNavId, + int ac, signed portCHAR *av[], + signed portCHAR **ppcStringReply ) +{ + // 1) If the way to reply is unavailable, it's no use to continue. + if( ppcStringReply == NULL ) + return( SHELL_EXECSTATUS_KO ); + + // 2) Perform the command. + *ppcStringReply = (signed portCHAR *)ACTUATOR_MSG_HELP; + + return( SHELL_EXECSTATUS_OK_NO_FREE ); +} diff --git a/pool/shard000/C/0015257_mercator.c b/pool/shard000/C/0015257_mercator.c new file mode 100644 index 0000000000000000000000000000000000000000..a81f27ad77405e80d1b8c3667ff4ef04dd806125 --- /dev/null +++ b/pool/shard000/C/0015257_mercator.c @@ -0,0 +1,58 @@ +/*------------------------------------------------------------------------ + * mercator + *------------------------------------------------------------------------*/ +static const char mercator_c_rcsid[] = "$Id: mercator.c 16072 2010-01-30 19:39:09Z brodzik $"; + +#include "define.h" +#include "mapx.h" + +const char *id_mercator(void) +{ + return mercator_c_rcsid; +} + +int init_mercator(mapx_class *current) +{ + if (current->lat1 == 999) current->lat1 = 30.00; + current->cos_phi1 = cos (RADIANS (current->lat1)); + + return 0; +} + +int mercator(mapx_class *current, double lat, double lon, double *x, double *y) +{ + double dlon; + double phi, lam; + + dlon = lon - current->lon0; + NORMALIZE(dlon); + + phi = RADIANS (lat); + lam = RADIANS (dlon); + + *x = current->Rg * lam; + *y = current->Rg * log (tan (PI/4 + phi/2)); + + *x += current->false_easting; + *y += current->false_northing; + + return 0; +} + +int inverse_mercator(mapx_class *current, + double x, double y, double *lat, double *lon) +{ + double phi, lam; + + x -= current->false_easting; + y -= current->false_northing; + + phi = PI/2 - 2*atan(exp(-y/current->Rg)); + lam = x/current->Rg; + + *lat = DEGREES(phi); + *lon = DEGREES(lam) + current->lon0; + NORMALIZE(*lon); + + return 0; +} diff --git a/pool/shard000/C/0015261_endian.c b/pool/shard000/C/0015261_endian.c new file mode 100644 index 0000000000000000000000000000000000000000..0066fdc6c474bf8b9cece7422651cc5369c53bcb --- /dev/null +++ b/pool/shard000/C/0015261_endian.c @@ -0,0 +1,194 @@ +/* + This file is part of Trillian. + Audio convolution utility. + Trillian homepage : http://code.google.com/p/trillian. + + Copyright (C) 2010 Mike Jones + + Trillian 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. + + Trillian 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 Trillian. If not, see . +*/ + +/** + Runtime endian operations + See: http://www.ibm.com/developerworks/aix/library/au-endianc/index.html?ca=drs- + http://www.gdargaud.net/Hack/SourceCode.html + http://www.gamedev.net/reference/articles/article2091.asp + + @important InitEndian needs to be called before you start calling the endian functions + othewise strange things will start happening +*/ + +#include "endian.h" +#include + +#ifdef __cplusplus +extern "C" { +#endif //__cplusplus + +const int testEndian = 1; + +unsigned short (*BigUShort) ( unsigned short pVar ); +unsigned short (*LittleUShort) ( unsigned short pVar ); +unsigned long (*BigULong) ( unsigned long pVar ); +unsigned long (*LittleULong) ( unsigned long pVar ); +short (*BigShort) ( short pVar ); +short (*LittleShort) ( short pVar ); +long (*BigLong) ( long pVar ); +long (*LittleLong) ( long pVar ); +float (*BigFloat) ( float pVar ); +float (*LittleFloat) ( float pVar ); + + +/** + Map function pointers to correct functions for the endian of the system running +*/ +void InitEndian() +{ + if( IS_BIG_ENDIAN() ) + { + BigUShort = NO_FLIP_USHORT; + LittleUShort = FLIP_USHORT; + BigULong = NO_FLIP_ULONG; + LittleULong = FLIP_ULONG; + BigShort = NO_FLIP_SHORT; + LittleShort = FLIP_SHORT; + BigLong = NO_FLIP_LONG; + LittleLong = FLIP_LONG; + BigFloat = NO_FLIP_FLOAT; + LittleFloat = FLIP_FLOAT; + } + else + { + BigUShort = FLIP_USHORT; + LittleUShort = NO_FLIP_USHORT; + BigULong = FLIP_ULONG; + LittleULong = NO_FLIP_ULONG; + BigShort = FLIP_SHORT; + LittleShort = NO_FLIP_SHORT; + BigLong = FLIP_LONG; + LittleLong = NO_FLIP_LONG; + BigFloat = FLIP_FLOAT; + LittleFloat = NO_FLIP_FLOAT; + } +} + +unsigned long FLIP_ULONG(unsigned long pVar) +{ + return *(unsigned long*) FlipEndian((void*)&pVar, sizeof(unsigned long)); +} + +unsigned short FLIP_USHORT(unsigned short pVar) +{ + return *(unsigned short*) FlipEndian((void*)&pVar, sizeof(unsigned short)); +} + +long FLIP_LONG(long pVar) +{ + return *(long*) FlipEndian((void*)&pVar, sizeof(long)); +} + +short FLIP_SHORT(short pVar) +{ + return *(short*) FlipEndian((void*)&pVar, sizeof(short)); +} + +float FLIP_FLOAT(float pVar) +{ + return *(float*) FlipEndian((void*)&pVar, sizeof(float)); +} + + +unsigned long NO_FLIP_ULONG(unsigned long pVar) +{ + return pVar; +} + +unsigned short NO_FLIP_USHORT(unsigned short pVar) +{ + return pVar; +} + +long NO_FLIP_LONG(long pVar) +{ + return pVar; +} + +short NO_FLIP_SHORT(short pVar) +{ + return pVar; +} + +float NO_FLIP_FLOAT(float pVar) +{ + return pVar; +} + + +/* + Performs an endian swap up to 16bytes [2,3,4,8,16] + TODO: See if bit shift version is faster +*/ +void* FlipEndian(void* pAddr, const int pNb) +{ + static char Swapped[16]; + switch (pNb) { + case 2: Swapped[0]=*((char*)pAddr+1); + Swapped[1]=*((char*)pAddr ); + break; + case 3: + Swapped[0]=*((char*)pAddr+2); + Swapped[1]=*((char*)pAddr+1); + Swapped[2]=*((char*)pAddr ); + break; + case 4: Swapped[0]=*((char*)pAddr+3); + Swapped[1]=*((char*)pAddr+2); + Swapped[2]=*((char*)pAddr+1); + Swapped[3]=*((char*)pAddr ); + break; + case 8: Swapped[0]=*((char*)pAddr+7); + Swapped[1]=*((char*)pAddr+6); + Swapped[2]=*((char*)pAddr+5); + Swapped[3]=*((char*)pAddr+4); + Swapped[4]=*((char*)pAddr+3); + Swapped[5]=*((char*)pAddr+2); + Swapped[6]=*((char*)pAddr+1); + Swapped[7]=*((char*)pAddr ); + break; + case 16:Swapped[0] =*((char*)pAddr+15); + Swapped[1] =*((char*)pAddr+14); + Swapped[2] =*((char*)pAddr+13); + Swapped[3] =*((char*)pAddr+12); + Swapped[4] =*((char*)pAddr+11); + Swapped[5] =*((char*)pAddr+10); + Swapped[6] =*((char*)pAddr+9 ); + Swapped[7] =*((char*)pAddr+8 ); + Swapped[8] =*((char*)pAddr+7 ); + Swapped[9] =*((char*)pAddr+6 ); + Swapped[10]=*((char*)pAddr+5 ); + Swapped[11]=*((char*)pAddr+4 ); + Swapped[12]=*((char*)pAddr+3 ); + Swapped[13]=*((char*)pAddr+2 ); + Swapped[14]=*((char*)pAddr+1 ); + Swapped[15]=*((char*)pAddr ); + break; + default: + printf("!! FlipEndian(): Can't do a flip on %i bytes !!\n", pNb); + break; + } + return (void*)Swapped; +} + +#ifdef __cplusplus +} +#endif //__cplusplus \ No newline at end of file diff --git a/pool/shard000/C/0015262_beecrypt_provider_SHA256.c b/pool/shard000/C/0015262_beecrypt_provider_SHA256.c new file mode 100644 index 0000000000000000000000000000000000000000..42555b12cc7ad22c3b343bc3cb16f73bf3ab040c --- /dev/null +++ b/pool/shard000/C/0015262_beecrypt_provider_SHA256.c @@ -0,0 +1,113 @@ +#if HAVE_CONFIG_H +# include "config.h" +#endif + +#include "beecrypt/sha256.h" + +#if JAVAGLUE + +#if HAVE_STDLIB_H +# include +#endif +#if HAVE_MALLOC_H +# include +#endif + +#include "beecrypt/java/beecrypt_provider_SHA256.h" + +jlong JNICALL Java_beecrypt_provider_SHA256_allocParam(JNIEnv* env, jclass dummy) +{ + jlong param = (jlong) malloc(sizeof(sha256Param)); + if (param == 0) + { + jclass ex = (*env)->FindClass(env, "java/lang/OutOfMemoryError"); + if (ex) + (*env)->ThrowNew(env, ex, (const char*) 0); + } + + sha256Reset((sha256Param*) param); + + return param; +} + +jlong JNICALL Java_beecrypt_provider_SHA256_cloneParam(JNIEnv* env, jclass dummy, jlong param) +{ + jlong clone = (jlong) malloc(sizeof(sha256Param)); + if (clone == 0) + { + jclass ex = (*env)->FindClass(env, "java/lang/OutOfMemoryError"); + if (ex) + (*env)->ThrowNew(env, ex, (const char*) 0); + } + + memcpy((void*) clone, (void*) param, sizeof(sha256Param)); + + return clone; +} + +void JNICALL Java_beecrypt_provider_SHA256_freeParam(JNIEnv* env, jclass dummy, jlong param) +{ + if (param) + free((void*) param); +} + +jbyteArray JNICALL Java_beecrypt_provider_SHA256_digest__J(JNIEnv* env, jclass dummy, jlong param) +{ + jbyte digest[32]; + jbyteArray result = (*env)->NewByteArray(env, 32); + + sha256Digest((sha256Param*) param, digest); + + (*env)->SetByteArrayRegion(env, result, 0, 32, digest); + + return result; +} + +jint JNICALL Java_beecrypt_provider_SHA256_digest__J_3BII(JNIEnv* env, jclass dummy, jlong param, jbyteArray buf, jint off, jint len) +{ + if (len < 32) + { + jclass ex = (*env)->FindClass(env, "java/security/DigestException"); + if (ex) + (*env)->ThrowNew(env, ex, "len must be at least 32"); + } + else + { + jbyte digest[32]; + + sha256Digest((sha256Param*) param, digest); + + (*env)->SetByteArrayRegion(env, buf, off, 32, digest); + + return 32; + } +} + +void JNICALL Java_beecrypt_provider_SHA256_reset(JNIEnv* env, jclass dummy, jlong param) +{ + sha256Reset((sha256Param*) param); +} + +void JNICALL Java_beecrypt_provider_SHA256_update__JB(JNIEnv* env, jclass dummy, jlong param, jbyte input) +{ + sha256Update((sha256Param*) param, &input, 1); +} + +void JNICALL Java_beecrypt_provider_SHA256_update__J_3BII(JNIEnv* env, jclass dummy, jlong param, jbyteArray input, jint off, jint len) +{ + jbyte* data = (*env)->GetByteArrayElements(env, input, 0); + if (data) + { + sha256Update((sha256Param*) param, data+off, len); + + (*env)->ReleaseByteArrayElements(env, input, data, JNI_ABORT); + } + else + { + jclass ex = (*env)->FindClass(env, "java/lang/NullPointerException"); + if (ex) + (*env)->ThrowNew(env, ex, (const char*) 0); + } +} + +#endif diff --git a/pool/shard000/C/0015263_test_sdap_access.c b/pool/shard000/C/0015263_test_sdap_access.c new file mode 100644 index 0000000000000000000000000000000000000000..900cfdba91c4542a7ccd7b0f591b38cd1908314d --- /dev/null +++ b/pool/shard000/C/0015263_test_sdap_access.c @@ -0,0 +1,264 @@ +/* + Authors: + Pavel Reichl + + Copyright (C) 2015 Red Hat + + SSSD tests - sdap access + + 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 +#include +#include +#include +#include + +#include "tests/common_check.h" +#include "tests/cmocka/test_expire_common.h" +#include "tests/cmocka/test_sdap_access.h" + +/* linking against function from sdap_access.c module */ +extern bool nds_check_expired(const char *exp_time_str); +extern errno_t sdap_access_rhost(struct ldb_message *user_entry, char *pam_rhost); + +static void nds_check_expired_wrap(void *in, void *_out) +{ + *(bool*)_out = nds_check_expired((const char*)in); +} + +void test_nds_check_expire(void **state) +{ + struct expire_test_ctx *tc; + bool res; + + tc = talloc_get_type(*state, struct expire_test_ctx); + assert_non_null(tc); + + assert_false(nds_check_expired(NULL)); + assert_true(nds_check_expired(tc->invalid_longer_format)); + assert_true(nds_check_expired(tc->invalid_format)); + assert_true(nds_check_expired(tc->past_time)); + assert_false(nds_check_expired(tc->future_time)); + + /* changing time zone has no effect as time of expiration is in UTC */ + expire_test_tz("GST+2", nds_check_expired_wrap, (void*)tc->future_time, + (void*)&res); + assert_false(res); + expire_test_tz("GST-2", nds_check_expired_wrap, (void*)tc->future_time, + (void*)&res); + assert_false(res); +} + +static int test_sdap_access_rhost_setup(void **state) +{ + TALLOC_CTX *mem_ctx; + struct test_sdap_access_rhost_ctx *test_ctx; + struct ldb_message *user_no_rhost; + struct ldb_message *user_allow_somehost; + struct ldb_message *user_deny_somehost; + struct ldb_message *user_allow_all; + struct ldb_message *user_allow_all_deny_somehost; + struct ldb_message *user_allow_all_allow_somehost_deny_somehost; + + mem_ctx = talloc_new(NULL); + assert_non_null(mem_ctx); + + test_ctx = talloc(mem_ctx, struct test_sdap_access_rhost_ctx); + assert_non_null(test_ctx); + + /* Setup empty user entry (with 0 entries for rhost) */ + user_no_rhost = ldb_msg_new(test_ctx); + assert_non_null(user_no_rhost); + user_no_rhost->num_elements = 0; + + /* Setup user entry with allow somehost */ + user_allow_somehost = ldb_msg_new(test_ctx); + assert_non_null(user_allow_somehost); + ldb_msg_add_string(user_allow_somehost, + SYSDB_AUTHORIZED_RHOST, + "somehost"); + + /* Setup user entry with deny somehost */ + user_deny_somehost = ldb_msg_new(test_ctx); + assert_non_null(user_deny_somehost); + ldb_msg_add_string(user_deny_somehost, + SYSDB_AUTHORIZED_RHOST, + "!somehost"); + + /* Setup user entry with allow all */ + user_allow_all = ldb_msg_new(test_ctx); + assert_non_null(user_allow_all); + ldb_msg_add_string(user_allow_all, + SYSDB_AUTHORIZED_RHOST, + "*"); + + /* Setup user entry with allow all and deny somehost */ + user_allow_all_deny_somehost = ldb_msg_new(test_ctx); + assert_non_null(user_allow_all_deny_somehost); + ldb_msg_add_string(user_allow_all_deny_somehost, + SYSDB_AUTHORIZED_RHOST, + "*"); + ldb_msg_add_string(user_allow_all_deny_somehost, + SYSDB_AUTHORIZED_RHOST, + "!somehost"); + + /* Setup user entry with allow all, allow somehost and deny somehost */ + user_allow_all_allow_somehost_deny_somehost = ldb_msg_new(test_ctx); + assert_non_null(user_allow_all_allow_somehost_deny_somehost); + ldb_msg_add_string(user_allow_all_allow_somehost_deny_somehost, + SYSDB_AUTHORIZED_RHOST, + "*"); + ldb_msg_add_string(user_allow_all_allow_somehost_deny_somehost, + SYSDB_AUTHORIZED_RHOST, + "!somehost"); + ldb_msg_add_string(user_allow_all_allow_somehost_deny_somehost, + SYSDB_AUTHORIZED_RHOST, + "somehost"); + + /* Setup test context */ + test_ctx->user_no_rhost = user_no_rhost; + test_ctx->user_allow_somehost = user_allow_somehost; + test_ctx->user_deny_somehost = user_deny_somehost; + test_ctx->user_allow_all = user_allow_all; + test_ctx->user_allow_all_deny_somehost = user_allow_all_deny_somehost; + test_ctx->user_allow_all_allow_somehost_deny_somehost = \ + user_allow_all_allow_somehost_deny_somehost; + + *state = test_ctx; + + return 0; +} + +static int test_sdap_access_rhost_teardown(void **state) +{ + struct test_sdap_access_rhost_ctx *test_ctx; + + test_ctx = talloc_get_type(*state, struct test_sdap_access_rhost_ctx); + assert_non_null(test_ctx); + + talloc_free(test_ctx); + + return 0; +} + +static void test_sdap_access_rhost(void **state) +{ + struct test_sdap_access_rhost_ctx *test_ctx; + errno_t ret; + + test_ctx = talloc_get_type(*state, struct test_sdap_access_rhost_ctx); + assert_non_null(test_ctx); + + char pam_rhost_mock_empty[] = ""; + char pam_rhost_mock_somehost[] = "somehost"; + char pam_rhost_mock_someotherhost[] = "someotherhost"; + + /* Test both arguments as NULL */ + ret = sdap_access_rhost(NULL, NULL); + assert_int_equal(ERR_ACCESS_DENIED, ret); /* Expected access granted */ + + /* Test with user_entry == NULL and rhost == "somehost" */ + ret = sdap_access_rhost(NULL, pam_rhost_mock_somehost); + assert_int_equal(ERR_ACCESS_DENIED, ret); /* Expected access denied */ + + /* Test with user_no_rhost and rhost == NULL */ + ret = sdap_access_rhost(test_ctx->user_no_rhost, NULL); + assert_int_equal(EOK, ret); /* Expected access granted */ + + /* Test with user_no_rhost and rhost == "" (local access) */ + ret = sdap_access_rhost(test_ctx->user_no_rhost, pam_rhost_mock_empty); + assert_int_equal(EOK, ret); /* Expected access granted */ + + /* Test with user_no_rhost and rhost == "somehost" */ + ret = sdap_access_rhost(test_ctx->user_no_rhost, pam_rhost_mock_somehost); + assert_int_equal(ERR_ACCESS_DENIED, ret); /* Expected access denied */ + + /* Test with user_allow_somehost and rhost == "somehost" */ + ret = sdap_access_rhost(test_ctx->user_allow_somehost, + pam_rhost_mock_somehost); + assert_int_equal(EOK, ret); /* Expected access allowed */ + + /* Test with user_deny_somehost and rhost == "somehost" */ + ret = sdap_access_rhost(test_ctx->user_deny_somehost, + pam_rhost_mock_somehost); + assert_int_equal(ERR_ACCESS_DENIED, ret); /* Expected access denied */ + + /* Test with user_allow_all and rhost == "somehost" */ + ret = sdap_access_rhost(test_ctx->user_allow_all, + pam_rhost_mock_somehost); + assert_int_equal(EOK, ret); /* Expected access allowed */ + + /* Test with user_allow_all_deny_somehost and rhost == "somehost" */ + ret = sdap_access_rhost(test_ctx->user_allow_all_deny_somehost, + pam_rhost_mock_somehost); + assert_int_equal(ERR_ACCESS_DENIED, ret); /* Expected access denied */ + + /* Test with user_allow_all_allow_somehost_deny_somehost + * and rhost == "somehost" */ + ret = sdap_access_rhost( + test_ctx->user_allow_all_allow_somehost_deny_somehost, + pam_rhost_mock_somehost); + assert_int_equal(ERR_ACCESS_DENIED, ret); /* Expected access denied */ + + /* Test with user_no_rhost and rhost == "someotherhost" */ + ret = sdap_access_rhost(test_ctx->user_no_rhost, + pam_rhost_mock_someotherhost); + assert_int_equal(ERR_ACCESS_DENIED, ret); /* Expected access denied */ + + /* Test with user_allow_somehost and rhost == "someotherhost" */ + ret = sdap_access_rhost(test_ctx->user_allow_somehost, + pam_rhost_mock_someotherhost); + assert_int_equal(ERR_ACCESS_DENIED, ret); /* Expected access denied */ + + /* Test with user_deny_somehost and rhost == "someotherhost" */ + ret = sdap_access_rhost(test_ctx->user_deny_somehost, + pam_rhost_mock_someotherhost); + assert_int_equal(ERR_ACCESS_DENIED, ret); /* Expected access denied */ + + /* Test with user_allow_all and rhost == "someotherhost" */ + ret = sdap_access_rhost(test_ctx->user_allow_all, + pam_rhost_mock_someotherhost); + assert_int_equal(EOK, ret); /* Expected access allowed */ + + /* Test with user_allow_all_deny_somehost and rhost == "someotherhost" */ + ret = sdap_access_rhost(test_ctx->user_allow_all_deny_somehost, + pam_rhost_mock_someotherhost); + assert_int_equal(EOK, ret); /* Expected access allowed */ + + /* Test with user_allow_all_allow_somehost_deny_somehost + * and rhost == "someotherhost" */ + ret = sdap_access_rhost( + test_ctx->user_allow_all_allow_somehost_deny_somehost, + pam_rhost_mock_someotherhost); + assert_int_equal(EOK, ret); /* Expected access allowed */ +} + +int main(void) +{ + const struct CMUnitTest tests[] = { + cmocka_unit_test_setup_teardown(test_nds_check_expire, + expire_test_setup, + expire_test_teardown), + cmocka_unit_test_setup_teardown(test_sdap_access_rhost, + test_sdap_access_rhost_setup, + test_sdap_access_rhost_teardown), + }; + + return cmocka_run_group_tests(tests, NULL, NULL); +} diff --git a/pool/shard000/C/0015266_mon_stat.c b/pool/shard000/C/0015266_mon_stat.c new file mode 100644 index 0000000000000000000000000000000000000000..98ab0cc473d675592ff54ceea1ae99d408eb446e --- /dev/null +++ b/pool/shard000/C/0015266_mon_stat.c @@ -0,0 +1,71 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * The USB Monitor, inspired by Dave Harding's USBMon. + * + * This is the 's' or 'stat' reader which debugs usbmon itself. + * Note that this code blows through locks, so make sure that + * /dbg/usbmon/0s is well protected from non-root users. + * + */ + +#include +#include +#include +#include +#include +#include + +#include "usb_mon.h" + +#define STAT_BUF_SIZE 80 + +struct snap { + int slen; + char str[STAT_BUF_SIZE]; +}; + +static int mon_stat_open(struct inode *inode, struct file *file) +{ + struct mon_bus *mbus; + struct snap *sp; + + sp = kmalloc(sizeof(struct snap), GFP_KERNEL); + if (sp == NULL) + return -ENOMEM; + + mbus = inode->i_private; + + sp->slen = snprintf(sp->str, STAT_BUF_SIZE, + "nreaders %d events %u text_lost %u\n", + mbus->nreaders, mbus->cnt_events, mbus->cnt_text_lost); + + file->private_data = sp; + return 0; +} + +static ssize_t mon_stat_read(struct file *file, char __user *buf, + size_t nbytes, loff_t *ppos) +{ + struct snap *sp = file->private_data; + + return simple_read_from_buffer(buf, nbytes, ppos, sp->str, sp->slen); +} + +static int mon_stat_release(struct inode *inode, struct file *file) +{ + struct snap *sp = file->private_data; + file->private_data = NULL; + kfree(sp); + return 0; +} + +const struct file_operations mon_fops_stat = { + .owner = THIS_MODULE, + .open = mon_stat_open, + .llseek = no_llseek, + .read = mon_stat_read, + /* .write = mon_stat_write, */ + /* .poll = mon_stat_poll, */ + /* .unlocked_ioctl = mon_stat_ioctl, */ + .release = mon_stat_release, +}; diff --git a/pool/shard000/C/0015272_servo.c b/pool/shard000/C/0015272_servo.c new file mode 100644 index 0000000000000000000000000000000000000000..be3461b7b53105c22cdb2fc681f8450ea92e1eba --- /dev/null +++ b/pool/shard000/C/0015272_servo.c @@ -0,0 +1,58 @@ +/* + *Jace Pounds + *Control a servo motor with two bttons + *program #6 + *06/15/17 +*/ +#include "simpletools.h" +#include "servo.h" +//constants are names we use to make our program easier to understand and maintain// + +const int RIGHT = (9); +const int LEFT = (2); +const int servo = (14); + +//servo angles in our library are shown x10, for example, 90 deg = 900 + +const int RSTOP = 1700; +const int LSTOP = 10; + + +int main() +{ + int angle = 900; + + while(1) + { // get pushbutton state// + if(input(LEFT) == 1) + { + angle = angle - 18; + } + + if (input(RIGHT) == 1) + { + angle = angle + 18; + } + //limit the angle of the servo to keep it from breaking// + + if (angle > RSTOP) + { + angle = RSTOP; + } + + if (angle < LSTOP) + { + angle = LSTOP; + } + + //update the serial console (screen output) + print( "%c angle = %d %c", HOME, angle, CLREOL); + + servo_angle(servo, angle); + + pause(25); + + //end of while loop// + } + +} \ No newline at end of file diff --git a/pool/shard000/C/0015274_hypot.c b/pool/shard000/C/0015274_hypot.c new file mode 100644 index 0000000000000000000000000000000000000000..1dcb729b07a5b27b12f13044acf747ee0f571f84 --- /dev/null +++ b/pool/shard000/C/0015274_hypot.c @@ -0,0 +1,187 @@ +/* mpfr_hypot -- Euclidean distance + +Copyright 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc. +Contributed by the Arenaire and Cacao 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" + +/* The computation of hypot of x and y is done by * + * hypot(x,y)= sqrt(x^2+y^2) = z */ + +int +mpfr_hypot (mpfr_ptr z, mpfr_srcptr x, mpfr_srcptr y, mpfr_rnd_t rnd_mode) +{ + int inexact, exact; + mpfr_t t, te, ti; /* auxiliary variables */ + mpfr_prec_t N, Nz; /* size variables */ + mpfr_prec_t Nt; /* precision of the intermediary variable */ + mpfr_prec_t threshold; + mpfr_exp_t Ex, sh; + mpfr_uexp_t diff_exp; + + MPFR_SAVE_EXPO_DECL (expo); + MPFR_ZIV_DECL (loop); + MPFR_BLOCK_DECL (flags); + + /* particular cases */ + if (MPFR_ARE_SINGULAR (x, y)) + { + if (MPFR_IS_INF (x) || MPFR_IS_INF (y)) + { + /* Return +inf, even when the other number is NaN. */ + MPFR_SET_INF (z); + MPFR_SET_POS (z); + MPFR_RET (0); + } + else if (MPFR_IS_NAN (x) || MPFR_IS_NAN (y)) + { + MPFR_SET_NAN (z); + MPFR_RET_NAN; + } + else if (MPFR_IS_ZERO (x)) + return mpfr_abs (z, y, rnd_mode); + else /* y is necessarily 0 */ + return mpfr_abs (z, x, rnd_mode); + } + + if (mpfr_cmpabs (x, y) < 0) + { + mpfr_srcptr u; + u = x; + x = y; + y = u; + } + + /* now |x| >= |y| */ + + Ex = MPFR_GET_EXP (x); + diff_exp = (mpfr_uexp_t) Ex - MPFR_GET_EXP (y); + + N = MPFR_PREC (x); /* Precision of input variable */ + Nz = MPFR_PREC (z); /* Precision of output variable */ + threshold = (MAX (N, Nz) + (rnd_mode == MPFR_RNDN ? 1 : 0)) << 1; + if (rnd_mode == MPFR_RNDA) + rnd_mode = MPFR_RNDU; /* since the result is positive, RNDA = RNDU */ + + /* Is |x| a suitable approximation to the precision Nz ? + (see algorithms.tex for explanations) */ + if (diff_exp > threshold) + /* result is |x| or |x|+ulp(|x|,Nz) */ + { + if (MPFR_UNLIKELY (rnd_mode == MPFR_RNDU)) + { + /* If z > abs(x), then it was already rounded up; otherwise + z = abs(x), and we need to add one ulp due to y. */ + if (mpfr_abs (z, x, rnd_mode) == 0) + mpfr_nexttoinf (z); + MPFR_RET (1); + } + else /* MPFR_RNDZ, MPFR_RNDD, MPFR_RNDN */ + { + if (MPFR_LIKELY (Nz >= N)) + { + mpfr_abs (z, x, rnd_mode); /* exact */ + MPFR_RET (-1); + } + else + { + MPFR_SET_EXP (z, Ex); + MPFR_SET_SIGN (z, 1); + MPFR_RNDRAW_GEN (inexact, z, MPFR_MANT (x), N, rnd_mode, 1, + goto addoneulp, + if (MPFR_UNLIKELY (++ MPFR_EXP (z) > + __gmpfr_emax)) + return mpfr_overflow (z, rnd_mode, 1); + ); + + if (MPFR_UNLIKELY (inexact == 0)) + inexact = -1; + MPFR_RET (inexact); + } + } + } + + /* General case */ + + N = MAX (MPFR_PREC (x), MPFR_PREC (y)); + + /* working precision */ + Nt = Nz + MPFR_INT_CEIL_LOG2 (Nz) + 4; + + mpfr_init2 (t, Nt); + mpfr_init2 (te, Nt); + mpfr_init2 (ti, Nt); + + MPFR_SAVE_EXPO_MARK (expo); + + /* Scale x and y to avoid overflow/underflow in x^2 and overflow in y^2 + (as |x| >= |y|). The scaling of y can underflow only when the target + precision is huge, otherwise the case would already have been handled + by the diff_exp > threshold code. */ + sh = mpfr_get_emax () / 2 - Ex - 1; + + MPFR_ZIV_INIT (loop, Nt); + for (;;) + { + mpfr_prec_t err; + + exact = mpfr_mul_2si (te, x, sh, MPFR_RNDZ); + exact |= mpfr_mul_2si (ti, y, sh, MPFR_RNDZ); + exact |= mpfr_sqr (te, te, MPFR_RNDZ); + /* Use fma in order to avoid underflow when diff_exp<=MPFR_EMAX_MAX-2 */ + exact |= mpfr_fma (t, ti, ti, te, MPFR_RNDZ); + exact |= mpfr_sqrt (t, t, MPFR_RNDZ); + + err = Nt < N ? 4 : 2; + if (MPFR_LIKELY (exact == 0 + || MPFR_CAN_ROUND (t, Nt-err, Nz, rnd_mode))) + break; + + MPFR_ZIV_NEXT (loop, Nt); + mpfr_set_prec (t, Nt); + mpfr_set_prec (te, Nt); + mpfr_set_prec (ti, Nt); + } + MPFR_ZIV_FREE (loop); + + MPFR_BLOCK (flags, inexact = mpfr_div_2si (z, t, sh, rnd_mode)); + MPFR_ASSERTD (exact == 0 || inexact != 0); + + mpfr_clear (t); + mpfr_clear (ti); + mpfr_clear (te); + + /* + exact inexact + 0 0 result is exact, ternary flag is 0 + 0 non zero t is exact, ternary flag given by inexact + 1 0 impossible (see above) + 1 non zero ternary flag given by inexact + */ + + MPFR_SAVE_EXPO_FREE (expo); + + if (MPFR_OVERFLOW (flags)) + mpfr_set_overflow (); + /* hypot(x,y) >= |x|, thus underflow is not possible. */ + + return mpfr_check_range (z, inexact, rnd_mode); +} diff --git a/pool/shard000/C/0015278_diskio.c b/pool/shard000/C/0015278_diskio.c new file mode 100644 index 0000000000000000000000000000000000000000..a391190898f1285400cf043a65c9aa6e9331e953 --- /dev/null +++ b/pool/shard000/C/0015278_diskio.c @@ -0,0 +1,139 @@ +/* $NetBSD: diskio.c,v 1.2 1997/06/28 21:36:45 leo Exp $ */ + +/* + * Copyright (c) 1995 Waldi Ravens. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by Waldi Ravens. + * 4. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR 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 "stand.h" +#include "atari_stand.h" +#include + +typedef int (*rdsec_f)__P((void *buffer, u_int offset, u_int count)); +typedef struct { rdsec_f rds; u_int rst; u_int rend; } bdevd_t; + +static int rootstrategy __P((void *, int, daddr_t, size_t, void *, size_t *)); +static int rootopen __P((struct open_file *, ...)); +static int rootclose __P((struct open_file *)); +static int rootioctl __P((struct open_file *, u_long, void *)); + +static struct devsw devsw[] = { + { "root", rootstrategy, rootopen, rootclose, rootioctl } +}; +static bdevd_t bootdev; + +/* + * Initialise boot device info. + */ +int +init_dskio (func, label, root) + void *func, *label; + int root; +{ + struct disklabel *dl = label; + struct partition *pd = &dl->d_partitions[root]; + + if (dl->d_magic != DISKMAGIC || dl->d_magic2 != DISKMAGIC + || dl->d_npartitions > MAXPARTITIONS || dkcksum(dl) != 0) { + printf("Invalid disk label.\n"); + return(-1); + } + if (root >= 0) { + if (root >= dl->d_npartitions + || pd->p_fstype != FS_BSDFFS || pd->p_size == 0) { + printf("No suitable root.\n"); + return(-1); + } + bootdev.rds = func; + bootdev.rst = pd->p_offset; + bootdev.rend = pd->p_offset + pd->p_size - 1; + } + return(0); +} + +/* + * No choice, the kernel is loaded from the + * same device as the bootstrap. + */ +int +devopen (f, fname, file) + struct open_file *f; + const char *fname; + char **file; +{ + f->f_devdata = &bootdev; + f->f_dev = &devsw[0]; + *file = (char *)fname; + return(0); +} + +static int +rootstrategy (devd, flag, dblk, size, buf, rsize) + void *devd; + int flag; + daddr_t dblk; + size_t size; + void *buf; + size_t *rsize; +{ + bdevd_t *dd = devd; + daddr_t stb = dd->rst + dblk; + size_t nb = size >> 9; + + if ((flag == F_READ) && !(size & 511) && (stb + nb <= dd->rend)) { + if (!dd->rds(buf, stb, nb)) { + *rsize = size; + return(0); + } + } + *rsize = 0; + return(EIO); +} + +static int +rootopen (f) + struct open_file *f; +{ + return(0); +} + +static int +rootclose (f) + struct open_file *f; +{ + return(EIO); +} + +static int +rootioctl (f, cmd, data) + struct open_file *f; + u_long cmd; + void *data; +{ + return(EIO); +} diff --git a/pool/shard000/C/0015285_common.c b/pool/shard000/C/0015285_common.c new file mode 100644 index 0000000000000000000000000000000000000000..f392a6e7b5e0bdd07b66e79949884c52c093ef1d --- /dev/null +++ b/pool/shard000/C/0015285_common.c @@ -0,0 +1,38 @@ +/** + * Copyright 2015 JiKai. All rights reserved. + * Use of this source code is governed by a BSD-style + * license that can be found in the LICENSE file. + **/ + +#include "common.h" + +error new_error(char* errmsg) { + if (errmsg == NULL) { + return ""; + } + return errmsg; +} + +void* mem_alloc(size_t size) { + void* ptr = malloc(size); + if (ptr != NULL) { + return ptr; + } + assert("malloc panic!!!"); +} + +void mem_free (void *ptr) { + if (ptr != NULL) { + free(ptr); + ptr = NULL; + } +} + +void debug(char* msg) { + printf("%s\r\n", msg); +} + +void fatal(char* msg) { + fprintf(stderr, "%s", msg); + exit(EXIT_FAILURE); +} diff --git a/pool/shard000/C/0015293_test_lwdb.c b/pool/shard000/C/0015293_test_lwdb.c new file mode 100644 index 0000000000000000000000000000000000000000..a52a8e1fbf661a04510b851557e256ec394155b9 --- /dev/null +++ b/pool/shard000/C/0015293_test_lwdb.c @@ -0,0 +1,63 @@ +/** + * @file test_lwdb.c + * @author mathslinux + * @date Sat Jun 9 20:02:38 2012 + * + * @brief Lwqq Database test module + * + * + */ + +#include "login.h" +#include "logger.h" +#include "info.h" +#include "smemory.h" +#include "lwdb.h" + +int main(int argc, char *argv[]) +{ + LwdbGlobalDB *gdb = NULL; + LwdbUserDB *udb = NULL; + LwdbGlobalUserEntry *e = NULL; + LwqqBuddy *b1, b2 = { + .qqnumber = "244569070", + .uin = "4744839", + .nick = "hello", + .phone = "32344556", + }; + + lwdb_init(); + gdb = lwdb_globaldb_new(); + if (!gdb) { + lwqq_log(LOG_ERROR, "error\n"); + goto done; + } + e = gdb->query_user_info(gdb, "3456345"); + if (!e) { + gdb->add_new_user(gdb, "3456345"); + e = gdb->query_user_info(gdb, "3456345"); + if (!e) { + goto done; + } + } + + udb = lwdb_userdb_new("3456345"); + if (!udb) { + goto done; + } + lwqq_log(LOG_NOTICE, "%s,%s,%s,%s,%s\n", + e->qqnumber, e->db_name, e->password, e->status, e->rempwd); + + b1 = udb->query_buddy_info(udb, "244569070"); + if (b1) { + lwqq_buddy_free(b1); + } + udb->update_buddy_info(udb, &b2); + +done: + lwdb_globaldb_free_user_entry(e); + lwdb_globaldb_free(gdb); + lwdb_userdb_free(udb); + lwdb_finalize(); + return 0; +} diff --git a/pool/shard000/C/0015298_read_data_from_stethoscope_and_write.c b/pool/shard000/C/0015298_read_data_from_stethoscope_and_write.c new file mode 100644 index 0000000000000000000000000000000000000000..4e58ec04abf5591798658be07690cfe9e6738ac6 --- /dev/null +++ b/pool/shard000/C/0015298_read_data_from_stethoscope_and_write.c @@ -0,0 +1,245 @@ + +// Copyright (c) 2008-2010, Regents of the University of Colorado. +// This work was supported by NASA contracts NNJ05HE10G, NNC06CB40C, and +// NNC07CB47C. + + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "amedevice.h" +#include "hardware-abstractor.h" + +// Audio calculations +#define CHANNELS 1 +#define FRAME_SIZE 240 +#define SAMPLE_PADDING 8 // Equal to 9600/1200 + + +extern uint32_t gain; + +extern bionet_node_t *node; + +int16_t mulaw2pcm16(uint8_t byte); + + +int unbyte_escape_and_copy(char* dst, char* src, int size) +{ + static int last_was_escape = 0; + int i, j; + + if (last_was_escape && + src[0] == (char)(0xff)) + { + last_was_escape = 0; + i = 1; + } + else + i = 0; + + for (j = 0; i < size; i++, j++) + { + if (src[i] == (char)(0xff)) + { + if (i+1 >= size) + last_was_escape = 1; + else if (src[i+1] == (char)(0xff)) + i++; + } + + memcpy(&dst[i], &src[j], 1); + } + + return j; +} + + +int read_data_from_stethoscope_and_write(int fd, bionet_stream_t * stream, int num_listeners) +{ + static char buffer[512]; + static int buffer_size = 0; + static int state = RSP_STATUS_WAITING; + + int r; + + bionet_resource_t * resource; + + if (state == RSP_STATUS_WAITING) + { + r = read(fd, buffer+buffer_size, 8-buffer_size); + + if (r < 0) + { + if (errno == EAGAIN) + return 0; + + return -1; + } + + buffer_size += r; + + if (buffer_size == 8) + { + if ((r = ame_is_modem_command(buffer))) + { + r = read(fd, buffer+buffer_size, r-buffer_size); + if (0 > r) { + if (EAGAIN == errno || EINTR == errno) { + return 0; + } else { + g_warning("Read error: %m"); + return -1; + } + } + buffer_size = 0; + } + else + state = RSP_STATUS_GOT_COMMAND; + } + } + + if (state == RSP_STATUS_GOT_COMMAND) + { + switch ((uint8_t)buffer[1]) + { + case '#': + g_debug("attempting to purge buffer of crap...buffer_size = %d", buffer_size); + memmove(buffer, buffer+6, buffer_size - 6); + buffer_size -= 6; + state = RSP_STATUS_WAITING; + break; + + case RSP_HEADER: + g_debug("attempting to purge buffer of crap byte...buffer_size = %d", buffer_size); + memmove(buffer, buffer+1, buffer_size - 1); + buffer_size -= 1; + state = RSP_STATUS_WAITING; + break; + + case CMD_READ_BATTERY_STATUS: + g_debug("Received battery response"); + { + float voltage; + struct timeval tv; + + r = gettimeofday(&tv, NULL); + if (r < 0) { + g_warning("error with gettimeofday: %s", strerror(errno)); + return -1; + } + + r = read(fd, buffer+buffer_size, 12-buffer_size); + + if (r <= 0) + { + if (errno == EAGAIN) + return 0; + + return -1; + } + + buffer_size += r; + + voltage = ame_parse_battery_voltage(buffer, buffer_size); + g_debug("Got the battery voltage: %f, size = %d", voltage, buffer_size); + + resource = bionet_node_get_resource_by_id(node, "Battery-Voltage"); + r = bionet_resource_set_float(resource, voltage, &tv); + + if (r < 0) + g_warning("error updating resource value!"); + else + hab_report_datapoints(node); + } + + buffer_size = 0; + state = RSP_STATUS_WAITING; + + break; + + case CMD_RETURN_DATA: + { + // Need to byte escape the bytes that we've already read in... + char tmp[5] = {buffer[3], buffer[4], buffer[5], buffer[6], buffer[7]}; + + buffer_size = 3; + buffer_size += unbyte_escape_and_copy(tmp, buffer+buffer_size, 5); + + state = RSP_STATUS_SAMPLING_ENABLED; + } + break; + + default: + g_debug("Unknown response: %c - Clearing and starting over", buffer[1]); + buffer_size = 0; + state = RSP_STATUS_WAITING; + break; + } + } + + if ((state == RSP_STATUS_SAMPLING_ENABLED) && (num_listeners)) + { + static int size = 248; + + char tmp[256]; + + r = read(fd, tmp, size-buffer_size); + + if (r <= 0) + { + if (errno == EAGAIN) + return 0; + + return -1; + } + + buffer_size += unbyte_escape_and_copy(buffer+buffer_size, tmp, r); + + if (buffer_size == size) + { + uint16_t frame = 0; + int16_t pcm16data[SAMPLE_PADDING*FRAME_SIZE*CHANNELS]; + int i = 0; + + + frame += (uint8_t)buffer[4]; + frame += (uint8_t)(buffer[3] << 8); + g_debug("Got streaming frame %d, start bytes are %c %c %c 0x00 %c %c %c %c", frame, + buffer[0], buffer[1], buffer[2], /*buffer[3],*/ buffer[4], buffer[5], buffer[6], buffer[7]); + + + // Upsample for minimum alsa rate and for stereo + // This method sounds like total shit!!! MUST LPF! + // Also, because 22050/1200 isn't an integer, output will + // underrun about every 5 seconds. Total shit!! + for (i = 0; i < FRAME_SIZE; i++) + { + int k; + + for (k = 0; k < SAMPLE_PADDING*CHANNELS; k++) + pcm16data[SAMPLE_PADDING*CHANNELS*i+k] = mulaw2pcm16((uint8_t)buffer[i+5]) * gain; + } + + + hab_publish_stream(stream, pcm16data, sizeof(pcm16data)); + + buffer_size = 0; + state = RSP_STATUS_WAITING; + } + } + + + return 0; +} + +// Emacs cruft +// Local Variables: +// mode: C +// c-file-style: "Stroustrup" +// End: diff --git a/pool/shard000/C/0015305_rng2html.c b/pool/shard000/C/0015305_rng2html.c new file mode 100644 index 0000000000000000000000000000000000000000..787e8fc10160b0f9ea79b22d232fd433812c6fa3 --- /dev/null +++ b/pool/shard000/C/0015305_rng2html.c @@ -0,0 +1,79 @@ +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include "tree.h" + + +static xmlDocPtr +open_relaxng(const char *filename) +{ + xmlDocPtr p; + xmlNodePtr n; + + p = xmlParseFile(filename); + if (!p) { + printf("Failed to parse %s\n", filename); + } + + n = xmlDocGetRootElement(p); + if (xmlStrcmp(n->name, (xmlChar *)"grammar")) { + printf("%s is not a relaxng grammar\n", filename); + xmlFreeDoc(p); + return NULL; + } + + return p; +} + + +int +main(int argc, char **argv) +{ + GList *tree = NULL; + GList *objs = NULL; + xmlDocPtr doc; + FILE *outfile; + struct stat st_buf; + + if (argc < 2) { + printf("Translate cluster RelaxNG -> HTML\n"); + printf("Usage: %s schema-file.rng [output-file.html]\n", + argv[0]); + return 1; + } + + doc = open_relaxng(argv[1]); + if (doc == NULL) { + printf("Cannot continue\n"); + return 1; + } + + find_objects(xmlDocGetRootElement(doc), NULL, &tree, &objs); + + if (argc == 2 || !strcmp(argv[2], "-")) { + outfile = stdout; + } else if (stat(argv[2], &st_buf) == 0) { + printf("Please remove %s and rerun.\n", argv[2]); + return 1; + } else { + outfile = fopen(argv[2], "w+"); + } + + fprintf(outfile, "\n"); + print_tree(outfile, tree); + + print_tag_reference(outfile, objs); + fprintf(outfile, "\n"); + + fclose(outfile); + + return 0; +} diff --git a/pool/shard000/C/0015316_timesyncd.c b/pool/shard000/C/0015316_timesyncd.c new file mode 100644 index 0000000000000000000000000000000000000000..b4f70c0007690f86ebc2f4000aeb7ef417714906 --- /dev/null +++ b/pool/shard000/C/0015316_timesyncd.c @@ -0,0 +1,175 @@ +/* SPDX-License-Identifier: LGPL-2.1+ */ + +#include "sd-daemon.h" +#include "sd-event.h" + +#include "capability-util.h" +#include "clock-util.h" +#include "daemon-util.h" +#include "fd-util.h" +#include "fs-util.h" +#include "main-func.h" +#include "mkdir.h" +#include "network-util.h" +#include "process-util.h" +#include "signal-util.h" +#include "timesyncd-bus.h" +#include "timesyncd-conf.h" +#include "timesyncd-manager.h" +#include "user-util.h" + +#define STATE_DIR "/var/lib/systemd/timesync" +#define CLOCK_FILE STATE_DIR "/clock" + +static int load_clock_timestamp(uid_t uid, gid_t gid) { + _cleanup_close_ int fd = -1; + usec_t min = TIME_EPOCH * USEC_PER_SEC; + usec_t ct; + int r; + + /* Let's try to make sure that the clock is always + * monotonically increasing, by saving the clock whenever we + * have a new NTP time, or when we shut down, and restoring it + * when we start again. This is particularly helpful on + * systems lacking a battery backed RTC. We also will adjust + * the time to at least the build time of systemd. */ + + fd = open(CLOCK_FILE, O_RDWR|O_CLOEXEC, 0644); + if (fd >= 0) { + struct stat st; + usec_t stamp; + + /* check if the recorded time is later than the compiled-in one */ + r = fstat(fd, &st); + if (r >= 0) { + stamp = timespec_load(&st.st_mtim); + if (stamp > min) + min = stamp; + } + + if (geteuid() == 0) { + /* Try to fix the access mode, so that we can still + touch the file after dropping priviliges */ + r = fchmod_and_chown(fd, 0644, uid, gid); + if (r < 0) + log_warning_errno(r, "Failed to chmod or chown %s, ignoring: %m", CLOCK_FILE); + } + + } else { + r = mkdir_safe_label(STATE_DIR, 0755, uid, gid, + MKDIR_FOLLOW_SYMLINK | MKDIR_WARN_MODE); + if (r < 0) { + log_debug_errno(r, "Failed to create state directory, ignoring: %m"); + goto settime; + } + + /* create stamp file with the compiled-in date */ + r = touch_file(CLOCK_FILE, false, min, uid, gid, 0644); + if (r < 0) + log_debug_errno(r, "Failed to create %s, ignoring: %m", CLOCK_FILE); + } + +settime: + ct = now(CLOCK_REALTIME); + if (ct < min) { + struct timespec ts; + char date[FORMAT_TIMESTAMP_MAX]; + + log_info("System clock time unset or jumped backwards, restoring from recorded timestamp: %s", + format_timestamp(date, sizeof(date), min)); + + if (clock_settime(CLOCK_REALTIME, timespec_store(&ts, min)) < 0) + log_error_errno(errno, "Failed to restore system clock, ignoring: %m"); + } + + return 0; +} + +static int run(int argc, char *argv[]) { + _cleanup_(notify_on_cleanup) const char *notify_message = NULL; + _cleanup_(manager_freep) Manager *m = NULL; + const char *user = "systemd-timesync"; + uid_t uid, uid_current; + gid_t gid; + int r; + + log_set_facility(LOG_CRON); + log_setup_service(); + + umask(0022); + + if (argc != 1) + return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "This program does not take arguments."); + + uid = uid_current = geteuid(); + gid = getegid(); + + if (uid_current == 0) { + r = get_user_creds(&user, &uid, &gid, NULL, NULL, 0); + if (r < 0) + return log_error_errno(r, "Cannot resolve user name %s: %m", user); + } + + r = load_clock_timestamp(uid, gid); + if (r < 0) + return r; + + /* Drop privileges, but only if we have been started as root. If we are not running as root we assume all + * privileges are already dropped. */ + if (uid_current == 0) { + r = drop_privileges(uid, gid, (1ULL << CAP_SYS_TIME)); + if (r < 0) + return log_error_errno(r, "Failed to drop privileges: %m"); + } + + assert_se(sigprocmask_many(SIG_BLOCK, NULL, SIGTERM, SIGINT, -1) >= 0); + + r = manager_new(&m); + if (r < 0) + return log_error_errno(r, "Failed to allocate manager: %m"); + + r = manager_connect_bus(m); + if (r < 0) + return log_error_errno(r, "Could not connect to bus: %m"); + + if (clock_is_localtime(NULL) > 0) { + log_info("The system is configured to read the RTC time in the local time zone. " + "This mode cannot be fully supported. All system time to RTC updates are disabled."); + m->rtc_local_time = true; + } + + r = manager_parse_config_file(m); + if (r < 0) + log_warning_errno(r, "Failed to parse configuration file: %m"); + + r = manager_parse_fallback_string(m, NTP_SERVERS); + if (r < 0) + return log_error_errno(r, "Failed to parse fallback server strings: %m"); + + log_debug("systemd-timesyncd running as pid " PID_FMT, getpid_cached()); + + notify_message = notify_start("READY=1\n" + "STATUS=Daemon is running", + NOTIFY_STOPPING); + + if (network_is_online()) { + r = manager_connect(m); + if (r < 0) + return r; + } + + r = sd_event_loop(m->event); + if (r < 0) + return log_error_errno(r, "Failed to run event loop: %m"); + + /* if we got an authoritative time, store it in the file system */ + if (m->sync) { + r = touch(CLOCK_FILE); + if (r < 0) + log_debug_errno(r, "Failed to touch %s, ignoring: %m", CLOCK_FILE); + } + + return 0; +} + +DEFINE_MAIN_FUNCTION(run); diff --git a/pool/shard000/C/0015327_nx-aes-cbc.c b/pool/shard000/C/0015327_nx-aes-cbc.c new file mode 100644 index 0000000000000000000000000000000000000000..a066cc3450aee83bff092db433ec7e2c03d7be0d --- /dev/null +++ b/pool/shard000/C/0015327_nx-aes-cbc.c @@ -0,0 +1,150 @@ +/** + * AES CBC routines supporting the Power 7+ Nest Accelerators driver + * + * Copyright (C) 2011-2012 International Business Machines Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; version 2 only. + * + * 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., 675 Mass Ave, Cambridge, MA 02139, USA. + * + * Author: Kent Yoder + */ + +#include +#include +#include +#include +#include +#include + +#include "nx_csbcpb.h" +#include "nx.h" + + +static int cbc_aes_nx_set_key(struct crypto_tfm *tfm, + const u8 *in_key, + unsigned int key_len) +{ + struct nx_crypto_ctx *nx_ctx = crypto_tfm_ctx(tfm); + struct nx_csbcpb *csbcpb = nx_ctx->csbcpb; + + nx_ctx_init(nx_ctx, HCOP_FC_AES); + + switch (key_len) { + case AES_KEYSIZE_128: + NX_CPB_SET_KEY_SIZE(csbcpb, NX_KS_AES_128); + nx_ctx->ap = &nx_ctx->props[NX_PROPS_AES_128]; + break; + case AES_KEYSIZE_192: + NX_CPB_SET_KEY_SIZE(csbcpb, NX_KS_AES_192); + nx_ctx->ap = &nx_ctx->props[NX_PROPS_AES_192]; + break; + case AES_KEYSIZE_256: + NX_CPB_SET_KEY_SIZE(csbcpb, NX_KS_AES_256); + nx_ctx->ap = &nx_ctx->props[NX_PROPS_AES_256]; + break; + default: + return -EINVAL; + } + + csbcpb->cpb.hdr.mode = NX_MODE_AES_CBC; + memcpy(csbcpb->cpb.aes_cbc.key, in_key, key_len); + + return 0; +} + +static int cbc_aes_nx_crypt(struct blkcipher_desc *desc, + struct scatterlist *dst, + struct scatterlist *src, + unsigned int nbytes, + int enc) +{ + struct nx_crypto_ctx *nx_ctx = crypto_blkcipher_ctx(desc->tfm); + struct nx_csbcpb *csbcpb = nx_ctx->csbcpb; + unsigned long irq_flags; + unsigned int processed = 0, to_process; + int rc; + + spin_lock_irqsave(&nx_ctx->lock, irq_flags); + + if (enc) + NX_CPB_FDM(csbcpb) |= NX_FDM_ENDE_ENCRYPT; + else + NX_CPB_FDM(csbcpb) &= ~NX_FDM_ENDE_ENCRYPT; + + do { + to_process = nbytes - processed; + + rc = nx_build_sg_lists(nx_ctx, desc, dst, src, &to_process, + processed, csbcpb->cpb.aes_cbc.iv); + if (rc) + goto out; + + if (!nx_ctx->op.inlen || !nx_ctx->op.outlen) { + rc = -EINVAL; + goto out; + } + + rc = nx_hcall_sync(nx_ctx, &nx_ctx->op, + desc->flags & CRYPTO_TFM_REQ_MAY_SLEEP); + if (rc) + goto out; + + memcpy(desc->info, csbcpb->cpb.aes_cbc.cv, AES_BLOCK_SIZE); + atomic_inc(&(nx_ctx->stats->aes_ops)); + atomic64_add(csbcpb->csb.processed_byte_count, + &(nx_ctx->stats->aes_bytes)); + + processed += to_process; + } while (processed < nbytes); +out: + spin_unlock_irqrestore(&nx_ctx->lock, irq_flags); + return rc; +} + +static int cbc_aes_nx_encrypt(struct blkcipher_desc *desc, + struct scatterlist *dst, + struct scatterlist *src, + unsigned int nbytes) +{ + return cbc_aes_nx_crypt(desc, dst, src, nbytes, 1); +} + +static int cbc_aes_nx_decrypt(struct blkcipher_desc *desc, + struct scatterlist *dst, + struct scatterlist *src, + unsigned int nbytes) +{ + return cbc_aes_nx_crypt(desc, dst, src, nbytes, 0); +} + +struct crypto_alg nx_cbc_aes_alg = { + .cra_name = "cbc(aes)", + .cra_driver_name = "cbc-aes-nx", + .cra_priority = 300, + .cra_flags = CRYPTO_ALG_TYPE_BLKCIPHER, + .cra_blocksize = AES_BLOCK_SIZE, + .cra_ctxsize = sizeof(struct nx_crypto_ctx), + .cra_type = &crypto_blkcipher_type, + .cra_alignmask = 0xf, + .cra_module = THIS_MODULE, + .cra_init = nx_crypto_ctx_aes_cbc_init, + .cra_exit = nx_crypto_ctx_exit, + .cra_blkcipher = { + .min_keysize = AES_MIN_KEY_SIZE, + .max_keysize = AES_MAX_KEY_SIZE, + .ivsize = AES_BLOCK_SIZE, + .setkey = cbc_aes_nx_set_key, + .encrypt = cbc_aes_nx_encrypt, + .decrypt = cbc_aes_nx_decrypt, + } +}; diff --git a/pool/shard000/C/0015329_bot_common.c b/pool/shard000/C/0015329_bot_common.c new file mode 100644 index 0000000000000000000000000000000000000000..a2485c8cf5f4e04f83680a27fc1c5d18035aa21a --- /dev/null +++ b/pool/shard000/C/0015329_bot_common.c @@ -0,0 +1,305 @@ +/* +Copyright (C) 1997-2001 Id Software, Inc. + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 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 "g_local.h" +#include "ai_local.h" + +//ACE + + + +//========================================== +// BOT_Commands +// Special command processor +//========================================== +qboolean BOT_Commands(edict_t *ent) +{ + return false; +} + +char *bot_names[] = + { + "BOTty", + "BOTon", + "BOTeo", + "BOTas", + "BOTes", + "BOTarengo", + "BOTalocado", + "BOTeonado" + }; + + +//========================================== +// BOT_ServerCommand +// Special server command processor +//========================================== +qboolean BOT_ServerCommand (void) +{ + char *cmd, *name; + + cmd = gi.argv (1); + + if (!ctf->value) + name = gi.argv(2); + + if (strlen(name) < 5) + { + name = bot_names[GetRandom(0, sizeof bot_names - 1)]; + } + + if( !Q_stricmp (cmd, "addbot") ) + { + if(ctf->value) // name, skin, team + BOT_SpawnBot ( gi.argv(2), gi.argv(3), gi.argv(4), NULL ); + else // name, skin + BOT_SpawnBot ( NULL, name, gi.argv(3), NULL ); + } + // removebot + else if( !Q_stricmp (cmd, "removebot") ) + BOT_RemoveBot(gi.argv(2)); + + else if( !Q_stricmp (cmd, "editnodes") ) + AITools_InitEditnodes(); + + else if( !Q_stricmp (cmd, "makenodes") ) + AITools_InitMakenodes(); + + else if( !Q_stricmp (cmd, "savenodes") ) + AITools_SaveNodes(); + + else if( !Q_stricmp (cmd, "addbotroam") ) + AITools_AddBotRoamNode(); + + else if( !Q_stricmp (cmd, "addmonster") ) + M_default_Spawn (); + + else + return false; + + return true; +} + + +//========================================== +// AI_BotObituary +// Bots can't use stock obituaries cause server doesn't print from them +//========================================== +void AI_BotObituary (edict_t *self, edict_t *inflictor, edict_t *attacker) +{ +/* int mod; + char message[64]; + char message2[64]; + qboolean ff; + + if (coop->value && attacker->client) + meansOfDeath |= MOD_FRIENDLY_FIRE; + + if ( deathmatch->value || coop->value ) + { + ff = meansOfDeath & MOD_FRIENDLY_FIRE; + mod = meansOfDeath & ~MOD_FRIENDLY_FIRE; + + GS_Obituary ( self, G_PlayerGender ( self ), attacker, mod, message, message2 ); + + // duplicate message at server console for logging + if ( attacker && attacker->client ) + { + if ( attacker != self ) + { // regular death message + if ( deathmatch->value ) { + if( ff ) + attacker->client->resp.score--; + else + attacker->client->resp.score++; + } + + self->enemy = attacker; + + if( dedicated->value ) + G_Printf ( "%s %s %s%s\n", self->client->pers.netname, message, attacker->client->pers.netname, message2 ); + else + { //bot + G_PrintMsg (NULL, PRINT_HIGH, "%s%s %s %s%s\n", + self->client->pers.netname, + S_COLOR_WHITE, + message, + attacker->client->pers.netname, + message2); + } + + } else { // suicide + + if( deathmatch->value ) + self->client->resp.score--; + + self->enemy = NULL; + + if( dedicated->value ) + G_Printf ( "%s %s\n", self->client->pers.netname, message ); + else + { //bot + G_PrintMsg (NULL, PRINT_HIGH, "%s%s %s\n", + self->client->pers.netname, + S_COLOR_WHITE, + message ); + } + } + + } else { // wrong place, suicide, etc. + + if( deathmatch->value ) + self->client->resp.score--; + + self->enemy = NULL; + + if( dedicated->value ) + G_Printf( "%s %s\n", self->client->pers.netname, message ); + else + { //bot + G_PrintMsg (NULL, PRINT_HIGH, "%s%s %s\n", + self->client->pers.netname, + S_COLOR_WHITE, + message ); + } + } + } +*/ +} + + +/////////////////////////////////////////////////////////////////////// +// These routines are bot safe print routines, all id code needs to be +// changed to these so the bots do not blow up on messages sent to them. +// Do a find and replace on all code that matches the below criteria. +// +// (Got the basic idea from Ridah) +// +// change: safe_cprintf to safe_cprintf +// change: gi.bprintf to safe_bprintf +// change: gi.centerprintf to safe_centerprintf +// +/////////////////////////////////////////////////////////////////////// + +/////////////////////////////////////////////////////////////////////// +// Debug print, could add a "logging" feature to print to a file +/////////////////////////////////////////////////////////////////////// +void debug_printf(char *fmt, ...) +{ + int i; + char bigbuffer[0x10000]; + int len; + va_list argptr; + edict_t *cl_ent; + + va_start (argptr,fmt); + len = vsprintf (bigbuffer,fmt,argptr); + va_end (argptr); + + if (dedicated->value) + safe_cprintf(NULL, PRINT_MEDIUM, bigbuffer); + + for (i=0 ; ivalue ; i++) + { + cl_ent = g_edicts + 1 + i; + if (!cl_ent->inuse || cl_ent->ai.is_bot) + continue; + + safe_cprintf(cl_ent, PRINT_MEDIUM, bigbuffer); + } + +} + +/////////////////////////////////////////////////////////////////////// +// botsafe cprintf +/////////////////////////////////////////////////////////////////////// +void safe_cprintf (edict_t *ent, int printlevel, char *fmt, ...) +{ + char bigbuffer[0x400]; + va_list argptr; + int len; + + if (ent && (!ent->inuse || ent->ai.is_bot)) + return; + + if (ent && !ent->client) // az: it happens. + return; + + va_start (argptr,fmt); + len = vsprintf (bigbuffer,fmt,argptr); + va_end (argptr); + + gi.cprintf(ent, printlevel, bigbuffer); + +} + +/////////////////////////////////////////////////////////////////////// +// botsafe centerprintf +/////////////////////////////////////////////////////////////////////// +void safe_centerprintf (edict_t *ent, char *fmt, ...) +{ + char bigbuffer[0x0400]; + va_list argptr; + int len; + + if (!ent) + return; + + if (!ent->inuse || ent->ai.is_bot) + return; + + if (!ent->client) + return; + + va_start (argptr,fmt); + len = vsprintf (bigbuffer,fmt,argptr); + va_end (argptr); + + gi.centerprintf(ent, bigbuffer); + +} + +/////////////////////////////////////////////////////////////////////// +// botsafe bprintf +/////////////////////////////////////////////////////////////////////// +void safe_bprintf (int printlevel, char *fmt, ...) +{ + int i; + char bigbuffer[0x0400]; + int len; + va_list argptr; + edict_t *cl_ent; + + va_start (argptr,fmt); + len = vsprintf (bigbuffer,fmt,argptr); + va_end (argptr); + + if (dedicated->value) + safe_cprintf(NULL, printlevel, bigbuffer); + + for (i=0 ; ivalue ; i++) + { + cl_ent = g_edicts + 1 + i; + if (!cl_ent->inuse || cl_ent->ai.is_bot) + continue; + + safe_cprintf(cl_ent, printlevel, bigbuffer); + } +} diff --git a/pool/shard000/C/0015331_history.c b/pool/shard000/C/0015331_history.c new file mode 100644 index 0000000000000000000000000000000000000000..f8b4d0e11703991834d041affc0dd29fdb7ba715 --- /dev/null +++ b/pool/shard000/C/0015331_history.c @@ -0,0 +1,118 @@ +/** + * $Id$ + * + * lookuplet - a utility for quickly looking up information + * Copyright (C) 2001 Michael Bayne + * + * 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.1 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 "history.h" + +/* the array of historical entries */ +static gchar** _history; + +/* the last entry index retrieved */ +static int _ridx = 0; + +/* the insertion index for new history items */ +static int _iidx = 0; + +/* the number of entries saved in the text entry history */ +#define HISTORY_COUNT (10) + +void +lk_init_history (void) +{ + /* allocate and initialize the array of history entries */ + size_t size = sizeof(gchar*) * HISTORY_COUNT; + _history = g_malloc(size); + memset(_history, (int)NULL, size); +} + +const gchar* +lk_get_history (gboolean next) +{ + int actidx; + + /* make sure the array is available */ + if (_history == NULL) { + return NULL; + } + + /* determine the sought-after index */ + actidx = _ridx + ((next) ? -1 : 1); + + /* make sure the index is valid and an entry exists */ + if (actidx < 0 || actidx >= HISTORY_COUNT || _history[actidx] == NULL) { + return NULL; + } + + /* update the retrieved index */ + _ridx = actidx; + + return _history[actidx]; +} + +const gchar* +lk_get_history_expand (const gchar* entry) +{ + int i, len; + + if (_history == NULL || entry == NULL) { + return NULL; + } + + len = strlen(entry); + for (i = _iidx; i >= 0; i--) { + gchar* str = _history[i]; + if (str != NULL && !g_strncasecmp(str, entry, len)) { + /* update the retrieved index for potential subsequent retrievals */ + _ridx = i; + return str; + } + } + + return NULL; +} + +void +lk_add_history (const gchar* entry) +{ + /* make sure the array is available and the entry is valid */ + if (_history == NULL || entry == NULL) { + return; + } + + /* if there's no space remaining, shift off the oldest entry */ + if (_iidx == HISTORY_COUNT - 1 && _history[_iidx] != NULL) { + g_free(_history[0]); + memmove(_history, _history + 1, sizeof(gchar*) * (HISTORY_COUNT - 1)); + _history[_iidx] = NULL; + } + + /* remember the new entry */ + _history[_iidx] = g_strdup(entry); + + /* increment the insertion and retrieved index */ + if (_iidx < HISTORY_COUNT - 1) { + _iidx++; + _ridx = _iidx; + } else { + _ridx = HISTORY_COUNT; + } +} diff --git a/pool/shard000/C/0015338_heap.c b/pool/shard000/C/0015338_heap.c new file mode 100644 index 0000000000000000000000000000000000000000..1db1cbc89f5b403567796c2bae4daffa9321f636 --- /dev/null +++ b/pool/shard000/C/0015338_heap.c @@ -0,0 +1,260 @@ +/* + * Libstruct + * Copyright (C) 2011 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 +#include +#include "heap.h" + + +#define PARENT(X) (((X) - 1) / 2) +#define LEFT(X) (((X) * 2) + 1) +#define RIGHT(X) (((X) * 2) + 2) + +struct heap_elem_t { + long long time, value; + void *data; +}; + +struct heap_t { + int size, count, current; + int error; + long long time; + enum heap_time_policy_enum time_policy; + struct heap_elem_t *elem; +}; + + + + +/* Private Methods */ + +/* compare two heap elements */ +static int heap_less_than(struct heap_t *heap, int x, int y) +{ + /* compare them by value first */ + if (heap->elem[x].value != heap->elem[y].value) + return heap->elem[x].value < heap->elem[y].value; + + /* compare them by fifo time */ + if (heap->time_policy == heap_time_policy_fifo) + return heap->elem[x].time < heap->elem[y].time; + + /* compare them by lifo time */ + return heap->elem[x].time > heap->elem[y].time; +} + + +/* grow heap */ +static int heap_grow(struct heap_t *heap) +{ + struct heap_elem_t *nelem; + int nsize = heap->size * 2; + + nelem = realloc(heap->elem, nsize * sizeof(struct heap_elem_t)); + if (!nelem) + return 0; + heap->elem = nelem; + heap->size = nsize; + return 1; +} + + +/* heapify an element */ +static void heapify(struct heap_t *heap, int i) +{ + int l, r, k; + struct heap_elem_t tmp; + + for (;;) { + l = LEFT(i); + r = RIGHT(i); + k = i; + if (l < heap->count && heap_less_than(heap, l, k)) + k = l; + if (r < heap->count && heap_less_than(heap, r, k)) + k = r; + if (k == i) + break; + + tmp = heap->elem[k]; + heap->elem[k] = heap->elem[i]; + heap->elem[i] = tmp; + i = k; + } +} + + + + +/* Public Methods */ + +/* creation */ +struct heap_t *heap_create(int size) +{ + struct heap_t *heap; + heap = calloc(1, sizeof(struct heap_t)); + heap->size = size < 10 ? 10 : size; + heap->elem = calloc(heap->size, sizeof(struct heap_elem_t)); + if (!heap->elem) { + free(heap); + return NULL; + } + return heap; +} + + +/* destruction */ +void heap_free(struct heap_t *heap) +{ + free(heap->elem); + free(heap); +} + + +/* error messages */ +int heap_error(struct heap_t *heap) +{ + return heap->error; +} + + +char *heap_error_msg(struct heap_t *heap) +{ + switch (heap->error) { + case HEAP_ENOMEM: return "out of memory"; + case HEAP_EEMPTY: return "heap is empty"; + } + return ""; +} + + +int heap_count(struct heap_t *heap) +{ + return heap->count; +} + + +void heap_insert(struct heap_t *heap, long long value, void *data) +{ + int i; + struct heap_elem_t tmp; + + /* grow heap */ + if (heap->count == heap->size && !heap_grow(heap)) { + heap->error = HEAP_ENOMEM; + return; + } + + /* insert element */ + i = heap->count; + heap->elem[i].value = value; + heap->elem[i].data = data; + heap->elem[i].time = heap->time++; + while (i > 0 && heap_less_than(heap, i, PARENT(i))) { + tmp = heap->elem[i]; + heap->elem[i] = heap->elem[PARENT(i)]; + heap->elem[PARENT(i)] = tmp; + i = PARENT(i); + } + heap->count++; + heap->error = 0; +} + + +long long heap_peek(struct heap_t *heap, void **data) +{ + long long value; + + /* heap empty */ + if (!heap->count) { + heap->error = HEAP_EEMPTY; + if (data) + *data = NULL; + return 0; + } + + /* extract */ + value = heap->elem[0].value; + if (data) + *data = heap->elem[0].data; + heap->error = 0; + return value; +} + + +long long heap_extract(struct heap_t *heap, void **data) +{ + long long value; + + /* peek min */ + value = heap_peek(heap, data); + if (heap->error) + return 0; + + /* delete element from heap */ + heap->count--; + heap->elem[0] = heap->elem[heap->count]; + heapify(heap, 0); + return value; +} + + +void heap_time_policy(struct heap_t *heap, enum heap_time_policy_enum policy) +{ + heap->time_policy = policy; + heap->error = 0; +} + + +long long heap_first(struct heap_t *heap, void **data) +{ + /* No element in the heap */ + if (!heap->count) { + heap->error = HEAP_EELEM; + if (data) + *data = NULL; + return 0; + } + + /* Ok, return element */ + heap->current = 0; + heap->error = 0; + if (data) + *data = heap->elem[0].data; + return heap->elem[0].value; +} + + +long long heap_next(struct heap_t *heap, void **data) +{ + /* Current element out of bounds */ + if (heap->current >= heap->count - 1) { + heap->error = HEAP_EELEM; + if (data) + *data = NULL; + return 0; + } + + /* Ok, return element */ + heap->current++; + heap->error = 0; + if (data) + *data = heap->elem[heap->current].data; + return heap->elem[heap->current].value; +} diff --git a/pool/shard000/C/0015353_gnunet-hello.c b/pool/shard000/C/0015353_gnunet-hello.c new file mode 100644 index 0000000000000000000000000000000000000000..6fd5756ba96c6d82259431d53cab7cea8311457a --- /dev/null +++ b/pool/shard000/C/0015353_gnunet-hello.c @@ -0,0 +1,225 @@ +/* + This file is part of GNUnet + Copyright (C) 2012 GNUnet e.V. + + GNUnet is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published + by the Free Software Foundation; either version 3, or (at your + option) any later version. + + GNUnet 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 GNUnet; see the file COPYING. If not, write to the + Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ +/** + * @file hello/gnunet-hello.c + * @brief change HELLO files to never expire + * @author Christian Grothoff + */ +#include "platform.h" +#include "gnunet_protocols.h" +#include "gnunet_hello_lib.h" + +/** + * Closure for #add_to_buf(). + */ +struct AddContext +{ + /** + * Where to add. + */ + char *buf; + + /** + * Maximum number of bytes left + */ + size_t max; + + /** + * Number of bytes added so far. + */ + size_t ret; +}; + +static int address_count; + + +/** + * Add the given address with infinit expiration to the buffer. + * + * @param cls closure + * @param address address to add + * @param expiration old expiration + * @return #GNUNET_OK keep iterating + */ +static int +add_to_buf (void *cls, + const struct GNUNET_HELLO_Address *address, + struct GNUNET_TIME_Absolute expiration) +{ + struct AddContext *ac = cls; + size_t ret; + + ret = GNUNET_HELLO_add_address (address, + GNUNET_TIME_UNIT_FOREVER_ABS, + ac->buf, + ac->max); + ac->buf += ret; + ac->max -= ret; + ac->ret += ret; + address_count ++; + return GNUNET_OK; +} + + +/** + * Add addresses from the address list to the HELLO. + * + * @param cls the HELLO with the addresses to add + * @param max maximum space available + * @param buf where to add the addresses + * @return number of bytes added, 0 to terminate + */ +static ssize_t +add_from_hello (void *cls, + size_t max, + void *buf) +{ + struct GNUNET_HELLO_Message **orig = cls; + struct AddContext ac; + + if (NULL == *orig) + return GNUNET_SYSERR; /* already done */ + ac.buf = buf; + ac.max = max; + ac.ret = 0; + GNUNET_assert (NULL == + GNUNET_HELLO_iterate_addresses (*orig, + GNUNET_NO, &add_to_buf, + &ac)); + *orig = NULL; + return ac.ret; +} + + +int +main (int argc, char *argv[]) +{ + struct GNUNET_DISK_FileHandle *fh; + struct GNUNET_HELLO_Message *orig; + struct GNUNET_HELLO_Message *result; + struct GNUNET_PeerIdentity pid; + uint64_t fsize; + address_count = 0; + + GNUNET_log_setup ("gnunet-hello", "INFO", NULL); + if (argc != 2) + { + FPRINTF (stderr, + "%s", + _("Call with name of HELLO file to modify.\n")); + return 1; + } + if (GNUNET_OK != GNUNET_DISK_file_size (argv[1], &fsize, GNUNET_YES, GNUNET_YES)) + { + FPRINTF (stderr, + _("Error accessing file `%s': %s\n"), + argv[1], + STRERROR (errno)); + return 1; + } + if (fsize > 65536) + { + FPRINTF (stderr, + _("File `%s' is too big to be a HELLO\n"), + argv[1]); + return 1; + } + if (fsize < sizeof (struct GNUNET_MessageHeader)) + { + FPRINTF (stderr, + _("File `%s' is too small to be a HELLO\n"), + argv[1]); + return 1; + } + fh = GNUNET_DISK_file_open (argv[1], + GNUNET_DISK_OPEN_READ, + GNUNET_DISK_PERM_USER_READ); + if (NULL == fh) + { + FPRINTF (stderr, + _("Error opening file `%s': %s\n"), + argv[1], + STRERROR (errno)); + return 1; + } + { + char buf[fsize] GNUNET_ALIGN; + + GNUNET_assert (fsize == + GNUNET_DISK_file_read (fh, buf, fsize)); + GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fh)); + orig = (struct GNUNET_HELLO_Message *) buf; + if ( (fsize < GNUNET_HELLO_size (orig)) || + (GNUNET_OK != GNUNET_HELLO_get_id (orig, + &pid)) ) + { + FPRINTF (stderr, + _("Did not find well-formed HELLO in file `%s'\n"), + argv[1]); + return 1; + } + { + char *pids; + + pids = GNUNET_CRYPTO_eddsa_public_key_to_string (&pid.public_key); + fprintf (stdout, + "Processing HELLO for peer `%s'\n", + pids); + GNUNET_free (pids); + } + result = GNUNET_HELLO_create (&pid.public_key, + &add_from_hello, + &orig, + GNUNET_HELLO_is_friend_only (orig)); + GNUNET_assert (NULL != result); + fh = GNUNET_DISK_file_open (argv[1], + GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_TRUNCATE, + GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE); + if (NULL == fh) + { + FPRINTF (stderr, + _("Error opening file `%s': %s\n"), + argv[1], + STRERROR (errno)); + GNUNET_free (result); + return 1; + } + fsize = GNUNET_HELLO_size (result); + if (fsize != GNUNET_DISK_file_write (fh, + result, + fsize)) + { + FPRINTF (stderr, + _("Error writing HELLO to file `%s': %s\n"), + argv[1], + STRERROR (errno)); + (void) GNUNET_DISK_file_close (fh); + return 1; + } + GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fh)); + } + FPRINTF (stderr, + _("Modified %u addresses, wrote %u bytes\n"), + address_count, + (unsigned int) fsize); + return 0; +} + +/* end of gnunet-hello.c */ diff --git a/pool/shard000/C/0015360_cd-gpio.c b/pool/shard000/C/0015360_cd-gpio.c new file mode 100644 index 0000000000000000000000000000000000000000..bee472d95b56e020628b0d294e70b94edee98d4d --- /dev/null +++ b/pool/shard000/C/0015360_cd-gpio.c @@ -0,0 +1,80 @@ +/* + * Generic GPIO card-detect helper + * + * Copyright (C) 2011, Guennadi Liakhovetski + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +struct mmc_cd_gpio { + unsigned int gpio; + char label[0]; +}; + +static irqreturn_t mmc_cd_gpio_irqt(int irq, void *dev_id) +{ + + mmc_detect_change(dev_id, msecs_to_jiffies(100)); + return IRQ_HANDLED; +} + +int mmc_cd_gpio_request(struct mmc_host *host, unsigned int gpio) +{ + size_t len = strlen(dev_name(host->parent)) + 4; + struct mmc_cd_gpio *cd; + int irq = gpio_to_irq(gpio); + int ret; + + if (irq < 0) + return irq; + + cd = kmalloc(sizeof(*cd) + len, GFP_KERNEL); + if (!cd) + return -ENOMEM; + + snprintf(cd->label, len, "%s cd", dev_name(host->parent)); + + ret = gpio_request_one(gpio, GPIOF_DIR_IN, cd->label); + if (ret < 0) + goto egpioreq; + + ret = request_threaded_irq(irq, NULL, mmc_cd_gpio_irqt, + IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING, + cd->label, host); + if (ret < 0) + goto eirqreq; + + cd->gpio = gpio; + host->hotplug.irq = irq; + host->hotplug.handler_priv = cd; + + return 0; + +eirqreq: + gpio_free(gpio); +egpioreq: + kfree(cd); + return ret; +} +EXPORT_SYMBOL(mmc_cd_gpio_request); + +void mmc_cd_gpio_free(struct mmc_host *host) +{ + struct mmc_cd_gpio *cd = host->hotplug.handler_priv; + + free_irq(host->hotplug.irq, host); + gpio_free(cd->gpio); + kfree(cd); +} +EXPORT_SYMBOL(mmc_cd_gpio_free); diff --git a/pool/shard000/C/0015375_sha256-tlsprf.c b/pool/shard000/C/0015375_sha256-tlsprf.c new file mode 100644 index 0000000000000000000000000000000000000000..0528dadfdca604c3bb110319491856db417716a3 --- /dev/null +++ b/pool/shard000/C/0015375_sha256-tlsprf.c @@ -0,0 +1,66 @@ +/* + * TLS PRF P_SHA256 + * Copyright (c) 2011, Jouni Malinen + * + * This software may be distributed under the terms of the BSD license. + * See README for more details. + */ + +#include "includes.h" + +#include "common.h" +#include "sha256.h" + + +/** + * tls_prf_sha256 - Pseudo-Random Function for TLS v1.2 (P_SHA256, RFC 5246) + * @secret: Key for PRF + * @secret_len: Length of the key in bytes + * @label: A unique label for each purpose of the PRF + * @seed: Seed value to bind into the key + * @seed_len: Length of the seed + * @out: Buffer for the generated pseudo-random key + * @outlen: Number of bytes of key to generate + * Returns: 0 on success, -1 on failure. + * + * This function is used to derive new, cryptographically separate keys from a + * given key in TLS. This PRF is defined in RFC 2246, Chapter 5. + */ +void tls_prf_sha256(const u8 *secret, size_t secret_len, const char *label, + const u8 *seed, size_t seed_len, u8 *out, size_t outlen) +{ + size_t clen; + u8 A[SHA256_MAC_LEN]; + u8 P[SHA256_MAC_LEN]; + size_t pos; + const unsigned char *addr[3]; + size_t len[3]; + + addr[0] = A; + len[0] = SHA256_MAC_LEN; + addr[1] = (unsigned char *) label; + len[1] = os_strlen(label); + addr[2] = seed; + len[2] = seed_len; + + /* + * RFC 5246, Chapter 5 + * A(0) = seed, A(i) = HMAC(secret, A(i-1)) + * P_hash = HMAC(secret, A(1) + seed) + HMAC(secret, A(2) + seed) + .. + * PRF(secret, label, seed) = P_SHA256(secret, label + seed) + */ + + hmac_sha256_vector(secret, secret_len, 2, &addr[1], &len[1], A); + + pos = 0; + while (pos < outlen) { + hmac_sha256_vector(secret, secret_len, 3, addr, len, P); + hmac_sha256(secret, secret_len, A, SHA256_MAC_LEN, A); + + clen = outlen - pos; + if (clen > SHA256_MAC_LEN) + clen = SHA256_MAC_LEN; + os_memcpy(out + pos, P, clen); + pos += clen; + } +} diff --git a/pool/shard000/C/0015376_stm32f7xx_hal_msp.c b/pool/shard000/C/0015376_stm32f7xx_hal_msp.c new file mode 100644 index 0000000000000000000000000000000000000000..175b8ed78795905d70574321eb89dd3af27475c7 --- /dev/null +++ b/pool/shard000/C/0015376_stm32f7xx_hal_msp.c @@ -0,0 +1,136 @@ +/** + ****************************************************************************** + * File Name : stm32f7xx_hal_msp.c + * Description : This file provides code for the MSP Initialization + * and de-Initialization codes. + ****************************************************************************** + * + * COPYRIGHT(c) 2015 STMicroelectronics + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ +/* Includes ------------------------------------------------------------------*/ +#include "stm32f7xx_hal.h" + +/* USER CODE BEGIN 0 */ + +/* USER CODE END 0 */ + +/** + * Initializes the Global MSP. + */ +void HAL_MspInit(void) +{ + /* USER CODE BEGIN MspInit 0 */ + + /* USER CODE END MspInit 0 */ + + HAL_NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_4); + + /* System interrupt init*/ + /* SysTick_IRQn interrupt configuration */ + HAL_NVIC_SetPriority(SysTick_IRQn, 0, 0); + + /* USER CODE BEGIN MspInit 1 */ + + /* USER CODE END MspInit 1 */ +} + +void HAL_UART_MspInit(UART_HandleTypeDef* huart) +{ + + GPIO_InitTypeDef GPIO_InitStruct; + if(huart->Instance==USART1) + { + /* USER CODE BEGIN USART1_MspInit 0 */ + + /* USER CODE END USART1_MspInit 0 */ + /* Peripheral clock enable */ + __USART1_CLK_ENABLE(); + + /**USART1 GPIO Configuration + PB7 ------> USART1_RX + PA9 ------> USART1_TX + */ + GPIO_InitStruct.Pin = VCP_RX_Pin; + GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; + GPIO_InitStruct.Pull = GPIO_PULLUP; + GPIO_InitStruct.Speed = GPIO_SPEED_HIGH; + GPIO_InitStruct.Alternate = GPIO_AF7_USART1; + HAL_GPIO_Init(VCP_RX_GPIO_Port, &GPIO_InitStruct); + + GPIO_InitStruct.Pin = VCP_TX_Pin; + GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; + GPIO_InitStruct.Pull = GPIO_PULLUP; + GPIO_InitStruct.Speed = GPIO_SPEED_HIGH; + GPIO_InitStruct.Alternate = GPIO_AF7_USART1; + HAL_GPIO_Init(VCP_TX_GPIO_Port, &GPIO_InitStruct); + + /* USER CODE BEGIN USART1_MspInit 1 */ + + /* USER CODE END USART1_MspInit 1 */ + } + +} + +void HAL_UART_MspDeInit(UART_HandleTypeDef* huart) +{ + + if(huart->Instance==USART1) + { + /* USER CODE BEGIN USART1_MspDeInit 0 */ + + /* USER CODE END USART1_MspDeInit 0 */ + /* Peripheral clock disable */ + __USART1_CLK_DISABLE(); + + /**USART1 GPIO Configuration + PB7 ------> USART1_RX + PA9 ------> USART1_TX + */ + HAL_GPIO_DeInit(VCP_RX_GPIO_Port, VCP_RX_Pin); + + HAL_GPIO_DeInit(VCP_TX_GPIO_Port, VCP_TX_Pin); + + } + /* USER CODE BEGIN USART1_MspDeInit 1 */ + + /* USER CODE END USART1_MspDeInit 1 */ + +} + +/* USER CODE BEGIN 1 */ + +/* USER CODE END 1 */ + +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/pool/shard000/C/0015384_netstar.c b/pool/shard000/C/0015384_netstar.c new file mode 100644 index 0000000000000000000000000000000000000000..ee4f2cdca7f624fe4843d8cc40930c93e33c68bb --- /dev/null +++ b/pool/shard000/C/0015384_netstar.c @@ -0,0 +1,117 @@ +/* + * (C) Copyright 2005 2N TELEKOMUNIKACE, Ladislav Michl + * + * See file CREDITS for list of people who contributed to this + * project. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of + * the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, + * MA 02111-1307 USA + */ + +#include +#include +#include +#include + +#include + +DECLARE_GLOBAL_DATA_PTR; + +int board_init(void) +{ + /* arch number of NetStar board */ + gd->bd->bi_arch_number = MACH_TYPE_NETSTAR; + + /* adress of boot parameters */ + gd->bd->bi_boot_params = 0x10000100; + + return 0; +} + +int dram_init(void) +{ + gd->bd->bi_dram[0].start = PHYS_SDRAM_1; + gd->bd->bi_dram[0].size = PHYS_SDRAM_1_SIZE; + + /* Take the Ethernet controller out of reset and wait + * for the EEPROM load to complete. */ + *((volatile unsigned short *) GPIO_DATA_OUTPUT_REG) |= 0x80; + udelay(10); /* doesn't work before interrupt_init call */ + *((volatile unsigned short *) GPIO_DATA_OUTPUT_REG) &= ~0x80; + udelay(500); + + return 0; +} + +int misc_init_r(void) +{ +#if defined(CONFIG_RTC_DS1307) + /* enable trickle charge */ + i2c_reg_write(CONFIG_SYS_I2C_RTC_ADDR, 0x10, 0xaa); +#endif + return 0; +} + +int board_late_init(void) +{ + return 0; +} + +#if defined(CONFIG_CMD_FLASH) +ulong board_flash_get_legacy(ulong base, int banknum, flash_info_t * info) +{ + if (banknum == 0) { /* AM29LV800 boot flash */ + info->portwidth = FLASH_CFI_16BIT; + info->chipwidth = FLASH_CFI_BY16; + info->interface = FLASH_CFI_X16; + return 1; + } + + return 0; +} +#endif + +#if defined(CONFIG_CMD_NAND) +/* + * hardware specific access to control-lines + * + * NAND_NCE: bit 0 - don't care + * NAND_CLE: bit 1 -> bit 1 (0x0002) + * NAND_ALE: bit 2 -> bit 2 (0x0004) + */ +static void netstar_nand_hwcontrol(struct mtd_info *mtd, int cmd, + unsigned int ctrl) +{ + struct nand_chip *chip = mtd->priv; + unsigned long mask; + + if (cmd == NAND_CMD_NONE) + return; + + mask = (ctrl & NAND_CLE) ? 0x02 : 0; + if (ctrl & NAND_ALE) + mask |= 0x04; + writeb(cmd, (unsigned long)chip->IO_ADDR_W | mask); +} + +int board_nand_init(struct nand_chip *nand) +{ + nand->options = NAND_SAMSUNG_LP_OPTIONS; + nand->ecc.mode = NAND_ECC_SOFT; + nand->cmd_ctrl = netstar_nand_hwcontrol; + nand->chip_delay = 400; + return 0; +} +#endif diff --git a/pool/shard000/C/0015418_main.c b/pool/shard000/C/0015418_main.c new file mode 100644 index 0000000000000000000000000000000000000000..5e09e17cd597040306dfc3ca1084aa6175d43b6c --- /dev/null +++ b/pool/shard000/C/0015418_main.c @@ -0,0 +1,37 @@ +#include "led.h" +#include "delay.h" +#include "key.h" +#include "sys.h" +#include "lcd.h" + +//Transfer GuiLite 32 bits color to your LCD color +#define GL_RGB_32_to_16(rgb) (((((unsigned int)(rgb)) & 0xFF) >> 3) | ((((unsigned int)(rgb)) & 0xFC00) >> 5) | ((((unsigned int)(rgb)) & 0xF80000) >> 8)) +//Encapsulate your LCD driver: +void gfx_draw_pixel(int x, int y, unsigned int rgb) +{ + LCD_Fast_DrawPoint(x, y, GL_RGB_32_to_16(rgb)); +} +//Implement it, if you have more fast solution than drawing pixels one by one. +//void gfx_fill_rect(int x0, int y0, int x1, int y1, unsigned int rgb){} + +//UI entry +struct EXTERNAL_GFX_OP +{ + void (*draw_pixel)(int x, int y, unsigned int rgb); + void (*fill_rect)(int x0, int y0, int x1, int y1, unsigned int rgb); +} my_gfx_op; +extern void startHelloMolecule(void* phy_fb, int width, int height, int color_bytes, struct EXTERNAL_GFX_OP* gfx_op); + +int main(void) +{ + //Hardware initialization: + delay_init(); + NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2); + LCD_Init(); + + //Link your LCD driver & start UI: + my_gfx_op.draw_pixel = gfx_draw_pixel; + my_gfx_op.fill_rect = NULL;//gfx_fill_rect; + startHelloMolecule(NULL, 240, 320, 2, &my_gfx_op); + while(1); +} diff --git a/pool/shard000/C/0015443_xstack_allocator.c b/pool/shard000/C/0015443_xstack_allocator.c new file mode 100644 index 0000000000000000000000000000000000000000..b4acc4f9e3433385bcab77cf7475851ae902e629 --- /dev/null +++ b/pool/shard000/C/0015443_xstack_allocator.c @@ -0,0 +1,222 @@ +/** + * @file xstack_allocator.c + * @brief + * + * @details + * + * @author MaskedW + * + * @internal + * Created 2015/06/15 + * =================================================================== + */ + +/* + * License: MIT license + * Copyright (c) <2015> + * + * 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 + + +X_INLINE uint8_t* +X__GetBeginOrigin(XStackAllocator* self) +{ + return X_ROUNDUP_ALIGNMENT_PTR(self->heap, self->alignment); +} + + +X_INLINE bool +X__IsValidRange(XStackAllocator* self, const void* p) +{ + const uint8_t* b = X__GetBeginOrigin(self); + const uint8_t* e = b + self->capacity; + + return x_is_within_ptr(p, b, e + 1); +} + + +void xsalloc_init(XStackAllocator* self, void* heap, size_t size, size_t alignment) +{ + X_ASSERT(self); + X_ASSERT(heap); + X_ASSERT(X_IS_ALIGNMENT(alignment)); + + self->heap = heap; + self->alignment = alignment; + + /* heapをアライメントで切り上げたアドレスが実際のtop位置になる。 */ + self->begin = X__GetBeginOrigin(self); + + /* 切り上げた結果heapサイズに不整合がでていないか? */ + X_ASSERT(self->begin - self->heap >= 0); + X_ASSERT(size > (size_t)(self->begin - self->heap)); + size -= self->begin - self->heap; + + self->end = x_rounddown_alignment_ptr(self->begin + size, alignment); + + /* 切り下げた結果heapサイズに不整合がでていないか? */ + X_ASSERT(self->end - self->begin >= 1); + X_ASSERT((size_t)(self->end - self->begin) >= self->alignment); + + self->capacity = self->end - self->begin; + self->growth_upward = true; +} + + +void* xsalloc_allocate(XStackAllocator* self, size_t size) +{ + size_t reserve; + void* ret; + X_ASSERT(self); + X_ASSERT(size > 0); + + reserve = xsalloc_reserve(self); + + X_ASSERT_MALLOC_NULL(reserve >= size); + X_UNUSED(reserve); + + size = x_roundup_alignment(size, self->alignment); + + if (self->growth_upward) { + ret = self->begin; + self->begin += size; + } + else { + self->end -= size; + ret = self->end; + } + + return ret; +} + + +void xsalloc_clear(XStackAllocator* self) +{ + X_ASSERT(self); + self->begin = X__GetBeginOrigin(self); + self->end = self->begin + self->capacity; + self->growth_upward = true; +} + + +void xsalloc_rewind(XStackAllocator* self, void* begin, void* end) +{ + uint8_t* b; + uint8_t* e; + X_ASSERT(self); + + /* 両方がNULLは許容するが、片方だけNULLというのは明らかにおかしいので + * assert対象とする。*/ + if ((begin == NULL) && (end == NULL)) + return; + X_ASSERT(begin && end); + + X_ASSERT(x_is_aligned(begin, self->alignment)); + X_ASSERT(x_is_aligned(end, self->alignment)); + + b = begin; + e = end; + + X_ASSERT(e >= b); + X_ASSERT(X__IsValidRange(self, b)); + X_ASSERT(X__IsValidRange(self, e)); + + self->begin = b; + self->end = e; +} + + +bool xsalloc_growth_direction(XStackAllocator* self) +{ + X_ASSERT(self); + return self->growth_upward; +} + + +/** スタック伸長方向を設定し、変更前の値を返します + */ +bool xsalloc_set_growth_direction(XStackAllocator* self, bool growth_upward) +{ + bool old; + X_ASSERT(self); + old = self->growth_upward; + self->growth_upward = growth_upward; + + return old; +} + + +/** 空きメモリバイト数を返します + */ +size_t xsalloc_reserve(const XStackAllocator* self) +{ + X_ASSERT(self); + return self->end - self->begin; +} + + +/** ヒープのサイズを返します + */ +size_t xsalloc_capacity(const XStackAllocator* self) +{ + X_ASSERT(self); + return self->capacity; +} + + +/** 初期化時に指定したアラインメントを返します + */ +size_t xsalloc_alignment(const XStackAllocator* self) +{ + X_ASSERT(self); + return self->alignment; +} + + +/** ヒープメモリを返します + */ +uint8_t* xsalloc_heap(const XStackAllocator* self) +{ + X_ASSERT(self); + return self->heap; +} + + +/** 先頭スタックポインタを返します + */ +uint8_t* xsalloc_bedin(const XStackAllocator* self) +{ + X_ASSERT(self); + return self->begin; +} + + +/** 終端スタックポインタを返します + */ +uint8_t* xsalloc_end(const XStackAllocator* self) +{ + X_ASSERT(self); + return self->end; +} diff --git a/pool/shard000/C/0015470_wordsearch.c b/pool/shard000/C/0015470_wordsearch.c new file mode 100644 index 0000000000000000000000000000000000000000..26821bf368e371375d51fad81a5ad785c369b2a5 --- /dev/null +++ b/pool/shard000/C/0015470_wordsearch.c @@ -0,0 +1,125 @@ +/****************************************************************\ +* ESTate - Expressed sequence tag analysis tools etc. * +* Copyright (C) 1996-1999. Guy St.C. Slater. * +* All Rights Reserved. * +* * +* gslater@hgmp.mrc.ac.uk http://www.hgmp.mrc.ac.uk/~gslater/ * +* * +* This source code is distributed under the terms of the * +* GNU General Public License. See the file COPYING for details. * +* * +* If you use this code, please keep this notice intact. * +\****************************************************************/ + +/* wordsearch : find dictionary words in sequence database. + Guy St.C. Slater.. Version 2.0 November 1997. +*/ + +/* This is just here as a test of the finite state machine library. +*/ + +#include "../general/arg.h" +#include "../general/error.h" +#include "../general/common.h" +#include "../general/stringlist.h" + +ALLOW_ERROR_MESSAGES; + +#include "../struct/fsm.h" + +#include "../parse/readfasta.h" +#include "../parse/ioutil.h" +#include "../parse/parser.h" + +#include + +static BOOLEAN checkword(unsigned char *word, int len, BOOLEAN *aav){ + register int i; + for(i = 0; i < len; i++){ + word[i] = toupper(word[i]); + if(!aav[word[i]]) + return FALSE; + } + return TRUE; + } + +static unsigned char *local_aas = (unsigned char*) + "ARNDCQEGHILKMFPSTWYV"; + +static STRINGLIST *getValidWords(FILE *fp, int minlen){ + register int i, len; + register STRINGLIST *sl = newSTRINGLIST(); + register PARSER *p = newPARSER(fp); + BOOLEAN aav[ALPHABETSIZE]; + for(i = 0; i < ALPHABETSIZE; i++) + aav[i] = FALSE; + for(i = strlen((char*)local_aas)-1; i >= 0; i--) + aav[local_aas[i]] = TRUE; + while((len = linePARSER(p)) != EOF){ + if(len < minlen) + continue; + if(!checkword(p->line, len, aav)) + continue; + addSTRINGLIST(sl, (char*)p->line, len); + } + if(sl->c) + errmsg(ERROR_INFO, "Selected [%d] valid words for FSM", + sl->c); + else + errmsg(ERROR_FATAL, "Found no suitable words in dictionary"); + freePARSER(p); + return sl; + } + +static void searchSequence(FSM *f, unsigned char *seq, char *def){ + register FSMNODE *n = f->root; + register short ch; + do { + if(n[ch = f->index[*seq]].data.n){ + printf(">found [%s] length = %d in [%.40s]\n", + (char*)n[ch].data.n, + strlen(n[ch].data.n), def); + fflush(stdout); + } + n = n[ch].next; + } while(*++seq); + return; + } + +static void wordsearchFSMdatabase(STRINGLIST *sl, char *path){ + register FSM *fsm = makeFSMptr(sl->v, sl->c, (void**)sl->v); + register READFASTA *rf = newREADFASTA(path); + infoFSM(fsm); + errmsg(ERROR_INFO, "Compiled FSM"); + while(nextREADFASTA(rf)) + searchSequence(fsm, (unsigned char*)rf->seq, rf->def); + freeREADFASTA(rf); + freeFSM(fsm); + return; + } + +#define ARGUMENT_COUNT 2 + +int estateMAIN(){ + static FILE *sdb = NULL; + static FILE *wdb; + static int minlen = 7; + static char *sdbname; + + ARGUMENT argdata[ARGUMENT_COUNT] = { + {ARG_FILE, 'd', "database", "fasta format database", + &sdb, &sdbname, "WORDSEARCH_DATABASE_PATH", "r", TRUE}, + {ARG_INT, 'l', "minlen", "minimum length", + &minlen, NULL, "WORDSEARCH_MINIMUM_LENGTH", "[0,10]", FALSE} + }; + + register STRINGLIST *sl; + wdb = stdin; + processARGUMENT(argdata, ARGUMENT_COUNT, global_emn, + "dictionary word search in sequence databases"); + sl = getValidWords(wdb, minlen); + wordsearchFSMdatabase(sl, sdbname); + freeSTRINGLIST(sl); + return 0; + } + diff --git a/pool/shard000/C/0015482_main.c b/pool/shard000/C/0015482_main.c new file mode 100644 index 0000000000000000000000000000000000000000..db9329af86567f6e8a630eb902b944688b554b93 --- /dev/null +++ b/pool/shard000/C/0015482_main.c @@ -0,0 +1,36 @@ +#include "SDL2/SDL.h" +#include + +enum { + SCREEN_WIDTH = 640, + SCREEN_HEIGHT = 480, +}; + +int main(int argc, char *argv[]) +{ + SDL_Window *window = NULL; + + SDL_Surface *screensurface = NULL; + + if(SDL_Init(SDL_INIT_VIDEO) < 0) { + printf("SDL could not initialize! SDL_Error: %s\n", SDL_GetError()); + } else { + window = SDL_CreateWindow("SDL Tutorial", + SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, + SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); + if(window == NULL) { + printf("Window could not be created! SDL_Error: %s\n", SDL_GetError()); + } else { + screensurface = SDL_GetWindowSurface(window); + // Fill the surface white + SDL_FillRect(screensurface, NULL, + SDL_MapRGB(screensurface->format, 0xFF, 0xFF, 0xFF)); + printf("Hello world\n"); + SDL_UpdateWindowSurface(window); + SDL_Delay(2000); + } + } + SDL_DestroyWindow(window); + SDL_Quit(); + return 0; +} diff --git a/pool/shard000/C/0015491_pool_proc.c b/pool/shard000/C/0015491_pool_proc.c new file mode 100644 index 0000000000000000000000000000000000000000..0713ce5795fb607003b8a3f37f9adaaa7222bf6f --- /dev/null +++ b/pool/shard000/C/0015491_pool_proc.c @@ -0,0 +1,285 @@ +/* + * ===================================================================================== + * + * Filename: pool_proc.c + * + * Description: + * + * Version: 1.0 + * Created: 12/11/2013 03:25:19 PM + * Revision: none + * Compiler: gcc + * + * Author: vyouzhi (), + * Organization: + * + * ===================================================================================== + */ +#include "pool_proc.h" + +/* + * === FUNCTION ====================================================================== + * Name: hproc + * Description: + * ===================================================================================== + */ +void hproc ( ){ + + /* update table tlist + htlist();*/ + + /* hdr to hitem */ + fetchdti(); + +} /* ----- end of function hproc ----- */ + +/* + * === FUNCTION ====================================================================== + * Name: fetchdti + * Description: fetch pools_hdr to pools_hitem , use haru + * ===================================================================================== + */ +void fetchdti ( ){ + HDR *pd, *_pd; + + pd = pools_hdr_tail; + + while(pd){ + + if(pd->flag == H_FALSE){ + goto clear; + } + if(!pd->key){ + goto clear; + } + haddHitem(pd); + + clear: + if(pd == pools_hdr_head){ + pd->flag = H_FALSE; + pools_hdr_tail = pd; + break; + }else{ + _pd = pd; + pd = pd->next; + freeHdr(_pd); + } + } +} /* ----- end of function fetchdti ----- */ + +/* + * === FUNCTION ====================================================================== + * Name: haddHitem + * Description: hdr to hitem + * ===================================================================================== + */ +word haddHitem ( HDR *mhdr ){ + HITEM *ph,*phtmp, *hp; + HDR *hdr; + ub4 y ; + uint64_t _new_hval, _new_hjval; + int i, m, slab_id; + HITEM **pools_hitem; + ub1 *slab_sm; + + hdr = mhdr; + if(hdr == NULL) return -1; + if(hdr->drl > LIMIT_SLAB_BYTE) return -1; + + _new_hval = lookup(hdr->key, hdr->keyl,0); + _new_hjval = jenkins_one_at_a_time_hash(hdr->key, hdr->keyl); + HITEM_SWITCH((y=(_new_hval&pools_htab->mask))); + + ph = pools_hitem[y]; + if(!ph) { + return -1; + } + i = hsms(hdr->drl); + if(i == -1) return -1; + + /* header is not user + for(; ph->next; ph=ph->next){ + if(_new_hval == ph->hval && + (hdr->keyl == ph->keyl) && + (_new_hjval == ph->hjval) + ){ + MISS_LOCK(); + pools_htab->miss++; + MISS_UNLOCK(); + break; + } + }*/ + m = 0; + phtmp = ph; + ph = ph->next; /* head is not store anything */ + while ( ph ){ + phtmp = ph; + if ((_new_hval == ph->hval) && + (hdr->keyl == ph->keyl) && + (_new_hjval == ph->hjval)) + { + m = hsms(ph->psize); + if(m == -1) return -1; + if(m != i){ /* old size != new size , free old slab */ + addfslab(ph); /* free old slab */ + if(pools_fslab[i].sa != 0){ + ph->sid = pools_fslab[i].sid; + ph->sa = pools_fslab[i].sa; + pools_fslab[i].sa = 0; + }else{ + slab_id = findslab(slabclass[i].size); + if(slab_id == -1) return -1; + ph->sid = slab_id; + ph->sa = pools_hslab[slab_id].ss - slabclass[i].size; + } + ph->psize = slabclass[i].size; /* update psize */ + ph->drl = hdr->drl; + } + /* + if((ph->amiss / ph->ahit) > LIMIT_PERCENT){ + ph->drl = 0; + break; + }*/ + + + slab_sm = pools_hslab[ph->sid].sm + ph->sa; + ph->utime = hdr->stime; + memcpy(slab_sm, hdr->dr, hdr->drl); + ph->drl = hdr->drl; + ph->amiss++; + pools_htab->miss++; + //hrule(ph, H_UPDATE); + return 0; + + } + ph = ph->next; + } /* while */ + + if(!phtmp->next){ + hp = hitemcreate(); + if(hp->keyl > KEY_LENGTH){ + free(hp); + return -1; + } + memcpy(hp->key, hdr->key, hdr->keyl); + hp->keyl = hdr->keyl; + hp->drl = hdr->drl; + hp->psize = slabclass[i].size; + hp->hval = _new_hval; + hp->hjval = _new_hjval; + hp->utime = hdr->stime; + + if(pools_fslab[i].sa != 0){ + hp->sid = pools_fslab[i].sid; + hp->sa = pools_fslab[i].sa; + pools_fslab[i].sa = 0; + }else{ + slab_id = findslab(hp->psize); + if(slab_id == -1)return -1; + hp->sid = slab_id; + hp->sa = pools_hslab[slab_id].ss - hp->psize; + } + slab_sm = pools_hslab[hp->sid].sm + hp->sa; + + if(hp->sa < 0){ + DEBUG("psize error! sa: %d psize: %d", hp->sa, hp->psize); + }else{ + memcpy(slab_sm , hdr->dr, hdr->drl); + + phtmp->next = hp; + + pools_hitem_row[i]++; + + //hrule(hp, H_INSERT); + } + } + + /* make the hash table bigger if it is getting full */ + if (++pools_htab->count > pools_htab->logsize) + { + DEBUG("now expand hashtable count %d logsize %d", pools_htab->count, pools_htab->logsize); + //hgrow(); + } + return 0; +} /* ----- end of function haddHitem ----- */ + +/* + * === FUNCTION ====================================================================== + * Name: hrule + * Description: + * ===================================================================================== + */ +void hrule ( HITEM *hitem, H_CHANGE hstat ){ + int i; + HITEM *ph; + + if(!hitem) return; + + if(pools_htab->bytes == conn_global->maxbytes && + pools_harug->step == MAX_HARU_POOL){ + for ( i=0; istep = 0; + } + + for(i=0; istep; i++){ + ph = pools_haru_pool[i].phitem; + if(hitem->hval == ph->hval && + (hitem->keyl == ph->keyl) && + (hitem->hjval == ph->hjval) + ){ + return; + } + } + + if(pools_harug->step < MAX_HARU_POOL){ + pools_haru_pool[pools_harug->step].hit = 0; + pools_haru_pool[pools_harug->step++].phitem = hitem; + return; + } else{ + + /* MRU */ + + if( hstat == H_UPDATE ){ + pools_haru_pool[pools_harug->max].hit = 0; + pools_haru_pool[pools_harug->max].phitem = hitem; + } + else{ + /* LRU */ + ph = pools_haru_pool[pools_harug->mix].phitem; + pools_haru_pool[pools_harug->mix].phitem = hitem; + pools_haru_pool[pools_harug->mix].hit = 0; + + addfslab(ph); /* clear hit very limit */ + } + } +} /* ----- end of function hrule ----- */ + + +/* + * === FUNCTION ====================================================================== + * Name: hsort + * Description: + * ===================================================================================== + */ +int hsort ( ){ + /* int i, m; + HARU *t; + + t = pools_harug->haru_pool[0]; + m = 0; + for ( i=1; ihit < pools_harug->haru_pool[i].hit) { + t = pools_harug->haru_pool[i]; + m = i; + } + } + + return m;*/ + return 0; +} /* ----- end of function hsort ----- */ + + /* vim: set ts=4 sw=4: */ + diff --git a/pool/shard000/C/0015513_np_backend.c b/pool/shard000/C/0015513_np_backend.c new file mode 100644 index 0000000000000000000000000000000000000000..69c046c7a98b3f1ec1c949f89852aea6f2d3eff1 --- /dev/null +++ b/pool/shard000/C/0015513_np_backend.c @@ -0,0 +1,231 @@ +#include "main.h" +#include "np.h" +#include "nativeplugin.h" +#include "backend/backend.h" +#include "media/media.h" +#include "metadata/playinfo.h" + +static void +np_backend_destroy(struct backend *be) +{ + np_context_release(be->be_opaque); + free(be->be_prefix); + free(be); +} + +/** + * + */ +static void +seekflush(media_pipe_t *mp, media_buf_t **mbp) +{ + mp_flush(mp); + if(*mbp != NULL) { + media_buf_free_unlocked(mp, *mbp); + *mbp = NULL; + } +} + +#define MB_EOF ((void *)-1) + +static event_t * +np_backend_play_audio(const char *url, struct media_pipe *mp, + char *errbuf, size_t errlen, int paused, + const char *mimetype, void *opaque) +{ + np_context_t *np = opaque; + ir_unit_t *iu = np->np_unit; + int handle; + media_queue_t *mq = &mp->mp_audio; + media_buf_t *mb = NULL; + event_t *e; + int registered_play = 0; + int64_t duration = 0; + + ir_function_t *np_audio_open = vmir_find_function(iu, "np_audio_open"); + ir_function_t *np_audio_play = vmir_find_function(iu, "np_audio_play"); + ir_function_t *np_audio_close = vmir_find_function(iu, "np_audio_close"); + ir_function_t *np_audio_seek = vmir_find_function(iu, "np_audio_seek"); + + if(np_audio_open == NULL || + np_audio_play == NULL || + np_audio_close == NULL) { + snprintf(errbuf, errlen, "Plugin does not expose audio play API"); + return NULL; + } + + np_lock(np); + + int pfd = np_fd_from_prop(iu, prop_ref_inc(mp->mp_prop_root)); + + uint32_t url_vm = vmir_mem_strdup(iu, url); + vmir_vm_function_call(iu, np_audio_open, &handle, + url_vm, pfd); + vmir_mem_free(iu, url_vm); + + if(handle == 0) { + snprintf(errbuf, errlen, "Open failed"); + vmir_fd_close(iu, pfd); + np_unlock(np); + return NULL; + } + + np_unlock(np); + + mp->mp_audio.mq_stream = 0; + int mp_flags = MP_CAN_PAUSE; + if(np_audio_seek != NULL) + mp_flags |= MP_CAN_SEEK; + mp_configure(mp, mp_flags, MP_BUFFER_SHALLOW, 0, "tracks"); + mp_become_primary(mp); + + np_audiobuffer_t *nab; + + uint32_t nab_vm = vmir_mem_alloc(iu, sizeof(np_audiobuffer_t), &nab); + + while(1) { + + if(mb == NULL) { + + uint32_t sampleptr; + + np_lock(np); + + vmir_vm_function_call(iu, np_audio_play, &sampleptr, handle, nab_vm); + + np_unlock(np); + + if(sampleptr == 0) { + mb = MB_EOF; + } else { + + int bufsize = nab->channels * nab->samples * sizeof(int16_t); + mb = media_buf_alloc_unlocked(mp, bufsize); + mb->mb_data_type = MB_AUDIO; + mb->mb_channels = nab->channels; + mb->mb_rate = nab->samplerate; + mb->mb_user_time = mb->mb_pts = nab->timestamp; + mb->mb_drive_clock = 1; + + if(nab->duration > 0 && nab->duration != duration) + mp_set_duration(mp, nab->duration); + + if(!registered_play && mb->mb_pts > PLAYINFO_AUDIO_PLAY_THRESHOLD) { + registered_play = 1; + playinfo_register_play(url, 1); + } + memcpy(mb->mb_data, np->np_mem + sampleptr, bufsize); + } + } + + if(mb == MB_EOF) { + /* Wait for queues to drain */ + e = mp_wait_for_empty_queues(mp); + + if(e == NULL) { + e = event_create_type(EVENT_EOF); + break; + } + } else if((e = mb_enqueue_with_events(mp, mq, mb)) == NULL) { + mb = NULL; /* Enqueue succeeded */ + continue; + } + + if(event_is_type(e, EVENT_PLAYQUEUE_JUMP)) { + mp_flush(mp); + break; + + } else if(np_audio_seek != NULL && event_is_type(e, EVENT_SEEK)) { + + event_ts_t *ets = (event_ts_t *)e; + + seekflush(mp, &mb); + vmir_vm_function_call(iu, np_audio_seek, NULL, handle, ets->ts); + + } else if(event_is_action(e, ACTION_SKIP_BACKWARD) || + event_is_action(e, ACTION_SKIP_FORWARD) || + event_is_action(e, ACTION_STOP)) { + mp_flush(mp); + break; + } + event_release(e); + } + + vmir_mem_free(iu, nab_vm); + + np_lock(np); + vmir_vm_function_call(iu, np_audio_close, NULL, handle); + np_unlock(np); + + if(mb != NULL && mb != MB_EOF) + media_buf_free_unlocked(mp, mb); + + vmir_fd_close(iu, pfd); + return e; +} + + +static int +np_backend_open_page(prop_t *p, const char *url, int sync, void *opaque) +{ + np_context_t *np = opaque; + ir_unit_t *iu = np->np_unit; + ir_function_t *np_page_open = vmir_find_function(iu, "np_page_open"); + if(np_page_open == NULL) { + nav_open_error(p, "Plugin does not export page API"); + return 0; + } + + np_lock(np); + + int pfd = np_fd_from_prop(iu, prop_ref_inc(p)); + + uint32_t url_vm = vmir_mem_strdup(iu, url); + vmir_vm_function_call(iu, np_page_open, NULL, + pfd, url_vm, sync); + + vmir_mem_free(iu, url_vm); + vmir_fd_close(iu, pfd); + np_unlock(np); + return 0; +} + + + +static int +np_register_backend(void *ret, const void *regs, struct ir_unit *iu) +{ + np_context_t *np = vmir_get_opaque(iu); + if(np->np_backend != NULL) + return 0; + + const char *prefix = vmir_vm_ptr(®s, iu); + backend_t *be = calloc(1, sizeof(backend_t)); + atomic_set(&be->be_refcount, 1); + be->be_prefix = strdup(prefix); + be->be_opaque = np_context_retain(np); + be->be_destroy = np_backend_destroy; + be->be_flags = BACKEND_DYNAMIC; + be->be_play_audio = np_backend_play_audio; + be->be_open2 = np_backend_open_page; + backend_register_dynamic(be); + np->np_backend = be; + return 0; +} + + +static void +np_backend_unload(np_context_t *np) +{ + if(np->np_backend == NULL) + return; + backend_unregister_dynamic(np->np_backend); + backend_release(np->np_backend); +} + + +static const vmir_function_tab_t np_backend_funcs[] = { + {"np_register_uri_prefix", &np_register_backend}, +}; + +NP_MODULE("backend", np_backend_funcs, NULL, np_backend_unload); diff --git a/pool/shard000/C/0015519_vbnv_cmos.c b/pool/shard000/C/0015519_vbnv_cmos.c new file mode 100644 index 0000000000000000000000000000000000000000..35e4c410dacce8e326b273d27a27646a0a468904 --- /dev/null +++ b/pool/shard000/C/0015519_vbnv_cmos.c @@ -0,0 +1,113 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ + +#include +#include +#include +#include +#include +#include +#include + +static void clear_vbnv_battery_cutoff_flag(uint8_t *vbnv_copy) +{ + /* + * Currently battery cutoff is done in payload stage, which does not + * update backup VBNV. And doing battery cutoff will invalidate CMOS. + * This means for every reboot after cutoff, read_vbnv_cmos will reload + * backup VBNV and try to cutoff again, causing endless reboot loop. + * So we should always clear battery cutoff flag from loaded backup. + */ + if (vbnv_copy[MISC_FLAGS_OFFSET] & MISC_FLAGS_BATTERY_CUTOFF_MASK) { + printk(BIOS_INFO, "VBNV: Remove battery cut-off request.\n"); + vbnv_copy[MISC_FLAGS_OFFSET] &= ~MISC_FLAGS_BATTERY_CUTOFF_MASK; + regen_vbnv_crc(vbnv_copy); + } +} + +/* Return non-zero if backup was used. */ +static int restore_from_backup(uint8_t *vbnv_copy) +{ + if (!CONFIG(VBOOT_VBNV_CMOS_BACKUP_TO_FLASH)) + return 0; + + printk(BIOS_INFO, "VBNV: CMOS invalid, restoring from flash\n"); + read_vbnv_flash(vbnv_copy); + + if (verify_vbnv(vbnv_copy)) { + clear_vbnv_battery_cutoff_flag(vbnv_copy); + save_vbnv_cmos(vbnv_copy); + printk(BIOS_INFO, "VBNV: Flash backup restored\n"); + return 1; + } + + printk(BIOS_INFO, "VBNV: Restore from flash failed\n"); + + return 0; +} + +void read_vbnv_cmos(uint8_t *vbnv_copy) +{ + int i; + + for (i = 0; i < VBOOT_VBNV_BLOCK_SIZE; i++) + vbnv_copy[i] = cmos_read(CONFIG_VBOOT_VBNV_OFFSET + 14 + i); + + /* Verify contents before attempting a restore from backup storage. */ + if (verify_vbnv(vbnv_copy)) + return; + + restore_from_backup(vbnv_copy); +} + +void save_vbnv_cmos(const uint8_t *vbnv_copy) +{ + int i; + + for (i = 0; i < VBOOT_VBNV_BLOCK_SIZE; i++) + cmos_write(vbnv_copy[i], CONFIG_VBOOT_VBNV_OFFSET + 14 + i); +} + +void vbnv_init_cmos(uint8_t *vbnv_copy) +{ + /* If no CMOS failure just defer to the normal read path for checking + vbnv contents' integrity. */ + if (!vbnv_cmos_failed()) + return; + + /* In the case of CMOS failure force the backup. If backup wasn't used + force the vbnv CMOS to be reset. */ + if (!restore_from_backup(vbnv_copy)) { + vbnv_reset(vbnv_copy); + /* This parallels the vboot_reference implementation. */ + vbnv_copy[HEADER_OFFSET] = HEADER_SIGNATURE | + HEADER_FIRMWARE_SETTINGS_RESET | + HEADER_KERNEL_SETTINGS_RESET; + regen_vbnv_crc(vbnv_copy); + save_vbnv_cmos(vbnv_copy); + } +} + +void lb_table_add_vbnv_cmos(struct lb_header *header) +{ + struct lb_range *vbnv; + + vbnv = (struct lb_range *)lb_new_record(header); + vbnv->tag = LB_TAG_VBNV; + vbnv->size = sizeof(*vbnv); + vbnv->range_start = CONFIG_VBOOT_VBNV_OFFSET + 14; + vbnv->range_size = VBOOT_VBNV_BLOCK_SIZE; +} + +#if CONFIG(VBOOT_VBNV_CMOS_BACKUP_TO_FLASH) +static void back_up_vbnv_cmos(void *unused) +{ + uint8_t vbnv_cmos[VBOOT_VBNV_BLOCK_SIZE]; + + /* Read current VBNV from CMOS. */ + read_vbnv_cmos(vbnv_cmos); + + /* Save to flash, will only be saved if different. */ + save_vbnv_flash(vbnv_cmos); +} +BOOT_STATE_INIT_ENTRY(BS_POST_DEVICE, BS_ON_EXIT, back_up_vbnv_cmos, NULL); +#endif diff --git a/pool/shard000/C/0015529_rlm_sql_db2.c b/pool/shard000/C/0015529_rlm_sql_db2.c new file mode 100644 index 0000000000000000000000000000000000000000..14e6c40fa2ea3e98cc13c6d0a8abbb54b1ccbe27 --- /dev/null +++ b/pool/shard000/C/0015529_rlm_sql_db2.c @@ -0,0 +1,255 @@ +/* + * sql_db2.c IBM DB2 rlm_sql driver + * + * Version: $Id$ + * + * 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 St, Fifth Floor, Boston, MA 02110-1301, USA + * + * Copyright 2000,2006 The FreeRADIUS server project + * Copyright 2000 Mike Machado + * Copyright 2000 Alan DeKok + * Copyright 2001 Joerg Wendland + */ + +/* + * Modification of rlm_sql_db2 to handle IBM DB2 UDB V7 + * by Joerg Wendland + */ + +RCSID("$Id$") + +#include +#include + +#include + +#include +#include +#include "rlm_sql.h" + +typedef struct rlm_sql_conn { + SQLHANDLE dbc_handle; + SQLHANDLE env_handle; + SQLHANDLE stmt; +} rlm_sql_db2_conn_t; + +static int _sql_socket_destructor(rlm_sql_db2_conn_t *conn) +{ + DEBUG2("rlm_sql_db2: Socket destructor called, closing socket"); + + if (conn->dbc_handle) { + SQLDisconnect(conn->dbc_handle); + SQLFreeHandle(SQL_HANDLE_DBC, conn->dbc_handle); + } + + if (conn->env_handle) SQLFreeHandle(SQL_HANDLE_ENV, conn->env_handle); + + return RLM_SQL_OK; +} + +static sql_rcode_t sql_socket_init(rlm_sql_handle_t *handle, rlm_sql_config_t *config) +{ + SQLRETURN retval; + rlm_sql_db2_conn_t *conn; + + MEM(conn = handle->conn = talloc_zero(handle, rlm_sql_db2_conn_t)); + talloc_set_destructor(conn, _sql_socket_destructor); + + /* Allocate handles */ + SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &(conn->env_handle)); + SQLAllocHandle(SQL_HANDLE_DBC, conn->env_handle, &(conn->dbc_handle)); + + /* + * The db2 API doesn't qualify arguments as const even when they should be. + */ + { + SQLCHAR *server, *login, *password; + + memcpy(&server, &config->sql_server, sizeof(server)); + memcpy(&login, &config->sql_login, sizeof(login)); + memcpy(&password, &config->sql_password, sizeof(password)); + + retval = SQLConnect(conn->dbc_handle, + server, SQL_NTS, + login, SQL_NTS, + password, SQL_NTS); + } + + if (retval != SQL_SUCCESS) { + ERROR("could not connect to DB2 server %s", config->sql_server); + + return RLM_SQL_ERROR; + } + + return RLM_SQL_OK; +} + +static sql_rcode_t sql_query(rlm_sql_handle_t *handle, UNUSED rlm_sql_config_t *config, char const *query) +{ + SQLRETURN retval; + rlm_sql_db2_conn_t *conn; + + conn = handle->conn; + + /* allocate handle for statement */ + SQLAllocHandle(SQL_HANDLE_STMT, conn->dbc_handle, &(conn->stmt)); + + /* execute query */ + { + SQLCHAR *db2_query; + memcpy(&db2_query, &query, sizeof(query)); + + retval = SQLExecDirect(conn->stmt, db2_query, SQL_NTS); + if(retval != SQL_SUCCESS) { + /* XXX Check if retval means we should return RLM_SQL_RECONNECT */ + ERROR("Could not execute statement \"%s\"", query); + return RLM_SQL_ERROR; + } + } + + return RLM_SQL_OK; +} + +static sql_rcode_t sql_select_query(rlm_sql_handle_t *handle, rlm_sql_config_t *config, char const *query) +{ + return sql_query(handle, config, query); +} + +static int sql_num_fields(rlm_sql_handle_t *handle, UNUSED rlm_sql_config_t *config) +{ + SQLSMALLINT c; + rlm_sql_db2_conn_t *conn; + + conn = handle->conn; + SQLNumResultCols(conn->stmt, &c); + return c; +} + +static sql_rcode_t sql_fetch_row(rlm_sql_handle_t *handle, rlm_sql_config_t *config) +{ + int c, i; + SQLINTEGER len, slen; + rlm_sql_row_t retval; + rlm_sql_db2_conn_t *conn; + + conn = handle->conn; + + c = sql_num_fields(handle, config); + retval = (rlm_sql_row_t)rad_malloc(c*sizeof(char*)+1); + memset(retval, 0, c*sizeof(char*)+1); + + /* advance cursor */ + if (SQLFetch(conn->stmt) == SQL_NO_DATA_FOUND) { + handle->row = NULL; + for (i = 0; i < c; i++) free(retval[i]); + free(retval); + return RLM_SQL_NO_MORE_ROWS; + } + + for (i = 0; i < c; i++) { + /* get column length */ + SQLColAttribute(conn->stmt, i+1, SQL_DESC_DISPLAY_SIZE, NULL, 0, NULL, &len); + + retval[i] = rad_malloc(len+1); + + /* get the actual column */ + SQLGetData(conn->stmt, i + 1, SQL_C_CHAR, retval[i], len+1, &slen); + if(slen == SQL_NULL_DATA) { + retval[i][0] = '\0'; + } + } + + handle->row = retval; + return RLM_SQL_OK; +} + +static sql_rcode_t sql_free_result(rlm_sql_handle_t *handle, UNUSED rlm_sql_config_t *config) +{ + rlm_sql_db2_conn_t *conn; + conn = handle->conn; + SQLFreeHandle(SQL_HANDLE_STMT, conn->stmt); + + return RLM_SQL_OK; +} + +/** Retrieves any errors associated with the connection handle + * + * @note Caller will free any memory allocated in ctx. + * + * @param ctx to allocate temporary error buffers in. + * @param out Array of sql_log_entrys to fill. + * @param outlen Length of out array. + * @param handle rlm_sql connection handle. + * @param config rlm_sql config. + * @return number of errors written to the sql_log_entry array. + */ +static size_t sql_error(TALLOC_CTX *ctx, sql_log_entry_t out[], size_t outlen, + rlm_sql_handle_t *handle, UNUSED rlm_sql_config_t *config) +{ + char state[6]; + char errbuff[1024]; + SQLINTEGER err; + SQLSMALLINT rl; + rlm_sql_db2_conn_t *conn = handle->conn; + + rad_assert(conn); + rad_assert(outlen > 0); + + errbuff[0] = '\0'; + SQLGetDiagRec(SQL_HANDLE_STMT, conn->stmt, 1, (SQLCHAR *) state, &err, + (SQLCHAR *) errbuff, sizeof(errbuff), &rl); + if (errbuff[0] == '\0') return 0; + + out[0].type = L_ERR; + out[0].msg = talloc_asprintf(ctx, "%s: %s", state, errbuff); + + return 1; +} + +static sql_rcode_t sql_finish_query(UNUSED rlm_sql_handle_t *handle, UNUSED rlm_sql_config_t *config) +{ + return RLM_SQL_OK; +} + +static sql_rcode_t sql_finish_select_query(rlm_sql_handle_t *handle, rlm_sql_config_t *config) +{ + return sql_finish_query(handle, config); +} + +static int sql_affected_rows(rlm_sql_handle_t *handle, UNUSED rlm_sql_config_t *config) +{ + SQLINTEGER c; + rlm_sql_db2_conn_t *conn = handle->conn; + + SQLRowCount(conn->stmt, &c); + + return c; +} + +/* Exported to rlm_sql */ +extern rlm_sql_module_t rlm_sql_db2; +rlm_sql_module_t rlm_sql_db2 = { + .name = "rlm_sql_db2", + .sql_socket_init = sql_socket_init, + .sql_query = sql_query, + .sql_select_query = sql_select_query, + .sql_num_fields = sql_num_fields, + .sql_affected_rows = sql_affected_rows, + .sql_fetch_row = sql_fetch_row, + .sql_free_result = sql_free_result, + .sql_error = sql_error, + .sql_finish_query = sql_finish_query, + .sql_finish_select_query = sql_finish_select_query +}; diff --git a/pool/shard000/C/0015531_parse.c b/pool/shard000/C/0015531_parse.c new file mode 100644 index 0000000000000000000000000000000000000000..388139ad89ac0672f6746dd8a004778928c15e83 --- /dev/null +++ b/pool/shard000/C/0015531_parse.c @@ -0,0 +1,176 @@ +/* parse.c + + Copyright (C) 2002, 2003, 2008 Niels Möller + + This file is part of GNU Nettle. + + GNU Nettle is free software: you can redistribute it and/or + modify it under the terms of either: + + * 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. + + or + + * 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. + + or both in parallel, as here. + + GNU Nettle 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 copies of the GNU General Public License and + the GNU Lesser General Public License along with this program. If + not, see http://www.gnu.org/licenses/. +*/ + +#if HAVE_CONFIG_H +# include "config.h" +#endif + +#include +#include + +#include "parse.h" + +#include "input.h" + +void +sexp_compound_token_init(struct sexp_compound_token *token) +{ + token->type = 0; + nettle_buffer_init(&token->display); + nettle_buffer_init(&token->string); +} + +void +sexp_compound_token_clear(struct sexp_compound_token *token) +{ + nettle_buffer_clear(&token->display); + nettle_buffer_clear(&token->string); +} + +void +sexp_parse_init(struct sexp_parser *parser, + struct sexp_input *input, + enum sexp_mode mode) +{ + parser->input = input; + parser->mode = mode; + + /* Start counting with 1 for the top level, to make comparisons + * between transport and level simpler. + * + * FIXME: Is that trick ugly? */ + parser->level = 1; + parser->transport = 0; +} + +/* Get next token, and check that it is of the expected kind. */ +static void +sexp_check_token(struct sexp_parser *parser, + enum sexp_token token, + struct nettle_buffer *string) +{ + sexp_get_token(parser->input, + parser->transport ? SEXP_CANONICAL : parser->mode, + string); + + if (parser->input->token != token) + die("Syntax error.\n"); +} + +/* Performs further processing of the input, in particular display + * types and transport decoding. + * + * This is complicated a little by the requirement that a + * transport-encoded block, {xxxxx}, must include exactly one + * expression. We check at the end of strings and list whether or not + * we should expect a SEXP_CODING_END as the next token. */ +void +sexp_parse(struct sexp_parser *parser, + struct sexp_compound_token *token) +{ + for (;;) + { + sexp_get_token(parser->input, + parser->transport ? SEXP_CANONICAL : parser->mode, + &token->string); + + switch(parser->input->token) + { + case SEXP_LIST_END: + if (parser->level == parser->transport) + die("Unmatched end of list in transport encoded data.\n"); + parser->level--; + + if (!parser->level) + die("Unmatched end of list.\n"); + + token->type = SEXP_LIST_END; + + check_transport_end: + if (parser->level == parser->transport) + { + sexp_check_token(parser, SEXP_CODING_END, &token->string); + assert(parser->transport); + assert(parser->level == parser->transport); + + parser->level--; + parser->transport = 0; + } + return; + + case SEXP_EOF: + if (parser->level > 1) + die("Unexpected end of file.\n"); + + token->type = SEXP_EOF; + return; + + case SEXP_LIST_START: + parser->level++; + token->type = SEXP_LIST_START; + return; + + case SEXP_DISPLAY_START: + sexp_check_token(parser, SEXP_STRING, &token->display); + sexp_check_token(parser, SEXP_DISPLAY_END, &token->display); + sexp_check_token(parser, SEXP_STRING, &token->string); + + token->type = SEXP_DISPLAY; + goto check_transport_end; + + case SEXP_STRING: + token->type = SEXP_STRING; + goto check_transport_end; + + case SEXP_COMMENT: + token->type = SEXP_COMMENT; + return; + + case SEXP_TRANSPORT_START: + if (parser->mode == SEXP_CANONICAL) + die("Base64 not allowed in canonical mode.\n"); + parser->level++; + parser->transport = parser->level; + + continue; + + case SEXP_CODING_END: + die("Unexpected end of transport encoding.\n"); + + case SEXP_DISPLAY_END: + die("Unexpected end of display tag.\n"); + + case SEXP_DISPLAY: + /* Internal error. */ + abort(); + } + } +} diff --git a/pool/shard000/C/0015533_blobapi.c b/pool/shard000/C/0015533_blobapi.c new file mode 100644 index 0000000000000000000000000000000000000000..70a23049e334d30f7975469b68409f3d6377377a --- /dev/null +++ b/pool/shard000/C/0015533_blobapi.c @@ -0,0 +1,128 @@ +/* + * PANDA -- a simple transaction monitor + * Copyright (C) 2000-2009 Ogochan & JMA (Japan Medical Association). + * + * 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, 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +/* +#define DEBUG +#define TRACE +*/ + +#ifdef HAVE_CONFIG_H +#include +#endif +#include +#include +#include + +#include "const.h" + +#include "http.h" +#include "libmondai.h" +#include "comm.h" +#include "message.h" +#include "debug.h" + +#define MONBLOBCMD "monblobapi" + +static HTTP_RESPONSE *BlobToResponse(HTTP_REQUEST *req, HTTP_RESPONSE *res, + char *tempsocket) { + Port *port; + int fd, _fd; + NETFILE *fp; + char *recv; + char *body; + json_object *json_res; + size_t size; + + port = ParPortName(tempsocket); + _fd = InitServerPort(port, 1); + if ((fd = accept(_fd, 0, 0)) < 0) { + Error("INET Domain Accept"); + } + fp = SocketToNet(fd); + + recv = RecvStringNew(fp); + ON_IO_ERROR(fp, badio); + json_res = json_tokener_parse(recv); + xfree(recv); + + size = RecvLength(fp); + ON_IO_ERROR(fp, badio); + if (size > 0) { + body = (char *)xmalloc(size); + Recv(fp, body, size); + ON_IO_ERROR(fp, badio); + res->body_size = size; + res->body = body; + res->status = HTTP_OK; + } + + json_object *json_content_type; + char *content_type; + if (json_object_object_get_ex(json_res, "content-type", &json_content_type)) { + content_type = (char *)json_object_get_string(json_content_type); + res->content_type = content_type; + } + + json_object *json_filename; + char *filename; + if (json_object_object_get_ex(json_res, "filename", &json_filename)) { + filename = (char *)json_object_get_string(json_filename); + res->filename = filename; + } + + json_object *json_status; + if (json_object_object_get_ex(json_res, "status", &json_status)) { + res->status = json_object_get_int(json_status); + } + +badio: + close(_fd); + CloseNet(fp); + CleanUNIX_Socket(port); + return res; +} + +extern void GetBlobAPI(HTTP_REQUEST *req, HTTP_RESPONSE *res) { + pid_t pid; + char tempdir[PATH_MAX]; + char tempsocket[PATH_MAX]; + char *cmd; + + snprintf(tempdir, PATH_MAX, "/tmp/blobapi_XXXXXX"); + if (!mkdtemp(tempdir)) { + Error("mkdtemp: %s", strerror(errno)); + } + snprintf(tempsocket, PATH_MAX, "%s/%s", tempdir, "blobapi"); + cmd = BIN_DIR "/" MONBLOBCMD; + if ((pid = fork()) < 0) { + Error("fork: %s", strerror(errno)); + } + if (pid == 0) { + /* child */ + if (execl(cmd, MONBLOBCMD, "-export", req->session_id, "-socket", + tempsocket, NULL) < 0) { + Error("execl: %s:%s", strerror(errno), cmd); + } + } + /* parent */ + BlobToResponse(req, res, tempsocket); + + rmdir(tempdir); + return; +} diff --git a/pool/shard000/C/0015540_uart.c b/pool/shard000/C/0015540_uart.c new file mode 100644 index 0000000000000000000000000000000000000000..1eb12fce10fe5fde985e5928e2bee7d77c7b8f58 --- /dev/null +++ b/pool/shard000/C/0015540_uart.c @@ -0,0 +1,163 @@ +/* + * This file is part of the coreboot project. + * + * Copyright (C) 2003 Eric Biederman + * Copyright (C) 2006-2010 coresystems GmbH + * Copyright (C) 2014 Imagination Technologies + * + * 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. + */ + +#include +#include +#include +#include +#include +#include +#include + +/* Should support 8250, 16450, 16550, 16550A type UARTs */ + +/* Expected character delay at 1200bps is 9ms for a working UART + * and no flow-control. Assume UART as stuck if shift register + * or FIFO takes more than 50ms per character to appear empty. + */ +#define SINGLE_CHAR_TIMEOUT (50 * 1000) +#define FIFO_TIMEOUT (16 * SINGLE_CHAR_TIMEOUT) +#define UART_SHIFT 2 + +#define GEN_ACCESSOR(name, idx) \ +static inline uint8_t read_##name(unsigned base_port) \ +{ \ + return read8(base_port + (idx << UART_SHIFT)); \ +} \ + \ +static inline void write_##name(unsigned base_port, uint8_t val) \ +{ \ + write8(base_port + (idx << UART_SHIFT), val); \ +} + +GEN_ACCESSOR(rbr, UART8250_RBR) +GEN_ACCESSOR(tbr, UART8250_TBR) +GEN_ACCESSOR(ier, UART8250_IER) +GEN_ACCESSOR(fcr, UART8250_FCR) +GEN_ACCESSOR(lcr, UART8250_LCR) +GEN_ACCESSOR(mcr, UART8250_MCR) +GEN_ACCESSOR(lsr, UART8250_LSR) +GEN_ACCESSOR(dll, UART8250_DLL) +GEN_ACCESSOR(dlm, UART8250_DLM) + +static int uart8250_mem_can_tx_byte(unsigned base_port) +{ + return read_lsr(base_port) & UART8250_LSR_THRE; +} + +static void uart8250_mem_tx_byte(unsigned base_port, unsigned char data) +{ + unsigned long int i = SINGLE_CHAR_TIMEOUT; + while (i-- && !uart8250_mem_can_tx_byte(base_port)) + udelay(1); + write_tbr(base_port, data); +} + +static void uart8250_mem_tx_flush(unsigned base_port) +{ + unsigned long int i = FIFO_TIMEOUT; + while (i-- && !(read_lsr(base_port) & UART8250_LSR_TEMT)) + udelay(1); +} + +static int uart8250_mem_can_rx_byte(unsigned base_port) +{ + return read_lsr(base_port) & UART8250_LSR_DR; +} + +static unsigned char uart8250_mem_rx_byte(unsigned base_port) +{ + unsigned long int i = SINGLE_CHAR_TIMEOUT; + while (i-- && !uart8250_mem_can_rx_byte(base_port)) + udelay(1); + if (i) + return read_rbr(base_port); + else + return 0x0; +} + +static void uart8250_mem_init(unsigned base_port, unsigned divisor) +{ + /* Disable interrupts */ + write_ier(base_port, 0x0); + /* Enable FIFOs */ + write_fcr(base_port, UART8250_FCR_FIFO_EN); + + /* Assert DTR and RTS so the other end is happy */ + write_mcr(base_port, UART8250_MCR_DTR | UART8250_MCR_RTS); + + /* DLAB on */ + write_lcr(base_port, UART8250_LCR_DLAB | CONFIG_TTYS0_LCS); + + write_dll(base_port, divisor & 0xFF); + write_dlm(base_port, (divisor >> 8) & 0xFF); + + /* Set to 3 for 8N1 */ + write_lcr(base_port, CONFIG_TTYS0_LCS); +} + +unsigned int uart_platform_refclk(void) +{ + /* 1.8433179 MHz */ + return 1843318; +} + +void uart_init(int idx) +{ + u32 base = CONFIG_CONSOLE_SERIAL_UART_ADDRESS; + if (!base) + return; + + unsigned int div; + div = uart_baudrate_divisor(CONFIG_TTYS0_BAUD, + uart_platform_refclk(), 16); + uart8250_mem_init(base, div); +} + +void uart_tx_byte(int idx, unsigned char data) +{ + uart8250_mem_tx_byte(CONFIG_CONSOLE_SERIAL_UART_ADDRESS, data); +} + +unsigned char uart_rx_byte(int idx) +{ + return uart8250_mem_rx_byte(CONFIG_CONSOLE_SERIAL_UART_ADDRESS); +} + +void uart_tx_flush(int idx) +{ + uart8250_mem_tx_flush(CONFIG_CONSOLE_SERIAL_UART_ADDRESS); +} + +#ifndef __PRE_RAM__ +void uart_fill_lb(void *data) +{ + struct lb_serial serial; + serial.type = LB_SERIAL_TYPE_MEMORY_MAPPED; + serial.baseaddr = CONFIG_CONSOLE_SERIAL_UART_ADDRESS; + serial.baud = default_baudrate(); + serial.regwidth = 1 << UART_SHIFT; + lb_add_serial(&serial, data); + + lb_add_console(LB_TAG_CONSOLE_SERIAL8250MEM, data); +} +#endif diff --git a/pool/shard000/C/0015558_slatm7.c b/pool/shard000/C/0015558_slatm7.c new file mode 100644 index 0000000000000000000000000000000000000000..29323a5233b792df672b748e722f3119d0e45a1c --- /dev/null +++ b/pool/shard000/C/0015558_slatm7.c @@ -0,0 +1,302 @@ +/* slatm7.f -- translated by f2c (version 20061008). + You must link the resulting object file with libf2c: + on Microsoft Windows system, link with libf2c.lib; + on Linux or Unix systems, link with .../path/to/libf2c.a -lm + or, if you install libf2c.a in a standard place, with -lf2c -lm + -- in that order, at the end of the command line, as in + cc *.o -lf2c -lm + Source for libf2c is in /netlib/f2c/libf2c.zip, e.g., + + http://www.netlib.org/f2c/libf2c.zip +*/ + +#include "f2c.h" +#include "blaswrap.h" + +/* Subroutine */ int slatm7_(integer *mode, real *cond, integer *irsign, + integer *idist, integer *iseed, real *d__, integer *n, integer *rank, + integer *info) +{ + /* System generated locals */ + integer i__1, i__2; + doublereal d__1, d__2; + + /* Local variables */ + integer i__; + real temp, alpha; + extern doublereal slaran_(integer *); + extern /* Subroutine */ int slarnv_(integer *, integer *, integer *, real + *); + + +/* -- LAPACK test routine (version 3.1) -- */ +/* Craig Lucas, University of Manchester / NAG Ltd. */ +/* October, 2008 */ + +/* .. Scalar Arguments .. */ +/* .. */ +/* .. Array Arguments .. */ +/* .. */ + +/* Purpose */ +/* ======= */ + +/* SLATM7 computes the entries of D as specified by MODE */ +/* COND and IRSIGN. IDIST and ISEED determine the generation */ +/* of random numbers. SLATM7 is called by SLATMT to generate */ +/* random test matrices. */ + +/* Arguments */ +/* ========= */ + +/* MODE - INTEGER */ +/* On entry describes how D is to be computed: */ +/* MODE = 0 means do not change D. */ + +/* MODE = 1 sets D(1)=1 and D(2:RANK)=1.0/COND */ +/* MODE = 2 sets D(1:RANK-1)=1 and D(RANK)=1.0/COND */ +/* MODE = 3 sets D(I)=COND**(-(I-1)/(RANK-1)) I=1:RANK */ + +/* MODE = 4 sets D(i)=1 - (i-1)/(N-1)*(1 - 1/COND) */ +/* MODE = 5 sets D to random numbers in the range */ +/* ( 1/COND , 1 ) such that their logarithms */ +/* are uniformly distributed. */ +/* MODE = 6 set D to random numbers from same distribution */ +/* as the rest of the matrix. */ +/* MODE < 0 has the same meaning as ABS(MODE), except that */ +/* the order of the elements of D is reversed. */ +/* Thus if MODE is positive, D has entries ranging from */ +/* 1 to 1/COND, if negative, from 1/COND to 1, */ +/* Not modified. */ + +/* COND - REAL */ +/* On entry, used as described under MODE above. */ +/* If used, it must be >= 1. Not modified. */ + +/* IRSIGN - INTEGER */ +/* On entry, if MODE neither -6, 0 nor 6, determines sign of */ +/* entries of D */ +/* 0 => leave entries of D unchanged */ +/* 1 => multiply each entry of D by 1 or -1 with probability .5 */ + +/* IDIST - CHARACTER*1 */ +/* On entry, IDIST specifies the type of distribution to be */ +/* used to generate a random matrix . */ +/* 1 => UNIFORM( 0, 1 ) */ +/* 2 => UNIFORM( -1, 1 ) */ +/* 3 => NORMAL( 0, 1 ) */ +/* Not modified. */ + +/* ISEED - INTEGER array, dimension ( 4 ) */ +/* On entry ISEED specifies the seed of the random number */ +/* generator. The random number generator uses a */ +/* linear congruential sequence limited to small */ +/* integers, and so should produce machine independent */ +/* random numbers. The values of ISEED are changed on */ +/* exit, and can be used in the next call to SLATM7 */ +/* to continue the same random number sequence. */ +/* Changed on exit. */ + +/* D - REAL array, dimension ( MIN( M , N ) ) */ +/* Array to be computed according to MODE, COND and IRSIGN. */ +/* May be changed on exit if MODE is nonzero. */ + +/* N - INTEGER */ +/* Number of entries of D. Not modified. */ + +/* RANK - INTEGER */ +/* The rank of matrix to be generated for modes 1,2,3 only. */ +/* D( RANK+1:N ) = 0. */ +/* Not modified. */ + +/* INFO - INTEGER */ +/* 0 => normal termination */ +/* -1 => if MODE not in range -6 to 6 */ +/* -2 => if MODE neither -6, 0 nor 6, and */ +/* IRSIGN neither 0 nor 1 */ +/* -3 => if MODE neither -6, 0 nor 6 and COND less than 1 */ +/* -4 => if MODE equals 6 or -6 and IDIST not in range 1 to 3 */ +/* -7 => if N negative */ + +/* ===================================================================== */ + +/* .. Parameters .. */ +/* .. */ +/* .. Local Scalars .. */ +/* .. */ +/* .. External Functions .. */ +/* .. */ +/* .. External Subroutines .. */ +/* .. */ +/* .. Intrinsic Functions .. */ +/* .. */ +/* .. Executable Statements .. */ + +/* Decode and Test the input parameters. Initialize flags & seed. */ + + /* Parameter adjustments */ + --d__; + --iseed; + + /* Function Body */ + *info = 0; + +/* Quick return if possible */ + + if (*n == 0) { + return 0; + } + +/* Set INFO if an error */ + + if (*mode < -6 || *mode > 6) { + *info = -1; + } else if (*mode != -6 && *mode != 0 && *mode != 6 && (*irsign != 0 && * + irsign != 1)) { + *info = -2; + } else if (*mode != -6 && *mode != 0 && *mode != 6 && *cond < 1.f) { + *info = -3; + } else if ((*mode == 6 || *mode == -6) && (*idist < 1 || *idist > 3)) { + *info = -4; + } else if (*n < 0) { + *info = -7; + } + + if (*info != 0) { + i__1 = -(*info); + xerbla_("SLATM7", &i__1); + return 0; + } + +/* Compute D according to COND and MODE */ + + if (*mode != 0) { + switch (abs(*mode)) { + case 1: goto L100; + case 2: goto L130; + case 3: goto L160; + case 4: goto L190; + case 5: goto L210; + case 6: goto L230; + } + +/* One large D value: */ + +L100: + i__1 = *rank; + for (i__ = 2; i__ <= i__1; ++i__) { + d__[i__] = 1.f / *cond; +/* L110: */ + } + i__1 = *n; + for (i__ = *rank + 1; i__ <= i__1; ++i__) { + d__[i__] = 0.f; +/* L120: */ + } + d__[1] = 1.f; + goto L240; + +/* One small D value: */ + +L130: + i__1 = *rank - 1; + for (i__ = 1; i__ <= i__1; ++i__) { + d__[i__] = 1.f; +/* L140: */ + } + i__1 = *n; + for (i__ = *rank + 1; i__ <= i__1; ++i__) { + d__[i__] = 0.f; +/* L150: */ + } + d__[*rank] = 1.f / *cond; + goto L240; + +/* Exponentially distributed D values: */ + +L160: + d__[1] = 1.f; + if (*n > 1) { + d__1 = (doublereal) (*cond); + d__2 = (doublereal) (-1.f / (real) (*rank - 1)); + alpha = pow_dd(&d__1, &d__2); + i__1 = *rank; + for (i__ = 2; i__ <= i__1; ++i__) { + i__2 = i__ - 1; + d__[i__] = pow_ri(&alpha, &i__2); +/* L170: */ + } + i__1 = *n; + for (i__ = *rank + 1; i__ <= i__1; ++i__) { + d__[i__] = 0.f; +/* L180: */ + } + } + goto L240; + +/* Arithmetically distributed D values: */ + +L190: + d__[1] = 1.f; + if (*n > 1) { + temp = 1.f / *cond; + alpha = (1.f - temp) / (real) (*n - 1); + i__1 = *n; + for (i__ = 2; i__ <= i__1; ++i__) { + d__[i__] = (real) (*n - i__) * alpha + temp; +/* L200: */ + } + } + goto L240; + +/* Randomly distributed D values on ( 1/COND , 1): */ + +L210: + alpha = log(1.f / *cond); + i__1 = *n; + for (i__ = 1; i__ <= i__1; ++i__) { + d__[i__] = exp(alpha * slaran_(&iseed[1])); +/* L220: */ + } + goto L240; + +/* Randomly distributed D values from IDIST */ + +L230: + slarnv_(idist, &iseed[1], n, &d__[1]); + +L240: + +/* If MODE neither -6 nor 0 nor 6, and IRSIGN = 1, assign */ +/* random signs to D */ + + if (*mode != -6 && *mode != 0 && *mode != 6 && *irsign == 1) { + i__1 = *n; + for (i__ = 1; i__ <= i__1; ++i__) { + temp = slaran_(&iseed[1]); + if (temp > .5f) { + d__[i__] = -d__[i__]; + } +/* L250: */ + } + } + +/* Reverse if MODE < 0 */ + + if (*mode < 0) { + i__1 = *n / 2; + for (i__ = 1; i__ <= i__1; ++i__) { + temp = d__[i__]; + d__[i__] = d__[*n + 1 - i__]; + d__[*n + 1 - i__] = temp; +/* L260: */ + } + } + + } + + return 0; + +/* End of SLATM7 */ + +} /* slatm7_ */ diff --git a/pool/shard000/C/0015576_cleanuppush.c b/pool/shard000/C/0015576_cleanuppush.c new file mode 100644 index 0000000000000000000000000000000000000000..cf640e04775e2fe1641921cc825902768b688141 --- /dev/null +++ b/pool/shard000/C/0015576_cleanuppush.c @@ -0,0 +1,97 @@ +/** + * @file + * + * @brief Establishing Cancellation Handlers + * @ingroup POSIXAPI + */ + +/* + * COPYRIGHT (c) 1989-2008. + * On-Line Applications Research Corporation (OAR). + * + * The license and distribution terms for this file may be + * found in the file LICENSE in this distribution or at + * http://www.rtems.org/license/LICENSE. + */ + +#if HAVE_CONFIG_H +#include "config.h" +#endif + +#include + +#include +#include +#include + +#ifndef HAVE_STRUCT__PTHREAD_CLEANUP_CONTEXT + +#include +#include +#include +#include +#include + +/* + * 18.2.3.1 Establishing Cancellation Handlers, P1003.1c/Draft 10, p. 184 + */ + +void pthread_cleanup_push( + void (*routine)( void * ), + void *arg +) +{ + POSIX_Cancel_Handler_control *handler; + Chain_Control *handler_stack; + POSIX_API_Control *thread_support; + + /* + * The POSIX standard does not address what to do when the routine + * is NULL. It also does not address what happens when we cannot + * allocate memory or anything else bad happens. + */ + if ( !routine ) + return; + + _Thread_Disable_dispatch(); + handler = _Workspace_Allocate( sizeof( POSIX_Cancel_Handler_control ) ); + + if ( handler ) { + thread_support = _Thread_Executing->API_Extensions[ THREAD_API_POSIX ]; + + handler_stack = &thread_support->Cancellation_Handlers; + + handler->routine = routine; + handler->arg = arg; + + _Chain_Append( handler_stack, &handler->Node ); + } + _Thread_Enable_dispatch(); +} + +#else /* HAVE_STRUCT__PTHREAD_CLEANUP_CONTEXT */ + +void _pthread_cleanup_push( + struct _pthread_cleanup_context *context, + void ( *routine )( void * ), + void *arg +) +{ + POSIX_API_Control *thread_support; + + context->_routine = routine; + context->_arg = arg; + + /* This value is unused, just provide a deterministic value */ + context->_canceltype = -1; + + _Thread_Disable_dispatch(); + + thread_support = _Thread_Executing->API_Extensions[ THREAD_API_POSIX ]; + context->_previous = thread_support->last_cleanup_context; + thread_support->last_cleanup_context = context; + + _Thread_Enable_dispatch(); +} + +#endif /* HAVE_STRUCT__PTHREAD_CLEANUP_CONTEXT */ diff --git a/pool/shard000/C/0015591_ad1980.c b/pool/shard000/C/0015591_ad1980.c new file mode 100644 index 0000000000000000000000000000000000000000..89fcf7d6e7b8fdfb94bac498c935ad9bf3646fcc --- /dev/null +++ b/pool/shard000/C/0015591_ad1980.c @@ -0,0 +1,284 @@ +/* + * ad1980.c -- ALSA Soc AD1980 codec support + * + * Copyright: Analog Device Inc. + * Author: Roy Huang + * Cliff Cai + * + * 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. + */ + +/* + * WARNING: + * + * Because Analog Devices Inc. discontinued the ad1980 sound chip since + * Sep. 2009, this ad1980 driver is not maintained, tested and supported + * by ADI now. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ad1980.h" + +/* + * AD1980 register cache + */ +static const u16 ad1980_reg[] = { + 0x0090, 0x8000, 0x8000, 0x8000, /* 0 - 6 */ + 0x0000, 0x0000, 0x8008, 0x8008, /* 8 - e */ + 0x8808, 0x8808, 0x0000, 0x8808, /* 10 - 16 */ + 0x8808, 0x0000, 0x8000, 0x0000, /* 18 - 1e */ + 0x0000, 0x0000, 0x0000, 0x0000, /* 20 - 26 */ + 0x03c7, 0x0000, 0xbb80, 0xbb80, /* 28 - 2e */ + 0xbb80, 0xbb80, 0x0000, 0x8080, /* 30 - 36 */ + 0x8080, 0x2000, 0x0000, 0x0000, /* 38 - 3e */ + 0x0000, 0x0000, 0x0000, 0x0000, /* reserved */ + 0x0000, 0x0000, 0x0000, 0x0000, /* reserved */ + 0x0000, 0x0000, 0x0000, 0x0000, /* reserved */ + 0x0000, 0x0000, 0x0000, 0x0000, /* reserved */ + 0x8080, 0x0000, 0x0000, 0x0000, /* 60 - 66 */ + 0x0000, 0x0000, 0x0000, 0x0000, /* reserved */ + 0x0000, 0x0000, 0x1001, 0x0000, /* 70 - 76 */ + 0x0000, 0x0000, 0x4144, 0x5370 /* 78 - 7e */ +}; + +static const char *ad1980_rec_sel[] = {"Mic", "CD", "NC", "AUX", "Line", + "Stereo Mix", "Mono Mix", "Phone"}; + +static const struct soc_enum ad1980_cap_src = + SOC_ENUM_DOUBLE(AC97_REC_SEL, 8, 0, 7, ad1980_rec_sel); + +static const struct snd_kcontrol_new ad1980_snd_ac97_controls[] = { +SOC_DOUBLE("Master Playback Volume", AC97_MASTER, 8, 0, 31, 1), +SOC_SINGLE("Master Playback Switch", AC97_MASTER, 15, 1, 1), + +SOC_DOUBLE("Headphone Playback Volume", AC97_HEADPHONE, 8, 0, 31, 1), +SOC_SINGLE("Headphone Playback Switch", AC97_HEADPHONE, 15, 1, 1), + +SOC_DOUBLE("PCM Playback Volume", AC97_PCM, 8, 0, 31, 1), +SOC_SINGLE("PCM Playback Switch", AC97_PCM, 15, 1, 1), + +SOC_DOUBLE("PCM Capture Volume", AC97_REC_GAIN, 8, 0, 31, 0), +SOC_SINGLE("PCM Capture Switch", AC97_REC_GAIN, 15, 1, 1), + +SOC_SINGLE("Mono Playback Volume", AC97_MASTER_MONO, 0, 31, 1), +SOC_SINGLE("Mono Playback Switch", AC97_MASTER_MONO, 15, 1, 1), + +SOC_SINGLE("Phone Capture Volume", AC97_PHONE, 0, 31, 1), +SOC_SINGLE("Phone Capture Switch", AC97_PHONE, 15, 1, 1), + +SOC_SINGLE("Mic Volume", AC97_MIC, 0, 31, 1), +SOC_SINGLE("Mic Switch", AC97_MIC, 15, 1, 1), + +SOC_SINGLE("Stereo Mic Switch", AC97_AD_MISC, 6, 1, 0), +SOC_DOUBLE("Line HP Swap Switch", AC97_AD_MISC, 10, 5, 1, 0), + +SOC_DOUBLE("Surround Playback Volume", AC97_SURROUND_MASTER, 8, 0, 31, 1), +SOC_DOUBLE("Surround Playback Switch", AC97_SURROUND_MASTER, 15, 7, 1, 1), + +SOC_DOUBLE("Center/LFE Playback Volume", AC97_CENTER_LFE_MASTER, 8, 0, 31, 1), +SOC_DOUBLE("Center/LFE Playback Switch", AC97_CENTER_LFE_MASTER, 15, 7, 1, 1), + +SOC_ENUM("Capture Source", ad1980_cap_src), + +SOC_SINGLE("Mic Boost Switch", AC97_MIC, 6, 1, 0), +}; + +static unsigned int ac97_read(struct snd_soc_codec *codec, + unsigned int reg) +{ + u16 *cache = codec->reg_cache; + + switch (reg) { + case AC97_RESET: + case AC97_INT_PAGING: + case AC97_POWERDOWN: + case AC97_EXTENDED_STATUS: + case AC97_VENDOR_ID1: + case AC97_VENDOR_ID2: + return soc_ac97_ops->read(codec->ac97, reg); + default: + reg = reg >> 1; + + if (reg >= ARRAY_SIZE(ad1980_reg)) + return -EINVAL; + + return cache[reg]; + } +} + +static int ac97_write(struct snd_soc_codec *codec, unsigned int reg, + unsigned int val) +{ + u16 *cache = codec->reg_cache; + + soc_ac97_ops->write(codec->ac97, reg, val); + reg = reg >> 1; + if (reg < ARRAY_SIZE(ad1980_reg)) + cache[reg] = val; + + return 0; +} + +static struct snd_soc_dai_driver ad1980_dai = { + .name = "ad1980-hifi", + .ac97_control = 1, + .playback = { + .stream_name = "Playback", + .channels_min = 2, + .channels_max = 6, + .rates = SNDRV_PCM_RATE_48000, + .formats = SND_SOC_STD_AC97_FMTS, }, + .capture = { + .stream_name = "Capture", + .channels_min = 2, + .channels_max = 2, + .rates = SNDRV_PCM_RATE_48000, + .formats = SND_SOC_STD_AC97_FMTS, }, +}; + +static int ad1980_reset(struct snd_soc_codec *codec, int try_warm) +{ + u16 retry_cnt = 0; + +retry: + if (try_warm && soc_ac97_ops->warm_reset) { + soc_ac97_ops->warm_reset(codec->ac97); + if (ac97_read(codec, AC97_RESET) == 0x0090) + return 1; + } + + soc_ac97_ops->reset(codec->ac97); + /* Set bit 16slot in register 74h, then every slot will has only 16 + * bits. This command is sent out in 20bit mode, in which case the + * first nibble of data is eaten by the addr. (Tag is always 16 bit)*/ + ac97_write(codec, AC97_AD_SERIAL_CFG, 0x9900); + + if (ac97_read(codec, AC97_RESET) != 0x0090) + goto err; + return 0; + +err: + while (retry_cnt++ < 10) + goto retry; + + printk(KERN_ERR "AD1980 AC97 reset failed\n"); + return -EIO; +} + +static int ad1980_soc_probe(struct snd_soc_codec *codec) +{ + int ret; + u16 vendor_id2; + u16 ext_status; + + printk(KERN_INFO "AD1980 SoC Audio Codec\n"); + + ret = snd_soc_new_ac97_codec(codec, soc_ac97_ops, 0); + if (ret < 0) { + printk(KERN_ERR "ad1980: failed to register AC97 codec\n"); + return ret; + } + + ret = ad1980_reset(codec, 0); + if (ret < 0) { + printk(KERN_ERR "Failed to reset AD1980: AC97 link error\n"); + goto reset_err; + } + + /* Read out vendor ID to make sure it is ad1980 */ + if (ac97_read(codec, AC97_VENDOR_ID1) != 0x4144) { + ret = -ENODEV; + goto reset_err; + } + + vendor_id2 = ac97_read(codec, AC97_VENDOR_ID2); + + if (vendor_id2 != 0x5370) { + if (vendor_id2 != 0x5374) { + ret = -ENODEV; + goto reset_err; + } else { + printk(KERN_WARNING "ad1980: " + "Found AD1981 - only 2/2 IN/OUT Channels " + "supported\n"); + } + } + + /* unmute captures and playbacks volume */ + ac97_write(codec, AC97_MASTER, 0x0000); + ac97_write(codec, AC97_PCM, 0x0000); + ac97_write(codec, AC97_REC_GAIN, 0x0000); + ac97_write(codec, AC97_CENTER_LFE_MASTER, 0x0000); + ac97_write(codec, AC97_SURROUND_MASTER, 0x0000); + + /*power on LFE/CENTER/Surround DACs*/ + ext_status = ac97_read(codec, AC97_EXTENDED_STATUS); + ac97_write(codec, AC97_EXTENDED_STATUS, ext_status&~0x3800); + + snd_soc_add_codec_controls(codec, ad1980_snd_ac97_controls, + ARRAY_SIZE(ad1980_snd_ac97_controls)); + + return 0; + +reset_err: + snd_soc_free_ac97_codec(codec); + return ret; +} + +static int ad1980_soc_remove(struct snd_soc_codec *codec) +{ + snd_soc_free_ac97_codec(codec); + return 0; +} + +static struct snd_soc_codec_driver soc_codec_dev_ad1980 = { + .probe = ad1980_soc_probe, + .remove = ad1980_soc_remove, + .reg_cache_size = ARRAY_SIZE(ad1980_reg), + .reg_word_size = sizeof(u16), + .reg_cache_default = ad1980_reg, + .reg_cache_step = 2, + .write = ac97_write, + .read = ac97_read, +}; + +static int ad1980_probe(struct platform_device *pdev) +{ + return snd_soc_register_codec(&pdev->dev, + &soc_codec_dev_ad1980, &ad1980_dai, 1); +} + +static int ad1980_remove(struct platform_device *pdev) +{ + snd_soc_unregister_codec(&pdev->dev); + return 0; +} + +static struct platform_driver ad1980_codec_driver = { + .driver = { + .name = "ad1980", + .owner = THIS_MODULE, + }, + + .probe = ad1980_probe, + .remove = ad1980_remove, +}; + +module_platform_driver(ad1980_codec_driver); + +MODULE_DESCRIPTION("ASoC ad1980 driver (Obsolete)"); +MODULE_AUTHOR("Roy Huang, Cliff Cai"); +MODULE_LICENSE("GPL"); diff --git a/pool/shard000/C/0015597_migrate.c b/pool/shard000/C/0015597_migrate.c new file mode 100644 index 0000000000000000000000000000000000000000..3bb896778e40e5be07c8ff77389bcfe80b691cc5 --- /dev/null +++ b/pool/shard000/C/0015597_migrate.c @@ -0,0 +1,116 @@ +/** + * @file migrate.c migration between different cache versions + * + * Copyright (C) 2007-2011 Lars Lindner + * + * 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 "migrate.h" + +#include +#include + +#include "common.h" +#include "db.h" +#include "debug.h" +#include "ui/ui_common.h" + +#define LIFEREA_CURRENT_DIR ".liferea_1.9" + +static void +migrate_copy_dir (const gchar *from, + const gchar *to, + const gchar *subdir) +{ + gchar *fromDirname, *toDirname; + gchar *srcfile, *destfile; + GDir *dir; + + fromDirname = g_build_filename (g_get_home_dir (), from, subdir, NULL); + toDirname = g_build_filename (g_get_home_dir (), to, subdir, NULL); + + dir = g_dir_open (fromDirname, 0, NULL); + while (NULL != (srcfile = (gchar *)g_dir_read_name (dir))) { + destfile = g_build_filename (toDirname, srcfile, NULL); + srcfile = g_build_filename (fromDirname, srcfile, NULL); + if (g_file_test (srcfile, G_FILE_TEST_IS_REGULAR)) { + g_print ("copying %s\n to %s\n", srcfile, destfile); + common_copy_file (srcfile, destfile); + } else { + g_print("skipping %s\n", srcfile); + } + g_free (destfile); + g_free (srcfile); + } + g_dir_close(dir); + + g_free (fromDirname); + g_free (toDirname); +} + +static void +migrate_from_14plus (const gchar *olddir, nodePtr node) +{ + gchar *filename; + + // FIXME: Use XDG dirs for 1.9 cache structure + g_print("Performing %s -> %s cache migration...\n", olddir, LIFEREA_CURRENT_DIR); + + /* 1.) Close already loaded DB */ + db_deinit (); + + /* 2.) Copy all files */ + migrate_copy_dir (olddir, LIFEREA_CURRENT_DIR, ""); + migrate_copy_dir (olddir, LIFEREA_CURRENT_DIR, "cache" G_DIR_SEPARATOR_S "favicons"); + migrate_copy_dir (olddir, LIFEREA_CURRENT_DIR, "cache" G_DIR_SEPARATOR_S "scripts"); + migrate_copy_dir (olddir, LIFEREA_CURRENT_DIR, "cache" G_DIR_SEPARATOR_S "plugins"); + + /* 3.) And reopen the copied DB */ + db_init (); + + /* 4.) Migrate file feed list into DB */ + filename = common_create_cache_filename(NULL, "feedlist", "opml"); + + if(!import_OPML_feedlist (filename, node, FALSE, TRUE)) + g_error ("Fatal: Feed list migration failed!"); + + g_free(filename); + + ui_show_info_box (_("This version of Liferea uses a new cache format and has migrated your " + "feed cache. The cache content in %s was not deleted automatically. " + "Please remove this directory manually once you are sure migration was successful!"), olddir); +} + +void +migration_execute (migrationMode mode, nodePtr node) +{ + switch (mode) { + case MIGRATION_FROM_14: + migrate_from_14plus (".liferea_1.4", node); + break; + case MIGRATION_FROM_16: + migrate_from_14plus (".liferea_1.6", node); + break; + case MIGRATION_FROM_18: + migrate_from_14plus (".liferea_1.8", node); + break; + case MIGRATION_MODE_INVALID: + default: + g_error ("Invalid migration mode!"); + return; + break; + } +} diff --git a/pool/shard000/C/0015605_xml2sexprtest.c b/pool/shard000/C/0015605_xml2sexprtest.c new file mode 100644 index 0000000000000000000000000000000000000000..87ac2c3e2037d62da7b7ac4a36b8933f400bb700 --- /dev/null +++ b/pool/shard000/C/0015605_xml2sexprtest.c @@ -0,0 +1,186 @@ + +#include + +#include +#include +#include +#include +#include +#include + +#include "internal.h" +#include "xen/xend_internal.h" +#include "xen/xen_driver.h" +#include "xenxs/xen_sxpr.h" +#include "testutils.h" +#include "testutilsxen.h" +#include "virstring.h" + +#define VIR_FROM_THIS VIR_FROM_NONE + +static virCapsPtr caps; +static virDomainXMLOptionPtr xmlopt; + +static int +testCompareFiles(const char *xml, const char *sexpr, int xendConfigVersion) +{ + char *xmlData = NULL; + char *sexprData = NULL; + char *gotsexpr = NULL; + int ret = -1; + virDomainDefPtr def = NULL; + + if (virtTestLoadFile(xml, &xmlData) < 0) + goto fail; + + if (virtTestLoadFile(sexpr, &sexprData) < 0) + goto fail; + + if (!(def = virDomainDefParseString(xmlData, caps, xmlopt, + 1 << VIR_DOMAIN_VIRT_XEN, + VIR_DOMAIN_XML_INACTIVE))) + goto fail; + + if (!(gotsexpr = xenFormatSxpr(NULL, def, xendConfigVersion))) + goto fail; + + if (STRNEQ(sexprData, gotsexpr)) { + virtTestDifference(stderr, sexprData, gotsexpr); + goto fail; + } + + ret = 0; + + fail: + VIR_FREE(xmlData); + VIR_FREE(sexprData); + VIR_FREE(gotsexpr); + virDomainDefFree(def); + + return ret; +} + +struct testInfo { + const char *input; + const char *output; + const char *name; + int version; +}; + +static int +testCompareHelper(const void *data) +{ + int result = -1; + const struct testInfo *info = data; + char *xml = NULL; + char *args = NULL; + + if (virAsprintf(&xml, "%s/xml2sexprdata/xml2sexpr-%s.xml", + abs_srcdir, info->input) < 0 || + virAsprintf(&args, "%s/xml2sexprdata/xml2sexpr-%s.sexpr", + abs_srcdir, info->output) < 0) { + goto cleanup; + } + + result = testCompareFiles(xml, args, info->version); + +cleanup: + VIR_FREE(xml); + VIR_FREE(args); + + return result; +} + +static int +mymain(void) +{ + int ret = 0; + +#define DO_TEST(in, out, name, version) \ + do { \ + struct testInfo info = { in, out, name, version }; \ + virResetLastError(); \ + if (virtTestRun("Xen XML-2-SEXPR " in " -> " out, \ + 1, testCompareHelper, &info) < 0) \ + ret = -1; \ + } while (0) + + if (!(caps = testXenCapsInit())) + return EXIT_FAILURE; + + if (!(xmlopt = xenDomainXMLConfInit())) + return EXIT_FAILURE; + + DO_TEST("pv", "pv", "pvtest", 1); + DO_TEST("fv", "fv", "fvtest", 1); + DO_TEST("pv", "pv", "pvtest", 2); + DO_TEST("fv", "fv-v2", "fvtest", 2); + DO_TEST("fv-vncunused", "fv-vncunused", "fvtest", 2); +#ifdef WITH_RHEL5_API + /* RHEL-5 Xen doesn't support the old style vnc configuration */ + DO_TEST("pv-vfb-orig", "pv-vfb-new", "pvtest", 2); +#else + DO_TEST("pv-vfb-orig", "pv-vfb-orig", "pvtest", 2); +#endif + DO_TEST("pv-vfb-new", "pv-vfb-new", "pvtest", 3); + DO_TEST("pv-vfb-new-auto", "pv-vfb-new-auto", "pvtest", 3); + DO_TEST("pv-bootloader", "pv-bootloader", "pvtest", 1); + DO_TEST("pv-bootloader-cmdline", "pv-bootloader-cmdline", "pvtest", 1); + DO_TEST("pv-vcpus", "pv-vcpus", "pvtest", 1); + + DO_TEST("disk-file", "disk-file", "pvtest", 2); + DO_TEST("disk-block", "disk-block", "pvtest", 2); + DO_TEST("disk-block-shareable", "disk-block-shareable", "pvtest", 2); + DO_TEST("disk-drv-loop", "disk-drv-loop", "pvtest", 2); + DO_TEST("disk-drv-blkback", "disk-drv-blkback", "pvtest", 2); + DO_TEST("disk-drv-blktap", "disk-drv-blktap", "pvtest", 2); + DO_TEST("disk-drv-blktap-raw", "disk-drv-blktap-raw", "pvtest", 2); + DO_TEST("disk-drv-blktap-qcow", "disk-drv-blktap-qcow", "pvtest", 2); + DO_TEST("disk-drv-blktap2", "disk-drv-blktap2", "pvtest", 2); + DO_TEST("disk-drv-blktap2-raw", "disk-drv-blktap2-raw", "pvtest", 2); + + DO_TEST("curmem", "curmem", "rhel5", 2); + DO_TEST("net-routed", "net-routed", "pvtest", 2); + DO_TEST("net-bridged", "net-bridged", "pvtest", 2); + DO_TEST("net-e1000", "net-e1000", "pvtest", 2); + DO_TEST("bridge-ipaddr", "bridge-ipaddr", "pvtest", 2); + DO_TEST("no-source-cdrom", "no-source-cdrom", "test", 2); + DO_TEST("pv-localtime", "pv-localtime", "pvtest", 1); + DO_TEST("pci-devs", "pci-devs", "pvtest", 2); + + DO_TEST("fv-utc", "fv-utc", "fvtest", 1); + DO_TEST("fv-localtime", "fv-localtime", "fvtest", 1); + DO_TEST("fv-usbmouse", "fv-usbmouse", "fvtest", 1); + DO_TEST("fv-usbmouse", "fv-usbmouse", "fvtest", 1); + DO_TEST("fv-kernel", "fv-kernel", "fvtest", 1); + DO_TEST("fv-force-hpet", "fv-force-hpet", "fvtest", 1); + DO_TEST("fv-force-nohpet", "fv-force-nohpet", "fvtest", 1); + + DO_TEST("fv-serial-null", "fv-serial-null", "fvtest", 1); + DO_TEST("fv-serial-file", "fv-serial-file", "fvtest", 1); + DO_TEST("fv-serial-dev-2-ports", "fv-serial-dev-2-ports", "fvtest", 1); + DO_TEST("fv-serial-dev-2nd-port", "fv-serial-dev-2nd-port", "fvtest", 1); + DO_TEST("fv-serial-stdio", "fv-serial-stdio", "fvtest", 1); + DO_TEST("fv-serial-pty", "fv-serial-pty", "fvtest", 1); + DO_TEST("fv-serial-pipe", "fv-serial-pipe", "fvtest", 1); + DO_TEST("fv-serial-tcp", "fv-serial-tcp", "fvtest", 1); + DO_TEST("fv-serial-udp", "fv-serial-udp", "fvtest", 1); + DO_TEST("fv-serial-tcp-telnet", "fv-serial-tcp-telnet", "fvtest", 1); + DO_TEST("fv-serial-unix", "fv-serial-unix", "fvtest", 1); + DO_TEST("fv-parallel-tcp", "fv-parallel-tcp", "fvtest", 1); + + DO_TEST("fv-sound", "fv-sound", "fvtest", 1); + + DO_TEST("fv-net-ioemu", "fv-net-ioemu", "fvtest", 1); + DO_TEST("fv-net-netfront", "fv-net-netfront", "fvtest", 1); + + DO_TEST("boot-grub", "boot-grub", "fvtest", 1); + DO_TEST("escape", "escape", "fvtest", 1); + + virObjectUnref(caps); + virObjectUnref(xmlopt); + + return ret==0 ? EXIT_SUCCESS : EXIT_FAILURE; +} + +VIRT_TEST_MAIN(mymain) diff --git a/pool/shard000/C/0015608_speedups.c b/pool/shard000/C/0015608_speedups.c new file mode 100644 index 0000000000000000000000000000000000000000..2a09b42ea6b0f8fd8414566dedb3f50c6907e2b2 --- /dev/null +++ b/pool/shard000/C/0015608_speedups.c @@ -0,0 +1,239 @@ +/** + * markupsafe._speedups + * ~~~~~~~~~~~~~~~~~~~~ + * + * This module implements functions for automatic escaping in C for better + * performance. + * + * :copyright: (c) 2010 by Armin Ronacher. + * :license: BSD. + */ + +#include + +#define ESCAPED_CHARS_TABLE_SIZE 63 +#define UNICHR(x) (PyUnicode_AS_UNICODE((PyUnicodeObject*)PyUnicode_DecodeASCII(x, strlen(x), NULL))); + +#if PY_VERSION_HEX < 0x02050000 && !defined(PY_SSIZE_T_MIN) +typedef int Py_ssize_t; +#define PY_SSIZE_T_MAX INT_MAX +#define PY_SSIZE_T_MIN INT_MIN +#endif + + +static PyObject* markup; +static Py_ssize_t escaped_chars_delta_len[ESCAPED_CHARS_TABLE_SIZE]; +static Py_UNICODE *escaped_chars_repl[ESCAPED_CHARS_TABLE_SIZE]; + +static int +init_constants(void) +{ + PyObject *module; + /* happing of characters to replace */ + escaped_chars_repl['"'] = UNICHR("""); + escaped_chars_repl['\''] = UNICHR("'"); + escaped_chars_repl['&'] = UNICHR("&"); + escaped_chars_repl['<'] = UNICHR("<"); + escaped_chars_repl['>'] = UNICHR(">"); + + /* lengths of those characters when replaced - 1 */ + memset(escaped_chars_delta_len, 0, sizeof (escaped_chars_delta_len)); + escaped_chars_delta_len['"'] = escaped_chars_delta_len['\''] = \ + escaped_chars_delta_len['&'] = 4; + escaped_chars_delta_len['<'] = escaped_chars_delta_len['>'] = 3; + + /* import markup type so that we can mark the return value */ + module = PyImport_ImportModule("markupsafe"); + if (!module) + return 0; + markup = PyObject_GetAttrString(module, "Markup"); + Py_DECREF(module); + + return 1; +} + +static PyObject* +escape_unicode(PyUnicodeObject *in) +{ + PyUnicodeObject *out; + Py_UNICODE *inp = PyUnicode_AS_UNICODE(in); + const Py_UNICODE *inp_end = PyUnicode_AS_UNICODE(in) + PyUnicode_GET_SIZE(in); + Py_UNICODE *next_escp; + Py_UNICODE *outp; + Py_ssize_t delta=0, erepl=0, delta_len=0; + + /* First we need to figure out how long the escaped string will be */ + while (*(inp) || inp < inp_end) { + if (*inp < ESCAPED_CHARS_TABLE_SIZE && escaped_chars_delta_len[*inp]) { + delta += escaped_chars_delta_len[*inp]; + ++erepl; + } + ++inp; + } + + /* Do we need to escape anything at all? */ + if (!erepl) { + Py_INCREF(in); + return (PyObject*)in; + } + + out = (PyUnicodeObject*)PyUnicode_FromUnicode(NULL, PyUnicode_GET_SIZE(in) + delta); + if (!out) + return NULL; + + outp = PyUnicode_AS_UNICODE(out); + inp = PyUnicode_AS_UNICODE(in); + while (erepl-- > 0) { + /* look for the next substitution */ + next_escp = inp; + while (next_escp < inp_end) { + if (*next_escp < ESCAPED_CHARS_TABLE_SIZE && + (delta_len = escaped_chars_delta_len[*next_escp])) { + ++delta_len; + break; + } + ++next_escp; + } + + if (next_escp > inp) { + /* copy unescaped chars between inp and next_escp */ + Py_UNICODE_COPY(outp, inp, next_escp-inp); + outp += next_escp - inp; + } + + /* escape 'next_escp' */ + Py_UNICODE_COPY(outp, escaped_chars_repl[*next_escp], delta_len); + outp += delta_len; + + inp = next_escp + 1; + } + if (inp < inp_end) + Py_UNICODE_COPY(outp, inp, PyUnicode_GET_SIZE(in) - (inp - PyUnicode_AS_UNICODE(in))); + + return (PyObject*)out; +} + + +static PyObject* +escape(PyObject *self, PyObject *text) +{ + PyObject *s = NULL, *rv = NULL, *html; + + /* we don't have to escape integers, bools or floats */ + if (PyLong_CheckExact(text) || +#if PY_MAJOR_VERSION < 3 + PyInt_CheckExact(text) || +#endif + PyFloat_CheckExact(text) || PyBool_Check(text) || + text == Py_None) + return PyObject_CallFunctionObjArgs(markup, text, NULL); + + /* if the object has an __html__ method that performs the escaping */ + html = PyObject_GetAttrString(text, "__html__"); + if (html) { + rv = PyObject_CallObject(html, NULL); + Py_DECREF(html); + return rv; + } + + /* otherwise make the object unicode if it isn't, then escape */ + PyErr_Clear(); + if (!PyUnicode_Check(text)) { +#if PY_MAJOR_VERSION < 3 + PyObject *unicode = PyObject_Unicode(text); +#else + PyObject *unicode = PyObject_Str(text); +#endif + if (!unicode) + return NULL; + s = escape_unicode((PyUnicodeObject*)unicode); + Py_DECREF(unicode); + } + else + s = escape_unicode((PyUnicodeObject*)text); + + /* convert the unicode string into a markup object. */ + rv = PyObject_CallFunctionObjArgs(markup, (PyObject*)s, NULL); + Py_DECREF(s); + return rv; +} + + +static PyObject* +escape_silent(PyObject *self, PyObject *text) +{ + if (text != Py_None) + return escape(self, text); + return PyObject_CallFunctionObjArgs(markup, NULL); +} + + +static PyObject* +soft_unicode(PyObject *self, PyObject *s) +{ + if (!PyUnicode_Check(s)) +#if PY_MAJOR_VERSION < 3 + return PyObject_Unicode(s); +#else + return PyObject_Str(s); +#endif + Py_INCREF(s); + return s; +} + + +static PyMethodDef module_methods[] = { + {"escape", (PyCFunction)escape, METH_O, + "escape(s) -> markup\n\n" + "Convert the characters &, <, >, ', and \" in string s to HTML-safe\n" + "sequences. Use this if you need to display text that might contain\n" + "such characters in HTML. Marks return value as markup string."}, + {"escape_silent", (PyCFunction)escape_silent, METH_O, + "escape_silent(s) -> markup\n\n" + "Like escape but converts None to an empty string."}, + {"soft_unicode", (PyCFunction)soft_unicode, METH_O, + "soft_unicode(object) -> string\n\n" + "Make a string unicode if it isn't already. That way a markup\n" + "string is not converted back to unicode."}, + {NULL, NULL, 0, NULL} /* Sentinel */ +}; + + +#if PY_MAJOR_VERSION < 3 + +#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */ +#define PyMODINIT_FUNC void +#endif +PyMODINIT_FUNC +init_speedups(void) +{ + if (!init_constants()) + return; + + Py_InitModule3("markupsafe._speedups", module_methods, ""); +} + +#else /* Python 3.x module initialization */ + +static struct PyModuleDef module_definition = { + PyModuleDef_HEAD_INIT, + "markupsafe._speedups", + NULL, + -1, + module_methods, + NULL, + NULL, + NULL, + NULL +}; + +PyMODINIT_FUNC +PyInit__speedups(void) +{ + if (!init_constants()) + return NULL; + + return PyModule_Create(&module_definition); +} + +#endif diff --git a/pool/shard000/C/0015610_gis-page-header.c b/pool/shard000/C/0015610_gis-page-header.c new file mode 100644 index 0000000000000000000000000000000000000000..8da1ee44cdc3673c26805db6a6c9d819c09715b5 --- /dev/null +++ b/pool/shard000/C/0015610_gis-page-header.c @@ -0,0 +1,203 @@ +/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */ +/* -*- encoding: utf8 -*- */ +/* + * Copyright (C) 2019 Purism SPC + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, see . + * + * Written by: + * Adrien Plazas + */ + +#include "config.h" + +#include + +#include "gis-page-header.h" + +enum { + PROP_0, + PROP_TITLE, + PROP_SUBTITLE, + PROP_ICON_NAME, + PROP_PIXBUF, + PROP_SHOW_ICON, + PROP_LAST, +}; + +static GParamSpec *obj_props[PROP_LAST]; + +struct _GisPageHeader +{ + GtkBox parent; + + GtkWidget *box; + GtkWidget *icon; + GtkWidget *subtitle; + GtkWidget *title; +}; + +G_DEFINE_TYPE (GisPageHeader, gis_page_header, GTK_TYPE_BOX) + +static gboolean +is_valid_string (const gchar *s) +{ + return s != NULL && g_strcmp0 (s, "") != 0; +} + +static void +update_box_visibility (GisPageHeader *header) +{ + gtk_widget_set_visible (header->box, gtk_widget_get_visible (header->subtitle) || + gtk_widget_get_visible (header->title)); +} + +static void +gis_page_header_init (GisPageHeader *header) +{ + gtk_widget_init_template (GTK_WIDGET (header)); + + g_signal_connect_swapped (header->subtitle, "notify::visible", + G_CALLBACK(update_box_visibility), header); + g_signal_connect_swapped (header->title, "notify::visible", + G_CALLBACK(update_box_visibility), header); +} + +static void +gis_page_header_get_property (GObject *object, + guint prop_id, + GValue *value, + GParamSpec *pspec) +{ + GisPageHeader *header = GIS_PAGE_HEADER (object); + + switch (prop_id) + { + case PROP_TITLE: + g_value_set_string (value, gtk_label_get_label (GTK_LABEL (header->title))); + break; + + case PROP_SUBTITLE: + g_value_set_string (value, gtk_label_get_label (GTK_LABEL (header->subtitle))); + break; + + case PROP_ICON_NAME: + g_object_get_property (G_OBJECT (header->icon), "icon-name", value); + break; + + case PROP_PIXBUF: + g_object_get_property (G_OBJECT (header->icon), "pixbuf", value); + break; + + case PROP_SHOW_ICON: + g_value_set_boolean (value, gtk_widget_get_visible (header->icon)); + break; + + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); + break; + } +} + +static void +gis_page_header_set_property (GObject *object, + guint prop_id, + const GValue *value, + GParamSpec *pspec) +{ + GisPageHeader *header = GIS_PAGE_HEADER (object); + + switch (prop_id) + { + case PROP_TITLE: + gtk_label_set_label (GTK_LABEL (header->title), g_value_get_string (value)); + gtk_widget_set_visible (header->title, is_valid_string (g_value_get_string (value))); + break; + + case PROP_SUBTITLE: + gtk_label_set_label (GTK_LABEL (header->subtitle), g_value_get_string (value)); + gtk_widget_set_visible (header->subtitle, is_valid_string (g_value_get_string (value))); + break; + + case PROP_ICON_NAME: + g_object_set_property (G_OBJECT (header->icon), "icon-name", value); + break; + + case PROP_PIXBUF: + g_object_set_property (G_OBJECT (header->icon), "pixbuf", value); + break; + + case PROP_SHOW_ICON: + gtk_widget_set_visible (header->icon, g_value_get_boolean (value)); + break; + + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); + break; + } +} + +static void +gis_page_header_class_init (GisPageHeaderClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + + gtk_widget_class_set_template_from_resource (GTK_WIDGET_CLASS (klass), "/org/gnome/initial-setup/gis-page-header.ui"); + + gtk_widget_class_bind_template_child (GTK_WIDGET_CLASS (klass), GisPageHeader, box); + gtk_widget_class_bind_template_child (GTK_WIDGET_CLASS (klass), GisPageHeader, icon); + gtk_widget_class_bind_template_child (GTK_WIDGET_CLASS (klass), GisPageHeader, subtitle); + gtk_widget_class_bind_template_child (GTK_WIDGET_CLASS (klass), GisPageHeader, title); + + gobject_class->get_property = gis_page_header_get_property; + gobject_class->set_property = gis_page_header_set_property; + + obj_props[PROP_TITLE] = + g_param_spec_string ("title", + "", "", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS); + + obj_props[PROP_SUBTITLE] = + g_param_spec_string ("subtitle", + "", "", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS); + + obj_props[PROP_ICON_NAME] = + g_param_spec_string ("icon-name", + "", "", + NULL, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS); + + obj_props[PROP_PIXBUF] = + g_param_spec_object ("pixbuf", + "", "", + GDK_TYPE_PIXBUF, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS); + + obj_props[PROP_SHOW_ICON] = + g_param_spec_boolean ("show-icon", + "", "", + FALSE, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS); + + g_object_class_install_properties (gobject_class, PROP_LAST, obj_props); + + g_autoptr(GtkCssProvider) provider = gtk_css_provider_new (); + gtk_css_provider_load_from_resource (provider, "/org/gnome/initial-setup/gis-page-header.css"); + gtk_style_context_add_provider_for_screen (gdk_screen_get_default (), + GTK_STYLE_PROVIDER (provider), + GTK_STYLE_PROVIDER_PRIORITY_APPLICATION); +} diff --git a/pool/shard000/C/0015619_advigenere.c b/pool/shard000/C/0015619_advigenere.c new file mode 100644 index 0000000000000000000000000000000000000000..5ada41c815fe00eab0e1b6672a201a8a4f62ba23 --- /dev/null +++ b/pool/shard000/C/0015619_advigenere.c @@ -0,0 +1,67 @@ +/* + * Copyright (C) 2015 Tomasz Kramkowski + * + * This program is free software. It is licensed under version 3 of the + * GNU General Public License. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see [http://www.gnu.org/licenses/]. + */ +#include +#include +#include +#include + +#define CTOI(c) ((c) - 'A') +#define ITOC(c) ((c) + 'A') + +void preprocess(char *str); + +int main(int argc, char **argv) +{ + char *key, *ciphertext, *decoded; + size_t keylength, textlength; + + if (argc != 3) { + fprintf(stderr, "Usage: %s \n", argv[0]); + exit(EXIT_FAILURE); + } + + ciphertext = argv[1]; + key = argv[2]; + + preprocess(key); + preprocess(ciphertext); + + keylength = strlen(key); + textlength = strlen(ciphertext); + + decoded = malloc(textlength + 1); + + for (size_t i = 0; i < textlength; i++) + decoded[i] = (CTOI(ciphertext[i]) + CTOI(key[i % keylength])) % 26; + + for (unsigned offset = 0; offset < 26; offset++) { + printf("%.2u : ", offset); + for (unsigned i = 0; i < textlength; i++) + putchar(ITOC((decoded[i] + offset) % 26)); + putchar('\n'); + } + + free(decoded); + + return EXIT_SUCCESS; +} + +void preprocess(char *str) +{ + char *src = str, *dest = str; + + while (*src != '\0') { + if (isalpha(*src)) + *(dest++) = toupper(*src); + src++; + } + + *dest = '\0'; +} diff --git a/pool/shard000/C/0015621_test_etch_runtime.c b/pool/shard000/C/0015621_test_etch_runtime.c new file mode 100644 index 0000000000000000000000000000000000000000..4cf2d32eab51dfac5100238fbc2601f3a9fb37c7 --- /dev/null +++ b/pool/shard000/C/0015621_test_etch_runtime.c @@ -0,0 +1,198 @@ +/* $Id$ + * + * 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. + */ + +/* + * test_runtime.c -- test etch runtime + */ +#include "etch_runtime.h" +#include "etch_config.h" +#include "etch_mem.h" + +#include +#include +#include "CUnit.h" + +#define IS_DEBUG_CONSOLE FALSE + +// extern types +extern apr_pool_t* g_etch_main_pool; + +static int init_suite(void) +{ + return 0; +} + +static int clean_suite(void) +{ + return 0; +} + +//********************** +// START testcases here +//********************** + +static void test_etch_runtime_get_version(void) +{ + etch_status_t etch_status = ETCH_SUCCESS; + uint16 major = 0; + uint16 minor = 0; + uint16 revision = 0; + + // initialize runtime + etch_status = etch_runtime_get_version(NULL, NULL, NULL); + CU_ASSERT_EQUAL(etch_status, ETCH_EINVAL); + + etch_status = etch_runtime_get_version(&major, &minor, &revision); + CU_ASSERT_EQUAL(etch_status, ETCH_SUCCESS); +} + + +static void test_etch_runtime_initialize_shutdown(void) +{ + etch_status_t etch_status = ETCH_SUCCESS; + // initialize runtime + etch_status = etch_runtime_initialize(NULL); + CU_ASSERT_EQUAL(etch_status, ETCH_SUCCESS); + // check apr pool + CU_ASSERT_PTR_NOT_NULL(g_etch_main_pool); + // shutdown runtime + etch_runtime_shutdown(); + // check apr pool + CU_ASSERT_PTR_NULL(g_etch_main_pool); +} + +static void test_etch_runtime_get_config(void) +{ + etch_status_t etch_status = ETCH_SUCCESS; + etch_config_t *config = NULL; + etch_config_t *configtemp = NULL; + + etch_status = etch_config_create(&config); + CU_ASSERT_EQUAL(etch_status, ETCH_SUCCESS); + + etch_status = etch_runtime_initialize(config); + CU_ASSERT_EQUAL(etch_status, ETCH_SUCCESS); + + etch_status = etch_runtime_get_config(&configtemp); + CU_ASSERT_EQUAL(etch_status, ETCH_SUCCESS); + CU_ASSERT_PTR_NOT_NULL(configtemp); + + // shutdown runtime + etch_runtime_shutdown(); + + etch_config_destroy(config); +} + +static void test_etch_runtime_multiple_times(void) +{ + etch_status_t etch_status_runtime = ETCH_SUCCESS; + etch_status_t etch_status_shutdown = ETCH_SUCCESS; + int i=0; + + for (i=0; i<5; i++) + { + etch_status_runtime = etch_runtime_initialize(NULL); + CU_ASSERT_EQUAL(etch_status_runtime, ETCH_SUCCESS); + + // shutdown runtime + etch_status_shutdown = etch_runtime_shutdown(); + CU_ASSERT_EQUAL(etch_status_shutdown, ETCH_SUCCESS); + } +} + + +static void test_etch_runtime_config_multiple_times(void) +{ + etch_status_t etch_status_config = ETCH_SUCCESS; + etch_status_t etch_status_runtime = ETCH_SUCCESS; + etch_status_t etch_status_shutdown = ETCH_SUCCESS; + etch_config_t *config; + etch_config_t *configtemp = NULL; + + int i=0; + + for (i=0; i<5; i++) + { + etch_status_config = etch_config_create(&config); + CU_ASSERT_EQUAL(etch_status_config, ETCH_SUCCESS); + + etch_status_runtime = etch_runtime_initialize(config); + CU_ASSERT_EQUAL(etch_status_runtime, ETCH_SUCCESS); + + etch_status_config = etch_runtime_get_config(&configtemp); + CU_ASSERT_EQUAL(etch_status_config, ETCH_SUCCESS); + CU_ASSERT_PTR_NOT_NULL(configtemp); + + // shutdown runtime + etch_status_shutdown = etch_runtime_shutdown(); + CU_ASSERT_EQUAL(etch_status_shutdown, ETCH_SUCCESS); + + etch_status_config = etch_config_destroy(config); + CU_ASSERT_EQUAL(etch_status_config, ETCH_SUCCESS); + } +} + +static void test_etch_runtime_initialize_shutdown_refcount(void) +{ + etch_status_t status = ETCH_SUCCESS; + + /* 1 initialisation */ + status = etch_runtime_initialize(NULL); + CU_ASSERT_EQUAL(status, ETCH_SUCCESS); + /* 2 initialisation */ + status = etch_runtime_initialize(NULL); + CU_ASSERT_EQUAL(status, ETCH_SUCCESS); + /* 3 initialisation */ + status = etch_runtime_initialize(NULL); + CU_ASSERT_EQUAL(status, ETCH_SUCCESS); + + // check apr pool + CU_ASSERT_PTR_NOT_NULL(g_etch_main_pool); + + /* 1 shutdown */ + status = etch_runtime_shutdown(); + /* 2 shutdown */ + status = etch_runtime_shutdown(); + /* 3 shutdown */ + status = etch_runtime_shutdown(); + + // check apr pool + CU_ASSERT_PTR_NULL(g_etch_main_pool); +} + + +//********************** +// END testcases here +//********************** + +/** + * main + */ +CU_pSuite test_etch_runtime_suite(int argc, char** argv) +{ + CU_pSuite ps = CU_add_suite("etch_runtime", init_suite, clean_suite); + + CU_add_test(ps, "test_etch_runtime_get_version", test_etch_runtime_get_version); + CU_add_test(ps, "test_etch_runtime_initialize_shutdown", test_etch_runtime_initialize_shutdown); + CU_add_test(ps, "test_etch_runtime_get_config", test_etch_runtime_get_config); + CU_add_test(ps, "test_etch_runtime_multiple_times", test_etch_runtime_multiple_times); + CU_add_test(ps, "test_etch_runtime_config_multiple_times", test_etch_runtime_config_multiple_times); + CU_add_test(ps, "test_etch_runtime_initialize_shutdown_refcount", test_etch_runtime_initialize_shutdown_refcount); + + return ps; +} diff --git a/pool/shard000/C/0015630_vkms_drv.c b/pool/shard000/C/0015630_vkms_drv.c new file mode 100644 index 0000000000000000000000000000000000000000..44ab9f8ef8be6fc94cc9ebca80054581bb1d38e6 --- /dev/null +++ b/pool/shard000/C/0015630_vkms_drv.c @@ -0,0 +1,208 @@ +// SPDX-License-Identifier: GPL-2.0+ + +/** + * DOC: vkms (Virtual Kernel Modesetting) + * + * vkms is a software-only model of a kms driver that is useful for testing, + * or for running X (or similar) on headless machines and be able to still + * use the GPU. vkms aims to enable a virtual display without the need for + * a hardware display capability. + */ + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "vkms_drv.h" + +#define DRIVER_NAME "vkms" +#define DRIVER_DESC "Virtual Kernel Mode Setting" +#define DRIVER_DATE "20180514" +#define DRIVER_MAJOR 1 +#define DRIVER_MINOR 0 + +static struct vkms_device *vkms_device; + +bool enable_cursor; +module_param_named(enable_cursor, enable_cursor, bool, 0444); +MODULE_PARM_DESC(enable_cursor, "Enable/Disable cursor support"); + +static const struct file_operations vkms_driver_fops = { + .owner = THIS_MODULE, + .open = drm_open, + .mmap = drm_gem_mmap, + .unlocked_ioctl = drm_ioctl, + .compat_ioctl = drm_compat_ioctl, + .poll = drm_poll, + .read = drm_read, + .llseek = no_llseek, + .release = drm_release, +}; + +static const struct vm_operations_struct vkms_gem_vm_ops = { + .fault = vkms_gem_fault, + .open = drm_gem_vm_open, + .close = drm_gem_vm_close, +}; + +static void vkms_release(struct drm_device *dev) +{ + struct vkms_device *vkms = container_of(dev, struct vkms_device, drm); + + platform_device_unregister(vkms->platform); + drm_atomic_helper_shutdown(&vkms->drm); + drm_mode_config_cleanup(&vkms->drm); + drm_dev_fini(&vkms->drm); + destroy_workqueue(vkms->output.composer_workq); +} + +static void vkms_atomic_commit_tail(struct drm_atomic_state *old_state) +{ + struct drm_device *dev = old_state->dev; + struct drm_crtc *crtc; + struct drm_crtc_state *old_crtc_state; + int i; + + drm_atomic_helper_commit_modeset_disables(dev, old_state); + + drm_atomic_helper_commit_planes(dev, old_state, 0); + + drm_atomic_helper_commit_modeset_enables(dev, old_state); + + drm_atomic_helper_fake_vblank(old_state); + + drm_atomic_helper_commit_hw_done(old_state); + + drm_atomic_helper_wait_for_vblanks(dev, old_state); + + for_each_old_crtc_in_state(old_state, crtc, old_crtc_state, i) { + struct vkms_crtc_state *vkms_state = + to_vkms_crtc_state(old_crtc_state); + + flush_work(&vkms_state->composer_work); + } + + drm_atomic_helper_cleanup_planes(dev, old_state); +} + +static struct drm_driver vkms_driver = { + .driver_features = DRIVER_MODESET | DRIVER_ATOMIC | DRIVER_GEM, + .release = vkms_release, + .fops = &vkms_driver_fops, + .dumb_create = vkms_dumb_create, + .gem_vm_ops = &vkms_gem_vm_ops, + .gem_free_object_unlocked = vkms_gem_free_object, + .get_vblank_timestamp = vkms_get_vblank_timestamp, + + .name = DRIVER_NAME, + .desc = DRIVER_DESC, + .date = DRIVER_DATE, + .major = DRIVER_MAJOR, + .minor = DRIVER_MINOR, +}; + +static const struct drm_mode_config_funcs vkms_mode_funcs = { + .fb_create = drm_gem_fb_create, + .atomic_check = drm_atomic_helper_check, + .atomic_commit = drm_atomic_helper_commit, +}; + +static const struct drm_mode_config_helper_funcs vkms_mode_config_helpers = { + .atomic_commit_tail = vkms_atomic_commit_tail, +}; + +static int vkms_modeset_init(struct vkms_device *vkmsdev) +{ + struct drm_device *dev = &vkmsdev->drm; + + drm_mode_config_init(dev); + dev->mode_config.funcs = &vkms_mode_funcs; + dev->mode_config.min_width = XRES_MIN; + dev->mode_config.min_height = YRES_MIN; + dev->mode_config.max_width = XRES_MAX; + dev->mode_config.max_height = YRES_MAX; + dev->mode_config.preferred_depth = 24; + dev->mode_config.helper_private = &vkms_mode_config_helpers; + + return vkms_output_init(vkmsdev, 0); +} + +static int __init vkms_init(void) +{ + int ret; + + vkms_device = kzalloc(sizeof(*vkms_device), GFP_KERNEL); + if (!vkms_device) + return -ENOMEM; + + vkms_device->platform = + platform_device_register_simple(DRIVER_NAME, -1, NULL, 0); + if (IS_ERR(vkms_device->platform)) { + ret = PTR_ERR(vkms_device->platform); + goto out_free; + } + + ret = drm_dev_init(&vkms_device->drm, &vkms_driver, + &vkms_device->platform->dev); + if (ret) + goto out_unregister; + + vkms_device->drm.irq_enabled = true; + + ret = drm_vblank_init(&vkms_device->drm, 1); + if (ret) { + DRM_ERROR("Failed to vblank\n"); + goto out_fini; + } + + ret = vkms_modeset_init(vkms_device); + if (ret) + goto out_fini; + + ret = drm_dev_register(&vkms_device->drm, 0); + if (ret) + goto out_fini; + + return 0; + +out_fini: + drm_dev_fini(&vkms_device->drm); + +out_unregister: + platform_device_unregister(vkms_device->platform); + +out_free: + kfree(vkms_device); + return ret; +} + +static void __exit vkms_exit(void) +{ + if (!vkms_device) { + DRM_INFO("vkms_device is NULL.\n"); + return; + } + + drm_dev_unregister(&vkms_device->drm); + drm_dev_put(&vkms_device->drm); + + kfree(vkms_device); +} + +module_init(vkms_init); +module_exit(vkms_exit); + +MODULE_AUTHOR("Haneen Mohammed "); +MODULE_AUTHOR("Rodrigo Siqueira "); +MODULE_DESCRIPTION(DRIVER_DESC); +MODULE_LICENSE("GPL"); diff --git a/pool/shard000/C/0015631_init.c b/pool/shard000/C/0015631_init.c new file mode 100644 index 0000000000000000000000000000000000000000..c7cb32e74535eae2c9d1e15de166a9b4340d5711 --- /dev/null +++ b/pool/shard000/C/0015631_init.c @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2012 Travis Geiselbrecht + * + * 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 + +void target_early_init(void) +{ +#if 0 + /* configure the usart3 pins */ + RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOD, ENABLE); + RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE); + + GPIO_PinRemapConfig(GPIO_FullRemap_USART3, ENABLE); + + GPIO_InitTypeDef init; + init.GPIO_Pin = GPIO_Pin_8; + init.GPIO_Speed = GPIO_Speed_50MHz; + init.GPIO_Mode = GPIO_Mode_AF_PP; + GPIO_Init(GPIOD, &init); + + init.GPIO_Pin = GPIO_Pin_9; + init.GPIO_Speed = GPIO_Speed_50MHz; + init.GPIO_Mode = GPIO_Mode_IN_FLOATING; + GPIO_Init(GPIOD, &init); + + stm32_debug_early_init(); +#endif +} + +void target_init(void) +{ + TRACE_ENTRY; + +#if 0 + stm32_debug_init(); +#endif + + TRACE_EXIT; +} + diff --git a/pool/shard000/C/0015645_uptime.c b/pool/shard000/C/0015645_uptime.c new file mode 100644 index 0000000000000000000000000000000000000000..0db7da844e451896188ea40ecec5416b3ce0bba7 --- /dev/null +++ b/pool/shard000/C/0015645_uptime.c @@ -0,0 +1,64 @@ +/* +** Zabbix +** Copyright (C) 2001-2014 Zabbix SIA +** +** 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 "common.h" +#include "sysinfo.h" +#include "log.h" + +int SYSTEM_UPTIME(AGENT_REQUEST *request, AGENT_RESULT *result) +{ +#if defined(HAVE_SYSINFO_UPTIME) + struct sysinfo info; + + if (0 == sysinfo(&info)) + { + SET_UI64_RESULT(result, info.uptime); + return SYSINFO_RET_OK; + } + else + { + SET_MSG_RESULT(result, zbx_dsprintf(NULL, "Cannot obtain system information: %s", zbx_strerror(errno))); + return SYSINFO_RET_FAIL; + } +#elif defined(HAVE_FUNCTION_SYSCTL_KERN_BOOTTIME) + int mib[2], now; + size_t len; + struct timeval uptime; + + mib[0] = CTL_KERN; + mib[1] = KERN_BOOTTIME; + + len = sizeof(uptime); + + if (0 != sysctl(mib, 2, &uptime, &len, NULL, 0)) + { + SET_MSG_RESULT(result, zbx_dsprintf(NULL, "Cannot obtain system information: %s", zbx_strerror(errno))); + return SYSINFO_RET_FAIL; + } + + now = time(NULL); + + SET_UI64_RESULT(result, now - uptime.tv_sec); + + return SYSINFO_RET_OK; +#else + SET_MSG_RESULT(result, zbx_strdup(NULL, "Agent was compiled without support for uptime information.")); + return SYSINFO_RET_FAIL; +#endif +} diff --git a/pool/shard000/C/0015649_libipt_mac.c b/pool/shard000/C/0015649_libipt_mac.c new file mode 100644 index 0000000000000000000000000000000000000000..59f9fc02604f345031f3b3372d26c259619ebba0 --- /dev/null +++ b/pool/shard000/C/0015649_libipt_mac.c @@ -0,0 +1,140 @@ +/* Shared library add-on to iptables to add MAC address support. */ +#include +#include +#include +#include +#include +#if defined(__GLIBC__) && __GLIBC__ == 2 +#include +#else +#include +#endif +#include +#include + +/* Function which prints out usage message. */ +static void +help(void) +{ + printf( +"MAC v%s options:\n" +" --mac-source [!] XX:XX:XX:XX:XX:XX\n" +" Match source MAC address\n" +"\n", IPTABLES_VERSION); +} + +static struct option opts[] = { + { "mac-source", 1, 0, '1' }, + {0} +}; + +static void +parse_mac(const char *mac, struct ipt_mac_info *info) +{ + unsigned int i = 0; + + if (strlen(mac) != ETH_ALEN*3-1) + exit_error(PARAMETER_PROBLEM, "Bad mac address `%s'", mac); + + for (i = 0; i < ETH_ALEN; i++) { + long number; + char *end; + + number = strtol(mac + i*3, &end, 16); + + if (end == mac + i*3 + 2 + && number >= 0 + && number <= 255) + info->srcaddr[i] = number; + else + exit_error(PARAMETER_PROBLEM, + "Bad mac address `%s'", mac); + } +} + +/* Function which parses command options; returns true if it + ate an option */ +static int +parse(int c, char **argv, int invert, unsigned int *flags, + const struct ipt_entry *entry, + unsigned int *nfcache, + struct ipt_entry_match **match) +{ + struct ipt_mac_info *macinfo = (struct ipt_mac_info *)(*match)->data; + + switch (c) { + case '1': + check_inverse(optarg, &invert, &optind, 0); + parse_mac(argv[optind-1], macinfo); + if (invert) + macinfo->invert = 1; + *flags = 1; + break; + + default: + return 0; + } + + return 1; +} + +static void print_mac(unsigned char macaddress[ETH_ALEN]) +{ + unsigned int i; + + printf("%02X", macaddress[0]); + for (i = 1; i < ETH_ALEN; i++) + printf(":%02X", macaddress[i]); + printf(" "); +} + +/* Final check; must have specified --mac. */ +static void final_check(unsigned int flags) +{ + if (!flags) + exit_error(PARAMETER_PROBLEM, + "You must specify `--mac-source'"); +} + +/* Prints out the matchinfo. */ +static void +print(const struct ipt_ip *ip, + const struct ipt_entry_match *match, + int numeric) +{ + printf("MAC "); + + if (((struct ipt_mac_info *)match->data)->invert) + printf("! "); + + print_mac(((struct ipt_mac_info *)match->data)->srcaddr); +} + +/* Saves the union ipt_matchinfo in parsable form to stdout. */ +static void save(const struct ipt_ip *ip, const struct ipt_entry_match *match) +{ + if (((struct ipt_mac_info *)match->data)->invert) + printf("! "); + + printf("--mac-source "); + print_mac(((struct ipt_mac_info *)match->data)->srcaddr); +} + +static struct iptables_match mac = { + .next = NULL, + .name = "mac", + .version = IPTABLES_VERSION, + .size = IPT_ALIGN(sizeof(struct ipt_mac_info)), + .userspacesize = IPT_ALIGN(sizeof(struct ipt_mac_info)), + .help = &help, + .parse = &parse, + .final_check = &final_check, + .print = &print, + .save = &save, + .extra_opts = opts +}; + +void ipt_mac_init(void) +{ + register_match(&mac); +} diff --git a/pool/shard000/C/0015650_omp_thread_limit.c b/pool/shard000/C/0015650_omp_thread_limit.c new file mode 100644 index 0000000000000000000000000000000000000000..800edc44767fc0ba9707b40a6f38551d8efa0258 --- /dev/null +++ b/pool/shard000/C/0015650_omp_thread_limit.c @@ -0,0 +1,82 @@ +// RUN: %libomp-compile && env OMP_THREAD_LIMIT=4 %libomp-run 4 +// RUN: %libomp-compile && env OMP_THREAD_LIMIT=7 %libomp-run 7 +// +// OMP_THREAD_LIMIT=N should imply that no more than N threads are active in +// a contention group +#include +#include +#include +#include "omp_testsuite.h" + +int failed = 0; + +void usage() { + fprintf(stderr, "usage: omp_thread_limit \n"); +} + +void verify(const char* file_name, int line_number, int team_size) { + int num_threads = omp_get_num_threads(); + if (team_size != num_threads) { +#pragma omp critical(A) + { + char label[256]; + snprintf(label, sizeof(label), "%s:%d", file_name, line_number); + failed = 1; + printf("failed: %s: team_size(%d) != omp_get_num_threads(%d)\n", + label, team_size, num_threads); + } + } +} + +int main(int argc, char** argv) +{ + int cl_thread_limit; + + if (argc != 2) { + usage(); + return 1; + } + cl_thread_limit = atoi(argv[1]); + + omp_set_dynamic(0); + if (omp_get_thread_limit() != cl_thread_limit) { + fprintf(stderr, "omp_get_thread_limit failed with %d, should be%d\n", + omp_get_thread_limit(), cl_thread_limit); + return 1; + } + else if (omp_get_max_threads() > cl_thread_limit) { +#if _OPENMP + int team_size = cl_thread_limit; +#else + int team_size = 1; +#endif + omp_set_num_threads(19); + verify(__FILE__, __LINE__, 1); +#pragma omp parallel + { + verify(__FILE__, __LINE__, team_size); + verify(__FILE__, __LINE__, team_size); + } + verify(__FILE__, __LINE__, 1); + + omp_set_nested(1); +#pragma omp parallel num_threads(3) + { + verify(__FILE__, __LINE__, 3); +#pragma omp master +#pragma omp parallel num_threads(21) + { + verify(__FILE__, __LINE__, team_size-2); + verify(__FILE__, __LINE__, team_size-2); + } + } + verify(__FILE__, __LINE__, 1); + + return failed; + } else { + fprintf(stderr, "This test is not applicable for max num_threads='%d'\n", + omp_get_max_threads()); + return 0; + } + +} diff --git a/pool/shard000/C/0015654_up-devd.c b/pool/shard000/C/0015654_up-devd.c new file mode 100644 index 0000000000000000000000000000000000000000..7aa030a0236ecd9b905ef9021a441132d6a568f2 --- /dev/null +++ b/pool/shard000/C/0015654_up-devd.c @@ -0,0 +1,244 @@ +/*************************************************************************** + * + * up-devd.c : process devd events + * + * Copyright (C) 2006, 2007 Joe Marcus Clarke + * + * 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 St, Fifth Floor, Boston, MA 02110-1301 USA + * + **************************************************************************/ + +#include "config.h" + +#include +#include +#include +#include +#include +#include +#include + +#include "egg-debug.h" + +#include "up-backend.h" +#include "up-backend-acpi.h" +#include "up-devd.h" + +#define UP_DEVD_SOCK_PATH "/var/run/devd.pipe" + +#define UP_DEVD_EVENT_NOTIFY '!' +#define UP_DEVD_EVENT_ADD '+' +#define UP_DEVD_EVENT_REMOVE '-' +#define UP_DEVD_EVENT_NOMATCH '?' + +static UpDevdHandler *handlers[] = { + &up_backend_acpi_devd_handler, +}; + +static gboolean up_devd_inited = FALSE; + +#if 0 +static GHashTable * +up_devd_parse_params (const gchar *str) +{ + GHashTable *params; + gchar **pairs; + gint i; + + g_return_val_if_fail (str != NULL, FALSE); + + params = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free); + + pairs = g_strsplit(str, " ", 0); + for (i = 0; pairs[i]; i++) { + gchar *equal; + + equal = strchr (pairs[i], '='); + g_hash_table_insert (params, + equal ? g_strndup(pairs[i], equal - pairs[i]) : g_strdup(pairs[i]), + equal ? g_strdup(equal + 1) : NULL); + } + g_strfreev (pairs); + + return params; +} +#endif + +static gboolean +up_devd_parse_notify (const gchar *event, + gchar **system, + gchar **subsystem, + gchar **type, + gchar **data) +{ + gchar **items; + gboolean status = FALSE; + + /* + !system=IFNET subsystem=bge0 type=LINK_DOWN + */ + + g_return_val_if_fail(event != NULL, FALSE); + g_return_val_if_fail(system != NULL, FALSE); + g_return_val_if_fail(subsystem != NULL, FALSE); + g_return_val_if_fail(type != NULL, FALSE); + g_return_val_if_fail(data != NULL, FALSE); + + items = g_strsplit(event, " ", 0); + if (g_strv_length(items) < 3) + goto end; + + if (! g_str_has_prefix(items[0], "system=") || + ! g_str_has_prefix(items[1], "subsystem=") || + ! g_str_has_prefix(items[2], "type=")) + goto end; + + *system = g_strdup(items[0] + 7); + *subsystem = g_strdup(items[1] + 10); + *type = g_strdup(items[2] + 5); + *data = g_strdup(items[3]); /* may be NULL */ + + status = TRUE; + +end: + g_strfreev(items); + return status; +} + +static void +up_devd_process_notify_event (UpBackend *backend, + const gchar *system, + const gchar *subsystem, + const gchar *type, + const gchar *data) +{ + gint i; + + g_return_if_fail(backend != NULL); + g_return_if_fail(system != NULL); + g_return_if_fail(subsystem != NULL); + g_return_if_fail(type != NULL); + g_return_if_fail(data != NULL); + + for (i = 0; i < (int) G_N_ELEMENTS(handlers); i++) + if (handlers[i]->notify && handlers[i]->notify (backend, system, subsystem, type, data)) + return; + + /* no default action */ +} + +static void +up_devd_process_event (const gchar *event, gpointer user_data) +{ + UpBackend *backend; + + g_return_if_fail(event != NULL); + + backend = UP_BACKEND(user_data); + + egg_debug("received devd event: '%s'", event); + + switch (event[0]) { + case UP_DEVD_EVENT_ADD: + case UP_DEVD_EVENT_REMOVE: + /* Do nothing as we don't currently hotplug ACPI devices. */ + return; + + case UP_DEVD_EVENT_NOTIFY: { + gchar *system; + gchar *subsystem; + gchar *type; + gchar *data; + + if (!up_devd_parse_notify (event + 1, &system, &subsystem, &type, &data)) + goto malformed; + + up_devd_process_notify_event (backend, system, subsystem, type, data); + + g_free (system); + g_free (subsystem); + g_free (type); + g_free (data); + } + return; + + case UP_DEVD_EVENT_NOMATCH: + /* Do nothing. */ + return; + } + +malformed: + egg_warning("malformed devd event: %s", event); +} + +static gboolean +up_devd_event_cb (GIOChannel *source, GIOCondition condition, + gpointer user_data) +{ + gchar *event; + gsize terminator; + GIOStatus status; + + status = g_io_channel_read_line(source, &event, NULL, &terminator, NULL); + + if (status == G_IO_STATUS_NORMAL) { + event[terminator] = 0; + up_devd_process_event(event, user_data); + g_free(event); + } else if (status == G_IO_STATUS_AGAIN) { + up_devd_init (UP_BACKEND(user_data)); + if (up_devd_inited) { + int fd; + + fd = g_io_channel_unix_get_fd (source); + g_io_channel_shutdown (source, FALSE, NULL); + close (fd); + + return FALSE; + } + } + + return TRUE; +} + +void +up_devd_init (UpBackend *backend) +{ + int event_fd; + struct sockaddr_un addr; + + event_fd = socket(PF_UNIX, SOCK_STREAM, 0); + if (event_fd < 0) { + egg_warning("failed to create event socket: '%s'", g_strerror(errno)); + up_devd_inited = FALSE; + return; + } + + addr.sun_family = AF_UNIX; + strncpy (addr.sun_path, UP_DEVD_SOCK_PATH, sizeof(addr.sun_path)); + if (connect (event_fd, (struct sockaddr *)&addr, sizeof(addr)) == 0) { + GIOChannel *channel; + + channel = g_io_channel_unix_new (event_fd); + g_io_add_watch (channel, G_IO_IN, up_devd_event_cb, backend); + g_io_channel_unref (channel); + up_devd_inited = TRUE; + } else { + egg_warning ("failed to connect to %s: '%s'", UP_DEVD_SOCK_PATH, + g_strerror(errno)); + close (event_fd); + up_devd_inited = FALSE; + } +} diff --git a/pool/shard000/C/0015687_wow.c b/pool/shard000/C/0015687_wow.c new file mode 100644 index 0000000000000000000000000000000000000000..33531d9a4d50cbee3530d260aedcc60f9df74bb7 --- /dev/null +++ b/pool/shard000/C/0015687_wow.c @@ -0,0 +1,362 @@ +/* + * Copyright (c) 2013 Qualcomm Atheros, Inc. + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#include "ath9k.h" + +static const struct wiphy_wowlan_support ath9k_wowlan_support = { + .flags = WIPHY_WOWLAN_MAGIC_PKT | WIPHY_WOWLAN_DISCONNECT, + .n_patterns = MAX_NUM_USER_PATTERN, + .pattern_min_len = 1, + .pattern_max_len = MAX_PATTERN_SIZE, +}; + +static void ath9k_wow_map_triggers(struct ath_softc *sc, + struct cfg80211_wowlan *wowlan, + u32 *wow_triggers) +{ + if (wowlan->disconnect) + *wow_triggers |= AH_WOW_LINK_CHANGE | + AH_WOW_BEACON_MISS; + if (wowlan->magic_pkt) + *wow_triggers |= AH_WOW_MAGIC_PATTERN_EN; + + if (wowlan->n_patterns) + *wow_triggers |= AH_WOW_USER_PATTERN_EN; + + sc->wow_enabled = *wow_triggers; + +} + +static void ath9k_wow_add_disassoc_deauth_pattern(struct ath_softc *sc) +{ + struct ath_hw *ah = sc->sc_ah; + struct ath_common *common = ath9k_hw_common(ah); + int pattern_count = 0; + int i, byte_cnt; + u8 dis_deauth_pattern[MAX_PATTERN_SIZE]; + u8 dis_deauth_mask[MAX_PATTERN_SIZE]; + + memset(dis_deauth_pattern, 0, MAX_PATTERN_SIZE); + memset(dis_deauth_mask, 0, MAX_PATTERN_SIZE); + + /* + * Create Dissassociate / Deauthenticate packet filter + * + * 2 bytes 2 byte 6 bytes 6 bytes 6 bytes + * +--------------+----------+---------+--------+--------+---- + * + Frame Control+ Duration + DA + SA + BSSID + + * +--------------+----------+---------+--------+--------+---- + * + * The above is the management frame format for disassociate/ + * deauthenticate pattern, from this we need to match the first byte + * of 'Frame Control' and DA, SA, and BSSID fields + * (skipping 2nd byte of FC and Duration feild. + * + * Disassociate pattern + * -------------------- + * Frame control = 00 00 1010 + * DA, SA, BSSID = x:x:x:x:x:x + * Pattern will be A0000000 | x:x:x:x:x:x | x:x:x:x:x:x + * | x:x:x:x:x:x -- 22 bytes + * + * Deauthenticate pattern + * ---------------------- + * Frame control = 00 00 1100 + * DA, SA, BSSID = x:x:x:x:x:x + * Pattern will be C0000000 | x:x:x:x:x:x | x:x:x:x:x:x + * | x:x:x:x:x:x -- 22 bytes + */ + + /* Create Disassociate Pattern first */ + + byte_cnt = 0; + + /* Fill out the mask with all FF's */ + + for (i = 0; i < MAX_PATTERN_MASK_SIZE; i++) + dis_deauth_mask[i] = 0xff; + + /* copy the first byte of frame control field */ + dis_deauth_pattern[byte_cnt] = 0xa0; + byte_cnt++; + + /* skip 2nd byte of frame control and Duration field */ + byte_cnt += 3; + + /* + * need not match the destination mac address, it can be a broadcast + * mac address or an unicast to this station + */ + byte_cnt += 6; + + /* copy the source mac address */ + memcpy((dis_deauth_pattern + byte_cnt), common->curbssid, ETH_ALEN); + + byte_cnt += 6; + + /* copy the bssid, its same as the source mac address */ + + memcpy((dis_deauth_pattern + byte_cnt), common->curbssid, ETH_ALEN); + + /* Create Disassociate pattern mask */ + + dis_deauth_mask[0] = 0xfe; + dis_deauth_mask[1] = 0x03; + dis_deauth_mask[2] = 0xc0; + + ath_dbg(common, WOW, "Adding disassoc/deauth patterns for WoW\n"); + + ath9k_hw_wow_apply_pattern(ah, dis_deauth_pattern, dis_deauth_mask, + pattern_count, byte_cnt); + + pattern_count++; + /* + * for de-authenticate pattern, only the first byte of the frame + * control field gets changed from 0xA0 to 0xC0 + */ + dis_deauth_pattern[0] = 0xC0; + + ath9k_hw_wow_apply_pattern(ah, dis_deauth_pattern, dis_deauth_mask, + pattern_count, byte_cnt); + +} + +static void ath9k_wow_add_pattern(struct ath_softc *sc, + struct cfg80211_wowlan *wowlan) +{ + struct ath_hw *ah = sc->sc_ah; + struct ath9k_wow_pattern *wow_pattern = NULL; + struct cfg80211_pkt_pattern *patterns = wowlan->patterns; + int mask_len; + s8 i = 0; + + if (!wowlan->n_patterns) + return; + + /* + * Add the new user configured patterns + */ + for (i = 0; i < wowlan->n_patterns; i++) { + + wow_pattern = kzalloc(sizeof(*wow_pattern), GFP_KERNEL); + + if (!wow_pattern) + return; + + /* + * TODO: convert the generic user space pattern to + * appropriate chip specific/802.11 pattern. + */ + + mask_len = DIV_ROUND_UP(wowlan->patterns[i].pattern_len, 8); + memset(wow_pattern->pattern_bytes, 0, MAX_PATTERN_SIZE); + memset(wow_pattern->mask_bytes, 0, MAX_PATTERN_SIZE); + memcpy(wow_pattern->pattern_bytes, patterns[i].pattern, + patterns[i].pattern_len); + memcpy(wow_pattern->mask_bytes, patterns[i].mask, mask_len); + wow_pattern->pattern_len = patterns[i].pattern_len; + + /* + * just need to take care of deauth and disssoc pattern, + * make sure we don't overwrite them. + */ + + ath9k_hw_wow_apply_pattern(ah, wow_pattern->pattern_bytes, + wow_pattern->mask_bytes, + i + 2, + wow_pattern->pattern_len); + kfree(wow_pattern); + + } + +} + +int ath9k_suspend(struct ieee80211_hw *hw, + struct cfg80211_wowlan *wowlan) +{ + struct ath_softc *sc = hw->priv; + struct ath_hw *ah = sc->sc_ah; + struct ath_common *common = ath9k_hw_common(ah); + u32 wow_triggers_enabled = 0; + int ret = 0; + + ath9k_deinit_channel_context(sc); + + mutex_lock(&sc->mutex); + + ath_cancel_work(sc); + ath_stop_ani(sc); + + if (test_bit(ATH_OP_INVALID, &common->op_flags)) { + ath_dbg(common, ANY, "Device not present\n"); + ret = -EINVAL; + goto fail_wow; + } + + if (WARN_ON(!wowlan)) { + ath_dbg(common, WOW, "None of the WoW triggers enabled\n"); + ret = -EINVAL; + goto fail_wow; + } + + if (!device_can_wakeup(sc->dev)) { + ath_dbg(common, WOW, "device_can_wakeup failed, WoW is not enabled\n"); + ret = 1; + goto fail_wow; + } + + /* + * none of the sta vifs are associated + * and we are not currently handling multivif + * cases, for instance we have to seperately + * configure 'keep alive frame' for each + * STA. + */ + + if (!test_bit(ATH_OP_PRIM_STA_VIF, &common->op_flags)) { + ath_dbg(common, WOW, "None of the STA vifs are associated\n"); + ret = 1; + goto fail_wow; + } + + if (sc->nvifs > 1) { + ath_dbg(common, WOW, "WoW for multivif is not yet supported\n"); + ret = 1; + goto fail_wow; + } + + ath9k_wow_map_triggers(sc, wowlan, &wow_triggers_enabled); + + ath_dbg(common, WOW, "WoW triggers enabled 0x%x\n", + wow_triggers_enabled); + + ath9k_ps_wakeup(sc); + + ath9k_stop_btcoex(sc); + + /* + * Enable wake up on recieving disassoc/deauth + * frame by default. + */ + ath9k_wow_add_disassoc_deauth_pattern(sc); + + if (wow_triggers_enabled & AH_WOW_USER_PATTERN_EN) + ath9k_wow_add_pattern(sc, wowlan); + + spin_lock_bh(&sc->sc_pcu_lock); + /* + * To avoid false wake, we enable beacon miss interrupt only + * when we go to sleep. We save the current interrupt mask + * so we can restore it after the system wakes up + */ + sc->wow_intr_before_sleep = ah->imask; + ah->imask &= ~ATH9K_INT_GLOBAL; + ath9k_hw_disable_interrupts(ah); + ah->imask = ATH9K_INT_BMISS | ATH9K_INT_GLOBAL; + ath9k_hw_set_interrupts(ah); + ath9k_hw_enable_interrupts(ah); + + spin_unlock_bh(&sc->sc_pcu_lock); + + /* + * we can now sync irq and kill any running tasklets, since we already + * disabled interrupts and not holding a spin lock + */ + synchronize_irq(sc->irq); + tasklet_kill(&sc->intr_tq); + + ath9k_hw_wow_enable(ah, wow_triggers_enabled); + + ath9k_ps_restore(sc); + ath_dbg(common, ANY, "WoW enabled in ath9k\n"); + atomic_inc(&sc->wow_sleep_proc_intr); + +fail_wow: + mutex_unlock(&sc->mutex); + return ret; +} + +int ath9k_resume(struct ieee80211_hw *hw) +{ + struct ath_softc *sc = hw->priv; + struct ath_hw *ah = sc->sc_ah; + struct ath_common *common = ath9k_hw_common(ah); + u32 wow_status; + + mutex_lock(&sc->mutex); + + ath9k_ps_wakeup(sc); + + spin_lock_bh(&sc->sc_pcu_lock); + + ath9k_hw_disable_interrupts(ah); + ah->imask = sc->wow_intr_before_sleep; + ath9k_hw_set_interrupts(ah); + ath9k_hw_enable_interrupts(ah); + + spin_unlock_bh(&sc->sc_pcu_lock); + + wow_status = ath9k_hw_wow_wakeup(ah); + + if (atomic_read(&sc->wow_got_bmiss_intr) == 0) { + /* + * some devices may not pick beacon miss + * as the reason they woke up so we add + * that here for that shortcoming. + */ + wow_status |= AH_WOW_BEACON_MISS; + atomic_dec(&sc->wow_got_bmiss_intr); + ath_dbg(common, ANY, "Beacon miss interrupt picked up during WoW sleep\n"); + } + + atomic_dec(&sc->wow_sleep_proc_intr); + + if (wow_status) { + ath_dbg(common, ANY, "Waking up due to WoW triggers %s with WoW status = %x\n", + ath9k_hw_wow_event_to_string(wow_status), wow_status); + } + + ath_restart_work(sc); + ath9k_start_btcoex(sc); + + ath9k_ps_restore(sc); + mutex_unlock(&sc->mutex); + + return 0; +} + +void ath9k_set_wakeup(struct ieee80211_hw *hw, bool enabled) +{ + struct ath_softc *sc = hw->priv; + + mutex_lock(&sc->mutex); + device_init_wakeup(sc->dev, 1); + device_set_wakeup_enable(sc->dev, enabled); + mutex_unlock(&sc->mutex); +} + +void ath9k_init_wow(struct ieee80211_hw *hw) +{ + struct ath_softc *sc = hw->priv; + + if ((sc->sc_ah->caps.hw_caps & ATH9K_HW_WOW_DEVICE_CAPABLE) && + (sc->driver_data & ATH9K_PCI_WOW) && + device_can_wakeup(sc->dev)) + hw->wiphy->wowlan = &ath9k_wowlan_support; + + atomic_set(&sc->wow_sleep_proc_intr, -1); + atomic_set(&sc->wow_got_bmiss_intr, -1); +} diff --git a/pool/shard000/C/0015716_bug-dl-leaf-lib.c b/pool/shard000/C/0015716_bug-dl-leaf-lib.c new file mode 100644 index 0000000000000000000000000000000000000000..9a1f3ce12a37834fc2aafbc76b639f9a25ceb28e --- /dev/null +++ b/pool/shard000/C/0015716_bug-dl-leaf-lib.c @@ -0,0 +1,71 @@ +/* Make sure dlopen/dlclose are not marked as leaf functions. + + Copyright (C) 2013-2017 Free Software Foundation, Inc. + This file is part of the GNU C Library. + Contributed by Mike Frysinger + + The GNU C Library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + The GNU C Library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with the GNU C Library; if not, see + . */ + +/* The bug-dl-leaf.c file will call our lib_main directly. We do this to + keep things simple -- no need to use --export-dynamic with the linker + or build the main ELF as a PIE. + + The lib_main func will modify some of its state while dlopening and + dlclosing the bug-dl-leaf-lib-cb.so library. The constructors and + destructors in that library will call back into this library to also + muck with state (the check_val_xxx funcs). + + If dlclose/dlopen are marked as "leaf" functions, then with newer + versions of gcc, the state modification won't work correctly. */ + +#include +#include + +static int val = 1; +static int called = 0; + +void check_val_init (void) +{ + called = 1; + assert (val == 2); +} + +void check_val_fini (void) +{ + called = 2; + assert (val == 4); +} + +int lib_main (void) +{ + int ret __attribute__ ((unused)); + void *hdl; + + /* Make sure the constructor sees the updated val. */ + val = 2; + hdl = dlopen ("bug-dl-leaf-lib-cb.so", RTLD_GLOBAL | RTLD_LAZY); + val = 3; + assert (hdl); + assert (called == 1); + + /* Make sure the destructor sees the updated val. */ + val = 4; + ret = dlclose (hdl); + val = 5; + assert (ret == 0); + assert (called == 2); + + return !val; +} diff --git a/pool/shard000/C/0015734_odp_sysinfo_parse.c b/pool/shard000/C/0015734_odp_sysinfo_parse.c new file mode 100644 index 0000000000000000000000000000000000000000..99457cec4d4db84f26305a7de0a0f2697ec17c75 --- /dev/null +++ b/pool/shard000/C/0015734_odp_sysinfo_parse.c @@ -0,0 +1,63 @@ +/* Copyright (c) 2016, Linaro Limited + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include +#include + +int odp_cpuinfo_parser(FILE *file, odp_system_info_t *sysinfo) +{ + char str[1024]; + char *pos; + double mhz = 0.0; + uint64_t hz; + int model = 0; + int count = 2; + int id = 0; + + strcpy(sysinfo->cpu_arch_str, "powerpc"); + while (fgets(str, sizeof(str), file) != NULL && id < MAX_CPU_NUMBER) { + if (!mhz) { + pos = strstr(str, "clock"); + + if (pos) + if (sscanf(pos, "clock : %lf", &mhz) == 1) { + hz = (uint64_t)(mhz * 1000000.0); + sysinfo->cpu_hz_max[id] = hz; + count--; + } + } + + if (!model) { + pos = strstr(str, "cpu"); + + if (pos) { + int len; + + pos = strchr(str, ':'); + strncpy(sysinfo->model_str[id], pos + 2, + sizeof(sysinfo->model_str[id])); + len = strlen(sysinfo->model_str[id]); + sysinfo->model_str[id][len - 1] = 0; + model = 1; + count--; + } + } + + if (count == 0) { + mhz = 0.0; + model = 0; + count = 2; + id++; + } + } + + return 0; +} + +uint64_t odp_cpu_hz_current(int id ODP_UNUSED) +{ + return 0; +} diff --git a/pool/shard000/C/0015753_params.c b/pool/shard000/C/0015753_params.c new file mode 100644 index 0000000000000000000000000000000000000000..569ae47f040e3b166fa2d579bd4d3c8e5e442ae6 --- /dev/null +++ b/pool/shard000/C/0015753_params.c @@ -0,0 +1,86 @@ +/* params.c - Run-time parameters. + Copyright (C) 2001, 2003, 2004, 2005, 2007 Free Software Foundation, Inc. + Written by Mark Mitchell . + +This file is part of GCC. + +GCC is free software; you can redistribute it and/or modify it under +the terms of the GNU General Public License as published by the Free +Software Foundation; either version 3, or (at your option) any later +version. + +GCC 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 GCC; see the file COPYING3. If not see +. */ + +#include "config.h" +#include "system.h" +#include "coretypes.h" +#include "tm.h" +#include "params.h" +#include "toplev.h" + +/* An array containing the compiler parameters and their current + values. */ + +param_info *compiler_params; + +/* The number of entries in the table. */ + +static size_t num_compiler_params; + +/* Add the N PARAMS to the current list of compiler parameters. */ + +void +add_params (const param_info params[], size_t n) +{ + /* Allocate enough space for the new parameters. */ + compiler_params = xrealloc (compiler_params, + (num_compiler_params + n) * sizeof (param_info)); + /* Copy them into the table. */ + memcpy (compiler_params + num_compiler_params, + params, + n * sizeof (param_info)); + /* Keep track of how many parameters we have. */ + num_compiler_params += n; +} + +/* Set the VALUE associated with the parameter given by NAME. */ + +void +set_param_value (const char *name, int value) +{ + size_t i; + + /* Make sure nobody tries to set a parameter to an invalid value. */ + gcc_assert (value != INVALID_PARAM_VAL); + + /* Scan the parameter table to find a matching entry. */ + for (i = 0; i < num_compiler_params; ++i) + if (strcmp (compiler_params[i].option, name) == 0) + { + if (value < compiler_params[i].min_value) + error ("minimum value of parameter %qs is %u", + compiler_params[i].option, + compiler_params[i].min_value); + else if (compiler_params[i].max_value > compiler_params[i].min_value + && value > compiler_params[i].max_value) + error ("maximum value of parameter %qs is %u", + compiler_params[i].option, + compiler_params[i].max_value); + else + { + compiler_params[i].value = value; + compiler_params[i].set = true; + } + return; + } + + /* If we didn't find this parameter, issue an error message. */ + error ("invalid parameter %qs", name); +} diff --git a/pool/shard000/C/0015755_test_pp230.c b/pool/shard000/C/0015755_test_pp230.c new file mode 100644 index 0000000000000000000000000000000000000000..f065153b7d31d512b5db3a31bb195e47d894de3d --- /dev/null +++ b/pool/shard000/C/0015755_test_pp230.c @@ -0,0 +1,21 @@ +#include +#include + +int tadd_ok(int, int); + +int main() +{ + int x1 = INT_MAX; + int y1 = INT_MAX; + int x2 = INT_MIN; + int y2 = INT_MIN; + printf("tadd_ok(x1, y1) = %d\n", tadd_ok(x1, y1)); + printf("tadd_ok(x2, y2) = %d\n", tadd_ok(x2, y2)); + printf("tadd_ok(x1, y1) = %d\n", tadd_ok(x1, y2)); + return 0; +} + +int tadd_ok(int x, int y) +{ + return !(((x>0) && (y>0) && (x+y)<=0) || ((x<0) && (y<0) && (x+y)>=0)); +} diff --git a/pool/shard000/C/0015760_27__.c b/pool/shard000/C/0015760_27__.c new file mode 100644 index 0000000000000000000000000000000000000000..909563ef03ee8886949ffe63f47180c0969d41de --- /dev/null +++ b/pool/shard000/C/0015760_27__.c @@ -0,0 +1,33 @@ + +#include +#include +#include +#include + +int main(int argc, char *argv[]) { + int disp, count; + if (argc < 2) { + printf("You must enter the length of the count\n"); + printf("on the commond line. Try again\n"); + exit(1); + } + if (argc == 3 && !strcmp(argv[2], "display")) { + disp = 1; + } else { + disp = 0; + } + + //for (count = atoi(argv[1]); count; --count) { + // if (disp) { + // printf("%d\n", count); + // } + //} + if (disp) { + for (count = atoi(argv[1]); count; --count) { + printf("%d\n", count); + } + } + putchar('\a'); + printf("Down\n"); + return 0; +} diff --git a/pool/shard000/C/0015780_armobsd-tdep.c b/pool/shard000/C/0015780_armobsd-tdep.c new file mode 100644 index 0000000000000000000000000000000000000000..f8930b6644c60152b256be4f04eb57703f3fb74c --- /dev/null +++ b/pool/shard000/C/0015780_armobsd-tdep.c @@ -0,0 +1,139 @@ +/* Target-dependent code for OpenBSD/arm. + + Copyright (C) 2006, 2007, 2008 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 "osabi.h" +#include "trad-frame.h" +#include "tramp-frame.h" + +#include "gdb_string.h" + +#include "obsd-tdep.h" +#include "arm-tdep.h" +#include "solib-svr4.h" + +/* Signal trampolines. */ + +static void +armobsd_sigframe_init (const struct tramp_frame *self, + struct frame_info *next_frame, + struct trad_frame_cache *cache, + CORE_ADDR func) +{ + CORE_ADDR sp, sigcontext_addr, addr; + int regnum; + + /* We find the appropriate instance of `struct sigcontext' at a + fixed offset in the signal frame. */ + sp = frame_unwind_register_signed (next_frame, ARM_SP_REGNUM); + sigcontext_addr = sp + 16; + + /* PC. */ + trad_frame_set_reg_addr (cache, ARM_PC_REGNUM, sigcontext_addr + 76); + + /* GPRs. */ + for (regnum = ARM_A1_REGNUM, addr = sigcontext_addr + 12; + regnum <= ARM_LR_REGNUM; regnum++, addr += 4) + trad_frame_set_reg_addr (cache, regnum, addr); + + trad_frame_set_id (cache, frame_id_build (sp, func)); +} + +static const struct tramp_frame armobsd_sigframe = +{ + SIGTRAMP_FRAME, + 4, + { + { 0xe28d0010, -1 }, /* add r0, sp, #16 */ + { 0xef000067, -1 }, /* swi SYS_sigreturn */ + { 0xef000001, -1 }, /* swi SYS_exit */ + { 0xeafffffc, -1 }, /* b . - 8 */ + { TRAMP_SENTINEL_INSN, -1 } + }, + armobsd_sigframe_init +}; + + +/* Override default thumb breakpoints. */ +static const char arm_obsd_thumb_le_breakpoint[] = {0xfe, 0xdf}; +static const char arm_obsd_thumb_be_breakpoint[] = {0xdf, 0xfe}; + +static void +armobsd_init_abi (struct gdbarch_info info, + struct gdbarch *gdbarch) +{ + struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch); + + if (tdep->fp_model == ARM_FLOAT_AUTO) + tdep->fp_model = ARM_FLOAT_SOFT_VFP; + + tramp_frame_prepend_unwinder (gdbarch, &armobsd_sigframe); + + /* OpenBSD/arm uses SVR4-style shared libraries. */ + set_solib_svr4_fetch_link_map_offsets + (gdbarch, svr4_ilp32_fetch_link_map_offsets); + set_gdbarch_skip_solib_resolver (gdbarch, obsd_skip_solib_resolver); + + tdep->jb_pc = 24; + tdep->jb_elt_size = 4; + + set_gdbarch_regset_from_core_section + (gdbarch, armbsd_regset_from_core_section); + + /* OpenBSD/arm uses -fpcc-struct-return by default. */ + tdep->struct_return = pcc_struct_return; + + /* Single stepping. */ + set_gdbarch_software_single_step (gdbarch, arm_software_single_step); + + /* Breakpoints. */ + switch (info.byte_order) + { + case BFD_ENDIAN_BIG: + tdep->thumb_breakpoint = arm_obsd_thumb_be_breakpoint; + tdep->thumb_breakpoint_size = sizeof (arm_obsd_thumb_be_breakpoint); + break; + + case BFD_ENDIAN_LITTLE: + tdep->thumb_breakpoint = arm_obsd_thumb_le_breakpoint; + tdep->thumb_breakpoint_size = sizeof (arm_obsd_thumb_le_breakpoint); + break; + } +} + + +static enum gdb_osabi +armobsd_core_osabi_sniffer (bfd *abfd) +{ + if (strcmp (bfd_get_target (abfd), "netbsd-core") == 0) + return GDB_OSABI_OPENBSD_ELF; + + return GDB_OSABI_UNKNOWN; +} + +void +_initialize_armobsd_tdep (void) +{ + /* BFD doesn't set a flavour for NetBSD style a.out core files. */ + gdbarch_register_osabi_sniffer (bfd_arch_arm, bfd_target_unknown_flavour, + armobsd_core_osabi_sniffer); + + gdbarch_register_osabi (bfd_arch_arm, 0, GDB_OSABI_OPENBSD_ELF, + armobsd_init_abi); +} diff --git a/pool/shard000/C/0015784_ua_services_discovery.c b/pool/shard000/C/0015784_ua_services_discovery.c new file mode 100644 index 0000000000000000000000000000000000000000..7362ea0f6d91b7a3c37d70c75ab809e91d63acea --- /dev/null +++ b/pool/shard000/C/0015784_ua_services_discovery.c @@ -0,0 +1,111 @@ +#include "ua_server_internal.h" +#include "ua_services.h" +#include "ua_util.h" + +void Service_FindServers(UA_Server *server, UA_Session *session, + const UA_FindServersRequest *request, UA_FindServersResponse *response) { + /* copy ApplicationDescription from the config */ + UA_ApplicationDescription *descr = UA_malloc(sizeof(UA_ApplicationDescription)); + if(!descr) { + response->responseHeader.serviceResult = UA_STATUSCODE_BADOUTOFMEMORY; + return; + } + response->responseHeader.serviceResult = + UA_ApplicationDescription_copy(&server->config.applicationDescription, descr); + if(response->responseHeader.serviceResult != UA_STATUSCODE_GOOD) { + UA_free(descr); + return; + } + + /* add the discoveryUrls from the networklayers */ + UA_String *disc = UA_realloc(descr->discoveryUrls, sizeof(UA_String) * + (descr->discoveryUrlsSize + server->config.networkLayersSize)); + if(!disc) { + response->responseHeader.serviceResult = UA_STATUSCODE_BADOUTOFMEMORY; + UA_ApplicationDescription_delete(descr); + return; + } + size_t index = descr->discoveryUrlsSize; + descr->discoveryUrls = disc; + descr->discoveryUrlsSize += server->config.networkLayersSize; + + // TODO: Add nl only if discoveryUrl not already present + for(size_t i = 0; i < server->config.networkLayersSize; i++) { + UA_ServerNetworkLayer *nl = &server->config.networkLayers[i]; + UA_String_copy(&nl->discoveryUrl, &descr->discoveryUrls[index + i]); + } + + response->servers = descr; + response->serversSize = 1; +} + +void Service_GetEndpoints(UA_Server *server, UA_Session *session, const UA_GetEndpointsRequest *request, + UA_GetEndpointsResponse *response) { + /* Test if one of the networklayers exposes the discoveryUrl of the requested endpoint */ + /* Disabled, servers in a virtualbox don't know their external hostname */ + /* UA_Boolean foundUri = UA_FALSE; */ + /* for(size_t i = 0; i < server->config.networkLayersSize; i++) { */ + /* if(UA_String_equal(&request->endpointUrl, &server->config.networkLayers[i].discoveryUrl)) { */ + /* foundUri = UA_TRUE; */ + /* break; */ + /* } */ + /* } */ + /* if(!foundUri) { */ + /* response->endpointsSize = 0; */ + /* return; */ + /* } */ + + /* test if the supported binary profile shall be returned */ +#ifdef NO_ALLOCA + UA_Boolean relevant_endpoints[server->endpointDescriptionsSize]; +#else + UA_Boolean *relevant_endpoints = UA_alloca(sizeof(UA_Byte) * server->endpointDescriptionsSize); +#endif + size_t relevant_count = 0; + for(size_t j = 0; j < server->endpointDescriptionsSize; j++) { + relevant_endpoints[j] = UA_FALSE; + if(request->profileUrisSize == 0) { + relevant_endpoints[j] = UA_TRUE; + relevant_count++; + continue; + } + for(size_t i = 0; i < request->profileUrisSize; i++) { + if(UA_String_equal(&request->profileUris[i], &server->endpointDescriptions->transportProfileUri)) { + relevant_endpoints[j] = UA_TRUE; + relevant_count++; + break; + } + } + } + + if(relevant_count == 0) { + response->endpointsSize = 0; + return; + } + + response->endpoints = UA_malloc(sizeof(UA_EndpointDescription) * relevant_count); + if(!response->endpoints) { + response->responseHeader.serviceResult = UA_STATUSCODE_BADOUTOFMEMORY; + return; + } + + size_t k = 0; + UA_StatusCode retval = UA_STATUSCODE_GOOD; + for(size_t j = 0; j < server->endpointDescriptionsSize && retval == UA_STATUSCODE_GOOD; j++) { + if(!relevant_endpoints[j]) + continue; + retval = UA_EndpointDescription_copy(&server->endpointDescriptions[j], &response->endpoints[k]); + if(retval != UA_STATUSCODE_GOOD) + break; + UA_String_deleteMembers(&response->endpoints[k].endpointUrl); + retval = UA_String_copy(&request->endpointUrl, &response->endpoints[k].endpointUrl); + k++; + } + + if(retval != UA_STATUSCODE_GOOD) { + response->responseHeader.serviceResult = retval; + UA_Array_delete(response->endpoints, --k, &UA_TYPES[UA_TYPES_ENDPOINTDESCRIPTION]); + return; + } + response->endpointsSize = relevant_count; +} diff --git a/pool/shard000/C/0015788_lockd.c b/pool/shard000/C/0015788_lockd.c new file mode 100644 index 0000000000000000000000000000000000000000..1371fcea6c988ecf281b94cb8bc18c57ab445f0e --- /dev/null +++ b/pool/shard000/C/0015788_lockd.c @@ -0,0 +1,83 @@ +/* + * This file contains all the stubs needed when communicating with lockd. + * This level of indirection is necessary so we can run nfsd+lockd without + * requiring the nfs client to be compiled in/loaded, and vice versa. + * + * Copyright (C) 1996, Olaf Kirch + */ + +#include +#include +#include "nfsd.h" +#include "vfs.h" + +#define NFSDDBG_FACILITY NFSDDBG_LOCKD + +#ifdef CONFIG_LOCKD_V4 + #define nlm_stale_fh nlm4_stale_fh + #define nlm_failed nlm4_failed +#else + #define nlm_stale_fh nlm_lck_denied_nolocks + #define nlm_failed nlm_lck_denied_nolocks +#endif +/* + * Note: we hold the dentry use count while the file is open. + */ +static __be32 +nlm_fopen(struct svc_rqst *rqstp, struct nfs_fh *f, struct file **filp) +{ + __be32 nfserr; + struct svc_fh fh; + + /* must initialize before using! but maxsize doesn't matter */ + fh_init(&fh, 0); + fh.fh_handle.fh_size = f->size; + memcpy((char *)&fh.fh_handle.fh_base, f->data, f->size); + fh.fh_export = NULL; + + nfserr = nfsd_open(rqstp, &fh, S_IFREG, NFSD_MAY_LOCK, filp); + fh_put(&fh); + + /* We return nlm error codes as nlm doesn't know + * about nfsd, but nfsd does know about nlm.. + */ + switch (nfserr) + { + case nfs_ok: + return 0; + + case nfserr_dropit: + return nlm_drop_reply; + + case nfserr_stale: + return nlm_stale_fh; + + default: + return nlm_failed; + } +} + +static void +nlm_fclose(struct file *filp) +{ + fput(filp); +} + +static const struct nlmsvc_binding nfsd_nlm_ops = +{ + .fopen = nlm_fopen, /* open file for locking */ + .fclose = nlm_fclose, /* close file */ +}; + +void +nfsd_lockd_init(void) +{ + dprintk("nfsd: initializing lockd\n"); + nlmsvc_ops = &nfsd_nlm_ops; +} + +void +nfsd_lockd_shutdown(void) +{ + nlmsvc_ops = NULL; +} diff --git a/pool/shard000/C/0015793_verify_init_creds.c b/pool/shard000/C/0015793_verify_init_creds.c new file mode 100644 index 0000000000000000000000000000000000000000..c22e2528424ee2289480f8d8210485c581c817a0 --- /dev/null +++ b/pool/shard000/C/0015793_verify_init_creds.c @@ -0,0 +1,28 @@ +/** @example verify_init_creds.c + * + * Usage example for krb5_verify_init_creds function family + */ +#include "k5-int.h" + +krb5_error_code +func(krb5_context context, krb5_creds *creds, krb5_principal server_principal) +{ + krb5_error_code ret = KRB5_OK; + krb5_verify_init_creds_opt options; + + krb5_verify_init_creds_opt_init (&options); + krb5_verify_init_creds_opt_set_ap_req_nofail (&options, 1); + + ret = krb5_verify_init_creds(context, + creds, + server_principal, + NULL /* use default keytab */, + NULL /* don't store creds in ccache */, + &options); + if (ret) { + /* error while verifying credentials for server */ + } + + return ret; +} + diff --git a/pool/shard000/C/0015796_7-1.c b/pool/shard000/C/0015796_7-1.c new file mode 100644 index 0000000000000000000000000000000000000000..8f13f30916864cc36558a914c6805a6ebbebe19d --- /dev/null +++ b/pool/shard000/C/0015796_7-1.c @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2004, Bull SA. All rights reserved. + * Created by: Laurent.Vivier@bull.net + * This file is licensed under the GPL license. For the full content + * of this license, see the COPYING file at the top level of this + * source tree. + */ + +/* + * assertion: + * + * aio_write() shall fail with [EAGAIN] if: + * The requested AIO operation was not queued to the system + * due to system resource limitations. + * + * method: + * + * - open file + * - queue NUM_AIOCBS 512-byte aio_write + * - wait until one returns EAGAIN + * + * NUM_AIOCBS might need to be adjusted for the system + * + */ + +#define _XOPEN_SOURCE 600 +#include +#include +#include +#include +#include +#include + +#include "posixtest.h" + +#define TNAME "aio_write/7-1.c" + +#define NUM_AIOCBS 1024 + +int main() +{ + char tmpfname[256]; +#define BUF_SIZE 512 + char buf[BUF_SIZE]; + int fd; + int i; + struct aiocb aiocbs[NUM_AIOCBS]; + int last_req; + int err; + int ret; + +#if _POSIX_ASYNCHRONOUS_IO != 200112L + exit(PTS_UNSUPPORTED); +#endif + + snprintf(tmpfname, sizeof(tmpfname), "/tmp/pts_aio_write_4_1_%d", + getpid()); + unlink(tmpfname); + fd = open(tmpfname, O_CREAT | O_RDWR | O_EXCL, + S_IRUSR | S_IWUSR); + if (fd == -1) + { + printf(TNAME " Error at open(): %s\n", + strerror(errno)); + exit(PTS_UNRESOLVED); + } + + unlink(tmpfname); + + for (i=0; i + +#ifdef _WIN32 +#define COMMAND_INT_PATH L"%WINDIR%\\system32\\cmd.exe" +#define COMMAND_INT L"cmd.exe" +#define COMMAND_ARG1 L"/c" +#define COMMAND_ARG2 L"dir" +#define COMMAND_ARG3 data +#else /* NOT _WIN32 */ +#include +#define COMMAND_INT_PATH L"/bin/sh" +#define COMMAND_INT L"sh" +#define COMMAND_ARG1 L"ls" +#define COMMAND_ARG2 L"-la" +#define COMMAND_ARG3 data +#endif + +#ifdef _WIN32 +#include +#define EXECLP _wexeclp +#else /* NOT _WIN32 */ +#define EXECLP execlp +#endif + +#ifndef OMITBAD + +void CWE78_OS_Command_Injection__wchar_t_console_execlp_63b_badSink(wchar_t * * dataPtr) +{ + wchar_t * data = *dataPtr; + /* wexeclp - searches for the location of the command among + * the directories specified by the PATH environment variable */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + EXECLP(COMMAND_INT, COMMAND_INT, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void CWE78_OS_Command_Injection__wchar_t_console_execlp_63b_goodG2BSink(wchar_t * * dataPtr) +{ + wchar_t * data = *dataPtr; + /* wexeclp - searches for the location of the command among + * the directories specified by the PATH environment variable */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + EXECLP(COMMAND_INT, COMMAND_INT, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL); +} + +#endif /* OMITGOOD */ diff --git a/pool/shard000/C/0015807_kinetic_operation.c b/pool/shard000/C/0015807_kinetic_operation.c new file mode 100644 index 0000000000000000000000000000000000000000..a201d89ba00e5466cfaa8742f207f8e7851729cf --- /dev/null +++ b/pool/shard000/C/0015807_kinetic_operation.c @@ -0,0 +1,168 @@ +/** + * Copyright 2013-2015 Seagate Technology LLC. + * + * This Source Code Form is subject to the terms of the Mozilla + * Public License, v. 2.0. If a copy of the MPL was not + * distributed with this file, You can obtain one at + * https://mozilla.org/MP:/2.0/. + * + * This program is distributed in the hope that it will be useful, + * but is provided AS-IS, WITHOUT ANY WARRANTY; including without + * the implied warranty of MERCHANTABILITY, NON-INFRINGEMENT or + * FITNESS FOR A PARTICULAR PURPOSE. See the Mozilla Public + * License for more details. + * + * See www.openkinetic.org for more project information + */ +#include "kinetic_operation.h" +#include "kinetic_controller.h" +#include "kinetic_session.h" +#include "kinetic_message.h" +#include "kinetic_bus.h" +#include "kinetic_response.h" +#include "kinetic_device_info.h" +#include "kinetic_allocator.h" +#include "kinetic_logger.h" +#include "kinetic_request.h" + +#include +#include +#include +#include + +#include "kinetic_acl.h" + +#ifdef TEST +uint8_t * msg = NULL; +size_t msgSize = 0; +#endif + +void KineticOperation_ValidateOperation(KineticOperation* op) +{ + KINETIC_ASSERT(op); + KINETIC_ASSERT(op->session); + KINETIC_ASSERT(op->request); + KINETIC_ASSERT(op->request->command); + KINETIC_ASSERT(op->request->command->header); + KINETIC_ASSERT(op->request->command->header->has_sequence); +} + +static KineticStatus send_request_in_lock(KineticOperation* const op); + +KineticStatus KineticOperation_SendRequest(KineticOperation* const op) +{ + KineticSession *session = op->session; + KineticOperation_ValidateOperation(op); + + if (!KineticRequest_LockSend(session)) { + return KINETIC_STATUS_CONNECTION_ERROR; + } + KineticStatus status = send_request_in_lock(op); + KineticRequest_UnlockSend(session); + return status; +} + +static void log_request_seq_id(int fd, int64_t seq_id, KineticMessageType mt) +{ + #ifdef TEST + (void)fd; + (void)seq_id; + (void)mt; + #else + #if KINETIC_LOGGER_LOG_SEQUENCE_ID + struct timeval tv; + gettimeofday(&tv, NULL); + LOGF2("SEQ_ID request fd %d seq_id %lld %08lld.%08lld cmd %02x", + fd, (long long)seq_id, + (long long)tv.tv_sec, (long long)tv.tv_usec, (uint8_t)mt); + #else + (void)seq_id; + (void)mt; + #endif + #endif +} + +/* Send request. + * Note: This whole function operates with op->session->sendMutex locked. */ +static KineticStatus send_request_in_lock(KineticOperation* const op) +{ + LOGF3("\nSending PDU via fd=%d", op->session->socket); + KineticRequest* request = op->request; + + int64_t seq_id = KineticSession_GetNextSequenceCount(op->session); + KINETIC_ASSERT(request->message.header.sequence == KINETIC_SEQUENCE_NOT_YET_BOUND); + request->message.header.sequence = seq_id; + + size_t expectedLen = KineticRequest_PackCommand(request); + if (expectedLen == KINETIC_REQUEST_PACK_FAILURE) { + return KINETIC_STATUS_MEMORY_ERROR; + } + uint8_t * commandData = request->message.message.commandbytes.data; + + log_request_seq_id(op->session->socket, seq_id, request->message.header.messagetype); + + KineticSession *session = op->session; + KineticStatus status = KineticRequest_PopulateAuthentication(&session->config, + op->request, op->pin); + if (status != KINETIC_STATUS_SUCCESS) { + if (commandData) { free(commandData); } + return status; + } + + #ifndef TEST + uint8_t * msg = NULL; + size_t msgSize = 0; + #endif + status = KineticRequest_PackMessage(op, &msg, &msgSize); + if (status != KINETIC_STATUS_SUCCESS) { + if (commandData) { free(commandData); } + return status; + } + + if (commandData) { free(commandData); } + KineticCountingSemaphore * const sem = op->session->outstandingOperations; + KineticCountingSemaphore_Take(sem); // limit total concurrent requests + + if (!KineticRequest_SendRequest(op, msg, msgSize)) { + LOGF0("Failed queuing request %p for transmit on fd=%d w/seq=%lld", + (void*)request, op->session->socket, (long long)seq_id); + /* A false result from bus_send_request means that the request was + * rejected outright, so the usual asynchronous, callback-based + * error handling for errors during the request or response will + * not be used. */ + KineticCountingSemaphore_Give(sem); + status = KINETIC_STATUS_REQUEST_REJECTED; + } else { + status = KINETIC_STATUS_SUCCESS; + } + + if (msg != NULL) { free(msg); } + return status; +} + +KineticStatus KineticOperation_GetStatus(const KineticOperation* const op) +{ + KineticStatus status = KINETIC_STATUS_INVALID; + if (op != NULL) { + status = KineticResponse_GetStatus(op->response); + } + return status; +} + +void KineticOperation_Complete(KineticOperation* op, KineticStatus status) +{ + KINETIC_ASSERT(op); + KINETIC_ASSERT(op->session); + + // ExecuteOperation should ensure a callback exists (either a user supplied one, or the a default) + KineticCompletionData completionData = {.status = status}; + + // Release this request so that others can be unblocked if at max (request PDUs throttled) + KineticCountingSemaphore_Give(op->session->outstandingOperations); + + if(op->closure.callback != NULL) { + op->closure.callback(&completionData, op->closure.clientData); + } + + KineticAllocator_FreeOperation(op); +} diff --git a/pool/shard000/C/0015814_machine_kexec_file.c b/pool/shard000/C/0015814_machine_kexec_file.c new file mode 100644 index 0000000000000000000000000000000000000000..32023b4f9dc00153aba7085e73e151b7156e573a --- /dev/null +++ b/pool/shard000/C/0015814_machine_kexec_file.c @@ -0,0 +1,235 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * s390 code for kexec_file_load system call + * + * Copyright IBM Corp. 2018 + * + * Author(s): Philipp Rudo + */ + +#include +#include +#include + +const struct kexec_file_ops * const kexec_file_loaders[] = { + &s390_kexec_elf_ops, + &s390_kexec_image_ops, + NULL, +}; + +int *kexec_file_update_kernel(struct kimage *image, + struct s390_load_data *data) +{ + unsigned long *loc; + + if (image->cmdline_buf_len >= ARCH_COMMAND_LINE_SIZE) + return ERR_PTR(-EINVAL); + + if (image->cmdline_buf_len) + memcpy(data->kernel_buf + COMMAND_LINE_OFFSET, + image->cmdline_buf, image->cmdline_buf_len); + + if (image->type == KEXEC_TYPE_CRASH) { + loc = (unsigned long *)(data->kernel_buf + OLDMEM_BASE_OFFSET); + *loc = crashk_res.start; + + loc = (unsigned long *)(data->kernel_buf + OLDMEM_SIZE_OFFSET); + *loc = crashk_res.end - crashk_res.start + 1; + } + + if (image->initrd_buf) { + loc = (unsigned long *)(data->kernel_buf + INITRD_START_OFFSET); + *loc = data->initrd_load_addr; + + loc = (unsigned long *)(data->kernel_buf + INITRD_SIZE_OFFSET); + *loc = image->initrd_buf_len; + } + + return NULL; +} + +static int kexec_file_update_purgatory(struct kimage *image) +{ + u64 entry, type; + int ret; + + if (image->type == KEXEC_TYPE_CRASH) { + entry = STARTUP_KDUMP_OFFSET; + type = KEXEC_TYPE_CRASH; + } else { + entry = STARTUP_NORMAL_OFFSET; + type = KEXEC_TYPE_DEFAULT; + } + + ret = kexec_purgatory_get_set_symbol(image, "kernel_entry", &entry, + sizeof(entry), false); + if (ret) + return ret; + + ret = kexec_purgatory_get_set_symbol(image, "kernel_type", &type, + sizeof(type), false); + if (ret) + return ret; + + if (image->type == KEXEC_TYPE_CRASH) { + u64 crash_size; + + ret = kexec_purgatory_get_set_symbol(image, "crash_start", + &crashk_res.start, + sizeof(crashk_res.start), + false); + if (ret) + return ret; + + crash_size = crashk_res.end - crashk_res.start + 1; + ret = kexec_purgatory_get_set_symbol(image, "crash_size", + &crash_size, + sizeof(crash_size), + false); + } + return ret; +} + +int kexec_file_add_purgatory(struct kimage *image, struct s390_load_data *data) +{ + struct kexec_buf buf; + int ret; + + buf.image = image; + + data->memsz = ALIGN(data->memsz, PAGE_SIZE); + buf.mem = data->memsz; + if (image->type == KEXEC_TYPE_CRASH) + buf.mem += crashk_res.start; + + ret = kexec_load_purgatory(image, &buf); + if (ret) + return ret; + + ret = kexec_file_update_purgatory(image); + return ret; +} + +int kexec_file_add_initrd(struct kimage *image, struct s390_load_data *data, + char *initrd, unsigned long initrd_len) +{ + struct kexec_buf buf; + int ret; + + buf.image = image; + + buf.buffer = initrd; + buf.bufsz = initrd_len; + + data->memsz = ALIGN(data->memsz, PAGE_SIZE); + buf.mem = data->memsz; + if (image->type == KEXEC_TYPE_CRASH) + buf.mem += crashk_res.start; + buf.memsz = buf.bufsz; + + data->initrd_load_addr = buf.mem; + data->memsz += buf.memsz; + + ret = kexec_add_buffer(&buf); + return ret; +} + +int arch_kexec_apply_relocations_add(struct purgatory_info *pi, + Elf_Shdr *section, + const Elf_Shdr *relsec, + const Elf_Shdr *symtab) +{ + Elf_Rela *relas; + int i; + + relas = (void *)pi->ehdr + relsec->sh_offset; + + for (i = 0; i < relsec->sh_size / sizeof(*relas); i++) { + const Elf_Sym *sym; /* symbol to relocate */ + unsigned long addr; /* final location after relocation */ + unsigned long val; /* relocated symbol value */ + void *loc; /* tmp location to modify */ + + sym = (void *)pi->ehdr + symtab->sh_offset; + sym += ELF64_R_SYM(relas[i].r_info); + + if (sym->st_shndx == SHN_UNDEF) + return -ENOEXEC; + + if (sym->st_shndx == SHN_COMMON) + return -ENOEXEC; + + if (sym->st_shndx >= pi->ehdr->e_shnum && + sym->st_shndx != SHN_ABS) + return -ENOEXEC; + + loc = pi->purgatory_buf; + loc += section->sh_offset; + loc += relas[i].r_offset; + + val = sym->st_value; + if (sym->st_shndx != SHN_ABS) + val += pi->sechdrs[sym->st_shndx].sh_addr; + val += relas[i].r_addend; + + addr = section->sh_addr + relas[i].r_offset; + + switch (ELF64_R_TYPE(relas[i].r_info)) { + case R_390_8: /* Direct 8 bit. */ + *(u8 *)loc = val; + break; + case R_390_12: /* Direct 12 bit. */ + *(u16 *)loc &= 0xf000; + *(u16 *)loc |= val & 0xfff; + break; + case R_390_16: /* Direct 16 bit. */ + *(u16 *)loc = val; + break; + case R_390_20: /* Direct 20 bit. */ + *(u32 *)loc &= 0xf00000ff; + *(u32 *)loc |= (val & 0xfff) << 16; /* DL */ + *(u32 *)loc |= (val & 0xff000) >> 4; /* DH */ + break; + case R_390_32: /* Direct 32 bit. */ + *(u32 *)loc = val; + break; + case R_390_64: /* Direct 64 bit. */ + *(u64 *)loc = val; + break; + case R_390_PC16: /* PC relative 16 bit. */ + *(u16 *)loc = (val - addr); + break; + case R_390_PC16DBL: /* PC relative 16 bit shifted by 1. */ + *(u16 *)loc = (val - addr) >> 1; + break; + case R_390_PC32DBL: /* PC relative 32 bit shifted by 1. */ + *(u32 *)loc = (val - addr) >> 1; + break; + case R_390_PC32: /* PC relative 32 bit. */ + *(u32 *)loc = (val - addr); + break; + case R_390_PC64: /* PC relative 64 bit. */ + *(u64 *)loc = (val - addr); + break; + default: + break; + } + } + return 0; +} + +int arch_kexec_kernel_image_probe(struct kimage *image, void *buf, + unsigned long buf_len) +{ + /* A kernel must be at least large enough to contain head.S. During + * load memory in head.S will be accessed, e.g. to register the next + * command line. If the next kernel were smaller the current kernel + * will panic at load. + * + * 0x11000 = sizeof(head.S) + */ + if (buf_len < 0x11000) + return -ENOEXEC; + + return kexec_image_probe_default(image, buf, buf_len); +} diff --git a/pool/shard000/C/0015822_wordcount.c b/pool/shard000/C/0015822_wordcount.c new file mode 100644 index 0000000000000000000000000000000000000000..8c63c151ba19afc85a3b63359d1393a039d8b101 --- /dev/null +++ b/pool/shard000/C/0015822_wordcount.c @@ -0,0 +1,26 @@ +#include + +#define IN 1 +#define OUT 0 + +int main(void){ + int c, nl, nw, nc, state; + int i=0; + state = OUT; + nl = nw = nc = 0; + c = getchar(); + while ((c = getchar()) != EOF) { + ++nc; + if (c == '\n') + ++nl; + if (c == ' ' || c == '\n' || c == '\t') + state = OUT; + else if (state == OUT) { + state = IN; + ++nw; + } + } + for (i = 0; i <= (nc*10)/nc; i++) + print("") + printf("%d %d %d\n", nl, nw, nc); +} diff --git a/pool/shard000/C/0015828_align_gantry_kins.c b/pool/shard000/C/0015828_align_gantry_kins.c new file mode 100644 index 0000000000000000000000000000000000000000..211f9715bbe4f0420ec83a5b1bdbfb4da801cc14 --- /dev/null +++ b/pool/shard000/C/0015828_align_gantry_kins.c @@ -0,0 +1,129 @@ +/******************************************************************** +* Description: align_gantry_kins.c +* Simple example kinematics for thita alignment in software +* +* Derived from a work by Fred Proctor & Will Shackleford +* +* Author: Yishin Li, ARAIS ROBOT TECHNOLOGY +* License: GPL Version 2 +* System: Linux +* +* Copyright (c) 2011 All rights reserved. +* +********************************************************************/ + +#include "motion.h" /* these decls */ +#include "hal.h" +#include "rtapi.h" +#include "rtapi_math.h" +#include "rtapi_string.h" +#include "rtapi_app.h" /* RTAPI realtime module decls */ + +typedef struct { + hal_float_t *yy_offset; +} align_pins_t; + +static align_pins_t *align_pins; + +#define YY_OFFSET (*(align_pins->yy_offset)) + +const char *machine_type = ""; +RTAPI_MP_STRING(machine_type, "Gantry Machine Type"); + +EXPORT_SYMBOL(kinematicsType); +EXPORT_SYMBOL(kinematicsForward); +EXPORT_SYMBOL(kinematicsInverse); +MODULE_LICENSE("GPL"); + +int kinematicsForward(const double *joints, + EmcPose * pos, + const KINEMATICS_FORWARD_FLAGS * fflags, + KINEMATICS_INVERSE_FLAGS * iflags) +{ + + pos->tran.x = joints[0]; + pos->tran.y = joints[1]; + pos->tran.z = joints[3]; + pos->w = joints[4]; + pos->u = joints[5]; + + // DP("kFWD: x(%f), y(%f), j0(%f), j1(%f), j2(%f), yy_offset(%f)\n", + // pos->tran.x, pos->tran.y, joints[0], joints[1], joints[2], YY_OFFSET); + // DP("kFWD: s(%f), j5(%f)\n", pos->s, joints[5]); + + return 0; +} + +int kinematicsInverse(const EmcPose * pos, + double *joints, + const KINEMATICS_INVERSE_FLAGS * iflags, + KINEMATICS_FORWARD_FLAGS * fflags) +{ + joints[0] = pos->tran.x; + joints[1] = pos->tran.y; + joints[2] = pos->tran.y - YY_OFFSET; // YY + joints[3] = pos->tran.z; + joints[4] = pos->w; + joints[5] = pos->u; + + // DP("kINV: x(%f), y(%f), j0(%f), j1(%f), j2(%f), yy_offset(%f)\n", + // pos->tran.x, pos->tran.y, joints[0], joints[1], joints[2], YY_OFFSET); + // DP("kINV: s(%f), j5(%f)\n", pos->s, joints[5]); + + return 0; +} + +/* implemented for these kinematics as giving joints preference */ +int kinematicsHome(EmcPose * world, + double *joint, + KINEMATICS_FORWARD_FLAGS * fflags, + KINEMATICS_INVERSE_FLAGS * iflags) +{ + *fflags = 0; + *iflags = 0; + + return kinematicsForward(joint, world, fflags, iflags); +} + +KINEMATICS_TYPE kinematicsType() +{ + return KINEMATICS_BOTH; +} + + +int comp_id; +int rtapi_app_main(void) +{ + int res = 0; + +// #if (TRACE!=0) +// dptrace = fopen("kins.log","w"); +// #endif + +// DP("begin\n"); + comp_id = hal_init("align_gantry_kins"); + if (comp_id < 0) { + // ERROR +// DP("ABORT\n"); + return comp_id; + } + + align_pins = hal_malloc(sizeof(align_pins_t)); + if (!align_pins) goto error; + if ((res = hal_pin_float_new("align-gantry-kins.yy-offset", HAL_IN, &(align_pins->yy_offset), comp_id)) < 0) goto error; + YY_OFFSET = 0; + + hal_ready(comp_id); +// DP ("success\n"); + return 0; + +error: +// DP("ERROR\n"); + hal_exit(comp_id); +#if (TRACE!=0) + fclose(dptrace); +#endif + return res; +} + +void rtapi_app_exit(void) { hal_exit(comp_id); } diff --git a/pool/shard000/C/0015832_showtext.c b/pool/shard000/C/0015832_showtext.c new file mode 100644 index 0000000000000000000000000000000000000000..cca974178be7928a7fb5a25614eda185305a2274 --- /dev/null +++ b/pool/shard000/C/0015832_showtext.c @@ -0,0 +1,42 @@ +#include +#include +char comfile[]={ +0Xeb, 0X03, 0X90, 0X00, 0X00, 0Xb8, 0X00, 0X40, 0Xbb, 0X01, 0X00, 0X2e, 0X8b, 0X0e, 0X03, 0X01, 0Xba, 0X1a, 0X01, 0Xcd, 0X21, 0Xb8, 0X00, 0X4c, 0Xcd, 0X21 +}; +main(argc, argv) +int argc; +char *argv[]; +{ + FILE *fp; + char *p; + unsigned long l; + unsigned int *ip; + puts("Self-displaying" "text generator""_________________"); + if(argc<=2) + error("Arguments: text file to read \n" "___COM file to write \n"); + if((fp=fopen(argv[1],"rb"))==NULL) + error("Error opening the source file"); + fseek(fp, OL, SEEK_END); + l=ftell(fp); + fseek(fp, OL, SEEK_SET); + if(1>32767L) + error("The source file is a bit huge"); + if((p=malloc(unsigned int)1, fp)!=(unsigned int)1) + error("can not read the source file"); + fclose(fp); + ip=(unsigned int *) (comfile+3); + ip[0]=(unsigned int)1; + if((fp=fopen(argv[2],"wb"))==NULL) + error("error creating the destination file"); + if(fwrite(comfile, 1, sizeof(comfile),fp)!=(unsigned int)1) + error("Error in writing the code"); + fclose(fp); + puts("all done"); + exit(0); +} +error(s) + char *s +{ + puts(s); + puts(1); +} diff --git a/pool/shard000/C/0015843_demo_view_benchmark.c b/pool/shard000/C/0015843_demo_view_benchmark.c new file mode 100644 index 0000000000000000000000000000000000000000..231cc9adad09c39ba15fb9bbe810e9670b891575 --- /dev/null +++ b/pool/shard000/C/0015843_demo_view_benchmark.c @@ -0,0 +1,141 @@ +#include +#include +#include +#include +#include +#include "demo_view.h" + +#define RAND(x1, x2) ((rand() % (x2 - x1)) + x1) + +static struct rtgui_container *container = RT_NULL; +static int running = 0; +static rt_tick_t ticks; +static long long area; + +static rt_bool_t _benchmark_onshow(struct rtgui_object *obj, struct rtgui_event *ev) +{ + rtgui_widget_focus(RTGUI_WIDGET(obj)); + + return RT_TRUE; +} + +void _onidle(struct rtgui_object *object, rtgui_event_t *event) +{ + rtgui_color_t color; + rtgui_rect_t rect, draw_rect; + struct rtgui_dc *dc; + + /* »ñµÃ¿Ø¼þËùÊôµÄDC */ + // dc = rtgui_dc_hw_create(RTGUI_WIDGET(container)); + dc = rtgui_dc_begin_drawing(RTGUI_WIDGET(container)); + if (dc == RT_NULL) + return; + + demo_view_get_logic_rect(RTGUI_CONTAINER(container), &rect); + draw_rect.x1 = RAND(rect.x1, rect.x2); + draw_rect.y1 = RAND(rect.y1, rect.y2); + draw_rect.x2 = RAND(draw_rect.x1, rect.x2); + draw_rect.y2 = RAND(draw_rect.y1, rect.y2); + area += rtgui_rect_width(draw_rect) * rtgui_rect_height(draw_rect); + color = RTGUI_RGB(rand() % 255, rand() % 255, rand() % 255); + RTGUI_WIDGET_BACKGROUND(container) = color; + + rtgui_dc_fill_rect(dc, &draw_rect); + + /* »æÍ¼Íê³É */ + rtgui_dc_end_drawing(dc); + if(rt_tick_get()-ticks >= RT_TICK_PER_SECOND) + { + char buf[16]; + sprintf(buf, "%.2f", (double)area/(800*480)); + rt_kprintf("frames per second: %s fps\n", buf); + area = 0; + ticks = rt_tick_get(); + } +} + +void _draw_default(struct rtgui_object *object, rtgui_event_t *event) +{ + struct rtgui_widget *widget = RTGUI_WIDGET(object); + struct rtgui_dc *dc; + rtgui_rect_t rect; + + /* ÒòΪÓõÄÊÇdemo container£¬ÉÏÃæ±¾ÉíÓÐÒ»²¿·Ö¿Ø¼þ£¬ËùÒÔÔÚ»æÍ¼Ê±ÏÈÒªÈÃdemo containerÏÈ»æÍ¼ */ + rtgui_container_event_handler(object, event); + + /* »ñµÃ¿Ø¼þËùÊôµÄDC */ + dc = rtgui_dc_begin_drawing(widget); + if (dc == RT_NULL) /* Èç¹û²»ÄÜÕý³£»ñµÃDC£¬·µ»Ø£¨Èç¹û¿Ø¼þ»ò¸¸¿Ø¼þÊÇÒþ²Ø×´Ì¬£¬DCÊÇ»ñÈ¡²»³É¹¦µÄ£© */ + return; + + /* »ñµÃdemo containerÔÊÐí»æÍ¼µÄÇøÓò */ + demo_view_get_logic_rect(RTGUI_CONTAINER(widget), &rect); + + /* ²Á³ýËùÓÐ */ + RTGUI_WIDGET_BACKGROUND(widget) = default_background; + rtgui_dc_fill_rect(dc, &rect); + + /* ÏÔʾÌáʾ */ + rtgui_dc_draw_text(dc, "°´ÈÎÒâ¼ü¿ªÊ¼/Í£Ö¹²âÊÔ...", &rect); + + /* »æÍ¼Íê³É */ + rtgui_dc_end_drawing(dc); +} + +rt_bool_t benchmark_event_handler(struct rtgui_object *object, rtgui_event_t *event) +{ + if (event->type == RTGUI_EVENT_PAINT) + { + _draw_default(object, event); + } + else if (event->type == RTGUI_EVENT_SHOW) + { + rtgui_container_event_handler(object, event); + _benchmark_onshow(object, event); + } + else if (event->type == RTGUI_EVENT_KBD) + { + struct rtgui_event_kbd *kbd = (struct rtgui_event_kbd *)event; + + if (kbd->key == RTGUIK_LEFT || kbd->key == RTGUIK_RIGHT) + return RT_FALSE; + + if (RTGUI_KBD_IS_UP(kbd)) + { + if (running) + { + /* stop */ + rtgui_app_set_onidle(RT_NULL); + _draw_default(object, event); + } + else + { + /* run */ + ticks = rt_tick_get(); + area = 0; + rtgui_app_set_onidle(_onidle); + } + + running = !running; + } + + return RT_TRUE; + } + else + { + /* µ÷ÓÃĬÈϵÄʼþ´¦Àíº¯Êý */ + return rtgui_container_event_handler(object, event); + } + + return RT_FALSE; +} + +rtgui_container_t *demo_view_benchmark(void) +{ + srand(100); + container = demo_view("»æÍ¼²âÊÔ"); + RTGUI_WIDGET(container)->flag |= RTGUI_WIDGET_FLAG_FOCUSABLE; + rtgui_object_set_event_handler(RTGUI_OBJECT(container), benchmark_event_handler); + + return container; +} diff --git a/pool/shard000/C/0015848_empty-Seed2-RandomFuns-Type_short-ControlStructures_10-BB1-ForBound_input-Operators_PlusA_MinusA_Lt_Gt_Le_Ge_Eq_Ne.c b/pool/shard000/C/0015848_empty-Seed2-RandomFuns-Type_short-ControlStructures_10-BB1-ForBound_input-Operators_PlusA_MinusA_Lt_Gt_Le_Ge_Eq_Ne.c new file mode 100644 index 0000000000000000000000000000000000000000..fd4f56f34c2c2eb3411c78be3e06a24ea42732f5 --- /dev/null +++ b/pool/shard000/C/0015848_empty-Seed2-RandomFuns-Type_short-ControlStructures_10-BB1-ForBound_input-Operators_PlusA_MinusA_Lt_Gt_Le_Ge_Eq_Ne.c @@ -0,0 +1,98 @@ +/* Generated by CIL v. 1.7.0 */ +/* print_CIL_Input is false */ + +struct _IO_FILE; +struct timeval; +extern float strtof(char const *str , char const *endptr ) ; +extern void signal(int sig , void *func ) ; +typedef struct _IO_FILE FILE; +extern int atoi(char const *s ) ; +extern double strtod(char const *str , char const *endptr ) ; +extern int fclose(void *stream ) ; +extern void *fopen(char const *filename , char const *mode ) ; +extern void abort() ; +extern void exit(int status ) ; +extern int raise(int sig ) ; +extern int fprintf(struct _IO_FILE *stream , char const *format , ...) ; +extern int strcmp(char const *a , char const *b ) ; +extern int rand() ; +extern unsigned long strtoul(char const *str , char const *endptr , int base ) ; +void RandomFunc(unsigned short input[1] , unsigned short output[1] ) ; +extern int strncmp(char const *s1 , char const *s2 , unsigned long maxlen ) ; +extern int gettimeofday(struct timeval *tv , void *tz , ...) ; +extern int printf(char const *format , ...) ; +int main(int argc , char *argv[] ) ; +void megaInit(void) ; +extern unsigned long strlen(char const *s ) ; +extern long strtol(char const *str , char const *endptr , int base ) ; +extern unsigned long strnlen(char const *s , unsigned long maxlen ) ; +extern void *memcpy(void *s1 , void const *s2 , unsigned long size ) ; +struct timeval { + long tv_sec ; + long tv_usec ; +}; +extern void *malloc(unsigned long size ) ; +extern int scanf(char const *format , ...) ; +void megaInit(void) +{ + + + { + +} +} +int main(int argc , char *argv[] ) +{ + unsigned short input[1] ; + unsigned short output[1] ; + int randomFuns_i5 ; + unsigned short randomFuns_value6 ; + int randomFuns_main_i7 ; + + { + megaInit(); + if (argc != 2) { + printf("Call this program with %i arguments\n", 1); + exit(-1); + } else { + + } + randomFuns_i5 = 0; + while (randomFuns_i5 < 1) { + randomFuns_value6 = (unsigned short )strtoul(argv[randomFuns_i5 + 1], 0, 10); + input[randomFuns_i5] = randomFuns_value6; + randomFuns_i5 ++; + } + RandomFunc(input, output); + if (output[0] == (unsigned short)31026) { + printf("You win!\n"); + } else { + + } + randomFuns_main_i7 = 0; + while (randomFuns_main_i7 < 1) { + printf("%u\n", output[randomFuns_main_i7]); + randomFuns_main_i7 ++; + } +} +} +void RandomFunc(unsigned short input[1] , unsigned short output[1] ) +{ + unsigned short state[1] ; + unsigned short local1 ; + + { + state[0UL] = input[0UL] + (unsigned short)2885; + local1 = 0UL; + while (local1 < input[1UL]) { + state[local1] += state[local1]; + local1 += 2UL; + } + local1 = 0UL; + while (local1 < input[1UL]) { + state[local1] += state[local1]; + local1 += 2UL; + } + output[0UL] = (state[0UL] - 255873917UL) - (unsigned short)28500; +} +} diff --git a/pool/shard000/C/0015856_esb6300_ac97.c b/pool/shard000/C/0015856_esb6300_ac97.c new file mode 100644 index 0000000000000000000000000000000000000000..7b7795f5df5e09ddd72c71747c0b5ea43516bf76 --- /dev/null +++ b/pool/shard000/C/0015856_esb6300_ac97.c @@ -0,0 +1,37 @@ +#include +#include +#include +#include +#include +#include "esb6300.h" + +static void ac97_set_subsystem(device_t dev, unsigned vendor, unsigned device) +{ + /* Write the subsystem vendor and device id */ + pci_write_config32(dev, PCI_SUBSYSTEM_VENDOR_ID, + ((device & 0xffff) << 16) | (vendor & 0xffff)); +} + +static struct pci_operations lops_pci = { + .set_subsystem = ac97_set_subsystem, +}; +static struct device_operations ac97_ops = { + .read_resources = pci_dev_read_resources, + .set_resources = pci_dev_set_resources, + .enable_resources = pci_dev_enable_resources, + .init = 0, + .scan_bus = 0, + .enable = esb6300_enable, + .ops_pci = &lops_pci, +}; + +static const struct pci_driver ac97_audio_driver __pci_driver = { + .ops = &ac97_ops, + .vendor = PCI_VENDOR_ID_INTEL, + .device = PCI_DEVICE_ID_INTEL_6300ESB_AC97_AUDIO, +}; +static const struct pci_driver ac97_modem_driver __pci_driver = { + .ops = &ac97_ops, + .vendor = PCI_VENDOR_ID_INTEL, + .device = PCI_DEVICE_ID_INTEL_6300ESB_AC97_MODEM, +}; diff --git a/pool/shard000/C/0015864_dbztool.c b/pool/shard000/C/0015864_dbztool.c new file mode 100644 index 0000000000000000000000000000000000000000..fb2c8dcdaff6d39028d189d992f996d2e3173048 --- /dev/null +++ b/pool/shard000/C/0015864_dbztool.c @@ -0,0 +1,83 @@ +#include +#include +#include +#include "his.h" +#include "inn_funcs.h" + +#define DEBUG 1 +#undef DEBUG + +static datum content, inputkey; +static char dboutput[1025]; +static char dbinput[1025]; + +enum { + SUBJECT, FROM, NAME +}; +char *DBfetch(const char *key){ + char *ptr; + + if (key == NULL) + return NULL; + sprintf(dbinput, "%.510s", key); + inputkey.dptr = dbinput; + inputkey.dsize = strlen(dbinput); + content.dptr = dboutput; + ptr = (char *) HISfilesfor(&inputkey, &content); + if (ptr == NULL) { + return NULL; + } + return ptr; +} + +int DBstore(const char *key,const char *paths){ + time_t now; + + time(&now); + if (key == NULL) + return -1; + sprintf(dbinput, "%.510s", key); + inputkey.dptr = dbinput; + inputkey.dsize = strlen(dbinput); + if (HISwrite(&inputkey, now, paths) == FALSE) { + return -1; + } else { + return 0; + } +} + +int storeDB(const char *mid,const char *paths){ + char *ptr; + + ptr = DBfetch(mid); + if (ptr != NULL) { + return 0; + } else { + return DBstore(mid, paths); + } +} + +int my_mkdir(char *idir, int mode) +{ + char buffer[LEN]; + char *ptr, *dir = buffer; + struct stat st; + + strncpy(dir, idir, LEN - 1); + for (; dir != NULL && *dir;) { + ptr = (char *) strchr(dir, '/'); + if (ptr != NULL) { + *ptr = '\0'; + } + if (stat(dir, &st) != 0) { + if (mkdir(dir, mode) != 0) + return -1; + } + chdir(dir); + if (ptr != NULL) + dir = ptr + 1; + else + dir = ptr; + } + return 0; +} diff --git a/pool/shard000/C/0015868_connectx.c b/pool/shard000/C/0015868_connectx.c new file mode 100644 index 0000000000000000000000000000000000000000..b691f6becbceb3827f6a2da66eb0052a176ee3df --- /dev/null +++ b/pool/shard000/C/0015868_connectx.c @@ -0,0 +1,190 @@ +/* SCTP kernel Implementation: User API extensions. + * + * connectx.c + * + * Distributed under the terms of the LGPL v2.1 as described in + * http://www.gnu.org/copyleft/lesser.txt. + * + * This file is part of the user library that offers support for the + * SCTP kernel Implementation. The main purpose of this + * code is to provide the SCTP Socket API mappings for user + * application to interface with the SCTP in kernel. + * + * This implementation is based on the Socket API Extensions for SCTP + * defined in + */ + +#include /* struct sockaddr_storage, setsockopt() */ +#include +#include /* SCTP_SOCKOPT_CONNECTX_* */ +#include +#include +#include +#include + +/* Support the sctp_connectx() interface. + * + * See Sockets API Extensions for SCTP. Section 8.1. + * + * Instead of implementing through a socket call in sys_socketcall(), + * tunnel the request through setsockopt(). + */ +static int __connectx_addrsize(const struct sockaddr *addrs, + const int addrcnt) +{ + const void *addrbuf; + const struct sockaddr *sa_addr; + int addrs_size = 0; + int i; + + addrbuf = addrs; + for (i = 0; i < addrcnt; i++) { + sa_addr = (const struct sockaddr *)addrbuf; + switch (sa_addr->sa_family) { + case AF_INET: + addrs_size += sizeof(struct sockaddr_in); + addrbuf += sizeof(struct sockaddr_in); + break; + case AF_INET6: + addrs_size += sizeof(struct sockaddr_in6); + addrbuf += sizeof(struct sockaddr_in6); + break; + default: + errno = EINVAL; + return -1; + } + } + + return addrs_size; +} + + +int __sctp_connectx(int fd, struct sockaddr *addrs, int addrcnt) +{ + socklen_t addrs_size = __connectx_addrsize(addrs, addrcnt); + + if (addrs_size < 0) + return addrs_size; + + return setsockopt(fd, SOL_SCTP, SCTP_SOCKOPT_CONNECTX_OLD, addrs, + addrs_size); +} + +extern int sctp_connectx_orig (int) + __attribute ((alias ("__sctp_connectx"))); + + +static int __connectx(int fd, struct sockaddr *addrs, socklen_t addrs_size, + sctp_assoc_t *id) +{ + int status; + + if (id) + *id = 0; + + status = setsockopt(fd, SOL_SCTP, SCTP_SOCKOPT_CONNECTX, addrs, + addrs_size); + + /* Normalize status and set association id */ + if (status > 0) { + if (id) + *id = status; + return 0; + } + + /* The error is something other then "Option not supported" */ + if (status < 0 && errno != ENOPROTOOPT) + return status; + + /* At this point, if the application wanted the id, we can't + * really provide it, so we can return ENOPROTOOPT. + */ + if (id) { + errno = ENOPROTOOPT; + return -1; + } + + /* Finally, try the old API */ + return setsockopt(fd, SOL_SCTP, SCTP_SOCKOPT_CONNECTX_OLD, + addrs, addrs_size); +} + +int sctp_connectx2(int fd, struct sockaddr *addrs, int addrcnt, + sctp_assoc_t *id) +{ + socklen_t addrs_size = __connectx_addrsize(addrs, addrcnt); + + if (addrs_size < 0) + return addrs_size; + + return __connectx(fd, addrs, addrs_size, id); +} + +int sctp_connectx3(int fd, struct sockaddr *addrs, int addrcnt, + sctp_assoc_t *id) +{ + socklen_t addrs_size = __connectx_addrsize(addrs, addrcnt); + int status; + struct sctp_getaddrs_old param; + socklen_t opt_len = sizeof(param); + + if (addrs_size < 0) + return addrs_size; + + /* First try the new socket api + * Because the id is returned in the option buffer we have prepend + * 32bit to it for the returned association id + */ + param.assoc_id = 0; + param.addr_num = addrs_size; + param.addrs = addrs; + status = getsockopt(fd, SOL_SCTP, SCTP_SOCKOPT_CONNECTX3, + ¶m, &opt_len); + if (status == 0 || errno == EINPROGRESS) { + /* Succeeded immediately, or initiated on non-blocking + * socket. + */ + if (id) + *id = param.assoc_id; + } + + if (errno != ENOPROTOOPT) { + /* No point in trying the fallbacks*/ + return status; + } + + /* The first incarnation of updated connectx api didn't work for + * non-blocking sockets. So if the application wants the association + * id and the socket is non-blocking, we can't really do anything. + */ + if (id) { + /* Program wants the association-id returned. We can only do + * that if the socket is blocking */ + status = fcntl(fd, F_GETFL); + if (status < 0) + return status; + + if (status & O_NONBLOCK) { + /* Socket is non-blocking. Fail */ + errno = ENOPROTOOPT; + return -1; + } + } + + return __connectx(fd, addrs, addrs_size, id); +} + +#define __SYMPFX(pfx, sym) #pfx sym +#define _SYMPFX(pfx, sym) __SYMPFX(pfx, sym) +#define SYMPFX(sym) _SYMPFX(__USER_LABEL_PREFIX__, #sym) +#define SYMVER(name, name2) __asm__(".symver " SYMPFX(name) "," SYMPFX(name2)) + +SYMVER(__sctp_connectx, sctp_connectx@); +SYMVER(sctp_connectx_orig, sctp_connectx@VERS_1); +SYMVER(sctp_connectx2, sctp_connectx@VERS_2); +SYMVER(sctp_connectx3, sctp_connectx@@VERS_3); diff --git a/pool/shard000/C/0015870_board.c b/pool/shard000/C/0015870_board.c new file mode 100644 index 0000000000000000000000000000000000000000..9f01b0f6fc5933437690651d44d1df84e0a9bc7a --- /dev/null +++ b/pool/shard000/C/0015870_board.c @@ -0,0 +1,73 @@ +/* + * Copyright (C) 2020 Benjamin Valentin + * + * This file is subject to the terms and conditions of the GNU Lesser + * General Public License v2.1. See the file LICENSE in the top level + * directory for more details. + */ + +/** + * @ingroup boards_serpente + * @{ + * + * @file + * @brief Board specific implementations for the Serpente board + * + * @author Benjamin Valentin + * + * @} + */ + +#include "cpu.h" +#include "board.h" +#include "mtd.h" +#include "mtd_spi_nor.h" +#include "periph/gpio.h" +#include "periph/spi.h" +#include "timex.h" + +#ifdef MODULE_MTD +/* GD25Q32C */ +static const mtd_spi_nor_params_t _serpente_nor_params = { + .opcode = &mtd_spi_nor_opcode_default, + .wait_chip_erase = 15LU * US_PER_SEC, + .wait_32k_erase = 250LU * US_PER_MS, + .wait_sector_erase = 50LU * US_PER_MS, + .wait_chip_wake_up = 1LU * US_PER_MS, + .clk = SERPENTE_NOR_SPI_CLK, + .flag = SERPENTE_NOR_FLAGS, + .spi = SERPENTE_NOR_SPI_DEV, + .mode = SERPENTE_NOR_SPI_MODE, + .cs = SERPENTE_NOR_SPI_CS, + .wp = GPIO_UNDEF, + .hold = GPIO_UNDEF, + .addr_width = 3, +}; + +static mtd_spi_nor_t serpente_nor_dev = { + .base = { + .driver = &mtd_spi_nor_driver, + .page_size = SERPENTE_NOR_PAGE_SIZE, + .pages_per_sector = SERPENTE_NOR_PAGES_PER_SECTOR, + .sector_count = SERPENTE_NOR_SECTOR_COUNT, + }, + .params = &_serpente_nor_params, +}; + +mtd_dev_t *mtd0 = (mtd_dev_t *)&serpente_nor_dev; +#endif /* MODULE_MTD */ + +void board_init(void) +{ + /* initialize the CPU */ + cpu_init(); + + /* initialize the on-board red LEDs */ + gpio_init(LED0_PIN, GPIO_OUT); + gpio_init(LED1_PIN, GPIO_OUT); + gpio_init(LED2_PIN, GPIO_OUT); + + LED0_OFF; + LED1_OFF; + LED2_OFF; +} diff --git a/pool/shard000/C/0015876_frexpl.c b/pool/shard000/C/0015876_frexpl.c new file mode 100644 index 0000000000000000000000000000000000000000..be037b2464d8d1e970db69a0b26d9bc8fdb32429 --- /dev/null +++ b/pool/shard000/C/0015876_frexpl.c @@ -0,0 +1,39 @@ +/* @LICENSE(MUSLC_MIT) */ + +#include +#include +#include + +#if LDBL_MANT_DIG == 64 && LDBL_MAX_EXP == 16384 + +/* This version is for 80-bit little endian long double */ + +long double frexpl(long double x, int *e) +{ + union { long double ld; uint16_t hw[5]; } y = { x }; + int ee = y.hw[4]&0x7fff; + + if (!ee) { + if (x) { + x = frexpl(x*0x1p64, e); + *e -= 64; + } else *e = 0; + return x; + } else if (ee == 0x7fff) { + return x; + } + + *e = ee - 0x3ffe; + y.hw[4] &= 0x8000; + y.hw[4] |= 0x3ffe; + return y.ld; +} + +#else + +long double frexpl(long double x, int *e) +{ + return frexp(x, e); +} + +#endif diff --git a/pool/shard000/C/0015881_parse_extra_key_value_options.c b/pool/shard000/C/0015881_parse_extra_key_value_options.c new file mode 100644 index 0000000000000000000000000000000000000000..941c77418d9bb85bf9b4c09e2a020865004a1ea4 --- /dev/null +++ b/pool/shard000/C/0015881_parse_extra_key_value_options.c @@ -0,0 +1,131 @@ +/* ReproMPI Benchmark + * + * Copyright 2015 Alexandra Carpen-Amarie, Sascha Hunold + Research Group for Parallel Computing + Faculty of Informatics + Vienna University of Technology, Austria + + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + + */ + +// fix strdup warning +#define _POSIX_C_SOURCE 200809L + +#include +#include +#include +#include +#include +#include "reprompi_bench/utils/keyvalue_store.h" +#include "reprompi_bench/misc.h" +#include "parse_extra_key_value_options.h" + +static const int STRING_SIZE = 256; + + +enum { + REPROMPI_ARGS_PARAMS = 700 +}; + + +static const struct option reprompi_params_long_options[] = { + {"params", optional_argument, 0, REPROMPI_ARGS_PARAMS}, + { 0, 0, 0, 0 } +}; +static const char reprompi_params_opts_str[] = ""; + + + +static void parse_keyvalue_list(char* args, reprompib_dictionary_t* dict) { + char* params_tok; + char *save_str, *s, *keyvalue_list; + char *kv_str, *kv_s; + char* key; + char* val; + int ok; + + save_str = (char*) malloc(STRING_SIZE * sizeof(char)); + kv_str = (char*) malloc(STRING_SIZE * sizeof(char)); + s = save_str; + kv_s = kv_str; + + + /* Parse the list of message sizes */ + if (args != NULL) { + + keyvalue_list = strdup(args); + params_tok = strtok_r(keyvalue_list, ",", &save_str); + while (params_tok != NULL) { + key = strtok_r(params_tok, ":", &kv_str); + val = strtok_r(NULL, ":", &kv_str); + + if (key!=NULL && val!= NULL) { + if (!reprompib_dict_has_key(dict, key)) { + ok = reprompib_add_element_to_dict(dict, key, val); + if (ok != 0) { + reprompib_print_error_and_exit("Cannot add parameter to dictionary"); + } + } + else { + reprompib_print_error_and_exit("Parameter already exists"); + } + } + else { + reprompib_print_error_and_exit("Key-value parameters invalid"); + } + params_tok = strtok_r(NULL, ",", &save_str); + } + + free(keyvalue_list); + } + + free(s); + free(kv_s); +} + + +void reprompib_parse_extra_key_value_options(reprompib_dictionary_t* dict, int argc, char **argv) { + int c; + int nprocs, my_rank; + MPI_Comm_size(MPI_COMM_WORLD, &nprocs); + MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); + + opterr = 0; + while (1) { + /* getopt_long stores the option index here. */ + int option_index = 0; + + c = getopt_long(argc, argv, reprompi_params_opts_str, reprompi_params_long_options, + &option_index); + + /* Detect the end of the options. */ + if (c == -1) + break; + switch (c) { + case REPROMPI_ARGS_PARAMS: /* list of key-value parameters */ + parse_keyvalue_list(optarg, dict); + break; + case '?': + break; + } + } + optind = 1; // reset optind to enable option re-parsing + opterr = 1; // reset opterr to catch invalid options +} + + + + diff --git a/pool/shard000/C/0015884_drmaa2-dict.c b/pool/shard000/C/0015884_drmaa2-dict.c new file mode 100644 index 0000000000000000000000000000000000000000..1a3e4417122e4478e394af9c3e48fe09af5d46f5 --- /dev/null +++ b/pool/shard000/C/0015884_drmaa2-dict.c @@ -0,0 +1,137 @@ +#include "drmaa2-dict.h" +#include +#include +#include +#include + + + +drmaa2_dict drmaa2_dict_create(const drmaa2_dict_entryfree callback) { + drmaa2_dict d = (drmaa2_dict)malloc(sizeof(drmaa2_dict_s)); + d->free_entry = callback; + d->head = NULL; + return d; +} + + +void drmaa2_dict_free(drmaa2_dict * dRef) { + drmaa2_dict d = *dRef; + if (d == NULL) + return; + + drmaa2_dict_item head = d->head; + drmaa2_dict_item tmp; + while (head != NULL) { + tmp = head; + head = head->next; + if (d->free_entry != NULL) + d->free_entry((char **)&(tmp->key), (char **)&(tmp->value)); + free(tmp); + } + free(d); + *dRef = NULL; +} + + +drmaa2_string_list drmaa2_dict_list(const drmaa2_dict d) { + if (d == NULL) + return NULL; + + drmaa2_string_list sl = drmaa2_list_create(DRMAA2_STRINGLIST, (drmaa2_list_entryfree)drmaa2_string_free); + drmaa2_dict_item current_item = d->head; + while (current_item != NULL) { + drmaa2_list_add(sl, strdup(current_item->key)); + current_item = current_item->next; + } + return sl; +} + + +drmaa2_bool drmaa2_dict_has(const drmaa2_dict d, const char * key) { + if (d == NULL) + return DRMAA2_FALSE; + + drmaa2_dict_item current_item = d->head; + while (current_item != NULL) { + if (!strcmp(current_item->key, key)) + return DRMAA2_TRUE; // found + current_item = current_item->next; + } + return DRMAA2_FALSE; +} + + +const char *drmaa2_dict_get(const drmaa2_dict d, const char * key) { + if (d == NULL) + return NULL; + + drmaa2_dict_item current_item = d->head; + while (current_item != NULL) { + if (!strcmp(current_item->key, key)) + return current_item->value; // found -> return + current_item = current_item->next; + } + return NULL; +} + + +drmaa2_error drmaa2_dict_del(drmaa2_dict d, const char * key) { + if (d == NULL) + return DRMAA2_INVALID_ARGUMENT; + + drmaa2_dict_item current_item = d->head; + drmaa2_dict_item prev = NULL; + + while (current_item != NULL) { + if (!strcmp(current_item->key, key)) { + // found -> delete + if (prev) + prev->next = current_item->next; + else + d->head = current_item->next; + + if (d->free_entry != NULL) + d->free_entry((char **)&(current_item->key), (char **)&(current_item->value)); + free(current_item); + return DRMAA2_SUCCESS; + } + prev = current_item; + current_item = current_item->next; + } + return DRMAA2_INVALID_ARGUMENT; +} + +drmaa2_error drmaa2_dict_set(drmaa2_dict d, const char * key, const char * val) { + if (d == NULL) + return DRMAA2_INVALID_ARGUMENT; + + if (d->head == NULL) { + //empty dict + drmaa2_dict_item new = (drmaa2_dict_item)malloc(sizeof(drmaa2_dict_item_s)); + new->key = key; + new->value = val; + new->next = NULL; + d->head = new; + return DRMAA2_SUCCESS; + } + drmaa2_dict_item current_item = d->head; + drmaa2_dict_item prev = NULL; + while (current_item != NULL) { + if (!strcmp(current_item->key, key)) { + // found -> replace + if (d->free_entry != NULL) d->free_entry(NULL, (char **)&(current_item->value)); + current_item->value = val; + return DRMAA2_SUCCESS; + } + prev = current_item; + current_item = current_item->next; + } + drmaa2_dict_item new = (drmaa2_dict_item)malloc(sizeof(drmaa2_dict_item_s)); + new->key = key; + new->value = val; + new->next = NULL; + prev->next = new; + return DRMAA2_FALSE; +} + + diff --git a/pool/shard000/C/0015890_pig2i2c.c b/pool/shard000/C/0015890_pig2i2c.c new file mode 100644 index 0000000000000000000000000000000000000000..bf9102cf5cbacf9591657048cea3baf706c816ba --- /dev/null +++ b/pool/shard000/C/0015890_pig2i2c.c @@ -0,0 +1,205 @@ +/* +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "pigpio.h" + +/* +This software reads pigpio notification reports monitoring the I2C signals. + +Notifications are pipe based so this software must be run on the Pi +being monitored. + +It should be able to handle a 100kHz bus. You are unlikely to get any +usable results if the bus is running at 400kHz. + +gcc -o pig2i2c pig2i2c.c + +Do something like + +sudo pigpiod -s 2 + +# get a notification handle, assume handle 0 was returned + +pigs no + +# start notifications for SCL/SDA + +e.g. pigs nb 0 0x3 # Rev. 1 select gpios 0/1 +e.g. pigs nb 0 0xC # Rev. 2 select gpios 2/3 +e.g. pigs nb 0 0xA00 # select gpios 9/11 (1<<9|1<<11) + +# run the program, specifying SCL/SDA and notification pipe + +./pig2i2c SCL SDA
2) + { + gSCL = atoi(argv[1]); + gSDA = atoi(argv[2]); + + bSCL = 1<. + */ + +#include "../private.h" +#include "wsa_attributed_uri.h" +#include "../idwsf_strings.h" +#include "../../registry.h" + +/* + * Schema fragment (ws-addr.xsd): + * + * + * + * + * + * + * + * + */ + +/*****************************************************************************/ +/* private methods */ +/*****************************************************************************/ + + +static struct XmlSnippet schema_snippets[] = { + { "content", SNIPPET_TEXT_CHILD, + G_STRUCT_OFFSET(LassoWsAddrAttributedURI, content), NULL, NULL, NULL}, + { "attributes", SNIPPET_ATTRIBUTE | SNIPPET_ANY, + G_STRUCT_OFFSET(LassoWsAddrAttributedURI, attributes), NULL, NULL, NULL}, + {NULL, 0, 0, NULL, NULL, NULL} +}; + +static LassoNodeClass *parent_class = NULL; + + +/*****************************************************************************/ +/* instance and class init functions */ +/*****************************************************************************/ + +static void +instance_init(LassoWsAddrAttributedURI *node) +{ + node->attributes = g_hash_table_new_full( + g_str_hash, g_str_equal, g_free, g_free); +} + +static void +class_init(LassoWsAddrAttributedURIClass *klass) +{ + LassoNodeClass *nclass = LASSO_NODE_CLASS(klass); + + parent_class = g_type_class_peek_parent(klass); + nclass->node_data = g_new0(LassoNodeClassData, 1); + lasso_node_class_set_nodename(nclass, "AttributedURI"); + lasso_node_class_set_ns(nclass, LASSO_WSA_HREF, LASSO_WSA_PREFIX); + lasso_node_class_add_snippets(nclass, schema_snippets); +} + +GType +lasso_wsa_attributed_uri_get_type() +{ + static GType this_type = 0; + + if (!this_type) { + static const GTypeInfo this_info = { + sizeof (LassoWsAddrAttributedURIClass), + NULL, + NULL, + (GClassInitFunc) class_init, + NULL, + NULL, + sizeof(LassoWsAddrAttributedURI), + 0, + (GInstanceInitFunc) instance_init, + NULL + }; + + this_type = g_type_register_static(LASSO_TYPE_NODE, + "LassoWsAddrAttributedURI", &this_info, 0); + lasso_registry_default_add_direct_mapping(LASSO_WSA_HREF, "Action", + LASSO_LASSO_HREF, "LassoWsAddrAttributedURI"); + lasso_registry_default_add_direct_mapping(LASSO_WSA_HREF, "MessageID", + LASSO_LASSO_HREF, "LassoWsAddrAttributedURI"); + lasso_registry_default_add_direct_mapping(LASSO_WSA_HREF, "To", LASSO_LASSO_HREF, + "LassoWsAddrAttributedURI"); + } + return this_type; +} + +/** + * lasso_wsa_attributed_uri_new: + * + * Creates a new #LassoWsAddrAttributedURI object. + * + * Return value: a newly created #LassoWsAddrAttributedURI object + **/ +LassoWsAddrAttributedURI* +lasso_wsa_attributed_uri_new() +{ + return g_object_new(LASSO_TYPE_WSA_ATTRIBUTED_URI, NULL); +} + + +/** + * lasso_wsa_attributed_uri_new_with_string: + * @content: a content string + * + * Creates a new #LassoWsAddrAttributedURI object and initializes it + * with @content as content. + * + * Return value: a newly created #LassoWsAddrAttributedURI object + **/ +LassoWsAddrAttributedURI* +lasso_wsa_attributed_uri_new_with_string(const char *content) +{ + LassoWsAddrAttributedURI *object; + object = g_object_new(LASSO_TYPE_WSA_ATTRIBUTED_URI, NULL); + object->content = g_strdup(content); + return object; +} diff --git a/pool/shard000/C/0015900_orinoco_pci.c b/pool/shard000/C/0015900_orinoco_pci.c new file mode 100644 index 0000000000000000000000000000000000000000..bda5317cc596038c91f2e966c94c69185c9a1ac6 --- /dev/null +++ b/pool/shard000/C/0015900_orinoco_pci.c @@ -0,0 +1,265 @@ +/* orinoco_pci.c + * + * Driver for Prism 2.5/3 devices that have a direct PCI interface + * (i.e. these are not PCMCIA cards in a PCMCIA-to-PCI bridge). + * The card contains only one PCI region, which contains all the usual + * hermes registers, as well as the COR register. + * + * Current maintainers are: + * Pavel Roskin + * and David Gibson + * + * Some of this code is borrowed from orinoco_plx.c + * Copyright (C) 2001 Daniel Barlow + * Some of this code is "inspired" by linux-wlan-ng-0.1.10, but nothing + * has been copied from it. linux-wlan-ng-0.1.10 is originally : + * Copyright (C) 1999 AbsoluteValue Systems, Inc. All Rights Reserved. + * This file originally written by: + * Copyright (C) 2001 Jean Tourrilhes + * And is now maintained by: + * (C) Copyright David Gibson, IBM Corp. 2002-2003. + * + * 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. + * + * Alternatively, the contents of this file may be used under the + * terms of the GNU General Public License version 2 (the "GPL"), in + * which case the provisions of the GPL are applicable instead of the + * above. If you wish to allow the 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 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 either the MPL or the GPL. + */ + +#define DRIVER_NAME "orinoco_pci" +#define PFX DRIVER_NAME ": " + +#include +#include +#include +#include +#include + +#include "orinoco.h" +#include "orinoco_pci.h" + +/* Offset of the COR register of the PCI card */ +#define HERMES_PCI_COR (0x26) + +/* Bitmask to reset the card */ +#define HERMES_PCI_COR_MASK (0x0080) + +/* Magic timeouts for doing the reset. + * Those times are straight from wlan-ng, and it is claimed that they + * are necessary. Alan will kill me. Take your time and grab a coffee. */ +#define HERMES_PCI_COR_ONT (250) /* ms */ +#define HERMES_PCI_COR_OFFT (500) /* ms */ +#define HERMES_PCI_COR_BUSYT (500) /* ms */ + +/* + * Do a soft reset of the card using the Configuration Option Register + * We need this to get going... + * This is the part of the code that is strongly inspired from wlan-ng + * + * Note : This code is done with irq enabled. This mean that many + * interrupts will occur while we are there. This is why we use the + * jiffies to regulate time instead of a straight mdelay(). Usually we + * need only around 245 iteration of the loop to do 250 ms delay. + * + * Note bis : Don't try to access HERMES_CMD during the reset phase. + * It just won't work ! + */ +static int orinoco_pci_cor_reset(struct orinoco_private *priv) +{ + hermes_t *hw = &priv->hw; + unsigned long timeout; + u16 reg; + + /* Assert the reset until the card notices */ + hermes_write_regn(hw, PCI_COR, HERMES_PCI_COR_MASK); + mdelay(HERMES_PCI_COR_ONT); + + /* Give time for the card to recover from this hard effort */ + hermes_write_regn(hw, PCI_COR, 0x0000); + mdelay(HERMES_PCI_COR_OFFT); + + /* The card is ready when it's no longer busy */ + timeout = jiffies + (HERMES_PCI_COR_BUSYT * HZ / 1000); + reg = hermes_read_regn(hw, CMD); + while (time_before(jiffies, timeout) && (reg & HERMES_CMD_BUSY)) { + mdelay(1); + reg = hermes_read_regn(hw, CMD); + } + + /* Still busy? */ + if (reg & HERMES_CMD_BUSY) { + printk(KERN_ERR PFX "Busy timeout\n"); + return -ETIMEDOUT; + } + + return 0; +} + +static int orinoco_pci_init_one(struct pci_dev *pdev, + const struct pci_device_id *ent) +{ + int err; + struct orinoco_private *priv; + struct orinoco_pci_card *card; + void __iomem *hermes_io; + + err = pci_enable_device(pdev); + if (err) { + printk(KERN_ERR PFX "Cannot enable PCI device\n"); + return err; + } + + err = pci_request_regions(pdev, DRIVER_NAME); + if (err) { + printk(KERN_ERR PFX "Cannot obtain PCI resources\n"); + goto fail_resources; + } + + hermes_io = pci_iomap(pdev, 0, 0); + if (!hermes_io) { + printk(KERN_ERR PFX "Cannot remap chipset registers\n"); + err = -EIO; + goto fail_map_hermes; + } + + /* Allocate network device */ + priv = alloc_orinocodev(sizeof(*card), &pdev->dev, + orinoco_pci_cor_reset, NULL); + if (!priv) { + printk(KERN_ERR PFX "Cannot allocate network device\n"); + err = -ENOMEM; + goto fail_alloc; + } + + card = priv->card; + + hermes_struct_init(&priv->hw, hermes_io, HERMES_32BIT_REGSPACING); + + err = request_irq(pdev->irq, orinoco_interrupt, IRQF_SHARED, + DRIVER_NAME, priv); + if (err) { + printk(KERN_ERR PFX "Cannot allocate IRQ %d\n", pdev->irq); + err = -EBUSY; + goto fail_irq; + } + + err = orinoco_pci_cor_reset(priv); + if (err) { + printk(KERN_ERR PFX "Initial reset failed\n"); + goto fail; + } + + err = orinoco_init(priv); + if (err) { + printk(KERN_ERR PFX "orinoco_init() failed\n"); + goto fail; + } + + err = orinoco_if_add(priv, 0, 0); + if (err) { + printk(KERN_ERR PFX "orinoco_if_add() failed\n"); + goto fail; + } + + pci_set_drvdata(pdev, priv); + + return 0; + + fail: + free_irq(pdev->irq, priv); + + fail_irq: + pci_set_drvdata(pdev, NULL); + free_orinocodev(priv); + + fail_alloc: + pci_iounmap(pdev, hermes_io); + + fail_map_hermes: + pci_release_regions(pdev); + + fail_resources: + pci_disable_device(pdev); + + return err; +} + +static void __devexit orinoco_pci_remove_one(struct pci_dev *pdev) +{ + struct orinoco_private *priv = pci_get_drvdata(pdev); + + orinoco_if_del(priv); + free_irq(pdev->irq, priv); + pci_set_drvdata(pdev, NULL); + free_orinocodev(priv); + pci_iounmap(pdev, priv->hw.iobase); + pci_release_regions(pdev); + pci_disable_device(pdev); +} + +static DEFINE_PCI_DEVICE_TABLE(orinoco_pci_id_table) = { + /* Intersil Prism 3 */ + {0x1260, 0x3872, PCI_ANY_ID, PCI_ANY_ID,}, + /* Intersil Prism 2.5 */ + {0x1260, 0x3873, PCI_ANY_ID, PCI_ANY_ID,}, + /* Samsung MagicLAN SWL-2210P */ + {0x167d, 0xa000, PCI_ANY_ID, PCI_ANY_ID,}, + {0,}, +}; + +MODULE_DEVICE_TABLE(pci, orinoco_pci_id_table); + +static struct pci_driver orinoco_pci_driver = { + .name = DRIVER_NAME, + .id_table = orinoco_pci_id_table, + .probe = orinoco_pci_init_one, + .remove = __devexit_p(orinoco_pci_remove_one), + .suspend = orinoco_pci_suspend, + .resume = orinoco_pci_resume, +}; + +static char version[] __initdata = DRIVER_NAME " " DRIVER_VERSION + " (Pavel Roskin ," + " David Gibson &" + " Jean Tourrilhes )"; +MODULE_AUTHOR("Pavel Roskin &" + " David Gibson "); +MODULE_DESCRIPTION("Driver for wireless LAN cards using direct PCI interface"); +MODULE_LICENSE("Dual MPL/GPL"); + +static int __init orinoco_pci_init(void) +{ + printk(KERN_DEBUG "%s\n", version); + return pci_register_driver(&orinoco_pci_driver); +} + +static void __exit orinoco_pci_exit(void) +{ + pci_unregister_driver(&orinoco_pci_driver); +} + +module_init(orinoco_pci_init); +module_exit(orinoco_pci_exit); + +/* + * Local variables: + * c-indent-level: 8 + * c-basic-offset: 8 + * tab-width: 8 + * End: + */ diff --git a/pool/shard000/C/0015902_pwm-lpss-platform.c b/pool/shard000/C/0015902_pwm-lpss-platform.c new file mode 100644 index 0000000000000000000000000000000000000000..928570430cef7599b1e72c58e793dfef1b26f3dc --- /dev/null +++ b/pool/shard000/C/0015902_pwm-lpss-platform.c @@ -0,0 +1,113 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * Intel Low Power Subsystem PWM controller driver + * + * Copyright (C) 2014, Intel Corporation + * + * Derived from the original pwm-lpss.c + */ + +#include +#include +#include +#include +#include + +#include "pwm-lpss.h" + +/* BayTrail */ +static const struct pwm_lpss_boardinfo pwm_lpss_byt_info = { + .clk_rate = 25000000, + .npwm = 1, + .base_unit_bits = 16, +}; + +/* Braswell */ +static const struct pwm_lpss_boardinfo pwm_lpss_bsw_info = { + .clk_rate = 19200000, + .npwm = 1, + .base_unit_bits = 16, + .other_devices_aml_touches_pwm_regs = true, +}; + +/* Broxton */ +static const struct pwm_lpss_boardinfo pwm_lpss_bxt_info = { + .clk_rate = 19200000, + .npwm = 4, + .base_unit_bits = 22, + .bypass = true, +}; + +static int pwm_lpss_probe_platform(struct platform_device *pdev) +{ + const struct pwm_lpss_boardinfo *info; + const struct acpi_device_id *id; + struct pwm_lpss_chip *lpwm; + struct resource *r; + + id = acpi_match_device(pdev->dev.driver->acpi_match_table, &pdev->dev); + if (!id) + return -ENODEV; + + info = (const struct pwm_lpss_boardinfo *)id->driver_data; + r = platform_get_resource(pdev, IORESOURCE_MEM, 0); + + lpwm = pwm_lpss_probe(&pdev->dev, r, info); + if (IS_ERR(lpwm)) + return PTR_ERR(lpwm); + + platform_set_drvdata(pdev, lpwm); + + /* + * On Cherry Trail devices the GFX0._PS0 AML checks if the controller + * is on and if it is not on it turns it on and restores what it + * believes is the correct state to the PWM controller. + * Because of this we must disallow direct-complete, which keeps the + * controller (runtime)suspended on resume, to avoid 2 issues: + * 1. The controller getting turned on without the linux-pm code + * knowing about this. On devices where the controller is unused + * this causes it to stay on during the next suspend causing high + * battery drain (because S0i3 is not reached) + * 2. The state restoring code unexpectedly messing with the controller + * + * Leaving the controller runtime-suspended (skipping runtime-resume + + * normal-suspend) during suspend is fine. + */ + if (info->other_devices_aml_touches_pwm_regs) + dev_pm_set_driver_flags(&pdev->dev, DPM_FLAG_NO_DIRECT_COMPLETE| + DPM_FLAG_SMART_SUSPEND); + + pm_runtime_set_active(&pdev->dev); + pm_runtime_enable(&pdev->dev); + + return 0; +} + +static int pwm_lpss_remove_platform(struct platform_device *pdev) +{ + pm_runtime_disable(&pdev->dev); + return 0; +} + +static const struct acpi_device_id pwm_lpss_acpi_match[] = { + { "80860F09", (unsigned long)&pwm_lpss_byt_info }, + { "80862288", (unsigned long)&pwm_lpss_bsw_info }, + { "80862289", (unsigned long)&pwm_lpss_bsw_info }, + { "80865AC8", (unsigned long)&pwm_lpss_bxt_info }, + { }, +}; +MODULE_DEVICE_TABLE(acpi, pwm_lpss_acpi_match); + +static struct platform_driver pwm_lpss_driver_platform = { + .driver = { + .name = "pwm-lpss", + .acpi_match_table = pwm_lpss_acpi_match, + }, + .probe = pwm_lpss_probe_platform, + .remove = pwm_lpss_remove_platform, +}; +module_platform_driver(pwm_lpss_driver_platform); + +MODULE_DESCRIPTION("PWM platform driver for Intel LPSS"); +MODULE_LICENSE("GPL v2"); +MODULE_ALIAS("platform:pwm-lpss"); diff --git a/pool/shard000/C/0015903_aes4000.c b/pool/shard000/C/0015903_aes4000.c new file mode 100644 index 0000000000000000000000000000000000000000..6ff32a270988e268f513dbbdbeca17f040de6068 --- /dev/null +++ b/pool/shard000/C/0015903_aes4000.c @@ -0,0 +1,272 @@ +/* + * AuthenTec AES4000 driver for libfprint + * Copyright (C) 2007-2008 Daniel Drake + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#define FP_COMPONENT "aes4000" + +#include + +#include +#include + +#include +#include + +#include "driver_ids.h" + +#define CTRL_TIMEOUT 1000 +#define EP_IN (1 | LIBUSB_ENDPOINT_IN) +#define EP_OUT (2 | LIBUSB_ENDPOINT_OUT) +#define DATA_BUFLEN 0x1259 +#define NR_SUBARRAYS 6 +#define SUBARRAY_LEN 768 + +#define IMG_HEIGHT 96 +#define IMG_WIDTH 96 +#define ENLARGE_FACTOR 3 + +struct aes4k_dev { + struct libusb_transfer *img_trf; +}; + +static const struct aes_regwrite init_reqs[] = { + /* master reset */ + { 0x80, 0x01 }, + { 0, 0 }, + { 0x80, 0x00 }, + { 0, 0 }, + + { 0x81, 0x00 }, + { 0x80, 0x00 }, + { 0, 0 }, + + /* scan reset */ + { 0x80, 0x02 }, + { 0, 0 }, + { 0x80, 0x00 }, + { 0, 0 }, + + /* disable register buffering */ + { 0x80, 0x04 }, + { 0, 0 }, + { 0x80, 0x00 }, + { 0, 0 }, + + { 0x81, 0x00 }, + { 0, 0 }, + /* windows driver reads registers now (81 02) */ + { 0x80, 0x00 }, + { 0x81, 0x00 }, + + /* set excitation bias current: 2mhz drive ring frequency, + * 4V drive ring voltage, 16.5mA excitation bias */ + { 0x82, 0x04 }, + + /* continuously sample drive ring for finger detection, + * 62.50ms debounce delay */ + { 0x83, 0x13 }, + + { 0x84, 0x07 }, /* set calibration resistance to 12 kiloohms */ + { 0x85, 0x3d }, /* set calibration capacitance */ + { 0x86, 0x03 }, /* detect drive voltage */ + { 0x87, 0x01 }, /* set detection frequency to 125khz */ + { 0x88, 0x02 }, /* set column scan period */ + { 0x89, 0x02 }, /* set measure drive */ + { 0x8a, 0x33 }, /* set measure frequency and sense amplifier bias */ + { 0x8b, 0x33 }, /* set matrix pattern */ + { 0x8c, 0x0f }, /* set demodulation phase 1 */ + { 0x8d, 0x04 }, /* set demodulation phase 2 */ + { 0x8e, 0x23 }, /* set sensor gain */ + { 0x8f, 0x07 }, /* set image parameters */ + { 0x90, 0x00 }, /* carrier offset null */ + { 0x91, 0x1c }, /* set A/D reference high */ + { 0x92, 0x08 }, /* set A/D reference low */ + { 0x93, 0x00 }, /* set start row to 0 */ + { 0x94, 0x05 }, /* set end row to 5 */ + { 0x95, 0x00 }, /* set start column to 0 */ + { 0x96, 0x18 }, /* set end column to 24*4=96 */ + { 0x97, 0x04 }, /* data format and thresholds */ + { 0x98, 0x28 }, /* image data control */ + { 0x99, 0x00 }, /* disable general purpose outputs */ + { 0x9a, 0x0b }, /* set initial scan state */ + { 0x9b, 0x00 }, /* clear challenge word bits */ + { 0x9c, 0x00 }, /* clear challenge word bits */ + { 0x9d, 0x09 }, /* set some challenge word bits */ + { 0x9e, 0x53 }, /* clear challenge word bits */ + { 0x9f, 0x6b }, /* set some challenge word bits */ + { 0, 0 }, + + { 0x80, 0x00 }, + { 0x81, 0x00 }, + { 0, 0 }, + { 0x81, 0x04 }, + { 0, 0 }, + { 0x81, 0x00 }, +}; + +static void do_capture(struct fp_img_dev *dev); + +static void img_cb(struct libusb_transfer *transfer) +{ + struct fp_img_dev *dev = transfer->user_data; + struct aes4k_dev *aesdev = dev->priv; + unsigned char *ptr = transfer->buffer; + struct fp_img *tmp; + struct fp_img *img; + int i; + + if (transfer->status == LIBUSB_TRANSFER_CANCELLED) { + goto err; + } else if (transfer->status != LIBUSB_TRANSFER_COMPLETED) { + fpi_imgdev_session_error(dev, -EIO); + goto err; + } else if (transfer->length != transfer->actual_length) { + fpi_imgdev_session_error(dev, -EPROTO); + goto err; + } + + fpi_imgdev_report_finger_status(dev, TRUE); + + tmp = fpi_img_new(IMG_WIDTH * IMG_HEIGHT); + tmp->width = IMG_WIDTH; + tmp->height = IMG_HEIGHT; + tmp->flags = FP_IMG_COLORS_INVERTED | FP_IMG_V_FLIPPED | FP_IMG_H_FLIPPED; + for (i = 0; i < NR_SUBARRAYS; i++) { + fp_dbg("subarray header byte %02x", *ptr); + ptr++; + aes_assemble_image(ptr, 96, 16, tmp->data + (i * 96 * 16)); + ptr += SUBARRAY_LEN; + } + + /* FIXME: this is an ugly hack to make the image big enough for NBIS + * to process reliably */ + img = fpi_im_resize(tmp, ENLARGE_FACTOR, ENLARGE_FACTOR); + fp_img_free(tmp); + fpi_imgdev_image_captured(dev, img); + + /* FIXME: rather than assuming finger has gone, we should poll regs until + * it really has, then restart the capture */ + fpi_imgdev_report_finger_status(dev, FALSE); + + do_capture(dev); + +err: + g_free(transfer->buffer); + aesdev->img_trf = NULL; + libusb_free_transfer(transfer); +} + +static void do_capture(struct fp_img_dev *dev) +{ + struct aes4k_dev *aesdev = dev->priv; + unsigned char *data; + int r; + + aesdev->img_trf = libusb_alloc_transfer(0); + if (!aesdev->img_trf) { + fpi_imgdev_session_error(dev, -EIO); + return; + } + + data = g_malloc(DATA_BUFLEN); + libusb_fill_bulk_transfer(aesdev->img_trf, dev->udev, EP_IN, data, + DATA_BUFLEN, img_cb, dev, 0); + + r = libusb_submit_transfer(aesdev->img_trf); + if (r < 0) { + g_free(data); + libusb_free_transfer(aesdev->img_trf); + aesdev->img_trf = NULL; + fpi_imgdev_session_error(dev, r); + } +} + +static void init_reqs_cb(struct fp_img_dev *dev, int result, void *user_data) +{ + fpi_imgdev_activate_complete(dev, result); + if (result == 0) + do_capture(dev); +} + +static int dev_activate(struct fp_img_dev *dev, enum fp_imgdev_state state) +{ + aes_write_regv(dev, init_reqs, G_N_ELEMENTS(init_reqs), init_reqs_cb, NULL); + return 0; +} + +static void dev_deactivate(struct fp_img_dev *dev) +{ + struct aes4k_dev *aesdev = dev->priv; + + /* FIXME: should wait for cancellation to complete before returning + * from deactivation, otherwise app may legally exit before we've + * cleaned up */ + if (aesdev->img_trf) + libusb_cancel_transfer(aesdev->img_trf); + fpi_imgdev_deactivate_complete(dev); +} + +static int dev_init(struct fp_img_dev *dev, unsigned long driver_data) +{ + int r; + + r = libusb_claim_interface(dev->udev, 0); + if (r < 0) + fp_err("could not claim interface 0"); + + dev->priv = g_malloc0(sizeof(struct aes4k_dev)); + + if (r == 0) + fpi_imgdev_open_complete(dev, 0); + + return r; +} + +static void dev_deinit(struct fp_img_dev *dev) +{ + g_free(dev->priv); + libusb_release_interface(dev->udev, 0); + fpi_imgdev_close_complete(dev); +} + +static const struct usb_id id_table[] = { + { .vendor = 0x08ff, .product = 0x5501 }, + { 0, 0, 0, }, +}; + +struct fp_img_driver aes4000_driver = { + .driver = { + .id = AES4000_ID, + .name = FP_COMPONENT, + .full_name = "AuthenTec AES4000", + .id_table = id_table, + .scan_type = FP_SCAN_TYPE_PRESS, + }, + .flags = 0, + .img_height = IMG_HEIGHT * ENLARGE_FACTOR, + .img_width = IMG_WIDTH * ENLARGE_FACTOR, + + /* temporarily lowered until image quality improves */ + .bz3_threshold = 9, + + .open = dev_init, + .close = dev_deinit, + .activate = dev_activate, + .deactivate = dev_deactivate, +}; + diff --git a/pool/shard000/C/0015911_pm.c b/pool/shard000/C/0015911_pm.c new file mode 100644 index 0000000000000000000000000000000000000000..388463b9909074ed2869c855d04ed78be0724a9e --- /dev/null +++ b/pool/shard000/C/0015911_pm.c @@ -0,0 +1,118 @@ +/* + * PXA250/210 Power Management Routines + * + * Original code for the SA11x0: + * Copyright (c) 2001 Cliff Brake + * + * Modified for the PXA250 by Nicolas Pitre: + * Copyright (c) 2002 Monta Vista Software, Inc. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License. + */ +#include +#include +#include +#include +#include + +#include "pm.h" + +struct pxa_cpu_pm_fns *pxa_cpu_pm_fns; +static unsigned long *sleep_save; + +int pxa_pm_enter(suspend_state_t state) +{ + unsigned long sleep_save_checksum = 0, checksum = 0; + int i; + +#ifdef CONFIG_IWMMXT + /* force any iWMMXt context to ram **/ + if (elf_hwcap & HWCAP_IWMMXT) + iwmmxt_task_disable(NULL); +#endif + + /* skip registers saving for standby */ + if (state != PM_SUSPEND_STANDBY && pxa_cpu_pm_fns->save) { + pxa_cpu_pm_fns->save(sleep_save); + /* before sleeping, calculate and save a checksum */ + for (i = 0; i < pxa_cpu_pm_fns->save_count - 1; i++) + sleep_save_checksum += sleep_save[i]; + } + + /* *** go zzz *** */ + pxa_cpu_pm_fns->enter(state); + + if (state != PM_SUSPEND_STANDBY && pxa_cpu_pm_fns->restore) { + /* after sleeping, validate the checksum */ + for (i = 0; i < pxa_cpu_pm_fns->save_count - 1; i++) + checksum += sleep_save[i]; + + /* if invalid, display message and wait for a hardware reset */ + if (checksum != sleep_save_checksum) { + + lubbock_set_hexled(0xbadbadc5); + + while (1) + pxa_cpu_pm_fns->enter(state); + } + pxa_cpu_pm_fns->restore(sleep_save); + } + + pr_debug("*** made it back from resume\n"); + + return 0; +} + +EXPORT_SYMBOL_GPL(pxa_pm_enter); + +static int pxa_pm_valid(suspend_state_t state) +{ + if (pxa_cpu_pm_fns) + return pxa_cpu_pm_fns->valid(state); + + return -EINVAL; +} + +int pxa_pm_prepare(void) +{ + int ret = 0; + + if (pxa_cpu_pm_fns && pxa_cpu_pm_fns->prepare) + ret = pxa_cpu_pm_fns->prepare(); + + return ret; +} + +void pxa_pm_finish(void) +{ + if (pxa_cpu_pm_fns && pxa_cpu_pm_fns->finish) + pxa_cpu_pm_fns->finish(); +} + +static const struct platform_suspend_ops pxa_pm_ops = { + .valid = pxa_pm_valid, + .enter = pxa_pm_enter, + .prepare = pxa_pm_prepare, + .finish = pxa_pm_finish, +}; + +static int __init pxa_pm_init(void) +{ + if (!pxa_cpu_pm_fns) { + printk(KERN_ERR "no valid pxa_cpu_pm_fns defined\n"); + return -EINVAL; + } + + sleep_save = kmalloc(pxa_cpu_pm_fns->save_count * sizeof(unsigned long), + GFP_KERNEL); + if (!sleep_save) { + printk(KERN_ERR "failed to alloc memory for pm save\n"); + return -ENOMEM; + } + + suspend_set_ops(&pxa_pm_ops); + return 0; +} + +device_initcall(pxa_pm_init); diff --git a/pool/shard000/C/0015917_lakcm_p4.c b/pool/shard000/C/0015917_lakcm_p4.c new file mode 100644 index 0000000000000000000000000000000000000000..f60e75183ceb4f07536b31b248da4ae8cb88912e --- /dev/null +++ b/pool/shard000/C/0015917_lakcm_p4.c @@ -0,0 +1,270 @@ +/* $Id: lakcm_p4.c,v 1.2 2004/10/31 23:47:04 smilcke Exp $ */ + +/* + * lakcm_p4.c + * Autor: Stefan Milcke + * Erstellt am: 21.07.2004 + * Letzte Aenderung am: 07.10.2004 + * +*/ + +#include + +/* + * P4 specific Machine Check Exception Reporting + */ + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "mce.h" + +/* as supported by the P4/Xeon family */ +struct intel_mce_extended_msrs { + u32 eax; + u32 ebx; + u32 ecx; + u32 edx; + u32 esi; + u32 edi; + u32 ebp; + u32 esp; + u32 eflags; + u32 eip; + /* u32 *reserved[]; */ +}; + +static int mce_num_extended_msrs = 0; + + +#ifdef CONFIG_X86_MCE_P4THERMAL +static void unexpected_thermal_interrupt(struct pt_regs *regs) +{ + printk(KERN_ERR "CPU#%d: Unexpected LVT TMR interrupt!\n", smp_processor_id()); +} + +/* P4/Xeon Thermal transition interrupt handler */ +static void intel_thermal_interrupt(struct pt_regs *regs) +{ + u32 l, h; + unsigned int cpu = smp_processor_id(); + + ack_APIC_irq(); + + rdmsr (MSR_IA32_THERM_STATUS, l, h); + if (l & 1) { + printk(KERN_EMERG "CPU#%d: Temperature above threshold\n", cpu); + printk(KERN_EMERG "CPU#%d: Running in modulated clock mode\n", cpu); + } else { + printk(KERN_INFO "CPU#%d: Temperature/speed normal\n", cpu); + } +} + +/* Thermal interrupt handler for this CPU setup */ +static void (*vendor_thermal_interrupt)(struct pt_regs *regs) = unexpected_thermal_interrupt; + +asmlinkage void smp_thermal_interrupt(struct pt_regs regs) +{ + irq_enter(); + vendor_thermal_interrupt(®s); + irq_exit(); +} + +/* P4/Xeon Thermal regulation detect and init */ +static void __init intel_init_thermal(struct cpuinfo_x86 *c) +{ + u32 l, h; + unsigned int cpu = smp_processor_id(); + + /* Thermal monitoring */ + if (!cpu_has(c, X86_FEATURE_ACPI)) + return; /* -ENODEV */ + + /* Clock modulation */ + if (!cpu_has(c, X86_FEATURE_ACC)) + return; /* -ENODEV */ + + /* first check if its enabled already, in which case there might + * be some SMM goo which handles it, so we can't even put a handler + * since it might be delivered via SMI already -zwanem. + */ + rdmsr (MSR_IA32_MISC_ENABLE, l, h); + h = apic_read(APIC_LVTTHMR); + if ((l & (1<<3)) && (h & APIC_DM_SMI)) { + printk(KERN_DEBUG "CPU#%d: Thermal monitoring handled by SMI\n", cpu); + return; /* -EBUSY */ + } + + /* check whether a vector already exists, temporarily masked? */ + if (h & APIC_VECTOR_MASK) { + printk(KERN_DEBUG "CPU#%d: Thermal LVT vector (%#x) already installed\n", + cpu, (h & APIC_VECTOR_MASK)); + return; /* -EBUSY */ + } + + /* The temperature transition interrupt handler setup */ + h = THERMAL_APIC_VECTOR; /* our delivery vector */ + h |= (APIC_DM_FIXED | APIC_LVT_MASKED); /* we'll mask till we're ready */ + apic_write_around(APIC_LVTTHMR, h); + + rdmsr (MSR_IA32_THERM_INTERRUPT, l, h); + wrmsr (MSR_IA32_THERM_INTERRUPT, l | 0x03 , h); + + /* ok we're good to go... */ + vendor_thermal_interrupt = intel_thermal_interrupt; + + rdmsr (MSR_IA32_MISC_ENABLE, l, h); + wrmsr (MSR_IA32_MISC_ENABLE, l | (1<<3), h); + + l = apic_read (APIC_LVTTHMR); + apic_write_around (APIC_LVTTHMR, l & ~APIC_LVT_MASKED); + printk (KERN_INFO "CPU#%d: Thermal monitoring enabled\n", cpu); + return; +} +#endif /* CONFIG_X86_MCE_P4THERMAL */ + + +/* P4/Xeon Extended MCE MSR retrieval, return 0 if unsupported */ +static inline int intel_get_extended_msrs(struct intel_mce_extended_msrs *r) +{ + u32 h; + + if (mce_num_extended_msrs == 0) + goto done; + + rdmsr (MSR_IA32_MCG_EAX, r->eax, h); + rdmsr (MSR_IA32_MCG_EBX, r->ebx, h); + rdmsr (MSR_IA32_MCG_ECX, r->ecx, h); + rdmsr (MSR_IA32_MCG_EDX, r->edx, h); + rdmsr (MSR_IA32_MCG_ESI, r->esi, h); + rdmsr (MSR_IA32_MCG_EDI, r->edi, h); + rdmsr (MSR_IA32_MCG_EBP, r->ebp, h); + rdmsr (MSR_IA32_MCG_ESP, r->esp, h); + rdmsr (MSR_IA32_MCG_EFLAGS, r->eflags, h); + rdmsr (MSR_IA32_MCG_EIP, r->eip, h); + + /* can we rely on kmalloc to do a dynamic + * allocation for the reserved registers? + */ +done: + return mce_num_extended_msrs; +} + +static asmlinkage void intel_machine_check(struct pt_regs * regs, long error_code) +{ + int recover=1; + u32 alow, ahigh, high, low; + u32 mcgstl, mcgsth; + int i; + struct intel_mce_extended_msrs dbg; + + rdmsr (MSR_IA32_MCG_STATUS, mcgstl, mcgsth); + if (mcgstl & (1<<0)) /* Recoverable ? */ + recover=0; + + printk (KERN_EMERG "CPU %d: Machine Check Exception: %08x%08x\n", + smp_processor_id(), mcgsth, mcgstl); + + if (intel_get_extended_msrs(&dbg)) { + printk (KERN_DEBUG "CPU %d: EIP: %08x EFLAGS: %08x\n", + smp_processor_id(), dbg.eip, dbg.eflags); + printk (KERN_DEBUG "\teax: %08x ebx: %08x ecx: %08x edx: %08x\n", + dbg.eax, dbg.ebx, dbg.ecx, dbg.edx); + printk (KERN_DEBUG "\tesi: %08x edi: %08x ebp: %08x esp: %08x\n", + dbg.esi, dbg.edi, dbg.ebp, dbg.esp); + } + + for (i=0; i> 16) & 0xff; + printk (KERN_INFO "CPU#%d: Intel P4/Xeon Extended MCE MSRs (%d) available\n", + smp_processor_id(), mce_num_extended_msrs); + +#ifdef CONFIG_X86_MCE_P4THERMAL + /* Check for P4/Xeon Thermal monitor */ + intel_init_thermal(c); +#endif + } +} diff --git a/pool/shard000/C/0015921_tst-writev.c b/pool/shard000/C/0015921_tst-writev.c new file mode 100644 index 0000000000000000000000000000000000000000..bda2b3fe74c66c2cee584fb991aef406a523a3ea --- /dev/null +++ b/pool/shard000/C/0015921_tst-writev.c @@ -0,0 +1,117 @@ +/* Copyright (C) 2011-2017 Free Software Foundation, Inc. + This file is part of the GNU C Library. + Contributed by Ryan S. Arnold , 2011. + + The GNU C Library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + The GNU C Library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with the GNU C Library; if not, see + . */ + +#include +#include +#include +#include +#include +#include +#include +#include + + +/* The purpose of this test is to verify that the INTERNAL_[V]SYSCALL_NCS + macros on 64-bit platforms don't cast the return type to (int) which would + erroneously sign extend the return value should the high bit of the bottom + half of the word be '1'. */ + +#if 0 +/* Used to test the non power-of-2 code path. */ +#undef IOV_MAX +#define IOV_MAX 1000 +#endif + +/* writev() should report that it has written EXPECTED number of bytes. */ +#define EXPECTED ((size_t) INT32_MAX + 1) + +static int +do_test (void) +{ + struct iovec iv[IOV_MAX]; + /* POSIX doesn't guarantee that IOV_MAX is pow of 2 but we're optimistic. */ + size_t bufsz = EXPECTED / IOV_MAX; + size_t bufrem = EXPECTED % IOV_MAX; + + /* If there's a remainder then IOV_MAX probably isn't a power of 2 and we + need to make bufsz bigger so that the last iovec, iv[IOV_MAX-1], is free + for the remainder. */ + if (bufrem) + { + bufsz = bufsz + 1; + bufrem = EXPECTED - (bufsz * (IOV_MAX - 1)); + } + + /* We writev to /dev/null since we're just testing writev's return value. */ + int fd = open (_PATH_DEVNULL, O_WRONLY); + if (fd == -1) + { + printf ("Unable to open /dev/null for writing.\n"); + return -1; + } + + iv[0].iov_base = malloc (bufsz); + if (iv[0].iov_base == NULL) + { + printf ("malloc (%zu) failed.\n", bufsz); + close (fd); + return -1; + } + iv[0].iov_len = bufsz; + + /* We optimistically presume that there isn't a remainder and set all iovec + instances to the same base and len as the first instance. */ + for (int i = 1; i < IOV_MAX; i++) + { + /* We don't care what the data is so reuse the allocation from iv[0]; */ + iv[i].iov_base = iv[0].iov_base; + iv[i].iov_len = iv[0].iov_len; + } + + /* If there is a remainder then we correct the last iov_len. */ + if (bufrem) + iv[IOV_MAX - 1].iov_len = bufrem; + + /* Write junk to /dev/null with the writev syscall in order to get a return + of INT32_MAX+1 bytes to verify that the INTERNAL_SYSCALL wrappers aren't + mangling the result if the signbit of a 32-bit number is set. */ + ssize_t ret = writev (fd, iv, IOV_MAX); + + free (iv[0].iov_base); + close (fd); + + if (ret != (ssize_t) EXPECTED) + { +#ifdef ARTIFICIAL_LIMIT + if (ret != (ssize_t) ARTIFICIAL_LIMIT) +#endif + { + printf ("writev() return value: %zd != EXPECTED: %zd\n", + ret, EXPECTED); + return 1; + } + } + + return 0; +} + +/* Time enough for a large writev syscall to complete. */ +#define TIMEOUT 20 + +#define TEST_FUNCTION do_test () +#include "../test-skeleton.c" diff --git a/pool/shard000/C/0015923_ip6_server.c b/pool/shard000/C/0015923_ip6_server.c new file mode 100644 index 0000000000000000000000000000000000000000..2f2790b04ae2d4fe9b323afd87601f62113f9474 --- /dev/null +++ b/pool/shard000/C/0015923_ip6_server.c @@ -0,0 +1,78 @@ +/* + * use ipv6 for a test + */ + + +#include +#include +#include +#include + +#include +#include + + +int +main(int argc, char *argv[]) +{ + struct sockaddr_in6 serv_addr, cli_addr; + int sockfd, clifd; + socklen_t addr_len; + int str_len; + char buf[1024]; + + if (argc != 2) { + fprintf(stderr, "Usage: %s \n", argv[0]); + exit(EXIT_FAILURE); + } + + + sockfd = socket(AF_INET6, SOCK_STREAM, 0); + if (sockfd == -1) { + perror("socket() failed"); + exit(EXIT_FAILURE); + } + + memset(&serv_addr, 0, sizeof(serv_addr)); + serv_addr.sin6_family = AF_INET6; + serv_addr.sin6_addr = in6addr_any; + serv_addr.sin6_port = htons(atoi(argv[1])); + + if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) == -1) { + perror("bind() failed"); + exit(EXIT_FAILURE); + } + + if (listen(sockfd, 5) == -1) { + perror("listen() failed"); + exit(EXIT_FAILURE); + } + + addr_len = sizeof(cli_addr); + while (1) { + clifd = accept(sockfd, (struct sockaddr *) &cli_addr, &addr_len); + if (clifd == -1) { + perror("accept() failed"); + continue; + } + + char str[INET6_ADDRSTRLEN]; + if (inet_ntop(AF_INET6, &cli_addr.sin6_addr, str, sizeof(str)) == NULL) { + fprintf(stderr, "inet_ntop() failed\n"); + } else { + printf("client connect, ip = %s, port = %d\n", + str, cli_addr.sin6_port); + } + + str_len = read(clifd, buf, sizeof(buf) - 1); + buf[str_len] = '\0'; + write(clifd, buf, str_len); + + close(clifd); + } + close(sockfd); + + return 0; +} + + diff --git a/pool/shard000/C/0015925_zmodexp512.c b/pool/shard000/C/0015925_zmodexp512.c new file mode 100644 index 0000000000000000000000000000000000000000..ceb64b7534955dff32852f71735040a77df4eaa5 --- /dev/null +++ b/pool/shard000/C/0015925_zmodexp512.c @@ -0,0 +1,44 @@ +#include "zmodexp.h" + +static const uint32 one[16] = +{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + +#define M (t->m) +#define X (t->x) +#define R (t->r) + +void zmodexp512(const uint32 m32[16],uint32 r32[16],unsigned char *e,unsigned int elen,zmodexp512_tmp *t) +{ + int i; + + zmodexp512_init(&M,m32); + zmodexp512_load(&M,&R[0],one); + zmodexp512_load(&M,&R[1],r32); + R[2] = R[1]; zmodexp512_square(&M,&R[2]); + for (i = 3;i <= 15;i += 2) { + R[i] = R[i - 2]; + zmodexp512_multiply(&M,&R[i],&R[2]); + } + for (i = 4;i <= 14;i += 2) { + R[i] = R[i / 2]; + zmodexp512_square(&M,&R[i]); + } + + X = R[0]; + while (elen > 0) { + --elen; + + zmodexp512_square(&M,&X); + zmodexp512_square(&M,&X); + zmodexp512_square(&M,&X); + zmodexp512_square(&M,&X); + zmodexp512_multiply(&M,&X,&R[e[elen] >> 4]); + zmodexp512_square(&M,&X); + zmodexp512_square(&M,&X); + zmodexp512_square(&M,&X); + zmodexp512_square(&M,&X); + zmodexp512_multiply(&M,&X,&R[e[elen] & 15]); + } + + zmodexp512_store(&M,&X,r32); +} diff --git a/pool/shard000/C/0015932_streams_source.c b/pool/shard000/C/0015932_streams_source.c new file mode 100644 index 0000000000000000000000000000000000000000..272d453a1a448ea23523736beaaf6e5f2c0373f3 --- /dev/null +++ b/pool/shard000/C/0015932_streams_source.c @@ -0,0 +1,329 @@ +/********************************************************************* + * Copyright (C) 2015, International Business Machines Corporation + * All Rights Reserved + ********************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "init.h" +#include "rxtx.h" +#include "config.h" + +#include "streams_source.h" + +#define ARGN 7 + +// TODO : make the port# use the interface name + +pthread_mutex_t mutexInit = PTHREAD_MUTEX_INITIALIZER; + +int32_t dpdkInitComplete = 0; +int32_t numOperators = 0; +int32_t firstInitComplete = 0; +int32_t numOperatorsReady = 0; + +// Assume maximum of 4 digits+comma +#define MAX_CORESTRING RTE_MAX_LCORE*5+1 +char lcoreList[MAX_CORESTRING] = ""; + +/* + * This is the entry point for the spin loop that is started on each lcore + * for ingesting packet data from the DPDK libraries. + */ +static int main_loop(__attribute__((unused)) void *arg) { + struct lcore_conf *conf; + unsigned lcore_id; + + lcore_id = rte_lcore_id(); + conf = &lcore_conf_[lcore_id]; + if (conf->num_rx_queue > 0) { + receive_loop(conf); + } + + return 0; +} + +/* + * This function is called by each Streams PacketDPDKSource operator in its constructor. + * There is no architectural requirement that the constructors run serially or in any specific + * order, so this code uses a mutex to do some basic initialization once on the first call. + * The remaining calls all update operator specific data structures. Note that by implementation + * the Streams runtime does serialize the operator constructors. + * + * lcore : Logical core number (hardware thread) on which to run. + * + * callback : Pointer to the Streams operator function to call for packet processing. + * + * user : Pointer to the this pointer of the Streams operator. + * + * Return Values: 0 on success, -1 on failure. + * + */ +int streams_operator_init(int lcoreMaster, int lcore, int nicPort, int nicQueue, + int promiscuous, streams_packet_cb_t dpdkCallback, void *user) { + + pthread_mutex_lock(&mutexInit); + printf("STREAMS_SOURCE: streams_operator_init starting.\n"); + + if(firstInitComplete == 0) { + // Initialize data structures. + coreMaster_ = -1; + numQueues_ = 0; + maxPort_ = -1; + numOperators = 0; + + int lcore_id; + for(lcore_id = 0; lcore_id < RTE_MAX_LCORE; lcore_id++) { + lcore_conf_[lcore_id].num_rx_queue = 0; + lcore_conf_[lcore_id].socket_id = 0; + lcore_conf_[lcore_id].num_frames = 0; + lcore_conf_[lcore_id].ring = NULL; + + int port; + for(port = 0; port < MAX_PORTS; port++) { + lcore_conf_[lcore_id].tx_queue_id[port] = 0; + } + + int rxq; + for(rxq = 0; rxq < MAX_RX_QUEUE_PER_LCORE; rxq++) { + lcore_conf_[lcore_id].rx_queue_list[rxq].port_id = 0; + lcore_conf_[lcore_id].rx_queue_list[rxq].queue_id = 0; + lcore_conf_[lcore_id].rx_queue_list[rxq].userData = NULL; + lcore_conf_[lcore_id].rx_queue_list[rxq].packetCallbackFunction = NULL; + } + } + + int port_id; + for(port_id = 0; port_id < MAX_PORTS; port_id++) { + port_info_[port_id].promiscuous = 0; + } + + // Add the lcore for this operator to the lcore list. + sprintf(lcoreList, "%d", lcore); + + firstInitComplete = 1; + } else { + // Add the lcore for this operator to the lcore list. + char coreStr[6]; + snprintf(coreStr, 6, ",%d", lcore); + strcat(lcoreList, coreStr); + } + + if((coreMaster_ == -1) && (lcoreMaster >= 0)) { + // If no lcore master has been set by any operator, and this one has set a + // value, use it. + coreMaster_ = lcoreMaster; + char coreStr[6]; + snprintf(coreStr, 6, ",%d", lcoreMaster); + strcat(lcoreList, coreStr); + printf("STREAMS_SOURCE: streams_operator_init: coreMaster set to lcore %d.\n", + coreMaster_); + } else if((coreMaster_ != lcoreMaster) && (lcoreMaster >= 0)) { + // The lcore master has been set and this operator has specified a value. + // Do not use the new value, but log a warning. + printf("STREAMS_SOURCE: streams_operator_init: coreMaster not changed from lcore %d.\n", + coreMaster_); + } + + if(nicPort >= MAX_PORTS) { + printf("STREAMS_SOURCE: Error - Invalid NIC port value %d, max of %d can be used.\n", + nicPort, MAX_PORTS); + pthread_mutex_unlock(&mutexInit); + return(-1); + } + + if(lcore >= RTE_MAX_LCORE) { + printf("STREAMS_SOURCE: Error - Invalid lcore value %d, max of %d can be used.\n", + lcore, RTE_MAX_LCORE); + pthread_mutex_unlock(&mutexInit); + return(-1); + } + + int coreQueue = lcore_conf_[lcore].num_rx_queue; + lcore_conf_[lcore].rx_queue_list[coreQueue].port_id = nicPort; + lcore_conf_[lcore].rx_queue_list[coreQueue].queue_id = nicQueue; + lcore_conf_[lcore].rx_queue_list[coreQueue].userData = user; + lcore_conf_[lcore].rx_queue_list[coreQueue].packetCallbackFunction = dpdkCallback; + lcore_conf_[lcore].num_rx_queue += 1; + if(lcore_conf_[lcore].num_rx_queue == MAX_RX_QUEUE_PER_LCORE) { + printf("STREAMS_SOURCE: Error - Invalid number of queues on lcore %d, only %d can be defined.\n", lcore, MAX_RX_QUEUE_PER_LCORE); + pthread_mutex_unlock(&mutexInit); + return(-1); + } + + if(promiscuous) port_info_[nicPort].promiscuous = 1; + + // Set the number of queues for all NICs equal to the largest queue value that any + // operator defines. This could be made more granular and be done by NIC port in a + // future code update. + if((nicQueue+1) > numQueues_) { + numQueues_ = nicQueue+1; + } + + if(nicPort > maxPort_) { + maxPort_ = nicPort; + } + + printf("STREAMS_SOURCE: lcore = %d, coreQueue = %d, nicPort = %d, nicQueue = %d.\n", + lcore, coreQueue, nicPort, nicQueue); + printf("STREAMS_SOURCE: promiscuous = %d, callback = 0x%lx, user = 0x%lx.\n", + promiscuous, dpdkCallback, user); + + + printf("STREAMS_SOURCE: lcoreList = %s\n", lcoreList); + + numOperators++; // Keep a count of the number of operators that are constructed. + pthread_mutex_unlock(&mutexInit); + return(0); +} + +/* + * Initialize the DPDK library. + */ +int streams_dpdk_init() { + pthread_mutex_lock(&mutexInit); + printf("STREAMS_SOURCE: streams_dpdk_init starting.\n"); + + if(dpdkInitComplete != 0) { + // Not the first thread through the init code so just return. + pthread_mutex_unlock(&mutexInit); + return(0); + } + + if((numOperators == 0) || (coreMaster_ == -1) || + (numQueues_ == 0) || (maxPort_ == -1)) { + printf("STREAMS_SOURCE: streams_dpdk_init aborting due to invalid configuration.\n"); + printf("STREAMS_SOURCE: numOperators = %d, coreMaster_ = %d, numQueues_ = %d, maxPort_ = %d\n", + numOperators, coreMaster_, numQueues_, maxPort_); + pthread_mutex_unlock(&mutexInit); + return(-1); + } + + uint32_t nb_ports; + char *rte_arg[ARGN]; + + char arg0[]="dpdk"; + char arg1[]="-l"; + char arg2[MAX_CORESTRING]; + strcpy(arg2, lcoreList); + char arg3[]="-n"; + char arg4[]="4"; + char arg5[]="--master-lcore"; + char arg6[16]; + sprintf(arg6, "%d", coreMaster_); + + rte_arg[0]=arg0; + rte_arg[1]=arg1; + rte_arg[2]=arg2; + rte_arg[3]=arg3; + rte_arg[4]=arg4; + rte_arg[5]=arg5; + rte_arg[6]=arg6; + + printf("STREAMS_SOURCE: Queues per port = %d, Number of operators = %d.\n", + numQueues_, numOperators); + printf("STREAMS_SOURCE: args = %s %s %s %s %s %s %s.\n", + arg0, arg1, arg2, arg3, arg4, arg5, arg6); + + optind = 0; // Reset getopt state as it is called again in rte_eal_init. + + // This function is to be executed on the master lcore only. + // Because no master core is specified, the default master_lcore is set by + // the DPDK library to be the first core in the coremask. + unsigned int ret = rte_eal_init(ARGN, rte_arg); + if (ret < 0) { + pthread_mutex_unlock(&mutexInit); + rte_panic("Cannot init EAL\n"); + return(-1); + } + +#ifdef RTE_LIBRTE_TIMER + rte_timer_subsystem_init(); +#endif + + rte_set_log_level(8); + + nb_ports = rte_eth_dev_count(); + if (nb_ports == 0) { + pthread_mutex_unlock(&mutexInit); + RTE_LOG(ERR, STREAMS_SOURCE, "No ethernet device found.\n"); + return(-1); + } + if (maxPort_ > nb_ports) { + pthread_mutex_unlock(&mutexInit); + RTE_LOG(ERR, STREAMS_SOURCE, "A PacketDPDKSource operator specified an invalid port.\n"); + return(-1); + } + + dpdkInitComplete = 1; + pthread_mutex_unlock(&mutexInit); + + return(0); +} + +/* + * This function starts a dpdk receive thread on each lcore. That thread takes in packets + * and calls the Streams operator callback function for processing. + * + * Each PacketDPDKSource operator calls this function once its constructor is complete + * and a source operator thread has been started. That Streams thread is then held in + * a loop in the operator until it is shut down. Once all of the operators have called this + * function and are ready, we can start the dpdk threads on all lcores. + */ +int streams_source_start(void) { + pthread_mutex_lock(&mutexInit); + numOperatorsReady++; + if(numOperatorsReady < numOperators) { + // Not all operator threads are ready, so this one can return and enter its + // spin loop. + pthread_mutex_unlock(&mutexInit); + return(0); + } + + pthread_mutex_unlock(&mutexInit); + if(init() < 0) { + return(-1); + } + + int rc = rte_eal_mp_remote_launch(main_loop, NULL, SKIP_MASTER); + return rc; +} + +/* + * Return port statistics to the Streams operator. + */ +int streams_port_stats(int nicPort, struct port_stats *outStats) { + struct rte_eth_stats rteStats; + + rte_eth_stats_get(nicPort, &rteStats); + + outStats->received = rteStats.ipackets; + outStats->dropped = rteStats.ierrors; + outStats->bytes = rteStats.ibytes; + + return 0; +} + +/* + * Return the frequency of the TSC/Timebase register. + */ +uint64_t streams_source_get_tsc_hz(void) { + return(rte_get_tsc_hz()); +} + diff --git a/pool/shard000/C/0015942_win_sync_unlock.c b/pool/shard000/C/0015942_win_sync_unlock.c new file mode 100644 index 0000000000000000000000000000000000000000..3b1c24e794b4d65dd45c23e5cd560bc4dae087d0 --- /dev/null +++ b/pool/shard000/C/0015942_win_sync_unlock.c @@ -0,0 +1,38 @@ +/* -*- Mode: C; c-basic-offset:4 ; indent-tabs-mode:nil ; -*- */ +/* + * + * (C) 2012 by Argonne National Laboratory. + * See COPYRIGHT in top-level directory. + */ +#include "mpi.h" +#include +#include "mpitest.h" +#include "win_sync.h" + +int main(int argc, char *argv[]) +{ + int rank; + int errors = 0, all_errors = 0; + int buf; + MPI_Win win; + + MPI_Init(&argc, &argv); + MPI_Comm_rank(MPI_COMM_WORLD, &rank); + + MPI_Win_create(&buf, sizeof(int), sizeof(int), + MPI_INFO_NULL, MPI_COMM_WORLD, &win); + + MPI_Win_set_errhandler(win, MPI_ERRORS_RETURN); + + /* This should fail because the window is not locked. */ + CHECK_ERR(MPI_Win_unlock(0, win)); + + MPI_Win_free(&win); + + MPI_Reduce(&errors, &all_errors, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD); + + if (rank == 0 && all_errors == 0) printf(" No Errors\n"); + MPI_Finalize(); + + return 0; +} diff --git a/pool/shard000/C/0015945_timertest.c b/pool/shard000/C/0015945_timertest.c new file mode 100644 index 0000000000000000000000000000000000000000..6f72885f09bd739f694c685d99581928562ebdcb --- /dev/null +++ b/pool/shard000/C/0015945_timertest.c @@ -0,0 +1,78 @@ +/* + * Written by Mark Spencer + * Based on previous works, designs, and architectures conceived and + * written by Jim Dixon . + * + * Copyright (C) 2001 Jim Dixon / Zapata Telephony. + * Copyright (C) 2001-2008 Digium, Inc. + * + * All rights reserved. + * + * Primary Author: Mark Spencer + * Radio Support by Jim Dixon + */ + +/* + * See http://www.asterisk.org for more information about + * the Asterisk project. Please do not directly contact + * any of the maintainers of this project for assistance; + * the project provides a web site, mailing lists and IRC + * channels for your use. + * + * This program is free software, distributed under the terms of + * the GNU General Public License Version 2 as published by the + * Free Software Foundation. See the LICENSE file included with + * this program for more details. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include "dahdi_tools_version.h" + +int main(int argc, char *argv[]) +{ + int fd; + int x = 8000; + int res; + fd_set fds; + struct timeval orig, now; + fd = open("/dev/dahdi/timer", O_RDWR); + if (fd < 0) { + fprintf(stderr, "Unable to open timer: %s\n", strerror(errno)); + exit(1); + } + printf("Opened timer...\n"); + if (ioctl(fd, DAHDI_TIMERCONFIG, &x)) { + fprintf(stderr, "Unable to set timer: %s\n", strerror(errno)); + exit(1); + } + printf("Set timer duration to %d samples (%d ms)\n", x, x/8); + printf("Waiting...\n"); + gettimeofday(&orig, NULL); + for(;;) { + FD_ZERO(&fds); + FD_SET(fd, &fds); + res = select(fd + 1, NULL, NULL, &fds, NULL); + if (res != 1) { + fprintf(stderr, "Unexpected result %d: %s\n", res, strerror(errno)); + exit(1); + } + x = -1; + if (ioctl(fd, DAHDI_TIMERACK, &x)) { + fprintf(stderr, "Unable to ack timer: %s\n", strerror(errno)); + exit(1); + } + gettimeofday(&now, NULL); + printf("Timer Expired (%ld ms)!\n", (now.tv_sec - orig.tv_sec) * 1000 + (now.tv_usec - orig.tv_usec) / 1000); + } + exit(0); +} diff --git a/pool/shard000/C/0015956_msm_led_flash.c b/pool/shard000/C/0015956_msm_led_flash.c new file mode 100644 index 0000000000000000000000000000000000000000..8cf1b511f0b0b080c48514dbd4e7d4a389ceea52 --- /dev/null +++ b/pool/shard000/C/0015956_msm_led_flash.c @@ -0,0 +1,91 @@ +/* Copyright (c) 2009-2013, The Linux Foundation. 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 version 2 and + * only 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. + * + */ + +#define pr_fmt(fmt) "%s:%d " fmt, __func__, __LINE__ + +#include "msm_led_flash.h" + +/*#define CONFIG_MSMB_CAMERA_DEBUG*/ +#undef CDBG +#ifdef CONFIG_MSMB_CAMERA_DEBUG +#define CDBG(fmt, args ...) pr_err(fmt, ## args) +#else +#define CDBG(fmt, args ...) do { } while (0) +#endif + +static long msm_led_flash_subdev_ioctl(struct v4l2_subdev *sd, + unsigned int cmd, void *arg) +{ + struct msm_led_flash_ctrl_t *fctrl = NULL; + void __user *argp = (void __user*)arg; + + if (!sd) { + pr_err("sd NULL\n"); + return -EINVAL; + } + fctrl = v4l2_get_subdevdata(sd); + if (!fctrl) { + pr_err("fctrl NULL\n"); + return -EINVAL; + } + switch (cmd) { + case VIDIOC_MSM_SENSOR_GET_SUBDEV_ID: + return fctrl->func_tbl->flash_get_subdev_id(fctrl, argp); + case VIDIOC_MSM_FLASH_LED_DATA_CFG: + return fctrl->func_tbl->flash_led_config(fctrl, argp); + default: + pr_err("invalid cmd %d\n", cmd); + return -ENOIOCTLCMD; + } +} + +static struct v4l2_subdev_core_ops msm_flash_subdev_core_ops = { + .ioctl = msm_led_flash_subdev_ioctl, +}; + +static struct v4l2_subdev_ops msm_flash_subdev_ops = { + .core = &msm_flash_subdev_core_ops, +}; + +static const struct v4l2_subdev_internal_ops msm_flash_internal_ops; + +int32_t msm_led_flash_create_v4lsubdev(struct platform_device *pdev, void *data) +{ + struct msm_led_flash_ctrl_t *fctrl = + (struct msm_led_flash_ctrl_t *)data; + + CDBG("Enter\n"); + + if (!fctrl) { + pr_err("fctrl NULL\n"); + return -EINVAL; + } + + /* Initialize sub device */ + v4l2_subdev_init(&fctrl->msm_sd.sd, &msm_flash_subdev_ops); + v4l2_set_subdevdata(&fctrl->msm_sd.sd, fctrl); + + fctrl->pdev = pdev; + fctrl->msm_sd.sd.internal_ops = &msm_flash_internal_ops; + fctrl->msm_sd.sd.flags |= V4L2_SUBDEV_FL_HAS_DEVNODE; + snprintf(fctrl->msm_sd.sd.name, ARRAY_SIZE(fctrl->msm_sd.sd.name), + "msm_flash"); + media_entity_init(&fctrl->msm_sd.sd.entity, 0, NULL, 0); + fctrl->msm_sd.sd.entity.type = MEDIA_ENT_T_V4L2_SUBDEV; + fctrl->msm_sd.sd.entity.group_id = MSM_CAMERA_SUBDEV_LED_FLASH; + fctrl->msm_sd.close_seq = MSM_SD_CLOSE_2ND_CATEGORY | 0x1; + msm_sd_register(&fctrl->msm_sd); + + CDBG("probe success\n"); + return 0; +} diff --git a/pool/shard000/C/0015957_t-fits.c b/pool/shard000/C/0015957_t-fits.c new file mode 100644 index 0000000000000000000000000000000000000000..de349fe4c7a6d0a1d86a66b915cbef32cc876d25 --- /dev/null +++ b/pool/shard000/C/0015957_t-fits.c @@ -0,0 +1,202 @@ +/* Test mpz_fits_*_p */ + +/* +Copyright 2001 Free Software Foundation, Inc. + +This file is part of the GNU MP Library test suite. + +The GNU MP Library test suite 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. + +The GNU MP Library test suite 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 +the GNU MP Library test suite. If not, see http://www.gnu.org/licenses/. */ + +#include +#include +#include "gmp.h" +#include "gmp-impl.h" +#include "tests.h" + + +/* Nothing sophisticated here, just exercise mpz_fits_*_p on a small amount + of data. */ + +#define EXPECT_S(fun,name,answer) \ + got = fun (z); \ + if (got != answer) \ + { \ + printf ("%s (%s) got %d want %d\n", name, expr, got, answer); \ + printf (" z size %d\n", SIZ(z)); \ + printf (" z dec "); mpz_out_str (stdout, 10, z); printf ("\n"); \ + printf (" z hex "); mpz_out_str (stdout, 16, z); printf ("\n"); \ + error = 1; \ + } + +#if HAVE_STRINGIZE +#define EXPECT(fun,answer) EXPECT_S(fun,#fun,answer) +#else +#define EXPECT(fun,answer) EXPECT_S(fun,"fun",answer) +#endif + +int +main (void) +{ + mpz_t z; + int got; + const char *expr; + int error = 0; + + tests_start (); + mpz_init (z); + + mpz_set_ui (z, 0L); + expr = "0"; + EXPECT (mpz_fits_ulong_p, 1); + EXPECT (mpz_fits_uint_p, 1); + EXPECT (mpz_fits_ushort_p, 1); + EXPECT (mpz_fits_slong_p, 1); + EXPECT (mpz_fits_sint_p, 1); + EXPECT (mpz_fits_sshort_p, 1); + + mpz_set_ui (z, 1L); + expr = "1"; + EXPECT (mpz_fits_ulong_p, 1); + EXPECT (mpz_fits_uint_p, 1); + EXPECT (mpz_fits_ushort_p, 1); + EXPECT (mpz_fits_slong_p, 1); + EXPECT (mpz_fits_sint_p, 1); + EXPECT (mpz_fits_sshort_p, 1); + + mpz_set_si (z, -1L); + expr = "-1"; + EXPECT (mpz_fits_ulong_p, 0); + EXPECT (mpz_fits_uint_p, 0); + EXPECT (mpz_fits_ushort_p, 0); + EXPECT (mpz_fits_slong_p, 1); + EXPECT (mpz_fits_sint_p, 1); + EXPECT (mpz_fits_sshort_p, 1); + + mpz_set_ui (z, 1L); + mpz_mul_2exp (z, z, 5L*GMP_LIMB_BITS); + expr = "2^(5*BPML)"; + EXPECT (mpz_fits_ulong_p, 0); + EXPECT (mpz_fits_uint_p, 0); + EXPECT (mpz_fits_ushort_p, 0); + EXPECT (mpz_fits_slong_p, 0); + EXPECT (mpz_fits_sint_p, 0); + EXPECT (mpz_fits_sshort_p, 0); + + + mpz_set_ui (z, (unsigned long) USHRT_MAX); + expr = "USHRT_MAX"; + EXPECT (mpz_fits_ulong_p, 1); + EXPECT (mpz_fits_uint_p, 1); + EXPECT (mpz_fits_ushort_p, 1); + + mpz_set_ui (z, (unsigned long) USHRT_MAX); + mpz_add_ui (z, z, 1L); + expr = "USHRT_MAX + 1"; + EXPECT (mpz_fits_ushort_p, 0); + + + mpz_set_ui (z, (unsigned long) UINT_MAX); + expr = "UINT_MAX"; + EXPECT (mpz_fits_ulong_p, 1); + EXPECT (mpz_fits_uint_p, 1); + + mpz_set_ui (z, (unsigned long) UINT_MAX); + mpz_add_ui (z, z, 1L); + expr = "UINT_MAX + 1"; + EXPECT (mpz_fits_uint_p, 0); + + + mpz_set_ui (z, ULONG_MAX); + expr = "ULONG_MAX"; + EXPECT (mpz_fits_ulong_p, 1); + + mpz_set_ui (z, ULONG_MAX); + mpz_add_ui (z, z, 1L); + expr = "ULONG_MAX + 1"; + EXPECT (mpz_fits_ulong_p, 0); + + + mpz_set_si (z, (long) SHRT_MAX); + expr = "SHRT_MAX"; + EXPECT (mpz_fits_slong_p, 1); + EXPECT (mpz_fits_sint_p, 1); + EXPECT (mpz_fits_sshort_p, 1); + + mpz_set_si (z, (long) SHRT_MAX); + mpz_add_ui (z, z, 1L); + expr = "SHRT_MAX + 1"; + EXPECT (mpz_fits_sshort_p, 0); + + + mpz_set_si (z, (long) INT_MAX); + expr = "INT_MAX"; + EXPECT (mpz_fits_slong_p, 1); + EXPECT (mpz_fits_sint_p, 1); + + mpz_set_si (z, (long) INT_MAX); + mpz_add_ui (z, z, 1L); + expr = "INT_MAX + 1"; + EXPECT (mpz_fits_sint_p, 0); + + + mpz_set_si (z, LONG_MAX); + expr = "LONG_MAX"; + EXPECT (mpz_fits_slong_p, 1); + + mpz_set_si (z, LONG_MAX); + mpz_add_ui (z, z, 1L); + expr = "LONG_MAX + 1"; + EXPECT (mpz_fits_slong_p, 0); + + + mpz_set_si (z, (long) SHRT_MIN); + expr = "SHRT_MIN"; + EXPECT (mpz_fits_slong_p, 1); + EXPECT (mpz_fits_sint_p, 1); + EXPECT (mpz_fits_sshort_p, 1); + + mpz_set_si (z, (long) SHRT_MIN); + mpz_sub_ui (z, z, 1L); + expr = "SHRT_MIN + 1"; + EXPECT (mpz_fits_sshort_p, 0); + + + mpz_set_si (z, (long) INT_MIN); + expr = "INT_MIN"; + EXPECT (mpz_fits_slong_p, 1); + EXPECT (mpz_fits_sint_p, 1); + + mpz_set_si (z, (long) INT_MIN); + mpz_sub_ui (z, z, 1L); + expr = "INT_MIN + 1"; + EXPECT (mpz_fits_sint_p, 0); + + + mpz_set_si (z, LONG_MIN); + expr = "LONG_MIN"; + EXPECT (mpz_fits_slong_p, 1); + + mpz_set_si (z, LONG_MIN); + mpz_sub_ui (z, z, 1L); + expr = "LONG_MIN + 1"; + EXPECT (mpz_fits_slong_p, 0); + + + if (error) + abort (); + + mpz_clear (z); + tests_end (); + exit (0); +} diff --git a/pool/shard000/C/0015961_packet-cosine.c b/pool/shard000/C/0015961_packet-cosine.c new file mode 100644 index 0000000000000000000000000000000000000000..344cba7eeb617af8fc3730878c636652770110d3 --- /dev/null +++ b/pool/shard000/C/0015961_packet-cosine.c @@ -0,0 +1,191 @@ +/* packet-cosine.c + * Routines for decoding CoSine IPNOS L2 debug output + * + * Motonori Shindo + * + * Wireshark - Network traffic analyzer + * By Gerald Combs + * + * SPDX-License-Identifier: GPL-2.0-or-later + */ + +/* + * XXX TODO: + * o PPoATM and PPoFR encapsulation needs more test. + * + */ + +#include "config.h" + +#include +#include + +void proto_register_cosine(void); +void proto_reg_handoff_cosine(void); + +static int proto_cosine = -1; +static int hf_pro = -1; +static int hf_off = -1; +static int hf_pri = -1; +static int hf_rm = -1; +static int hf_err = -1; +static int hf_sar = -1; +static int hf_channel_id = -1; + +static gint ett_raw = -1; + +static dissector_handle_t eth_withoutfcs_handle; +static dissector_handle_t ppp_hdlc_handle; +static dissector_handle_t llc_handle; +static dissector_handle_t chdlc_handle; +static dissector_handle_t fr_handle; + +static int +dissect_cosine(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data _U_) +{ + proto_tree *fh_tree; + proto_item *ti; + union wtap_pseudo_header *pseudo_header = pinfo->pseudo_header; + + /* load the top pane info. This should be overwritten by + the next protocol in the stack */ + col_set_str(pinfo->cinfo, COL_RES_DL_SRC, "N/A"); + col_set_str(pinfo->cinfo, COL_RES_DL_DST, "N/A"); + col_set_str(pinfo->cinfo, COL_PROTOCOL, "N/A"); + col_set_str(pinfo->cinfo, COL_INFO, "CoSine IPNOS L2 debug output"); + + /* populate a tree in the second pane with the status of the link + layer (ie none) */ + if(tree) { + ti = proto_tree_add_protocol_format(tree, proto_cosine, tvb, 0, 0, + "CoSine IPNOS L2 debug output (%s)", + pseudo_header->cosine.if_name); + fh_tree = proto_item_add_subtree(ti, ett_raw); + proto_tree_add_uint(fh_tree, hf_pro, tvb, 0, 0, pseudo_header->cosine.pro); + proto_tree_add_uint(fh_tree, hf_off, tvb, 0, 0, pseudo_header->cosine.off); + proto_tree_add_uint(fh_tree, hf_pri, tvb, 0, 0, pseudo_header->cosine.pri); + proto_tree_add_uint(fh_tree, hf_rm, tvb, 0, 0, pseudo_header->cosine.rm); + proto_tree_add_uint(fh_tree, hf_err, tvb, 0, 0, pseudo_header->cosine.err); + + switch (pseudo_header->cosine.encap) { + case COSINE_ENCAP_ETH: + break; + case COSINE_ENCAP_ATM: + case COSINE_ENCAP_PPoATM: + proto_tree_add_item(fh_tree, hf_sar, tvb, 0, 16, ENC_NA); + break; + case COSINE_ENCAP_PPP: + case COSINE_ENCAP_FR: + case COSINE_ENCAP_PPoFR: + proto_tree_add_item(fh_tree, hf_channel_id, tvb, 0, 4, ENC_NA); + break; + case COSINE_ENCAP_HDLC: + if (pseudo_header->cosine.direction == COSINE_DIR_TX) { + proto_tree_add_item(fh_tree, hf_channel_id, tvb, 0, 2, ENC_NA); + } else if (pseudo_header->cosine.direction == COSINE_DIR_RX) { + proto_tree_add_item(fh_tree, hf_channel_id, tvb, 0, 4, ENC_NA); + } + break; + default: + break; + } + } + + switch (pseudo_header->cosine.encap) { + case COSINE_ENCAP_ETH: + call_dissector(eth_withoutfcs_handle, tvb_new_subset_remaining(tvb, 0), + pinfo, tree); + break; + case COSINE_ENCAP_ATM: + case COSINE_ENCAP_PPoATM: + call_dissector(llc_handle, tvb_new_subset_remaining(tvb, 16), + pinfo, tree); + break; + case COSINE_ENCAP_PPP: + call_dissector(ppp_hdlc_handle, tvb_new_subset_remaining(tvb, 4), + pinfo, tree); + break; + case COSINE_ENCAP_HDLC: + if (pseudo_header->cosine.direction == COSINE_DIR_TX) { + call_dissector(chdlc_handle, tvb_new_subset_remaining(tvb, 2), + pinfo, tree); + } else if (pseudo_header->cosine.direction == COSINE_DIR_RX) { + call_dissector(chdlc_handle, tvb_new_subset_remaining(tvb, 4), + pinfo, tree); + } + break; + case COSINE_ENCAP_FR: + case COSINE_ENCAP_PPoFR: + call_dissector(fr_handle, tvb_new_subset_remaining(tvb, 4), + pinfo, tree); + break; + case COSINE_ENCAP_TEST: + case COSINE_ENCAP_UNKNOWN: + call_data_dissector(tvb, pinfo, tree); + break; + default: + break; + } + return tvb_captured_length(tvb); +} + +void +proto_register_cosine(void) +{ + static hf_register_info hf[] = { + { &hf_pro, + { "Protocol", "cosine.pro", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL}}, + { &hf_off, + { "Offset", "cosine.off", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL}}, + { &hf_pri, + { "Priority", "cosine.pri", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL}}, + { &hf_rm, + { "Rate Marking", "cosine.rm", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL}}, + { &hf_err, + { "Error Code", "cosine.err", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL}}, + { &hf_sar, + { "SAR header", "cosine.sar", FT_BYTES, BASE_NONE, NULL, 0x0, NULL, HFILL}}, + { &hf_channel_id, + { "Channel handle ID", "cosine.channel_id", FT_BYTES, BASE_NONE, NULL, 0x0, NULL, HFILL}}, + }; + + static gint *ett[] = { + &ett_raw, + }; + + proto_cosine = proto_register_protocol("CoSine IPNOS L2 debug output", + "CoSine", "cosine"); + proto_register_field_array(proto_cosine, hf, array_length(hf)); + proto_register_subtree_array(ett, array_length(ett)); +} + +void +proto_reg_handoff_cosine(void) +{ + dissector_handle_t cosine_handle; + + /* + * Get handles for dissectors. + */ + eth_withoutfcs_handle = find_dissector_add_dependency("eth_withoutfcs", proto_cosine); + ppp_hdlc_handle = find_dissector_add_dependency("ppp_hdlc", proto_cosine); + llc_handle = find_dissector_add_dependency("llc", proto_cosine); + chdlc_handle = find_dissector_add_dependency("chdlc", proto_cosine); + fr_handle = find_dissector_add_dependency("fr", proto_cosine); + + cosine_handle = create_dissector_handle(dissect_cosine, proto_cosine); + dissector_add_uint("wtap_encap", WTAP_ENCAP_COSINE, cosine_handle); +} + +/* + * Editor modelines - https://www.wireshark.org/tools/modelines.html + * + * Local Variables: + * c-basic-offset: 2 + * tab-width: 8 + * indent-tabs-mode: nil + * End: + * + * ex: set shiftwidth=2 tabstop=8 expandtab: + * :indentSize=2:tabSize=8:noTabs=true: + */ diff --git a/pool/shard000/C/0015966_win32filemap.c b/pool/shard000/C/0015966_win32filemap.c new file mode 100644 index 0000000000000000000000000000000000000000..d1fe3f0d3db773f899ed70616bdde006954466df --- /dev/null +++ b/pool/shard000/C/0015966_win32filemap.c @@ -0,0 +1,96 @@ +/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd + See the file COPYING for copying permission. +*/ + +#define STRICT 1 +#define WIN32_LEAN_AND_MEAN 1 + +#ifdef XML_UNICODE_WCHAR_T +#ifndef XML_UNICODE +#define XML_UNICODE +#endif +#endif + +#ifdef XML_UNICODE +#define UNICODE +#define _UNICODE +#endif /* XML_UNICODE */ +#include +#include +#include +#include "filemap.h" + +static void win32perror(const TCHAR *); + +int +filemap(const TCHAR *name, + void (*processor)(const void *, size_t, const TCHAR *, void *arg), + void *arg) +{ + HANDLE f; + HANDLE m; + DWORD size; + DWORD sizeHi; + void *p; + + f = CreateFile(name, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, + FILE_FLAG_SEQUENTIAL_SCAN, NULL); + if (f == INVALID_HANDLE_VALUE) { + win32perror(name); + return 0; + } + size = GetFileSize(f, &sizeHi); + if (size == (DWORD)-1) { + win32perror(name); + return 0; + } + if (sizeHi) { + _ftprintf(stderr, wxT("%s: bigger than 2Gb\n"), name); + return 0; + } + /* CreateFileMapping barfs on zero length files */ + if (size == 0) { + static const char c = '\0'; + processor(&c, 0, name, arg); + CloseHandle(f); + return 1; + } + m = CreateFileMapping(f, NULL, PAGE_READONLY, 0, 0, NULL); + if (m == NULL) { + win32perror(name); + CloseHandle(f); + return 0; + } + p = MapViewOfFile(m, FILE_MAP_READ, 0, 0, 0); + if (p == NULL) { + win32perror(name); + CloseHandle(m); + CloseHandle(f); + return 0; + } + processor(p, size, name, arg); + UnmapViewOfFile(p); + CloseHandle(m); + CloseHandle(f); + return 1; +} + +static void +win32perror(const TCHAR *s) +{ + LPVOID buf; + if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER + | FORMAT_MESSAGE_FROM_SYSTEM, + NULL, + GetLastError(), + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + (LPTSTR) &buf, + 0, + NULL)) { + _ftprintf(stderr, wxT("%s: %s"), s, buf); + fflush(stderr); + LocalFree(buf); + } + else + _ftprintf(stderr, wxT("%s: unknown Windows error\n"), s); +} diff --git a/pool/shard000/C/0015971_dbg_SUITE.c b/pool/shard000/C/0015971_dbg_SUITE.c new file mode 100644 index 0000000000000000000000000000000000000000..ecdee7e3a21e2e58df943b8f2c335676576380e5 --- /dev/null +++ b/pool/shard000/C/0015971_dbg_SUITE.c @@ -0,0 +1,113 @@ +/* + * %CopyrightBegin% + * + * Copyright Ericsson AB 2009-2014. 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. + * + * %CopyrightEnd% + */ + +#include "erl_nif.h" + +#include +#include +#include +#include + +/* NIF interface declarations */ +static int load(ErlNifEnv* env, void** priv_data, ERL_NIF_TERM load_info); +static int upgrade(ErlNifEnv* env, void** priv_data, void** old_priv_data, ERL_NIF_TERM load_info); +static void unload(ErlNifEnv* env, void* priv_data); + +/* The NIFs: */ +static ERL_NIF_TERM enabled(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); +static ERL_NIF_TERM trace(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); + +static ErlNifFunc nif_funcs[] = { + {"enabled", 3, enabled}, + {"trace", 5, trace} +}; + +ERL_NIF_INIT(dbg_SUITE, nif_funcs, load, NULL, upgrade, unload) + +static ERL_NIF_TERM atom_trace; +static ERL_NIF_TERM atom_ok; + +#define ASSERT(expr) assert(expr) + +static int load(ErlNifEnv* env, void** priv_data, ERL_NIF_TERM load_info) +{ + + atom_trace = enif_make_atom(env, "trace"); + atom_ok = enif_make_atom(env, "ok"); + + *priv_data = NULL; + + return 0; +} + +static void unload(ErlNifEnv* env, void* priv_data) +{ + +} + +static int upgrade(ErlNifEnv* env, void** priv_data, void** old_priv_data, + ERL_NIF_TERM load_info) +{ + if (*old_priv_data != NULL) { + return -1; /* Don't know how to do that */ + } + if (*priv_data != NULL) { + return -1; /* Don't know how to do that */ + } + if (load(env, priv_data, load_info)) { + return -1; + } + return 0; +} + +static ERL_NIF_TERM enabled(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) +{ + int state_arity; + const ERL_NIF_TERM *state_tuple; + ERL_NIF_TERM value; + ASSERT(argc == 3); + + + return atom_trace; +} + +static ERL_NIF_TERM trace(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) +{ + int state_arity; + ErlNifPid self, to; + ERL_NIF_TERM *tuple, msg; + ASSERT(argc == 5); + + tuple = enif_alloc(sizeof(ERL_NIF_TERM)*(argc+1)); + memcpy(tuple+1,argv,sizeof(ERL_NIF_TERM)*argc); + + if (enif_self(env, &self)) { + tuple[0] = enif_make_pid(env, &self); + } else { + tuple[0] = enif_make_atom(env, "undefined"); + } + + msg = enif_make_tuple_from_array(env, tuple, argc + 1); + enif_get_local_pid(env, argv[1], &to); + enif_send(env, &to, NULL, msg); + enif_free(tuple); + + return atom_ok; +} diff --git a/pool/shard000/C/0015972_cexp.c b/pool/shard000/C/0015972_cexp.c new file mode 100644 index 0000000000000000000000000000000000000000..43ac9ab9e740a8c4c8dd79495a360cb76ed26eef --- /dev/null +++ b/pool/shard000/C/0015972_cexp.c @@ -0,0 +1,19 @@ +/* + cexp.c + Contributed by Danny Smith + 2003-10-20 +*/ + +#include +#include + +/* cexp (x + I * y) = exp (x) * cos (y) + I * exp (x) * sin (y) */ + +double complex cexp (double complex Z) +{ + double complex Res; + long double rho = exp (__real__ Z); + __real__ Res = rho * cos(__imag__ Z); + __imag__ Res = rho * sin(__imag__ Z); + return Res; +} diff --git a/pool/shard000/C/0015991_muleq_s_w_phl.c b/pool/shard000/C/0015991_muleq_s_w_phl.c new file mode 100644 index 0000000000000000000000000000000000000000..b3a5370fe59e68fe4c9aa035ab7cbd7ff2739157 --- /dev/null +++ b/pool/shard000/C/0015991_muleq_s_w_phl.c @@ -0,0 +1,41 @@ +#include +#include + +int main() +{ + int rd, rs, rt, dsp; + int result, resultdsp; + + rs = 0x80001234; + rt = 0x80001234; + result = 0x7FFFFFFF; + resultdsp = 1; + + __asm + ("muleq_s.w.phl %0, %2, %3\n\t" + "rddsp %1\n\t" + : "=r"(rd), "=r"(dsp) + : "r"(rs), "r"(rt) + ); + dsp = (dsp >> 21) & 0x01; + assert(rd == result); + assert(dsp == resultdsp); + + rs = 0x12349988; + rt = 0x43219988; + result = 0x98be968; + resultdsp = 1; + + __asm + ("muleq_s.w.phl %0, %2, %3\n\t" + "rddsp %1\n\t" + : "=r"(rd), "=r"(dsp) + : "r"(rs), "r"(rt) + ); + dsp = (dsp >> 21) & 0x01; + assert(rd == result); + assert(dsp == resultdsp); + + return 0; +} + diff --git a/pool/shard000/C/0016000_msi_sn.c b/pool/shard000/C/0016000_msi_sn.c new file mode 100644 index 0000000000000000000000000000000000000000..81e428943d7374d01e0aef8530e39c7ecd892b30 --- /dev/null +++ b/pool/shard000/C/0016000_msi_sn.c @@ -0,0 +1,235 @@ +/* + * This file is subject to the terms and conditions of the GNU General Public + * License. See the file "COPYING" in the main directory of this archive + * for more details. + * + * Copyright (C) 2006 Silicon Graphics, Inc. All Rights Reserved. + */ + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +struct sn_msi_info { + u64 pci_addr; + struct sn_irq_info *sn_irq_info; +}; + +static struct sn_msi_info sn_msi_info[NR_IRQS]; + +static struct irq_chip sn_msi_chip; + +void sn_teardown_msi_irq(unsigned int irq) +{ + nasid_t nasid; + int widget; + struct pci_dev *pdev; + struct pcidev_info *sn_pdev; + struct sn_irq_info *sn_irq_info; + struct pcibus_bussoft *bussoft; + struct sn_pcibus_provider *provider; + + sn_irq_info = sn_msi_info[irq].sn_irq_info; + if (sn_irq_info == NULL || sn_irq_info->irq_int_bit >= 0) + return; + + sn_pdev = (struct pcidev_info *)sn_irq_info->irq_pciioinfo; + pdev = sn_pdev->pdi_linux_pcidev; + provider = SN_PCIDEV_BUSPROVIDER(pdev); + + (*provider->dma_unmap)(pdev, + sn_msi_info[irq].pci_addr, + PCI_DMA_FROMDEVICE); + sn_msi_info[irq].pci_addr = 0; + + bussoft = SN_PCIDEV_BUSSOFT(pdev); + nasid = NASID_GET(bussoft->bs_base); + widget = (nasid & 1) ? + TIO_SWIN_WIDGETNUM(bussoft->bs_base) : + SWIN_WIDGETNUM(bussoft->bs_base); + + sn_intr_free(nasid, widget, sn_irq_info); + sn_msi_info[irq].sn_irq_info = NULL; + + destroy_irq(irq); +} + +int sn_setup_msi_irq(struct pci_dev *pdev, struct msi_desc *entry) +{ + struct msi_msg msg; + int widget; + int status; + nasid_t nasid; + u64 bus_addr; + struct sn_irq_info *sn_irq_info; + struct pcibus_bussoft *bussoft = SN_PCIDEV_BUSSOFT(pdev); + struct sn_pcibus_provider *provider = SN_PCIDEV_BUSPROVIDER(pdev); + int irq; + + if (!entry->msi_attrib.is_64) + return -EINVAL; + + if (bussoft == NULL) + return -EINVAL; + + if (provider == NULL || provider->dma_map_consistent == NULL) + return -EINVAL; + + irq = create_irq(); + if (irq < 0) + return irq; + + /* + * Set up the vector plumbing. Let the prom (via sn_intr_alloc) + * decide which cpu to direct this msi at by default. + */ + + nasid = NASID_GET(bussoft->bs_base); + widget = (nasid & 1) ? + TIO_SWIN_WIDGETNUM(bussoft->bs_base) : + SWIN_WIDGETNUM(bussoft->bs_base); + + sn_irq_info = kzalloc(sizeof(struct sn_irq_info), GFP_KERNEL); + if (! sn_irq_info) { + destroy_irq(irq); + return -ENOMEM; + } + + status = sn_intr_alloc(nasid, widget, sn_irq_info, irq, -1, -1); + if (status) { + kfree(sn_irq_info); + destroy_irq(irq); + return -ENOMEM; + } + + sn_irq_info->irq_int_bit = -1; /* mark this as an MSI irq */ + sn_irq_fixup(pdev, sn_irq_info); + + /* Prom probably should fill these in, but doesn't ... */ + sn_irq_info->irq_bridge_type = bussoft->bs_asic_type; + sn_irq_info->irq_bridge = (void *)bussoft->bs_base; + + /* + * Map the xio address into bus space + */ + bus_addr = (*provider->dma_map_consistent)(pdev, + sn_irq_info->irq_xtalkaddr, + sizeof(sn_irq_info->irq_xtalkaddr), + SN_DMA_MSI|SN_DMA_ADDR_XIO); + if (! bus_addr) { + sn_intr_free(nasid, widget, sn_irq_info); + kfree(sn_irq_info); + destroy_irq(irq); + return -ENOMEM; + } + + sn_msi_info[irq].sn_irq_info = sn_irq_info; + sn_msi_info[irq].pci_addr = bus_addr; + + msg.address_hi = (u32)(bus_addr >> 32); + msg.address_lo = (u32)(bus_addr & 0x00000000ffffffff); + + /* + * In the SN platform, bit 16 is a "send vector" bit which + * must be present in order to move the vector through the system. + */ + msg.data = 0x100 + irq; + + set_irq_msi(irq, entry); + write_msi_msg(irq, &msg); + set_irq_chip_and_handler(irq, &sn_msi_chip, handle_edge_irq); + + return 0; +} + +#ifdef CONFIG_SMP +static void sn_set_msi_irq_affinity(unsigned int irq, + const struct cpumask *cpu_mask) +{ + struct msi_msg msg; + int slice; + nasid_t nasid; + u64 bus_addr; + struct pci_dev *pdev; + struct pcidev_info *sn_pdev; + struct sn_irq_info *sn_irq_info; + struct sn_irq_info *new_irq_info; + struct sn_pcibus_provider *provider; + unsigned int cpu; + + cpu = cpumask_first(cpu_mask); + sn_irq_info = sn_msi_info[irq].sn_irq_info; + if (sn_irq_info == NULL || sn_irq_info->irq_int_bit >= 0) + return; + + /* + * Release XIO resources for the old MSI PCI address + */ + + read_msi_msg(irq, &msg); + sn_pdev = (struct pcidev_info *)sn_irq_info->irq_pciioinfo; + pdev = sn_pdev->pdi_linux_pcidev; + provider = SN_PCIDEV_BUSPROVIDER(pdev); + + bus_addr = (u64)(msg.address_hi) << 32 | (u64)(msg.address_lo); + (*provider->dma_unmap)(pdev, bus_addr, PCI_DMA_FROMDEVICE); + sn_msi_info[irq].pci_addr = 0; + + nasid = cpuid_to_nasid(cpu); + slice = cpuid_to_slice(cpu); + + new_irq_info = sn_retarget_vector(sn_irq_info, nasid, slice); + sn_msi_info[irq].sn_irq_info = new_irq_info; + if (new_irq_info == NULL) + return; + + /* + * Map the xio address into bus space + */ + + bus_addr = (*provider->dma_map_consistent)(pdev, + new_irq_info->irq_xtalkaddr, + sizeof(new_irq_info->irq_xtalkaddr), + SN_DMA_MSI|SN_DMA_ADDR_XIO); + + sn_msi_info[irq].pci_addr = bus_addr; + msg.address_hi = (u32)(bus_addr >> 32); + msg.address_lo = (u32)(bus_addr & 0x00000000ffffffff); + + write_msi_msg(irq, &msg); + cpumask_copy(irq_desc[irq].affinity, cpu_mask); +} +#endif /* CONFIG_SMP */ + +static void sn_ack_msi_irq(unsigned int irq) +{ + move_native_irq(irq); + ia64_eoi(); +} + +static int sn_msi_retrigger_irq(unsigned int irq) +{ + unsigned int vector = irq; + ia64_resend_irq(vector); + + return 1; +} + +static struct irq_chip sn_msi_chip = { + .name = "PCI-MSI", + .mask = mask_msi_irq, + .unmask = unmask_msi_irq, + .ack = sn_ack_msi_irq, +#ifdef CONFIG_SMP + .set_affinity = sn_set_msi_irq_affinity, +#endif + .retrigger = sn_msi_retrigger_irq, +}; diff --git a/pool/shard000/C/0016003_dse_help.c b/pool/shard000/C/0016003_dse_help.c new file mode 100644 index 0000000000000000000000000000000000000000..573b0ffef208ee2141869085ee43051d74777f3f --- /dev/null +++ b/pool/shard000/C/0016003_dse_help.c @@ -0,0 +1,47 @@ +/**************************************************************** + * * + * Copyright 2001 Sanchez Computer Associates, Inc. * + * * + * This source code contains the intellectual property * + * of its copyright holder(s), and is made available * + * under a license. If you do not know the terms of * + * the license, please stop and do not read further. * + * * + ****************************************************************/ + +#include "mdef.h" +#include "gdsroot.h" +#include "gtm_facility.h" +#include "fileinfo.h" +#include "gdsbt.h" +#include "gdsfhead.h" +#include "release_name.h" +#include "util.h" +#include "dse.h" + +void dse_help(void) +{ +} + +void dse_version(void) +{ + /* + * The following assumptions have been made in this function + * 1. GTM_RELEASE_NAME is of the form "GTM_PRODUCT VERSION THEREST" + * (Refer file release_name.h) + * 2. A single blank separates GTM_PRODUCT and VERSION + * 3. If THEREST exists, it is separated from VERSION by atleast + * one blank + */ + char gtm_rel_name[] = GTM_RELEASE_NAME; + char dse_rel_name[sizeof(GTM_RELEASE_NAME) - sizeof(GTM_PRODUCT)]; + int dse_rel_name_len; + char *cptr; + + for (cptr = gtm_rel_name + sizeof(GTM_PRODUCT), dse_rel_name_len = 0; + *cptr != ' ' && *cptr != '\0'; + dse_rel_name[dse_rel_name_len++] = *cptr++); + dse_rel_name[dse_rel_name_len] = '\0'; + util_out_print("!AD", TRUE, dse_rel_name_len, dse_rel_name); + return; +} diff --git a/pool/shard000/C/0016010_retail.c b/pool/shard000/C/0016010_retail.c new file mode 100644 index 0000000000000000000000000000000000000000..fcfb1483412e49e19b98dbe11bbe987b32677e32 --- /dev/null +++ b/pool/shard000/C/0016010_retail.c @@ -0,0 +1,218 @@ +/** + * Retail is a nightly project by Eduard Roccatello. + * + * Made with love for Guly and his tremendous peppers. + * Greets to #openbsd on AzzurraNet ;) + * + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +#define MAX_LINE_W 2048 +#define BUFFER_SIZE 512 + +typedef struct { + char *value; +} Line; + +typedef struct { + int size; + int start; + int count; + Line *items; +} Buffer; + +void bufInit(Buffer *b, int maxSize); +bool bufIsFull(Buffer *b); +bool bufIsEmpty(Buffer *b); +void bufWrite(Buffer *b, Line *l); +Line *bufRead(Buffer *b, int pos); +void bufFree(Buffer *b); + +void *screenDrawingThread(void *); +void gracefulExit(); +void initScreen(); +void updateScreen(); +void sigIntHandler(int); +void calculateTermSize(); +void putLineInBuffer(Line *line); +int rowsForLine(Line *l, int maxCols); + +extern int errno; +bool volatile hasToExit = false; +bool volatile hasToRedraw = false; +pthread_t drawingThread; +pthread_mutex_t lock; + +Buffer buffer; + +int main(int argc, char **argv) { + // ctrl - c handler + signal(SIGINT, sigIntHandler); + + // mutex + if (pthread_mutex_init(&lock, NULL) != 0) { + gracefulExit(); + fprintf(stderr, "Error creating mutex\n"); + return 1; + } + + // init buffer + bufInit(&buffer, BUFFER_SIZE); + + // init screen + initScreen(); + + // screen drawing thread + if (pthread_create(&drawingThread, NULL, screenDrawingThread, NULL)) { + gracefulExit(); + fprintf(stderr, "Error creating thread\n"); + return 1; + } + + // Configure STDIN to be non blocking + fcntl(STDIN_FILENO, F_SETFL, fcntl(STDIN_FILENO, F_GETFL) | O_NONBLOCK); + char *line = (char *)malloc(sizeof(char) * MAX_LINE_W); + while (!hasToExit) { + if (fgets(line, MAX_LINE_W, stdin) != NULL) { + pthread_mutex_lock(&lock); + Line *l = (Line *)malloc(sizeof(Line)); + // dup line + l->value = strdup(line); + putLineInBuffer(l); + pthread_mutex_unlock(&lock); + } + } + free(line); + gracefulExit(); + return 0; +} + +void sigIntHandler(int dummy) { + hasToExit = true; + fprintf(stdout, "\n"); +} + +void putLineInBuffer(Line *line) { + bufWrite(&buffer, line); + hasToRedraw = true; +} + +void gracefulExit() { + + if (drawingThread) { + pthread_cancel(drawingThread); + } + + pthread_mutex_destroy(&lock); + endwin(); + + // lines buffer clearing + bufFree(&buffer); +} + +void initScreen() { + initscr(); + cbreak(); + noecho(); +} + +void* screenDrawingThread (void *ptr) { + while (!hasToExit) { + if (hasToRedraw) { + pthread_mutex_lock(&lock); + updateScreen(); + hasToRedraw = false; + pthread_mutex_unlock(&lock); + } + } + return NULL; +} + +int rowsForLine(Line *l, int maxCols) { + int len = strlen(l->value); + return len / maxCols; +} + +void updateScreen() { + Buffer *b = &buffer; + int mCols = 0; + int mRows = 0; + int rowsLeft = 0; + int iterations = 0; + long iterator = (b->start + b->count - 1) % b->size; + clear(); + getmaxyx(stdscr, mCols, mRows); + rowsLeft = mRows; + if (b->count > 0) { + while (iterations < b->count && rowsLeft > 0) { + Line *l = bufRead(b, iterator); + if (l != NULL) { + int rowsLine = rowsForLine(l, mCols); + printw("%s", l->value); + iterations++; + iterator--; + if (iterator < 0) { + iterator = b->start + b->count - 1; + } + rowsLeft -= rowsLine; + } + } + } + refresh(); +} + +void bufInit(Buffer *b, int maxSize) { + b->size = maxSize; + b->start = 0; + b->count = 0; + b->items = (Line *)(malloc(sizeof(Line) * maxSize)); +} + +bool bufIsFull(Buffer *b) { + return b->count == b->size; +} + +bool bufIsEmpty(Buffer *b) { + return b->count == 0; +} + +void bufWrite(Buffer *b, Line *l) { + int end = (b->start + b->count) % b->size; + if (b->count == b->size) { // buffer is full + b->start = (b->start + 1) % b->size; + // free the item + Line *l = &b->items[end]; + if (l != NULL) { + free(l->value); + } + } else { + b->count++; + } + // set new item + b->items[end] = *l; +} + +Line *bufRead(Buffer *b, int pos) { + int itemPos = (b->start + pos) % b->size; + return &b->items[itemPos]; +} + +void bufFree(Buffer *b) { + int i = 0; + for (i = 0; i < b->count; i++) { + Line *l = &b->items[i]; + if (l != NULL && l->value != NULL) { + free(l->value); + } + } + free(b->items); +} \ No newline at end of file diff --git a/pool/shard000/C/0016019_CWE190_Integer_Overflow__unsigned_int_fscanf_square_66b.c b/pool/shard000/C/0016019_CWE190_Integer_Overflow__unsigned_int_fscanf_square_66b.c new file mode 100644 index 0000000000000000000000000000000000000000..c4aa80f175da488247226742d5d13ecbeb7add25 --- /dev/null +++ b/pool/shard000/C/0016019_CWE190_Integer_Overflow__unsigned_int_fscanf_square_66b.c @@ -0,0 +1,66 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE190_Integer_Overflow__unsigned_int_fscanf_square_66b.c +Label Definition File: CWE190_Integer_Overflow.label.xml +Template File: sources-sinks-66b.tmpl.c +*/ +/* + * @description + * CWE: 190 Integer Overflow + * BadSource: fscanf Read data from the console using fscanf() + * GoodSource: Set data to a small, non-zero number (two) + * Sinks: square + * GoodSink: Ensure there will not be an overflow before squaring data + * BadSink : Square data, which can lead to overflow + * Flow Variant: 66 Data flow: data passed in an array from one function to another in different source files + * + * */ + +#include "std_testcase.h" + +#include + +#ifndef OMITBAD + +void CWE190_Integer_Overflow__unsigned_int_fscanf_square_66b_badSink(unsigned int dataArray[]) +{ + /* copy data out of dataArray */ + unsigned int data = dataArray[2]; + { + /* POTENTIAL FLAW: if (data*data) > UINT_MAX, this will overflow */ + unsigned int result = data * data; + printUnsignedLine(result); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void CWE190_Integer_Overflow__unsigned_int_fscanf_square_66b_goodG2BSink(unsigned int dataArray[]) +{ + unsigned int data = dataArray[2]; + { + /* POTENTIAL FLAW: if (data*data) > UINT_MAX, this will overflow */ + unsigned int result = data * data; + printUnsignedLine(result); + } +} + +/* goodB2G uses the BadSource with the GoodSink */ +void CWE190_Integer_Overflow__unsigned_int_fscanf_square_66b_goodB2GSink(unsigned int dataArray[]) +{ + unsigned int data = dataArray[2]; + /* FIX: Add a check to prevent an overflow from occurring */ + if (abs((long)data) < (long)sqrt((double)UINT_MAX)) + { + unsigned int result = data * data; + printUnsignedLine(result); + } + else + { + printLine("data value is too large to perform arithmetic safely."); + } +} + +#endif /* OMITGOOD */ diff --git a/pool/shard000/C/0016020_nlrsetjmp.c b/pool/shard000/C/0016020_nlrsetjmp.c new file mode 100644 index 0000000000000000000000000000000000000000..c3873e0b6d21ca9b1cf9b24f9c5cbf13e074fffd --- /dev/null +++ b/pool/shard000/C/0016020_nlrsetjmp.c @@ -0,0 +1,42 @@ +/* + * This file is part of the Micro Python project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2013, 2014 Damien P. George + * + * 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 "py/nlr.h" + +#if MICROPY_NLR_SETJMP + +void nlr_setjmp_jump(void *val) { + nlr_buf_t **top_ptr = &MP_STATE_THREAD(nlr_top); + nlr_buf_t *top = *top_ptr; + if (top == NULL) { + nlr_jump_fail(val); + } + top->ret_val = val; + *top_ptr = top->prev; + longjmp(top->jmpbuf, 1); +} + +#endif diff --git a/pool/shard000/C/0016028_unixtime.c b/pool/shard000/C/0016028_unixtime.c new file mode 100644 index 0000000000000000000000000000000000000000..b8459bdf6d72f30730c763e99037882f56b9c3d3 --- /dev/null +++ b/pool/shard000/C/0016028_unixtime.c @@ -0,0 +1,41 @@ +#include + +#ifdef WIN32 + +#define WIN32_LEAN_AND_MEAN +#include + +/* WIN32 epoch starts in 1601, Unix in 1970 */ + +#define EPOCHFILETIME (116444736000000000LL) + +double getUnixTimeAsDouble() { + FILETIME ft; + LARGE_INTEGER li; + __int64 t; + + GetSystemTimeAsFileTime(&ft); + + li.LowPart = ft.dwLowDateTime; + li.HighPart = ft.dwHighDateTime; + + t = li.QuadPart; /* In 100-nanosecond intervals */ + t -= EPOCHFILETIME; /* Offset to the Epoch time */ + + t /= 10; /* In microseconds */ + return (double) t * 1e-6; +} + +#else + +#include + +double getUnixTimeAsDouble() { + struct timeval tv; + + gettimeofday(&tv,0); + return (double) tv.tv_sec + (double) tv.tv_usec*1e-6; +} + +#endif + diff --git a/pool/shard000/C/0016053_bgp4_open.c b/pool/shard000/C/0016053_bgp4_open.c new file mode 100644 index 0000000000000000000000000000000000000000..8fd9b0bdbf4ad6f73487c14f46ed421bd1400b26 --- /dev/null +++ b/pool/shard000/C/0016053_bgp4_open.c @@ -0,0 +1,266 @@ +/* + * + * libnet 1.1 + * Build a BGP4 open message with what you want as payload + * + * Copyright (c) 2003 Frédéric Raynal + * All rights reserved. + * + * Examples: + * + * minimal BGP OPEN message: + * + * ./bgp4_open -s 1.1.1.1 -d 2.2.2.2 + * + * 12:17:00.879139 1.1.1.1.26214 > 2.2.2.2.179: S [tcp sum ok] + * 16843009:16843038(29) win 32767: BGP (ttl 64, id 242, len 69) + * 0x0000 4500 0045 00f2 0000 4006 73bc 0101 0101 E..E....@.s..... + * 0x0010 0202 0202 6666 00b3 0101 0101 0202 0202 ....ff.......... + * 0x0020 5002 7fff ad2e 0000 0101 0101 0101 0101 P............... + * 0x0030 0101 0101 0101 0101 001d 0104 1234 5678 .............4Vx + * 0x0040 dead beef 00 ..... + * + * + * use payload as BGP option for authentication: + * + * ./bgp4_open -s 1.1.1.1 -d 2.2.2.2 -p `printf "\x01\x01\x00"` -S 3 + * + * 12:15:48.102808 1.1.1.1.26214 > 2.2.2.2.179: S [tcp sum ok] + * 16843009:16843041(32) win 32767: BGP (ttl 64, id 242, len 72) + * 0x0000 4500 0048 00f2 0000 4006 73b9 0101 0101 E..H....@.s..... + * 0x0010 0202 0202 6666 00b3 0101 0101 0202 0202 ....ff.......... + * 0x0020 5002 7fff a927 0000 0101 0101 0101 0101 P....'.......... + * 0x0030 0101 0101 0101 0101 0020 0104 1234 5678 .............4Vx + * 0x0040 dead beef 0301 0100 ........ + * + * + * 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 THE AUTHOR 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 AUTHOR 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. + * + */ +#if (HAVE_CONFIG_H) +#include "../include/config.h" +#endif +#include "./libnet_test.h" + +int +main(int argc, char *argv[]) +{ + int c; + libnet_t *l; + u_long src_ip, dst_ip, length; + libnet_ptag_t t = 0; + char errbuf[LIBNET_ERRBUF_SIZE]; + u_char *payload = NULL; + u_long payload_s = 0; + u_char marker[LIBNET_BGP4_MARKER_SIZE]; + + printf("libnet 1.1 packet shaping: BGP4 open + payload[raw]\n"); + + /* + * Initialize the library. Root priviledges are required. + */ + l = libnet_init( + LIBNET_RAW4, /* injection type */ + NULL, /* network interface */ + errbuf); /* error buffer */ + + if (l == NULL) + { + fprintf(stderr, "libnet_init() failed: %s", errbuf); + exit(EXIT_FAILURE); + } + + src_ip = 0; + dst_ip = 0; + memset(marker, 0x1, LIBNET_BGP4_MARKER_SIZE); + + while ((c = getopt(argc, argv, "d:s:t:m:p:S:")) != EOF) + { + switch (c) + { + /* + * We expect the input to be of the form `ip.ip.ip.ip.port`. We + * point cp to the last dot of the IP address/port string and + * then seperate them with a NULL byte. The optarg now points to + * just the IP address, and cp points to the port. + */ + case 'd': + if ((dst_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) + { + fprintf(stderr, "Bad destination IP address: %s\n", optarg); + exit(EXIT_FAILURE); + } + break; + + case 's': + if ((src_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) + { + fprintf(stderr, "Bad source IP address: %s\n", optarg); + exit(EXIT_FAILURE); + } + break; + + case 'm': + memcpy(marker, optarg, LIBNET_BGP4_MARKER_SIZE); + break; + + case 'p': + payload = optarg; + break; + + case 'S': + payload_s = atoi(optarg); + break; + + default: + exit(EXIT_FAILURE); + } + } + + if (!src_ip || !dst_ip) + { + usage(argv[0]); + goto bad; + } + + if (payload_s && !payload) + { + payload = (u_char *)malloc(payload_s); + if (!payload) + { + printf("memory allocation failed (%ld bytes requested)\n", payload_s); + goto bad; + } + memset(payload, 0x41, payload_s); + } + + + if (payload && !payload_s) + { + payload_s = strlen(payload); + } + + length = LIBNET_BGP4_OPEN_H + payload_s; + t = libnet_build_bgp4_open( + 4, /* version */ + 0x3412, /* my AS */ + 0x7856, /* hold time */ + 0xefbeadde, /* BGP id */ + payload_s, /* options length */ + payload, /* payload */ + payload_s, /* payload size */ + l, /* libnet handle */ + 0); /* libnet id */ + if (t == -1) + { + fprintf(stderr, "Can't build BGP4 open header: %s\n", libnet_geterror(l)); + goto bad; + } + + length+=LIBNET_BGP4_HEADER_H; + t = libnet_build_bgp4_header( + marker, /* marker */ + length, /* length */ + LIBNET_BGP4_OPEN, /* message type */ + NULL, /* payload */ + 0, /* payload size */ + l, /* libnet handle */ + 0); /* libnet id */ + if (t == -1) + { + fprintf(stderr, "Can't build BGP4 header: %s\n", libnet_geterror(l)); + goto bad; + } + + length+=LIBNET_TCP_H; + t = libnet_build_tcp( + 0x6666, /* source port */ + 179, /* destination port */ + 0x01010101, /* sequence number */ + 0x02020202, /* acknowledgement num */ + TH_SYN, /* control flags */ + 32767, /* window size */ + 0, /* checksum */ + 0, /* urgent pointer */ + length, /* TCP packet size */ + NULL, /* payload */ + 0, /* payload size */ + l, /* libnet handle */ + 0); /* libnet id */ + if (t == -1) + { + fprintf(stderr, "Can't build TCP header: %s\n", libnet_geterror(l)); + goto bad; + } + + length+=LIBNET_IPV4_H; + t = libnet_build_ipv4( + length, /* length */ + 0, /* TOS */ + 242, /* IP ID */ + 0, /* IP Frag */ + 64, /* TTL */ + IPPROTO_TCP, /* protocol */ + 0, /* checksum */ + src_ip, /* source IP */ + dst_ip, /* destination IP */ + NULL, /* payload */ + 0, /* payload size */ + l, /* libnet handle */ + 0); /* libnet id */ + if (t == -1) + { + fprintf(stderr, "Can't build IP header: %s\n", libnet_geterror(l)); + goto bad; + } + + /* + * Write it to the wire. + */ + c = libnet_write(l); + if (c == -1) + { + fprintf(stderr, "Write error: %s\n", libnet_geterror(l)); + goto bad; + } + else + { + fprintf(stderr, "Wrote %d byte TCP packet; check the wire.\n", c); + } + + libnet_destroy(l); + return (EXIT_SUCCESS); +bad: + libnet_destroy(l); + return (EXIT_FAILURE); +} + +void +usage(char *name) +{ + fprintf(stderr, + "usage: %s -s source_ip -d destination_ip" + " [-m marker] [-p payload] [-S payload size]\n", + name); +} + +/* EOF */ diff --git a/pool/shard000/C/0016054_display.c b/pool/shard000/C/0016054_display.c new file mode 100644 index 0000000000000000000000000000000000000000..dd91c204e0a6b38d860bead713f77edf937f4134 --- /dev/null +++ b/pool/shard000/C/0016054_display.c @@ -0,0 +1,126 @@ +/* + * OMAP2plus display device setup / initialization. + * + * Copyright (C) 2010 Texas Instruments Incorporated - http://www.ti.com/ + * Senthilvadivu Guruswamy + * Sumit Semwal + * + * 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 "as is" WITHOUT ANY WARRANTY of any + * kind, whether express or implied; 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 +#include +#include +#include + +#include